2 * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
4 * Copyright (C) 2002-2010 Aleph One Ltd.
5 * for Toby Churchill Ltd and Brightstar Engineering
7 * Created by Charles Manning <charles@aleph1.co.uk>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2 as
11 * published by the Free Software Foundation.
14 #include "yaffs_trace.h"
16 #include "yaffsinterface.h"
17 #include "yaffs_guts.h"
18 #include "yaffs_tagsvalidity.h"
19 #include "yaffs_getblockinfo.h"
21 #include "yaffs_tagscompat.h"
22 #ifndef CONFIG_YAFFS_USE_OWN_SORT
23 #include "yaffs_qsort.h"
25 #include "yaffs_nand.h"
27 #include "yaffs_checkptrw.h"
29 #include "yaffs_nand.h"
30 #include "yaffs_packedtags2.h"
33 /* Note YAFFS_GC_GOOD_ENOUGH must be <= YAFFS_GC_PASSIVE_THRESHOLD */
34 #define YAFFS_GC_GOOD_ENOUGH 2
35 #define YAFFS_GC_PASSIVE_THRESHOLD 4
37 #define YAFFS_SMALL_HOLE_THRESHOLD 3
39 #include "yaffs_ecc.h"
42 /* Robustification (if it ever comes about...) */
43 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND);
44 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
46 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
48 const yaffs_ExtendedTags *tags);
49 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
50 const yaffs_ExtendedTags *tags);
52 /* Other local prototypes */
53 static void yaffs_UpdateParent(yaffs_Object *obj);
54 static int yaffs_UnlinkObject(yaffs_Object *obj);
55 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
57 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
59 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev,
61 yaffs_ExtendedTags *tags,
63 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
64 int chunkInNAND, int inScan);
66 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
67 yaffs_ObjectType type);
68 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
70 static int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name,
71 int force, int isShrink, int shadows);
72 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
73 static int yaffs_CheckStructures(void);
74 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
75 int chunkOffset, int *limit);
76 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
78 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev, int blockNo);
81 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
84 static int yaffs_UnlinkWorker(yaffs_Object *obj);
86 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
89 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
90 yaffs_BlockInfo **blockUsedPtr);
92 static void yaffs_VerifyFreeChunks(yaffs_Device *dev);
94 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
96 static void yaffs_VerifyDirectory(yaffs_Object *directory);
98 static int yaffs_CheckFileSanity(yaffs_Object *in);
100 #define yaffs_CheckFileSanity(in)
103 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
104 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
106 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
108 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
109 yaffs_ExtendedTags *tags);
111 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
113 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
114 yaffs_FileStructure *fStruct,
117 static int yaffs_HandleHole(yaffs_Object *obj, loff_t newSize);
118 static void yaffs_SkipRestOfBlock(yaffs_Device *dev);
119 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
122 yaffs_ExtendedTags *tags);
124 /* Function to calculate chunk and offset */
126 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut,
132 chunk = (__u32)(addr >> dev->chunkShift);
134 if (dev->chunkDiv == 1) {
135 /* easy power of 2 case */
136 offset = (__u32)(addr & dev->chunkMask);
138 /* Non power-of-2 case */
142 chunk /= dev->chunkDiv;
144 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
145 offset = (__u32)(addr - chunkBase);
152 /* Function to return the number of shifts for a power of 2 greater than or
153 * equal to the given number
154 * Note we don't try to cater for all possible numbers and this does not have to
155 * be hellishly efficient.
158 static __u32 ShiftsGE(__u32 x)
163 nShifts = extraBits = 0;
178 /* Function to return the number of shifts to get a 1 in bit 0
181 static __u32 Shifts(__u32 x)
201 * Temporary buffer manipulations.
204 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
207 __u8 *buf = (__u8 *)1;
209 memset(dev->tempBuffer, 0, sizeof(dev->tempBuffer));
211 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
212 dev->tempBuffer[i].line = 0; /* not in use */
213 dev->tempBuffer[i].buffer = buf =
214 YMALLOC_DMA(dev->param.totalBytesPerChunk);
217 return buf ? YAFFS_OK : YAFFS_FAIL;
220 __u8 *yaffs_GetTempBuffer(yaffs_Device *dev, int lineNo)
225 if (dev->tempInUse > dev->maxTemp)
226 dev->maxTemp = dev->tempInUse;
228 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
229 if (dev->tempBuffer[i].line == 0) {
230 dev->tempBuffer[i].line = lineNo;
231 if ((i + 1) > dev->maxTemp) {
232 dev->maxTemp = i + 1;
233 for (j = 0; j <= i; j++)
234 dev->tempBuffer[j].maxLine =
235 dev->tempBuffer[j].line;
238 return dev->tempBuffer[i].buffer;
242 T(YAFFS_TRACE_BUFFERS,
243 (TSTR("Out of temp buffers at line %d, other held by lines:"),
245 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
246 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
248 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
251 * If we got here then we have to allocate an unmanaged one
255 dev->unmanagedTempAllocations++;
256 return YMALLOC(dev->nDataBytesPerChunk);
260 void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer,
267 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
268 if (dev->tempBuffer[i].buffer == buffer) {
269 dev->tempBuffer[i].line = 0;
275 /* assume it is an unmanaged one. */
276 T(YAFFS_TRACE_BUFFERS,
277 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
280 dev->unmanagedTempDeallocations++;
286 * Determine if we have a managed buffer.
288 int yaffs_IsManagedTempBuffer(yaffs_Device *dev, const __u8 *buffer)
292 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
293 if (dev->tempBuffer[i].buffer == buffer)
297 for (i = 0; i < dev->param.nShortOpCaches; i++) {
298 if (dev->srCache[i].data == buffer)
302 if (buffer == dev->checkpointBuffer)
305 T(YAFFS_TRACE_ALWAYS,
306 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
313 * Chunk bitmap manipulations
316 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
318 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
320 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
324 return dev->chunkBits +
325 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
328 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
330 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
331 chunk < 0 || chunk >= dev->param.nChunksPerBlock) {
333 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),
339 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device *dev, int blk)
341 __u8 *blkBits = yaffs_BlockBits(dev, blk);
343 memset(blkBits, 0, dev->chunkBitmapStride);
346 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device *dev, int blk, int chunk)
348 __u8 *blkBits = yaffs_BlockBits(dev, blk);
350 yaffs_VerifyChunkBitId(dev, blk, chunk);
352 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
355 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device *dev, int blk, int chunk)
357 __u8 *blkBits = yaffs_BlockBits(dev, blk);
359 yaffs_VerifyChunkBitId(dev, blk, chunk);
361 blkBits[chunk / 8] |= (1 << (chunk & 7));
364 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device *dev, int blk, int chunk)
366 __u8 *blkBits = yaffs_BlockBits(dev, blk);
367 yaffs_VerifyChunkBitId(dev, blk, chunk);
369 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
372 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device *dev, int blk)
374 __u8 *blkBits = yaffs_BlockBits(dev, blk);
376 for (i = 0; i < dev->chunkBitmapStride; i++) {
384 static int yaffs_CountChunkBits(yaffs_Device *dev, int blk)
386 __u8 *blkBits = yaffs_BlockBits(dev, blk);
389 for (i = 0; i < dev->chunkBitmapStride; i++) {
406 static int yaffs_SkipVerification(yaffs_Device *dev)
409 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
412 static int yaffs_SkipFullVerification(yaffs_Device *dev)
415 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
418 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
421 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
424 static const char *blockStateName[] = {
437 static void yaffs_VerifyBlock(yaffs_Device *dev, yaffs_BlockInfo *bi, int n)
442 if (yaffs_SkipVerification(dev))
445 /* Report illegal runtime states */
446 if (bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
447 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has undefined state %d"TENDSTR), n, bi->blockState));
449 switch (bi->blockState) {
450 case YAFFS_BLOCK_STATE_UNKNOWN:
451 case YAFFS_BLOCK_STATE_SCANNING:
452 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
453 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has bad run-state %s"TENDSTR),
454 n, blockStateName[bi->blockState]));
457 /* Check pages in use and soft deletions are legal */
459 actuallyUsed = bi->pagesInUse - bi->softDeletions;
461 if (bi->pagesInUse < 0 || bi->pagesInUse > dev->param.nChunksPerBlock ||
462 bi->softDeletions < 0 || bi->softDeletions > dev->param.nChunksPerBlock ||
463 actuallyUsed < 0 || actuallyUsed > dev->param.nChunksPerBlock)
464 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
465 n, bi->pagesInUse, bi->softDeletions));
468 /* Check chunk bitmap legal */
469 inUse = yaffs_CountChunkBits(dev, n);
470 if (inUse != bi->pagesInUse)
471 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
472 n, bi->pagesInUse, inUse));
474 /* Check that the sequence number is valid.
475 * Ten million is legal, but is very unlikely
477 if (dev->param.isYaffs2 &&
478 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
479 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000))
480 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has suspect sequence number of %d"TENDSTR),
481 n, bi->sequenceNumber));
484 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev, yaffs_BlockInfo *bi,
487 yaffs_VerifyBlock(dev, bi, n);
489 /* After collection the block should be in the erased state */
490 /* This will need to change if we do partial gc */
492 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
493 bi->blockState != YAFFS_BLOCK_STATE_EMPTY) {
494 T(YAFFS_TRACE_ERROR, (TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
499 static void yaffs_VerifyBlocks(yaffs_Device *dev)
502 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
503 int nIllegalBlockStates = 0;
505 if (yaffs_SkipVerification(dev))
508 memset(nBlocksPerState, 0, sizeof(nBlocksPerState));
510 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
511 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, i);
512 yaffs_VerifyBlock(dev, bi, i);
514 if (bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
515 nBlocksPerState[bi->blockState]++;
517 nIllegalBlockStates++;
520 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
521 T(YAFFS_TRACE_VERIFY, (TSTR("Block summary"TENDSTR)));
523 T(YAFFS_TRACE_VERIFY, (TSTR("%d blocks have illegal states"TENDSTR), nIllegalBlockStates));
524 if (nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
525 T(YAFFS_TRACE_VERIFY, (TSTR("Too many allocating blocks"TENDSTR)));
527 for (i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
528 T(YAFFS_TRACE_VERIFY,
529 (TSTR("%s %d blocks"TENDSTR),
530 blockStateName[i], nBlocksPerState[i]));
532 if (dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
533 T(YAFFS_TRACE_VERIFY,
534 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
535 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
537 if (dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
538 T(YAFFS_TRACE_VERIFY,
539 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
540 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
542 if (nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
543 T(YAFFS_TRACE_VERIFY,
544 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
545 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
547 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
552 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
553 * case those tests will not be performed.
555 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
557 if (obj && yaffs_SkipVerification(obj->myDev))
560 if (!(tags && obj && oh)) {
561 T(YAFFS_TRACE_VERIFY,
562 (TSTR("Verifying object header tags %p obj %p oh %p"TENDSTR),
567 if (oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
568 oh->type > YAFFS_OBJECT_TYPE_MAX)
569 T(YAFFS_TRACE_VERIFY,
570 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
571 tags->objectId, oh->type));
573 if (tags->objectId != obj->objectId)
574 T(YAFFS_TRACE_VERIFY,
575 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
576 tags->objectId, obj->objectId));
580 * Check that the object's parent ids match if parentCheck requested.
582 * Tests do not apply to the root object.
585 if (parentCheck && tags->objectId > 1 && !obj->parent)
586 T(YAFFS_TRACE_VERIFY,
587 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
588 tags->objectId, oh->parentObjectId));
590 if (parentCheck && obj->parent &&
591 oh->parentObjectId != obj->parent->objectId &&
592 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
593 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
594 T(YAFFS_TRACE_VERIFY,
595 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
596 tags->objectId, oh->parentObjectId, obj->parent->objectId));
598 if (tags->objectId > 1 && oh->name[0] == 0) /* Null name */
599 T(YAFFS_TRACE_VERIFY,
600 (TSTR("Obj %d header name is NULL"TENDSTR),
603 if (tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
604 T(YAFFS_TRACE_VERIFY,
605 (TSTR("Obj %d header name is 0xFF"TENDSTR),
611 static int yaffs_VerifyTnodeWorker(yaffs_Object *obj, yaffs_Tnode *tn,
612 __u32 level, int chunkOffset)
615 yaffs_Device *dev = obj->myDev;
621 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
622 if (tn->internal[i]) {
623 ok = yaffs_VerifyTnodeWorker(obj,
626 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
629 } else if (level == 0) {
630 yaffs_ExtendedTags tags;
631 __u32 objectId = obj->objectId;
633 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
635 for (i = 0; i < YAFFS_NTNODES_LEVEL0; i++) {
636 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
639 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
640 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
641 if (tags.objectId != objectId || tags.chunkId != chunkOffset) {
642 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
643 objectId, chunkOffset, theChunk,
644 tags.objectId, tags.chunkId));
657 static void yaffs_VerifyFile(yaffs_Object *obj)
659 int requiredTallness;
665 yaffs_ExtendedTags tags;
672 if (yaffs_SkipVerification(obj->myDev))
676 objectId = obj->objectId;
678 /* Check file size is consistent with tnode depth */
679 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
680 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
681 requiredTallness = 0;
683 x >>= YAFFS_TNODES_INTERNAL_BITS;
687 actualTallness = obj->variant.fileVariant.topLevel;
689 /* Check that the chunks in the tnode tree are all correct.
690 * We do this by scanning through the tnode tree and
691 * checking the tags for every chunk match.
694 if (yaffs_SkipNANDVerification(dev))
697 for (i = 1; i <= lastChunk; i++) {
698 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant, i);
701 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
703 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
704 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
705 if (tags.objectId != objectId || tags.chunkId != i) {
706 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
707 objectId, i, theChunk,
708 tags.objectId, tags.chunkId));
716 static void yaffs_VerifyHardLink(yaffs_Object *obj)
718 if (obj && yaffs_SkipVerification(obj->myDev))
721 /* Verify sane equivalent object */
724 static void yaffs_VerifySymlink(yaffs_Object *obj)
726 if (obj && yaffs_SkipVerification(obj->myDev))
729 /* Verify symlink string */
732 static void yaffs_VerifySpecial(yaffs_Object *obj)
734 if (obj && yaffs_SkipVerification(obj->myDev))
738 static void yaffs_VerifyObject(yaffs_Object *obj)
747 __u32 chunkShouldNotBeDeleted;
753 if (obj->beingCreated)
758 if (yaffs_SkipVerification(dev))
761 /* Check sane object header chunk */
763 chunkMin = dev->internalStartBlock * dev->param.nChunksPerBlock;
764 chunkMax = (dev->internalEndBlock+1) * dev->param.nChunksPerBlock - 1;
766 chunkInRange = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
767 chunkIdOk = chunkInRange || (obj->hdrChunk == 0);
768 chunkValid = chunkInRange &&
769 yaffs_CheckChunkBit(dev,
770 obj->hdrChunk / dev->param.nChunksPerBlock,
771 obj->hdrChunk % dev->param.nChunksPerBlock);
772 chunkShouldNotBeDeleted = chunkInRange && !chunkValid;
775 (!chunkIdOk || chunkShouldNotBeDeleted)) {
776 T(YAFFS_TRACE_VERIFY,
777 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
778 obj->objectId, obj->hdrChunk,
779 chunkIdOk ? "" : ",out of range",
780 chunkShouldNotBeDeleted ? ",marked as deleted" : ""));
783 if (chunkValid && !yaffs_SkipNANDVerification(dev)) {
784 yaffs_ExtendedTags tags;
785 yaffs_ObjectHeader *oh;
786 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
788 oh = (yaffs_ObjectHeader *)buffer;
790 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk, buffer,
793 yaffs_VerifyObjectHeader(obj, oh, &tags, 1);
795 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
798 /* Verify it has a parent */
799 if (obj && !obj->fake &&
800 (!obj->parent || obj->parent->myDev != dev)) {
801 T(YAFFS_TRACE_VERIFY,
802 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
803 obj->objectId, obj->parent));
806 /* Verify parent is a directory */
807 if (obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
808 T(YAFFS_TRACE_VERIFY,
809 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
810 obj->objectId, obj->parent->variantType));
813 switch (obj->variantType) {
814 case YAFFS_OBJECT_TYPE_FILE:
815 yaffs_VerifyFile(obj);
817 case YAFFS_OBJECT_TYPE_SYMLINK:
818 yaffs_VerifySymlink(obj);
820 case YAFFS_OBJECT_TYPE_DIRECTORY:
821 yaffs_VerifyDirectory(obj);
823 case YAFFS_OBJECT_TYPE_HARDLINK:
824 yaffs_VerifyHardLink(obj);
826 case YAFFS_OBJECT_TYPE_SPECIAL:
827 yaffs_VerifySpecial(obj);
829 case YAFFS_OBJECT_TYPE_UNKNOWN:
831 T(YAFFS_TRACE_VERIFY,
832 (TSTR("Obj %d has illegaltype %d"TENDSTR),
833 obj->objectId, obj->variantType));
838 static void yaffs_VerifyObjects(yaffs_Device *dev)
842 struct ylist_head *lh;
844 if (yaffs_SkipVerification(dev))
847 /* Iterate through the objects in each hash entry */
849 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
850 ylist_for_each(lh, &dev->objectBucket[i].list) {
852 obj = ylist_entry(lh, yaffs_Object, hashLink);
853 yaffs_VerifyObject(obj);
861 * Simple hash function. Needs to have a reasonable spread
864 static Y_INLINE int yaffs_HashFunction(int n)
867 return n % YAFFS_NOBJECT_BUCKETS;
871 * Access functions to useful fake objects.
872 * Note that root might have a presence in NAND if permissions are set.
875 yaffs_Object *yaffs_Root(yaffs_Device *dev)
880 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
882 return dev->lostNFoundDir;
887 * Erased NAND checking functions
890 int yaffs_CheckFF(__u8 *buffer, int nBytes)
892 /* Horrible, slow implementation */
901 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
904 int retval = YAFFS_OK;
905 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
906 yaffs_ExtendedTags tags;
909 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
911 if (tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
914 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
915 T(YAFFS_TRACE_NANDACCESS,
916 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
920 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
927 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
930 yaffs_ExtendedTags *tags)
932 int retval = YAFFS_OK;
933 yaffs_ExtendedTags tempTags;
934 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
937 result = yaffs_ReadChunkWithTagsFromNAND(dev,chunkInNAND,buffer,&tempTags);
938 if(memcmp(buffer,data,dev->nDataBytesPerChunk) ||
939 tempTags.objectId != tags->objectId ||
940 tempTags.chunkId != tags->chunkId ||
941 tempTags.byteCount != tags->byteCount)
944 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
949 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
951 yaffs_ExtendedTags *tags,
958 yaffs_InvalidateCheckpoint(dev);
961 yaffs_BlockInfo *bi = 0;
964 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
970 /* First check this chunk is erased, if it needs
971 * checking. The checking policy (unless forced
972 * always on) is as follows:
974 * Check the first page we try to write in a block.
975 * If the check passes then we don't need to check any
976 * more. If the check fails, we check again...
977 * If the block has been erased, we don't need to check.
979 * However, if the block has been prioritised for gc,
980 * then we think there might be something odd about
981 * this block and stop using it.
983 * Rationale: We should only ever see chunks that have
984 * not been erased if there was a partially written
985 * chunk due to power loss. This checking policy should
986 * catch that case with very few checks and thus save a
987 * lot of checks that are most likely not needed.
990 * If an erase check fails or the write fails we skip the
994 /* let's give it a try */
997 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
998 bi->skipErasedCheck = 0;
1000 if (!bi->skipErasedCheck) {
1001 erasedOk = yaffs_CheckChunkErased(dev, chunk);
1002 if (erasedOk != YAFFS_OK) {
1003 T(YAFFS_TRACE_ERROR,
1004 (TSTR("**>> yaffs chunk %d was not erased"
1007 /* If not erased, delete this one,
1008 * skip rest of block and
1009 * try another chunk */
1010 yaffs_DeleteChunk(dev,chunk,1,__LINE__);
1011 yaffs_SkipRestOfBlock(dev);
1016 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
1019 if(!bi->skipErasedCheck)
1020 writeOk = yaffs_VerifyChunkWritten(dev, chunk, data, tags);
1022 if (writeOk != YAFFS_OK) {
1023 /* Clean up aborted write, skip to next block and
1024 * try another chunk */
1025 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
1029 bi->skipErasedCheck = 1;
1031 /* Copy the data into the robustification buffer */
1032 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1034 } while (writeOk != YAFFS_OK &&
1035 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1041 T(YAFFS_TRACE_ERROR,
1042 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1045 dev->nRetriedWrites += (attempts - 1);
1053 * Oldest Dirty Sequence Number handling.
1056 /* yaffs_CalcOldestDirtySequence()
1057 * yaffs_FindOldestDirtySequence()
1058 * Calculate the oldest dirty sequence number if we don't know it.
1060 static void yaffs_CalcOldestDirtySequence(yaffs_Device *dev)
1064 unsigned blockNo = 0;
1067 if(!dev->param.isYaffs2)
1070 /* Find the oldest dirty sequence number. */
1071 seq = dev->sequenceNumber + 1;
1073 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
1074 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
1075 (b->pagesInUse - b->softDeletions) < dev->param.nChunksPerBlock &&
1076 b->sequenceNumber < seq) {
1077 seq = b->sequenceNumber;
1084 dev->oldestDirtySequence = seq;
1085 dev->oldestDirtyBlock = blockNo;
1091 static void yaffs_FindOldestDirtySequence(yaffs_Device *dev)
1093 if(dev->param.isYaffs2 && !dev->oldestDirtySequence)
1094 yaffs_CalcOldestDirtySequence(dev);
1098 * yaffs_ClearOldestDirtySequence()
1099 * Called when a block is erased or marked bad. (ie. when its sequenceNumber
1100 * becomes invalid). If the value matches the oldest then we clear
1101 * dev->oldestDirtySequence to force its recomputation.
1103 static void yaffs_ClearOldestDirtySequence(yaffs_Device *dev, yaffs_BlockInfo *bi)
1106 if(!dev->param.isYaffs2)
1109 if(!bi || bi->sequenceNumber == dev->oldestDirtySequence){
1110 dev->oldestDirtySequence = 0;
1111 dev->oldestDirtyBlock = 0;
1116 * yaffs_UpdateOldestDirtySequence()
1117 * Update the oldest dirty sequence number whenever we dirty a block.
1118 * Only do this if the oldestDirtySequence is actually being tracked.
1120 static void yaffs_UpdateOldestDirtySequence(yaffs_Device *dev, unsigned blockNo, yaffs_BlockInfo *bi)
1122 if(dev->param.isYaffs2 && dev->oldestDirtySequence){
1123 if(dev->oldestDirtySequence > bi->sequenceNumber){
1124 dev->oldestDirtySequence = bi->sequenceNumber;
1125 dev->oldestDirtyBlock = blockNo;
1131 * Block retiring for handling a broken block.
1134 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND)
1136 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1138 yaffs_InvalidateCheckpoint(dev);
1140 yaffs_ClearOldestDirtySequence(dev,bi);
1142 if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
1143 if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
1144 T(YAFFS_TRACE_ALWAYS, (TSTR(
1145 "yaffs: Failed to mark bad and erase block %d"
1146 TENDSTR), blockInNAND));
1148 yaffs_ExtendedTags tags;
1149 int chunkId = blockInNAND * dev->param.nChunksPerBlock;
1151 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
1153 memset(buffer, 0xff, dev->nDataBytesPerChunk);
1154 yaffs_InitialiseTags(&tags);
1155 tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
1156 if (dev->param.writeChunkWithTagsToNAND(dev, chunkId -
1157 dev->chunkOffset, buffer, &tags) != YAFFS_OK)
1158 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
1159 TCONT("write bad block marker to block %d")
1160 TENDSTR), blockInNAND));
1162 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
1166 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1167 bi->gcPrioritise = 0;
1168 bi->needsRetiring = 0;
1170 dev->nRetiredBlocks++;
1174 * Functions for robustisizing TODO
1178 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
1180 const yaffs_ExtendedTags *tags)
1183 chunkInNAND=chunkInNAND;
1188 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
1189 const yaffs_ExtendedTags *tags)
1192 chunkInNAND=chunkInNAND;
1196 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1198 if (!bi->gcPrioritise) {
1199 bi->gcPrioritise = 1;
1200 dev->hasPendingPrioritisedGCs = 1;
1201 bi->chunkErrorStrikes++;
1203 if (bi->chunkErrorStrikes > 3) {
1204 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1205 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1211 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
1214 int blockInNAND = chunkInNAND / dev->param.nChunksPerBlock;
1215 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1217 yaffs_HandleChunkError(dev, bi);
1220 /* Was an actual write failure, so mark the block for retirement */
1221 bi->needsRetiring = 1;
1222 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1223 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1226 /* Delete the chunk */
1227 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1228 yaffs_SkipRestOfBlock(dev);
1232 /*---------------- Name handling functions ------------*/
1234 static __u16 yaffs_CalcNameSum(const YCHAR *name)
1239 const YUCHAR *bname = (const YUCHAR *) name;
1241 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1243 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1244 sum += yaffs_toupper(*bname) * i;
1246 sum += (*bname) * i;
1255 static void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
1257 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1258 memset(obj->shortName, 0, sizeof(YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1259 if (name && yaffs_strnlen(name,YAFFS_SHORT_NAME_LENGTH+1) <= YAFFS_SHORT_NAME_LENGTH)
1260 yaffs_strcpy(obj->shortName, name);
1262 obj->shortName[0] = _Y('\0');
1264 obj->sum = yaffs_CalcNameSum(name);
1267 /*-------------------- TNODES -------------------
1269 * List of spare tnodes
1270 * The list is hooked together using the first pointer
1274 /* yaffs_CreateTnodes creates a bunch more tnodes and
1275 * adds them to the tnode free list.
1276 * Don't use this function directly
1278 static Y_INLINE int yaffs_CalcTnodeSize(yaffs_Device *dev)
1281 /* Calculate the tnode size in bytes for variable width tnode support.
1282 * Must be a multiple of 32-bits */
1283 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1285 if (tnodeSize < sizeof(yaffs_Tnode))
1286 tnodeSize = sizeof(yaffs_Tnode);
1290 static int yaffs_CreateTnodes(yaffs_Device *dev, int nTnodes)
1293 int tnodeSize = yaffs_CalcTnodeSize(dev);
1294 yaffs_Tnode *newTnodes;
1298 yaffs_TnodeList *tnl;
1304 /* make these things */
1306 newTnodes = YMALLOC(nTnodes * tnodeSize);
1307 mem = (__u8 *)newTnodes;
1310 T(YAFFS_TRACE_ERROR,
1311 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1315 /* Hook them into the free list */
1317 for (i = 0; i < nTnodes - 1; i++) {
1318 newTnodes[i].internal[0] = &newTnodes[i + 1];
1319 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1320 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1324 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1325 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1326 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1328 dev->freeTnodes = newTnodes;
1330 /* New hookup for wide tnodes */
1331 for (i = 0; i < nTnodes - 1; i++) {
1332 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1333 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1334 curr->internal[0] = next;
1337 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1338 curr->internal[0] = dev->freeTnodes;
1339 dev->freeTnodes = (yaffs_Tnode *)mem;
1344 dev->nFreeTnodes += nTnodes;
1345 dev->nTnodesCreated += nTnodes;
1347 /* Now add this bunch of tnodes to a list for freeing up.
1348 * NB If we can't add this to the management list it isn't fatal
1349 * but it just means we can't free this bunch of tnodes later.
1352 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1354 T(YAFFS_TRACE_ERROR,
1356 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1359 tnl->tnodes = newTnodes;
1360 tnl->next = dev->allocatedTnodeList;
1361 dev->allocatedTnodeList = tnl;
1364 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1369 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1371 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device *dev)
1373 yaffs_Tnode *tn = NULL;
1375 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1376 tn = YMALLOC(yaffs_CalcTnodeSize(dev));
1378 dev->nTnodesCreated++;
1380 /* If there are none left make more */
1381 if (!dev->freeTnodes)
1382 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1384 if (dev->freeTnodes) {
1385 tn = dev->freeTnodes;
1386 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1387 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1388 /* Hoosterman, this thing looks like it isn't in the list */
1389 T(YAFFS_TRACE_ALWAYS,
1390 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1393 dev->freeTnodes = dev->freeTnodes->internal[0];
1397 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1402 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
1404 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1405 int tnodeSize = yaffs_CalcTnodeSize(dev);
1408 memset(tn, 0, tnodeSize);
1413 /* FreeTnode frees up a tnode and puts it back on the free list */
1414 static void yaffs_FreeTnode(yaffs_Device *dev, yaffs_Tnode *tn)
1417 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1419 dev->nTnodesCreated--;
1421 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1422 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1423 /* Hoosterman, this thing looks like it is already in the list */
1424 T(YAFFS_TRACE_ALWAYS,
1425 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1427 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1429 tn->internal[0] = dev->freeTnodes;
1430 dev->freeTnodes = tn;
1434 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1437 static void yaffs_DeinitialiseTnodes(yaffs_Device *dev)
1439 /* Free the list of allocated tnodes */
1440 yaffs_TnodeList *tmp;
1442 while (dev->allocatedTnodeList) {
1443 tmp = dev->allocatedTnodeList->next;
1445 YFREE(dev->allocatedTnodeList->tnodes);
1446 YFREE(dev->allocatedTnodeList);
1447 dev->allocatedTnodeList = tmp;
1451 dev->freeTnodes = NULL;
1452 dev->nFreeTnodes = 0;
1453 dev->nTnodesCreated = 0;
1456 static void yaffs_InitialiseTnodes(yaffs_Device *dev)
1458 dev->allocatedTnodeList = NULL;
1459 dev->freeTnodes = NULL;
1460 dev->nFreeTnodes = 0;
1461 dev->nTnodesCreated = 0;
1465 void yaffs_LoadLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
1468 __u32 *map = (__u32 *)tn;
1474 pos &= YAFFS_TNODES_LEVEL0_MASK;
1475 val >>= dev->chunkGroupBits;
1477 bitInMap = pos * dev->tnodeWidth;
1478 wordInMap = bitInMap / 32;
1479 bitInWord = bitInMap & (32 - 1);
1481 mask = dev->tnodeMask << bitInWord;
1483 map[wordInMap] &= ~mask;
1484 map[wordInMap] |= (mask & (val << bitInWord));
1486 if (dev->tnodeWidth > (32 - bitInWord)) {
1487 bitInWord = (32 - bitInWord);
1489 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1490 map[wordInMap] &= ~mask;
1491 map[wordInMap] |= (mask & (val >> bitInWord));
1495 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
1498 __u32 *map = (__u32 *)tn;
1504 pos &= YAFFS_TNODES_LEVEL0_MASK;
1506 bitInMap = pos * dev->tnodeWidth;
1507 wordInMap = bitInMap / 32;
1508 bitInWord = bitInMap & (32 - 1);
1510 val = map[wordInMap] >> bitInWord;
1512 if (dev->tnodeWidth > (32 - bitInWord)) {
1513 bitInWord = (32 - bitInWord);
1515 val |= (map[wordInMap] << bitInWord);
1518 val &= dev->tnodeMask;
1519 val <<= dev->chunkGroupBits;
1524 /* ------------------- End of individual tnode manipulation -----------------*/
1526 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1527 * The look up tree is represented by the top tnode and the number of topLevel
1528 * in the tree. 0 means only the level 0 tnode is in the tree.
1531 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1532 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
1533 yaffs_FileStructure *fStruct,
1536 yaffs_Tnode *tn = fStruct->top;
1538 int requiredTallness;
1539 int level = fStruct->topLevel;
1543 /* Check sane level and chunk Id */
1544 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
1547 if (chunkId > YAFFS_MAX_CHUNK_ID)
1550 /* First check we're tall enough (ie enough topLevel) */
1552 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1553 requiredTallness = 0;
1555 i >>= YAFFS_TNODES_INTERNAL_BITS;
1559 if (requiredTallness > fStruct->topLevel)
1560 return NULL; /* Not tall enough, so we can't find it */
1562 /* Traverse down to level 0 */
1563 while (level > 0 && tn) {
1564 tn = tn->internal[(chunkId >>
1565 (YAFFS_TNODES_LEVEL0_BITS +
1567 YAFFS_TNODES_INTERNAL_BITS)) &
1568 YAFFS_TNODES_INTERNAL_MASK];
1575 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1576 * This happens in two steps:
1577 * 1. If the tree isn't tall enough, then make it taller.
1578 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1580 * Used when modifying the tree.
1582 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1583 * be plugged into the ttree.
1586 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
1587 yaffs_FileStructure *fStruct,
1589 yaffs_Tnode *passedTn)
1591 int requiredTallness;
1599 /* Check sane level and page Id */
1600 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
1603 if (chunkId > YAFFS_MAX_CHUNK_ID)
1606 /* First check we're tall enough (ie enough topLevel) */
1608 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1609 requiredTallness = 0;
1611 x >>= YAFFS_TNODES_INTERNAL_BITS;
1616 if (requiredTallness > fStruct->topLevel) {
1617 /* Not tall enough, gotta make the tree taller */
1618 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1620 tn = yaffs_GetTnode(dev);
1623 tn->internal[0] = fStruct->top;
1625 fStruct->topLevel++;
1627 T(YAFFS_TRACE_ERROR,
1628 (TSTR("yaffs: no more tnodes" TENDSTR)));
1634 /* Traverse down to level 0, adding anything we need */
1636 l = fStruct->topLevel;
1640 while (l > 0 && tn) {
1642 (YAFFS_TNODES_LEVEL0_BITS +
1643 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1644 YAFFS_TNODES_INTERNAL_MASK;
1647 if ((l > 1) && !tn->internal[x]) {
1648 /* Add missing non-level-zero tnode */
1649 tn->internal[x] = yaffs_GetTnode(dev);
1650 if(!tn->internal[x])
1652 } else if (l == 1) {
1653 /* Looking from level 1 at level 0 */
1655 /* If we already have one, then release it.*/
1656 if (tn->internal[x])
1657 yaffs_FreeTnode(dev, tn->internal[x]);
1658 tn->internal[x] = passedTn;
1660 } else if (!tn->internal[x]) {
1661 /* Don't have one, none passed in */
1662 tn->internal[x] = yaffs_GetTnode(dev);
1663 if(!tn->internal[x])
1668 tn = tn->internal[x];
1672 /* top is level 0 */
1674 memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1675 yaffs_FreeTnode(dev, passedTn);
1682 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
1683 yaffs_ExtendedTags *tags, int objectId,
1688 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1689 if (yaffs_CheckChunkBit(dev, theChunk / dev->param.nChunksPerBlock,
1690 theChunk % dev->param.nChunksPerBlock)) {
1692 if(dev->chunkGroupSize == 1)
1695 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1697 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1709 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1710 * chunks and tnodes in the file
1711 * Returns 1 if the tree was deleted.
1712 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1715 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
1716 int chunkOffset, int *limit)
1721 yaffs_ExtendedTags tags;
1723 yaffs_Device *dev = in->myDev;
1729 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1731 if (tn->internal[i]) {
1732 if (limit && (*limit) < 0) {
1736 yaffs_DeleteWorker(in,
1744 YAFFS_TNODES_INTERNAL_BITS)
1749 yaffs_FreeTnode(dev,
1752 tn->internal[i] = NULL;
1756 return (allDone) ? 1 : 0;
1757 } else if (level == 0) {
1760 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1762 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1765 chunkInInode = (chunkOffset <<
1766 YAFFS_TNODES_LEVEL0_BITS) + i;
1769 yaffs_FindChunkInGroup(dev,
1775 if (foundChunk > 0) {
1776 yaffs_DeleteChunk(dev,
1781 *limit = *limit - 1;
1788 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1792 return (i < 0) ? 1 : 0;
1802 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1804 yaffs_BlockInfo *theBlock;
1807 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1809 blockNo = chunk / dev->param.nChunksPerBlock;
1810 theBlock = yaffs_GetBlockInfo(dev, blockNo);
1812 theBlock->softDeletions++;
1814 yaffs_UpdateOldestDirtySequence(dev, blockNo, theBlock);
1818 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1819 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1821 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1824 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1825 __u32 level, int chunkOffset)
1830 yaffs_Device *dev = in->myDev;
1835 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1837 if (tn->internal[i]) {
1839 yaffs_SoftDeleteWorker(in,
1845 YAFFS_TNODES_INTERNAL_BITS)
1848 yaffs_FreeTnode(dev,
1851 tn->internal[i] = NULL;
1853 /* Hoosterman... how could this happen? */
1857 return (allDone) ? 1 : 0;
1858 } else if (level == 0) {
1860 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1861 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1863 /* Note this does not find the real chunk, only the chunk group.
1864 * We make an assumption that a chunk group is not larger than
1867 yaffs_SoftDeleteChunk(dev, theChunk);
1868 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1882 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1885 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1886 if (obj->nDataChunks <= 0) {
1887 /* Empty file with no duplicate object headers, just delete it immediately */
1888 yaffs_FreeTnode(obj->myDev,
1889 obj->variant.fileVariant.top);
1890 obj->variant.fileVariant.top = NULL;
1891 T(YAFFS_TRACE_TRACING,
1892 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1894 yaffs_DoGenericObjectDeletion(obj);
1896 yaffs_SoftDeleteWorker(obj,
1897 obj->variant.fileVariant.top,
1898 obj->variant.fileVariant.
1900 obj->softDeleted = 1;
1905 /* Pruning removes any part of the file structure tree that is beyond the
1906 * bounds of the file (ie that does not point to chunks).
1908 * A file should only get pruned when its size is reduced.
1910 * Before pruning, the chunks must be pulled from the tree and the
1911 * level 0 tnode entries must be zeroed out.
1912 * Could also use this for file deletion, but that's probably better handled
1913 * by a special case.
1915 * This function is recursive. For levels > 0 the function is called again on
1916 * any sub-tree. For level == 0 we just check if the sub-tree has data.
1917 * If there is no data in a subtree then it is pruned.
1920 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1921 __u32 level, int del0)
1930 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1931 if (tn->internal[i]) {
1933 yaffs_PruneWorker(dev, tn->internal[i],
1935 (i == 0) ? del0 : 1);
1938 if (tn->internal[i])
1942 int tnodeSize_u32 = yaffs_CalcTnodeSize(dev)/sizeof(__u32);
1943 __u32 *map = (__u32 *)tn;
1945 for(i = 0; !hasData && i < tnodeSize_u32; i++){
1951 if (hasData == 0 && del0) {
1952 /* Free and return NULL */
1954 yaffs_FreeTnode(dev, tn);
1964 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1965 yaffs_FileStructure *fStruct)
1972 if (fStruct->topLevel > 0) {
1974 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1976 /* Now we have a tree with all the non-zero branches NULL but the height
1977 * is the same as it was.
1978 * Let's see if we can trim internal tnodes to shorten the tree.
1979 * We can do this if only the 0th element in the tnode is in use
1980 * (ie all the non-zero are NULL)
1983 while (fStruct->topLevel && !done) {
1987 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1988 if (tn->internal[i])
1993 fStruct->top = tn->internal[0];
1994 fStruct->topLevel--;
1995 yaffs_FreeTnode(dev, tn);
2005 /*-------------------- End of File Structure functions.-------------------*/
2007 /* yaffs_CreateFreeObjects creates a bunch more objects and
2008 * adds them to the object free list.
2010 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
2013 yaffs_Object *newObjects;
2014 yaffs_ObjectList *list;
2019 /* make these things */
2020 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
2021 list = YMALLOC(sizeof(yaffs_ObjectList));
2023 if (!newObjects || !list) {
2032 T(YAFFS_TRACE_ALLOCATE,
2033 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
2037 /* Hook them into the free list */
2038 for (i = 0; i < nObjects - 1; i++) {
2039 newObjects[i].siblings.next =
2040 (struct ylist_head *)(&newObjects[i + 1]);
2043 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
2044 dev->freeObjects = newObjects;
2045 dev->nFreeObjects += nObjects;
2046 dev->nObjectsCreated += nObjects;
2048 /* Now add this bunch of Objects to a list for freeing up. */
2050 list->objects = newObjects;
2051 list->next = dev->allocatedObjectList;
2052 dev->allocatedObjectList = list;
2058 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
2059 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
2061 yaffs_Object *tn = NULL;
2063 #ifdef CONFIG_YAFFS_VALGRIND_TEST
2064 tn = YMALLOC(sizeof(yaffs_Object));
2066 dev->nObjectsCreated++;
2068 /* If there are none left make more */
2069 if (!dev->freeObjects)
2070 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
2072 if (dev->freeObjects) {
2073 tn = dev->freeObjects;
2075 (yaffs_Object *) (dev->freeObjects->siblings.next);
2076 dev->nFreeObjects--;
2080 /* Now sweeten it up... */
2082 memset(tn, 0, sizeof(yaffs_Object));
2083 tn->beingCreated = 1;
2087 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
2088 YINIT_LIST_HEAD(&(tn->hardLinks));
2089 YINIT_LIST_HEAD(&(tn->hashLink));
2090 YINIT_LIST_HEAD(&tn->siblings);
2093 /* Now make the directory sane */
2095 tn->parent = dev->rootDir;
2096 ylist_add(&(tn->siblings), &dev->rootDir->variant.directoryVariant.children);
2099 /* Add it to the lost and found directory.
2100 * NB Can't put root or lostNFound in lostNFound so
2101 * check if lostNFound exists first
2103 if (dev->lostNFoundDir)
2104 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
2106 tn->beingCreated = 0;
2109 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2114 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
2119 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
2121 obj->fake = 1; /* it is fake so it might have no NAND presence... */
2122 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
2123 obj->unlinkAllowed = 0; /* ... or unlink it */
2126 obj->yst_mode = mode;
2128 obj->hdrChunk = 0; /* Not a valid chunk. */
2135 static void yaffs_UnhashObject(yaffs_Object *tn)
2138 yaffs_Device *dev = tn->myDev;
2140 /* If it is still linked into the bucket list, free from the list */
2141 if (!ylist_empty(&tn->hashLink)) {
2142 ylist_del_init(&tn->hashLink);
2143 bucket = yaffs_HashFunction(tn->objectId);
2144 dev->objectBucket[bucket].count--;
2148 /* FreeObject frees up a Object and puts it back on the free list */
2149 static void yaffs_FreeObject(yaffs_Object *tn)
2151 yaffs_Device *dev = tn->myDev;
2153 T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), tn, tn->myInode));
2159 if (!ylist_empty(&tn->siblings))
2164 /* We're still hooked up to a cached inode.
2165 * Don't delete now, but mark for later deletion
2167 tn->deferedFree = 1;
2171 yaffs_UnhashObject(tn);
2173 #ifdef CONFIG_YAFFS_VALGRIND_TEST
2175 dev->nObjectsCreated--;
2178 /* Link into the free list. */
2179 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2180 dev->freeObjects = tn;
2181 dev->nFreeObjects++;
2183 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2187 void yaffs_HandleDeferedFree(yaffs_Object *obj)
2189 if (obj->deferedFree)
2190 yaffs_FreeObject(obj);
2194 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
2196 /* Free the list of allocated Objects */
2198 yaffs_ObjectList *tmp;
2200 while (dev->allocatedObjectList) {
2201 tmp = dev->allocatedObjectList->next;
2202 YFREE(dev->allocatedObjectList->objects);
2203 YFREE(dev->allocatedObjectList);
2205 dev->allocatedObjectList = tmp;
2208 dev->freeObjects = NULL;
2209 dev->nFreeObjects = 0;
2210 dev->nObjectsCreated = 0;
2213 static void yaffs_InitialiseObjects(yaffs_Device *dev)
2217 dev->allocatedObjectList = NULL;
2218 dev->freeObjects = NULL;
2219 dev->nFreeObjects = 0;
2221 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2222 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2223 dev->objectBucket[i].count = 0;
2227 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
2231 int lowest = 999999;
2234 /* Search for the shortest list or one that
2238 for (i = 0; i < 10 && lowest > 4; i++) {
2239 dev->bucketFinder++;
2240 dev->bucketFinder %= YAFFS_NOBJECT_BUCKETS;
2241 if (dev->objectBucket[dev->bucketFinder].count < lowest) {
2242 lowest = dev->objectBucket[dev->bucketFinder].count;
2243 l = dev->bucketFinder;
2251 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
2253 int bucket = yaffs_FindNiceObjectBucket(dev);
2255 /* Now find an object value that has not already been taken
2256 * by scanning the list.
2260 struct ylist_head *i;
2262 __u32 n = (__u32) bucket;
2264 /* yaffs_CheckObjectHashSanity(); */
2268 n += YAFFS_NOBJECT_BUCKETS;
2269 if (1 || dev->objectBucket[bucket].count > 0) {
2270 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2271 /* If there is already one in the list */
2272 if (i && ylist_entry(i, yaffs_Object,
2273 hashLink)->objectId == n) {
2283 static void yaffs_HashObject(yaffs_Object *in)
2285 int bucket = yaffs_HashFunction(in->objectId);
2286 yaffs_Device *dev = in->myDev;
2288 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2289 dev->objectBucket[bucket].count++;
2292 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
2294 int bucket = yaffs_HashFunction(number);
2295 struct ylist_head *i;
2298 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2299 /* Look if it is in the list */
2301 in = ylist_entry(i, yaffs_Object, hashLink);
2302 if (in->objectId == number) {
2304 /* Don't tell the VFS about this one if it is defered free */
2305 if (in->deferedFree)
2316 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
2317 yaffs_ObjectType type)
2319 yaffs_Object *theObject=NULL;
2320 yaffs_Tnode *tn = NULL;
2323 number = yaffs_CreateNewObjectNumber(dev);
2325 if (type == YAFFS_OBJECT_TYPE_FILE) {
2326 tn = yaffs_GetTnode(dev);
2331 theObject = yaffs_AllocateEmptyObject(dev);
2334 yaffs_FreeTnode(dev,tn);
2340 theObject->fake = 0;
2341 theObject->renameAllowed = 1;
2342 theObject->unlinkAllowed = 1;
2343 theObject->objectId = number;
2344 yaffs_HashObject(theObject);
2345 theObject->variantType = type;
2346 #ifdef CONFIG_YAFFS_WINCE
2347 yfsd_WinFileTimeNow(theObject->win_atime);
2348 theObject->win_ctime[0] = theObject->win_mtime[0] =
2349 theObject->win_atime[0];
2350 theObject->win_ctime[1] = theObject->win_mtime[1] =
2351 theObject->win_atime[1];
2355 theObject->yst_atime = theObject->yst_mtime =
2356 theObject->yst_ctime = Y_CURRENT_TIME;
2359 case YAFFS_OBJECT_TYPE_FILE:
2360 theObject->variant.fileVariant.fileSize = 0;
2361 theObject->variant.fileVariant.scannedFileSize = 0;
2362 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2363 theObject->variant.fileVariant.topLevel = 0;
2364 theObject->variant.fileVariant.top = tn;
2366 case YAFFS_OBJECT_TYPE_DIRECTORY:
2367 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2369 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2372 case YAFFS_OBJECT_TYPE_SYMLINK:
2373 case YAFFS_OBJECT_TYPE_HARDLINK:
2374 case YAFFS_OBJECT_TYPE_SPECIAL:
2375 /* No action required */
2377 case YAFFS_OBJECT_TYPE_UNKNOWN:
2378 /* todo this should not happen */
2386 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
2388 yaffs_ObjectType type)
2390 yaffs_Object *theObject = NULL;
2393 theObject = yaffs_FindObjectByNumber(dev, number);
2396 theObject = yaffs_CreateNewObject(dev, number, type);
2403 static YCHAR *yaffs_CloneString(const YCHAR *str)
2405 YCHAR *newStr = NULL;
2411 len = yaffs_strnlen(str,YAFFS_MAX_ALIAS_LENGTH);
2412 newStr = YMALLOC((len + 1) * sizeof(YCHAR));
2414 yaffs_strncpy(newStr, str,len);
2422 * Mknod (create) a new object.
2423 * equivalentObject only has meaning for a hard link;
2424 * aliasString only has meaning for a symlink.
2425 * rdev only has meaning for devices (a subset of special objects)
2428 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2429 yaffs_Object *parent,
2434 yaffs_Object *equivalentObject,
2435 const YCHAR *aliasString, __u32 rdev)
2440 yaffs_Device *dev = parent->myDev;
2442 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2443 if (yaffs_FindObjectByName(parent, name))
2446 if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2447 str = yaffs_CloneString(aliasString);
2452 in = yaffs_CreateNewObject(dev, -1, type);
2467 in->variantType = type;
2469 in->yst_mode = mode;
2471 #ifdef CONFIG_YAFFS_WINCE
2472 yfsd_WinFileTimeNow(in->win_atime);
2473 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2474 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2477 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2479 in->yst_rdev = rdev;
2483 in->nDataChunks = 0;
2485 yaffs_SetObjectName(in, name);
2488 yaffs_AddObjectToDirectory(parent, in);
2490 in->myDev = parent->myDev;
2493 case YAFFS_OBJECT_TYPE_SYMLINK:
2494 in->variant.symLinkVariant.alias = str;
2496 case YAFFS_OBJECT_TYPE_HARDLINK:
2497 in->variant.hardLinkVariant.equivalentObject =
2499 in->variant.hardLinkVariant.equivalentObjectId =
2500 equivalentObject->objectId;
2501 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2503 case YAFFS_OBJECT_TYPE_FILE:
2504 case YAFFS_OBJECT_TYPE_DIRECTORY:
2505 case YAFFS_OBJECT_TYPE_SPECIAL:
2506 case YAFFS_OBJECT_TYPE_UNKNOWN:
2511 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2512 /* Could not create the object header, fail the creation */
2513 yaffs_DeleteObject(in);
2517 yaffs_UpdateParent(parent);
2523 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
2524 __u32 mode, __u32 uid, __u32 gid)
2526 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2527 uid, gid, NULL, NULL, 0);
2530 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
2531 __u32 mode, __u32 uid, __u32 gid)
2533 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2534 mode, uid, gid, NULL, NULL, 0);
2537 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
2538 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2540 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2541 uid, gid, NULL, NULL, rdev);
2544 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
2545 __u32 mode, __u32 uid, __u32 gid,
2548 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2549 uid, gid, NULL, alias, 0);
2552 /* yaffs_Link returns the object id of the equivalent object.*/
2553 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
2554 yaffs_Object *equivalentObject)
2556 /* Get the real object in case we were fed a hard link as an equivalent object */
2557 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2559 if (yaffs_MknodObject
2560 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2561 equivalentObject, NULL, 0)) {
2562 return equivalentObject;
2569 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
2570 const YCHAR *newName, int force, int shadows)
2575 yaffs_Object *existingTarget;
2578 newDir = obj->parent; /* use the old directory */
2580 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2581 T(YAFFS_TRACE_ALWAYS,
2583 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2588 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2589 if (obj->myDev->param.isYaffs2)
2590 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2592 unlinkOp = (newDir == obj->myDev->unlinkedDir
2593 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2595 deleteOp = (newDir == obj->myDev->deletedDir);
2597 existingTarget = yaffs_FindObjectByName(newDir, newName);
2599 /* If the object is a file going into the unlinked directory,
2600 * then it is OK to just stuff it in since duplicate names are allowed.
2601 * else only proceed if the new name does not exist and if we're putting
2602 * it into a directory.
2609 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2610 yaffs_SetObjectName(obj, newName);
2613 yaffs_AddObjectToDirectory(newDir, obj);
2618 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2619 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows) >= 0)
2626 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
2627 yaffs_Object *newDir, const YCHAR *newName)
2629 yaffs_Object *obj = NULL;
2630 yaffs_Object *existingTarget = NULL;
2636 if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2638 if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2641 dev = oldDir->myDev;
2643 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2644 /* Special case for case insemsitive systems (eg. WinCE).
2645 * While look-up is case insensitive, the name isn't.
2646 * Therefore we might want to change x.txt to X.txt
2648 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
2652 if(yaffs_strnlen(newName,YAFFS_MAX_NAME_LENGTH+1) > YAFFS_MAX_NAME_LENGTH)
2656 obj = yaffs_FindObjectByName(oldDir, oldName);
2658 if (obj && obj->renameAllowed) {
2660 /* Now do the handling for an existing target, if there is one */
2662 existingTarget = yaffs_FindObjectByName(newDir, newName);
2663 if (existingTarget &&
2664 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2665 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2666 /* There is a target that is a non-empty directory, so we fail */
2667 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2668 } else if (existingTarget && existingTarget != obj) {
2669 /* Nuke the target first, using shadowing,
2670 * but only if it isn't the same object.
2672 * Note we must disable gc otherwise it can mess up the shadowing.
2676 yaffs_ChangeObjectName(obj, newDir, newName, force,
2677 existingTarget->objectId);
2678 existingTarget->isShadowed = 1;
2679 yaffs_UnlinkObject(existingTarget);
2683 result = yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2685 yaffs_UpdateParent(oldDir);
2686 if(newDir != oldDir)
2687 yaffs_UpdateParent(newDir);
2694 /*------------------------- Block Management and Page Allocation ----------------*/
2696 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
2698 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2700 dev->blockInfo = NULL;
2701 dev->chunkBits = NULL;
2703 dev->allocationBlock = -1; /* force it to get a new one */
2705 /* If the first allocation strategy fails, thry the alternate one */
2706 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2707 if (!dev->blockInfo) {
2708 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2709 dev->blockInfoAlt = 1;
2711 dev->blockInfoAlt = 0;
2713 if (dev->blockInfo) {
2714 /* Set up dynamic blockinfo stuff. */
2715 dev->chunkBitmapStride = (dev->param.nChunksPerBlock + 7) / 8; /* round up bytes */
2716 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2717 if (!dev->chunkBits) {
2718 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2719 dev->chunkBitsAlt = 1;
2721 dev->chunkBitsAlt = 0;
2724 if (dev->blockInfo && dev->chunkBits) {
2725 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2726 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2733 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2735 if (dev->blockInfoAlt && dev->blockInfo)
2736 YFREE_ALT(dev->blockInfo);
2737 else if (dev->blockInfo)
2738 YFREE(dev->blockInfo);
2740 dev->blockInfoAlt = 0;
2742 dev->blockInfo = NULL;
2744 if (dev->chunkBitsAlt && dev->chunkBits)
2745 YFREE_ALT(dev->chunkBits);
2746 else if (dev->chunkBits)
2747 YFREE(dev->chunkBits);
2748 dev->chunkBitsAlt = 0;
2749 dev->chunkBits = NULL;
2752 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
2753 yaffs_BlockInfo *bi)
2756 if (!dev->param.isYaffs2)
2757 return 1; /* disqualification only applies to yaffs2. */
2759 if (!bi->hasShrinkHeader)
2760 return 1; /* can gc */
2762 yaffs_FindOldestDirtySequence(dev);
2764 /* Can't do gc of this block if there are any blocks older than this one that have
2767 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2771 * yaffs_FindRefreshBlock()
2772 * periodically finds the oldest full block by sequence number for refreshing.
2775 static __u32 yaffs_FindRefreshBlock(yaffs_Device *dev)
2780 __u32 oldestSequence = 0;
2782 yaffs_BlockInfo *bi;
2785 * If refresh period < 10 then refreshing is disabled.
2787 if(dev->param.refreshPeriod < 10 ||
2788 !dev->param.isYaffs2)
2792 * Fix broken values.
2794 if(dev->refreshSkip > dev->param.refreshPeriod)
2795 dev->refreshSkip = dev->param.refreshPeriod;
2797 if(dev->refreshSkip > 0)
2801 * Refresh skip is now zero.
2802 * We'll do a refresh this time around....
2803 * Update the refresh skip and find the oldest block.
2805 dev->refreshSkip = dev->param.refreshPeriod;
2806 dev->refreshCount++;
2807 bi = dev->blockInfo;
2808 for (b = dev->internalStartBlock; b <=dev->internalEndBlock; b++){
2810 if (bi->blockState == YAFFS_BLOCK_STATE_FULL){
2813 bi->sequenceNumber < oldestSequence){
2815 oldestSequence = bi->sequenceNumber;
2823 (TSTR("GC refresh count %d selected block %d with sequenceNumber %d" TENDSTR),
2824 dev->refreshCount, oldest, oldestSequence));
2831 static void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
2833 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2837 /* If the block is still healthy erase it and mark as clean.
2838 * If the block has had a data failure, then retire it.
2841 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2842 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2843 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2845 yaffs_ClearOldestDirtySequence(dev,bi);
2847 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2849 /* If this is the block being garbage collected then stop gc'ing this block */
2850 if(blockNo == dev->gcBlock)
2853 /* If this block is currently the best candidate for gc then drop as a candidate */
2854 if(blockNo == dev->gcDirtiest){
2855 dev->gcDirtiest = 0;
2856 dev->gcPagesInUse = 0;
2859 if (!bi->needsRetiring) {
2860 yaffs_InvalidateCheckpoint(dev);
2861 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2863 dev->nErasureFailures++;
2864 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2865 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2870 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2872 for (i = 0; i < dev->param.nChunksPerBlock; i++) {
2873 if (!yaffs_CheckChunkErased
2874 (dev, blockNo * dev->param.nChunksPerBlock + i)) {
2875 T(YAFFS_TRACE_ERROR,
2877 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2878 TENDSTR), blockNo, i));
2884 /* Clean it up... */
2885 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2886 bi->sequenceNumber = 0;
2887 dev->nErasedBlocks++;
2889 bi->softDeletions = 0;
2890 bi->hasShrinkHeader = 0;
2891 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2892 bi->gcPrioritise = 0;
2893 yaffs_ClearChunkBits(dev, blockNo);
2895 T(YAFFS_TRACE_ERASE,
2896 (TSTR("Erased block %d" TENDSTR), blockNo));
2898 dev->nFreeChunks -= dev->param.nChunksPerBlock; /* We lost a block of free space */
2900 yaffs_RetireBlock(dev, blockNo);
2901 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2902 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2906 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2910 yaffs_BlockInfo *bi;
2912 if (dev->nErasedBlocks < 1) {
2913 /* Hoosterman we've got a problem.
2914 * Can't get space to gc
2916 T(YAFFS_TRACE_ERROR,
2917 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2922 /* Find an empty block. */
2924 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2925 dev->allocationBlockFinder++;
2926 if (dev->allocationBlockFinder < dev->internalStartBlock
2927 || dev->allocationBlockFinder > dev->internalEndBlock) {
2928 dev->allocationBlockFinder = dev->internalStartBlock;
2931 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2933 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2934 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2935 dev->sequenceNumber++;
2936 bi->sequenceNumber = dev->sequenceNumber;
2937 dev->nErasedBlocks--;
2938 T(YAFFS_TRACE_ALLOCATE,
2939 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2940 dev->allocationBlockFinder, dev->sequenceNumber,
2941 dev->nErasedBlocks));
2942 return dev->allocationBlockFinder;
2946 T(YAFFS_TRACE_ALWAYS,
2948 ("yaffs tragedy: no more erased blocks, but there should have been %d"
2949 TENDSTR), dev->nErasedBlocks));
2956 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2958 if (!dev->nCheckpointBlocksRequired &&
2959 dev->param.isYaffs2) {
2960 /* Not a valid value so recalculate */
2963 int devBlocks = (dev->param.endBlock - dev->param.startBlock + 1);
2964 int tnodeSize = yaffs_CalcTnodeSize(dev);
2966 nBytes += sizeof(yaffs_CheckpointValidity);
2967 nBytes += sizeof(yaffs_CheckpointDevice);
2968 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2969 nBytes += devBlocks * dev->chunkBitmapStride;
2970 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2971 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2972 nBytes += sizeof(yaffs_CheckpointValidity);
2973 nBytes += sizeof(__u32); /* checksum*/
2975 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2977 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->param.nChunksPerBlock)) + 3;
2979 dev->nCheckpointBlocksRequired = nBlocks;
2982 return dev->nCheckpointBlocksRequired;
2986 * Check if there's space to allocate...
2987 * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2989 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev, int nChunks)
2992 int reservedBlocks = dev->param.nReservedBlocks;
2993 int checkpointBlocks;
2995 if (dev->param.isYaffs2) {
2996 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
2997 dev->blocksInCheckpoint;
2998 if (checkpointBlocks < 0)
2999 checkpointBlocks = 0;
3001 checkpointBlocks = 0;
3004 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->param.nChunksPerBlock);
3006 return (dev->nFreeChunks > (reservedChunks + nChunks));
3009 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
3010 yaffs_BlockInfo **blockUsedPtr)
3013 yaffs_BlockInfo *bi;
3015 if (dev->allocationBlock < 0) {
3016 /* Get next block to allocate off */
3017 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
3018 dev->allocationPage = 0;
3021 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev, 1)) {
3022 /* Not enough space to allocate unless we're allowed to use the reserve. */
3026 if (dev->nErasedBlocks < dev->param.nReservedBlocks
3027 && dev->allocationPage == 0) {
3028 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
3031 /* Next page please.... */
3032 if (dev->allocationBlock >= 0) {
3033 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3035 retVal = (dev->allocationBlock * dev->param.nChunksPerBlock) +
3036 dev->allocationPage;
3038 yaffs_SetChunkBit(dev, dev->allocationBlock,
3039 dev->allocationPage);
3041 dev->allocationPage++;
3045 /* If the block is full set the state to full */
3046 if (dev->allocationPage >= dev->param.nChunksPerBlock) {
3047 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3048 dev->allocationBlock = -1;
3057 T(YAFFS_TRACE_ERROR,
3058 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
3063 static int yaffs_GetErasedChunks(yaffs_Device *dev)
3067 n = dev->nErasedBlocks * dev->param.nChunksPerBlock;
3069 if (dev->allocationBlock > 0)
3070 n += (dev->param.nChunksPerBlock - dev->allocationPage);
3077 * yaffs_SkipRestOfBlock() skips over the rest of the allocation block
3078 * if we don't want to write to it.
3080 static void yaffs_SkipRestOfBlock(yaffs_Device *dev)
3082 if(dev->allocationBlock > 0){
3083 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3084 if(bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING){
3085 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3086 dev->allocationBlock = -1;
3092 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
3098 int retVal = YAFFS_OK;
3101 int isCheckpointBlock;
3105 int chunksBefore = yaffs_GetErasedChunks(dev);
3108 yaffs_ExtendedTags tags;
3110 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3112 yaffs_Object *object;
3114 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3117 T(YAFFS_TRACE_TRACING,
3118 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3121 bi->hasShrinkHeader,
3124 /*yaffs_VerifyFreeChunks(dev); */
3126 if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
3127 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3129 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
3133 if (isCheckpointBlock ||
3134 !yaffs_StillSomeChunkBits(dev, block)) {
3135 T(YAFFS_TRACE_TRACING,
3137 ("Collecting block %d that has no chunks in use" TENDSTR),
3139 yaffs_BlockBecameDirty(dev, block);
3142 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3144 yaffs_VerifyBlock(dev, bi, block);
3146 maxCopies = (wholeBlock) ? dev->param.nChunksPerBlock : 5;
3147 oldChunk = block * dev->param.nChunksPerBlock + dev->gcChunk;
3149 for (/* init already done */;
3150 retVal == YAFFS_OK &&
3151 dev->gcChunk < dev->param.nChunksPerBlock &&
3152 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
3154 dev->gcChunk++, oldChunk++) {
3155 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3157 /* This page is in use and might need to be copied off */
3163 yaffs_InitialiseTags(&tags);
3165 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3169 yaffs_FindObjectByNumber(dev,
3172 T(YAFFS_TRACE_GC_DETAIL,
3174 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3175 dev->gcChunk, tags.objectId, tags.chunkId,
3178 if (object && !yaffs_SkipVerification(dev)) {
3179 if (tags.chunkId == 0)
3180 matchingChunk = object->hdrChunk;
3181 else if (object->softDeleted)
3182 matchingChunk = oldChunk; /* Defeat the test */
3184 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
3186 if (oldChunk != matchingChunk)
3187 T(YAFFS_TRACE_ERROR,
3188 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3189 oldChunk, matchingChunk, tags.objectId, tags.chunkId));
3194 T(YAFFS_TRACE_ERROR,
3196 ("page %d in gc has no object: %d %d %d "
3198 tags.objectId, tags.chunkId, tags.byteCount));
3203 object->softDeleted &&
3204 tags.chunkId != 0) {
3205 /* Data chunk in a soft deleted file, throw it away
3206 * It's a soft deleted data chunk,
3207 * No need to copy this, just forget about it and
3208 * fix up the object.
3211 /* Free chunks already includes softdeleted chunks.
3212 * How ever this chunk is going to soon be really deleted
3213 * which will increment free chunks.
3214 * We have to decrement free chunks so this works out properly.
3218 object->nDataChunks--;
3220 if (object->nDataChunks <= 0) {
3221 /* remeber to clean up the object */
3222 dev->gcCleanupList[cleanups] =
3228 /* Todo object && object->deleted && object->nDataChunks == 0 */
3229 /* Deleted object header with no data chunks.
3230 * Can be discarded and the file deleted.
3232 object->hdrChunk = 0;
3233 yaffs_FreeTnode(object->myDev,
3236 object->variant.fileVariant.top = NULL;
3237 yaffs_DoGenericObjectDeletion(object);
3239 } else if (object) {
3240 /* It's either a data chunk in a live file or
3241 * an ObjectHeader, so we're interested in it.
3242 * NB Need to keep the ObjectHeaders of deleted files
3243 * until the whole file has been deleted off
3245 tags.serialNumber++;
3249 if (tags.chunkId == 0) {
3250 /* It is an object Id,
3251 * We need to nuke the shrinkheader flags first
3252 * Also need to clean up shadowing.
3253 * We no longer want the shrinkHeader flag since its work is done
3254 * and if it is left in place it will mess up scanning.
3257 yaffs_ObjectHeader *oh;
3258 oh = (yaffs_ObjectHeader *)buffer;
3261 tags.extraIsShrinkHeader = 0;
3263 oh->shadowsObject = 0;
3264 oh->inbandShadowsObject = 0;
3265 tags.extraShadows = 0;
3267 /* Update file size */
3268 if(object->variantType == YAFFS_OBJECT_TYPE_FILE){
3269 oh->fileSize = object->variant.fileVariant.fileSize;
3270 tags.extraFileLength = oh->fileSize;
3273 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
3275 yaffs_WriteNewChunkWithTagsToNAND(dev,(__u8 *) oh, &tags, 1);
3278 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3281 retVal = YAFFS_FAIL;
3284 /* Ok, now fix up the Tnodes etc. */
3286 if (tags.chunkId == 0) {
3288 object->hdrChunk = newChunk;
3289 object->serial = tags.serialNumber;
3291 /* It's a data chunk */
3293 ok = yaffs_PutChunkIntoFile
3301 if (retVal == YAFFS_OK)
3302 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3307 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3310 /* Do any required cleanups */
3311 for (i = 0; i < cleanups; i++) {
3312 /* Time to delete the file too */
3314 yaffs_FindObjectByNumber(dev,
3315 dev->gcCleanupList[i]);
3317 yaffs_FreeTnode(dev,
3318 object->variant.fileVariant.
3320 object->variant.fileVariant.top = NULL;
3323 ("yaffs: About to finally delete object %d"
3324 TENDSTR), object->objectId));
3325 yaffs_DoGenericObjectDeletion(object);
3326 object->myDev->nDeletedFiles--;
3333 yaffs_VerifyCollectedBlock(dev, bi, block);
3337 if (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3339 * The gc did not complete. Set block state back to FULL
3340 * because checkpointing does not restore gc.
3342 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3344 /* The gc completed. */
3345 chunksAfter = yaffs_GetErasedChunks(dev);
3346 if (chunksBefore >= chunksAfter) {
3349 ("gc did not increase free chunks before %d after %d"
3350 TENDSTR), chunksBefore, chunksAfter));
3362 * FindBlockForgarbageCollection is used to select the dirtiest block (or close enough)
3363 * for garbage collection.
3366 static unsigned yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
3372 unsigned selected = 0;
3373 int prioritised = 0;
3374 int prioritisedExists = 0;
3375 yaffs_BlockInfo *bi;
3378 /* First let's see if we need to grab a prioritised block */
3379 if (dev->hasPendingPrioritisedGCs && !aggressive) {
3380 dev->gcDirtiest = 0;
3381 bi = dev->blockInfo;
3382 for (i = dev->internalStartBlock;
3383 i <= dev->internalEndBlock && !selected;
3386 if (bi->gcPrioritise) {
3387 prioritisedExists = 1;
3388 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
3389 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
3398 * If there is a prioritised block and none was selected then
3399 * this happened because there is at least one old dirty block gumming
3400 * up the works. Let's gc the oldest dirty block.
3403 if(prioritisedExists &&
3405 dev->oldestDirtyBlock > 0)
3406 selected = dev->oldestDirtyBlock;
3408 if (!prioritisedExists) /* None found, so we can clear this */
3409 dev->hasPendingPrioritisedGCs = 0;
3412 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
3414 * else (we're doing a leasurely gc), then we only bother to do this if the
3415 * block has only a few pages in use.
3420 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
3422 threshold = dev->param.nChunksPerBlock;
3423 iterations = nBlocks;
3425 int maxThreshold = dev->param.nChunksPerBlock/2;
3426 threshold = background ?
3427 (dev->gcNotDone + 2) * 2 : 0;
3428 if(threshold <YAFFS_GC_PASSIVE_THRESHOLD)
3429 threshold = YAFFS_GC_PASSIVE_THRESHOLD;
3430 if(threshold > maxThreshold)
3431 threshold = maxThreshold;
3433 iterations = nBlocks / 16 + 1;
3434 if (iterations > 100)
3440 (dev->gcDirtiest < 1 ||
3441 dev->gcPagesInUse > YAFFS_GC_GOOD_ENOUGH);
3443 dev->gcBlockFinder++;
3444 if (dev->gcBlockFinder < dev->internalStartBlock ||
3445 dev->gcBlockFinder > dev->internalEndBlock)
3446 dev->gcBlockFinder = dev->internalStartBlock;
3448 bi = yaffs_GetBlockInfo(dev, dev->gcBlockFinder);
3450 pagesUsed = bi->pagesInUse - bi->softDeletions;
3452 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
3453 pagesUsed < dev->param.nChunksPerBlock &&
3454 (dev->gcDirtiest < 1 || pagesUsed < dev->gcPagesInUse) &&
3455 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
3456 dev->gcDirtiest = dev->gcBlockFinder;
3457 dev->gcPagesInUse = pagesUsed;
3461 if(dev->gcDirtiest > 0 && dev->gcPagesInUse <= threshold)
3462 selected = dev->gcDirtiest;
3466 * If nothing has been selected for a while, try selecting the oldest dirty
3467 * because that's gumming up the works.
3470 if(!selected && dev->param.isYaffs2 &&
3471 dev->gcNotDone >= ( background ? 10 : 20)){
3472 yaffs_FindOldestDirtySequence(dev);
3473 if(dev->oldestDirtyBlock > 0) {
3474 selected = dev->oldestDirtyBlock;
3475 dev->gcDirtiest = selected;
3476 dev->oldestDirtyGCs++;
3477 bi = yaffs_GetBlockInfo(dev, selected);
3478 dev->gcPagesInUse = bi->pagesInUse - bi->softDeletions;
3485 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR),
3487 dev->param.nChunksPerBlock - dev->gcPagesInUse,
3491 dev->backgroundGCs++;
3492 dev->gcDirtiest = 0;
3493 dev->gcPagesInUse = 0;
3495 if(dev->refreshSkip > 0)
3500 (TSTR("GC none: finder %d skip %d threshold %d dirtiest %d using %d oldest %d%s" TENDSTR),
3501 dev->gcBlockFinder, dev->gcNotDone,
3503 dev->gcDirtiest, dev->gcPagesInUse,
3504 dev->oldestDirtyBlock,
3505 background ? " bg" : ""));
3511 /* New garbage collector
3512 * If we're very low on erased blocks then we do aggressive garbage collection
3513 * otherwise we do "leasurely" garbage collection.
3514 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3515 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3517 * The idea is to help clear out space in a more spread-out manner.
3518 * Dunno if it really does anything useful.
3520 static int yaffs_CheckGarbageCollection(yaffs_Device *dev, int background)
3523 int gcOk = YAFFS_OK;
3529 int checkpointBlockAdjust;
3531 if(dev->param.gcControl &&
3532 (dev->param.gcControl(dev) & 1) == 0)
3535 if (dev->gcDisable) {
3536 /* Bail out so we don't get recursive gc */
3540 /* This loop should pass the first time.
3541 * We'll only see looping here if the collection does not increase space.
3547 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3548 if (checkpointBlockAdjust < 0)
3549 checkpointBlockAdjust = 0;
3551 minErased = dev->param.nReservedBlocks + checkpointBlockAdjust + 1;
3552 erasedChunks = dev->nErasedBlocks * dev->param.nChunksPerBlock;
3554 /* If we need a block soon then do aggressive gc.*/
3555 if (dev->nErasedBlocks < minErased)
3558 if(dev->gcSkip > 20)
3560 if(erasedChunks < dev->nFreeChunks/2 ||
3572 /* If we don't already have a block being gc'd then see if we should start another */
3574 if (dev->gcBlock < 1 && !aggressive) {
3575 dev->gcBlock = yaffs_FindRefreshBlock(dev);
3578 if (dev->gcBlock < 1) {
3579 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive, background);
3583 if (dev->gcBlock > 0) {
3590 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3591 dev->nErasedBlocks, aggressive));
3593 gcOk = yaffs_GarbageCollectBlock(dev, dev->gcBlock, aggressive);
3596 if (dev->nErasedBlocks < (dev->param.nReservedBlocks) && dev->gcBlock > 0) {
3599 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3600 TENDSTR), dev->nErasedBlocks, maxTries, dev->gcBlock));
3602 } while ((dev->nErasedBlocks < dev->param.nReservedBlocks) &&
3603 (dev->gcBlock > 0) &&
3606 return aggressive ? gcOk : YAFFS_OK;
3610 * yaffs_BackgroundGarbageCollect()
3611 * Garbage collects. Intended to be called from a background thread.
3612 * Returns non-zero if at least half the free chunks are erased.
3614 int yaffs_BackgroundGarbageCollect(yaffs_Device *dev, unsigned urgency)
3616 int erasedChunks = dev->nErasedBlocks * dev->param.nChunksPerBlock;
3618 T(YAFFS_TRACE_BACKGROUND, (TSTR("Background gc %u" TENDSTR),urgency));
3620 yaffs_CheckGarbageCollection(dev, 1);
3621 return erasedChunks > dev->nFreeChunks/2;
3624 /*------------------------- TAGS --------------------------------*/
3626 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
3629 return (tags->chunkId == chunkInObject &&
3630 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3635 /*-------------------- Data file manipulation -----------------*/
3637 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
3638 yaffs_ExtendedTags *tags)
3640 /*Get the Tnode, then get the level 0 offset chunk offset */
3643 yaffs_ExtendedTags localTags;
3646 yaffs_Device *dev = in->myDev;
3649 /* Passed a NULL, so use our own tags space */
3653 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3656 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3659 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3665 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
3666 yaffs_ExtendedTags *tags)
3668 /* Get the Tnode, then get the level 0 offset chunk offset */
3671 yaffs_ExtendedTags localTags;
3673 yaffs_Device *dev = in->myDev;
3677 /* Passed a NULL, so use our own tags space */
3681 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3685 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3688 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3691 /* Delete the entry in the filestructure (if found) */
3693 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, 0);
3699 #ifdef YAFFS_PARANOID
3701 static int yaffs_CheckFileSanity(yaffs_Object *in)
3709 yaffs_Tags localTags;
3710 yaffs_Tags *tags = &localTags;
3714 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3717 objId = in->objectId;
3718 fSize = in->variant.fileVariant.fileSize;
3720 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3722 for (chunk = 1; chunk <= nChunks; chunk++) {
3723 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3728 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunk);
3730 if (yaffs_CheckChunkBits
3731 (dev, theChunk / dev->param.nChunksPerBlock,
3732 theChunk % dev->param.nChunksPerBlock)) {
3734 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3738 (tags, in->objectId, chunk, chunkDeleted)) {
3748 /* T(("No level 0 found for %d\n", chunk)); */
3752 return failed ? YAFFS_FAIL : YAFFS_OK;
3757 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
3758 int chunkInNAND, int inScan)
3760 /* NB inScan is zero unless scanning.
3761 * For forward scanning, inScan is > 0;
3762 * for backward scanning inScan is < 0
3764 * chunkInNAND = 0 is a dummy insert to make sure the tnodes are there.
3768 yaffs_Device *dev = in->myDev;
3770 yaffs_ExtendedTags existingTags;
3771 yaffs_ExtendedTags newTags;
3772 unsigned existingSerial, newSerial;
3774 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3775 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3776 * If it is not during Scanning then something went wrong!
3779 T(YAFFS_TRACE_ERROR,
3781 ("yaffs tragedy:attempt to put data chunk into a non-file"
3786 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3790 tn = yaffs_AddOrFindLevel0Tnode(dev,
3791 &in->variant.fileVariant,
3798 /* Dummy insert, bail now */
3801 existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3804 /* If we're scanning then we need to test for duplicates
3805 * NB This does not need to be efficient since it should only ever
3806 * happen when the power fails during a write, then only one
3807 * chunk should ever be affected.
3809 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3810 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3813 if (existingChunk > 0) {
3814 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3815 * thus we have to do a FindChunkInFile to get the real chunk id.
3817 * We have a duplicate now we need to decide which one to use:
3819 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3820 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3821 * YAFFS1: Get both sets of tags and compare serial numbers.
3825 /* Only do this for forward scanning */
3826 yaffs_ReadChunkWithTagsFromNAND(dev,
3830 /* Do a proper find */
3832 yaffs_FindChunkInFile(in, chunkInInode,
3836 if (existingChunk <= 0) {
3837 /*Hoosterman - how did this happen? */
3839 T(YAFFS_TRACE_ERROR,
3841 ("yaffs tragedy: existing chunk < 0 in scan"
3846 /* NB The deleted flags should be false, otherwise the chunks will
3847 * not be loaded during a scan
3851 newSerial = newTags.serialNumber;
3852 existingSerial = existingTags.serialNumber;
3856 (in->myDev->param.isYaffs2 ||
3857 existingChunk <= 0 ||
3858 ((existingSerial + 1) & 3) == newSerial)) {
3859 /* Forward scanning.
3861 * Delete the old one and drop through to update the tnode
3863 yaffs_DeleteChunk(dev, existingChunk, 1,
3866 /* Backward scanning or we want to use the existing one
3868 * Delete the new one and return early so that the tnode isn't changed
3870 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3878 if (existingChunk == 0)
3881 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
3886 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
3889 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3891 if (chunkInNAND >= 0)
3892 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3895 T(YAFFS_TRACE_NANDACCESS,
3896 (TSTR("Chunk %d not found zero instead" TENDSTR),
3898 /* get sane (zero) data if you read a hole */
3899 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3905 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
3909 yaffs_ExtendedTags tags;
3910 yaffs_BlockInfo *bi;
3916 block = chunkId / dev->param.nChunksPerBlock;
3917 page = chunkId % dev->param.nChunksPerBlock;
3920 if (!yaffs_CheckChunkBit(dev, block, page))
3921 T(YAFFS_TRACE_VERIFY,
3922 (TSTR("Deleting invalid chunk %d"TENDSTR),
3925 bi = yaffs_GetBlockInfo(dev, block);
3927 yaffs_UpdateOldestDirtySequence(dev, block, bi);
3929 T(YAFFS_TRACE_DELETION,
3930 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3933 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->param.isYaffs2) {
3935 yaffs_InitialiseTags(&tags);
3937 tags.chunkDeleted = 1;
3939 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3940 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3942 dev->nUnmarkedDeletions++;
3945 /* Pull out of the management area.
3946 * If the whole block became dirty, this will kick off an erasure.
3948 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3949 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3950 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3951 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3954 yaffs_ClearChunkBit(dev, block, page);
3958 if (bi->pagesInUse == 0 &&
3959 !bi->hasShrinkHeader &&
3960 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3961 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3962 yaffs_BlockBecameDirty(dev, block);
3969 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
3970 const __u8 *buffer, int nBytes,
3973 /* Find old chunk Need to do this to get serial number
3974 * Write new one and patch into tree.
3975 * Invalidate old tags.
3979 yaffs_ExtendedTags prevTags;
3982 yaffs_ExtendedTags newTags;
3984 yaffs_Device *dev = in->myDev;
3986 yaffs_CheckGarbageCollection(dev,0);
3988 /* Get the previous chunk at this location in the file if it exists.
3989 * If it does not exist then put a zero into the tree. This creates
3990 * the tnode now, rather than later when it is harder to clean up.
3992 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3993 if(prevChunkId < 1 &&
3994 !yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0))
3997 /* Set up new tags */
3998 yaffs_InitialiseTags(&newTags);
4000 newTags.chunkId = chunkInInode;
4001 newTags.objectId = in->objectId;
4002 newTags.serialNumber =
4003 (prevChunkId > 0) ? prevTags.serialNumber + 1 : 1;
4004 newTags.byteCount = nBytes;
4006 if (nBytes < 1 || nBytes > dev->param.totalBytesPerChunk) {
4007 T(YAFFS_TRACE_ERROR,
4008 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
4014 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
4017 if (newChunkId > 0) {
4018 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
4020 if (prevChunkId > 0)
4021 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
4023 yaffs_CheckFileSanity(in);
4029 /* UpdateObjectHeader updates the header on NAND for an object.
4030 * If name is not NULL, then that new name is used.
4032 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
4033 int isShrink, int shadows)
4036 yaffs_BlockInfo *bi;
4038 yaffs_Device *dev = in->myDev;
4045 yaffs_ExtendedTags newTags;
4046 yaffs_ExtendedTags oldTags;
4047 YCHAR *alias = NULL;
4049 __u8 *buffer = NULL;
4050 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
4052 yaffs_ObjectHeader *oh = NULL;
4054 yaffs_strcpy(oldName, _Y("silly old name"));
4058 in == dev->rootDir || /* The rootDir should also be saved */
4061 yaffs_CheckGarbageCollection(dev,0);
4062 yaffs_CheckObjectDetailsLoaded(in);
4064 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
4065 oh = (yaffs_ObjectHeader *) buffer;
4067 prevChunkId = in->hdrChunk;
4069 if (prevChunkId > 0) {
4070 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
4073 yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
4075 memcpy(oldName, oh->name, sizeof(oh->name));
4078 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
4080 oh->type = in->variantType;
4081 oh->yst_mode = in->yst_mode;
4082 oh->shadowsObject = oh->inbandShadowsObject = shadows;
4084 #ifdef CONFIG_YAFFS_WINCE
4085 oh->win_atime[0] = in->win_atime[0];
4086 oh->win_ctime[0] = in->win_ctime[0];
4087 oh->win_mtime[0] = in->win_mtime[0];
4088 oh->win_atime[1] = in->win_atime[1];
4089 oh->win_ctime[1] = in->win_ctime[1];
4090 oh->win_mtime[1] = in->win_mtime[1];
4092 oh->yst_uid = in->yst_uid;
4093 oh->yst_gid = in->yst_gid;
4094 oh->yst_atime = in->yst_atime;
4095 oh->yst_mtime = in->yst_mtime;
4096 oh->yst_ctime = in->yst_ctime;
4097 oh->yst_rdev = in->yst_rdev;
4100 oh->parentObjectId = in->parent->objectId;
4102 oh->parentObjectId = 0;
4104 if (name && *name) {
4105 memset(oh->name, 0, sizeof(oh->name));
4106 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
4107 } else if (prevChunkId > 0)
4108 memcpy(oh->name, oldName, sizeof(oh->name));
4110 memset(oh->name, 0, sizeof(oh->name));
4112 oh->isShrink = isShrink;
4114 switch (in->variantType) {
4115 case YAFFS_OBJECT_TYPE_UNKNOWN:
4116 /* Should not happen */
4118 case YAFFS_OBJECT_TYPE_FILE:
4120 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
4121 || oh->parentObjectId ==
4122 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
4123 fileVariant.fileSize;
4125 case YAFFS_OBJECT_TYPE_HARDLINK:
4126 oh->equivalentObjectId =
4127 in->variant.hardLinkVariant.equivalentObjectId;
4129 case YAFFS_OBJECT_TYPE_SPECIAL:
4132 case YAFFS_OBJECT_TYPE_DIRECTORY:
4135 case YAFFS_OBJECT_TYPE_SYMLINK:
4136 alias = in->variant.symLinkVariant.alias;
4138 alias = _Y("no alias");
4139 yaffs_strncpy(oh->alias,
4141 YAFFS_MAX_ALIAS_LENGTH);
4142 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
4147 yaffs_InitialiseTags(&newTags);
4149 newTags.chunkId = 0;
4150 newTags.objectId = in->objectId;
4151 newTags.serialNumber = in->serial;
4153 /* Add extra info for file header */
4155 newTags.extraHeaderInfoAvailable = 1;
4156 newTags.extraParentObjectId = oh->parentObjectId;
4157 newTags.extraFileLength = oh->fileSize;
4158 newTags.extraIsShrinkHeader = oh->isShrink;
4159 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
4160 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
4161 newTags.extraObjectType = in->variantType;
4163 yaffs_VerifyObjectHeader(in, oh, &newTags, 1);
4165 /* Create new chunk in NAND */
4167 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
4168 (prevChunkId > 0) ? 1 : 0);
4170 if (newChunkId >= 0) {
4172 in->hdrChunk = newChunkId;
4174 if (prevChunkId > 0) {
4175 yaffs_DeleteChunk(dev, prevChunkId, 1,
4179 if (!yaffs_ObjectHasCachedWriteData(in))
4182 /* If this was a shrink, then mark the block that the chunk lives on */
4184 bi = yaffs_GetBlockInfo(in->myDev,
4185 newChunkId / in->myDev->param.nChunksPerBlock);
4186 bi->hasShrinkHeader = 1;
4191 retVal = newChunkId;
4196 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
4201 /*------------------------ Short Operations Cache ----------------------------------------
4202 * In many situations where there is no high level buffering (eg WinCE) a lot of
4203 * reads might be short sequential reads, and a lot of writes may be short
4204 * sequential writes. eg. scanning/writing a jpeg file.
4205 * In these cases, a short read/write cache can provide a huge perfomance benefit
4206 * with dumb-as-a-rock code.
4207 * In Linux, the page cache provides read buffering aand the short op cache provides write
4210 * There are a limited number (~10) of cache chunks per device so that we don't
4211 * need a very intelligent search.
4214 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
4216 yaffs_Device *dev = obj->myDev;
4218 yaffs_ChunkCache *cache;
4219 int nCaches = obj->myDev->param.nShortOpCaches;
4221 for (i = 0; i < nCaches; i++) {
4222 cache = &dev->srCache[i];
4223 if (cache->object == obj &&
4232 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
4234 yaffs_Device *dev = obj->myDev;
4235 int lowest = -99; /* Stop compiler whining. */
4237 yaffs_ChunkCache *cache;
4238 int chunkWritten = 0;
4239 int nCaches = obj->myDev->param.nShortOpCaches;
4245 /* Find the dirty cache for this object with the lowest chunk id. */
4246 for (i = 0; i < nCaches; i++) {
4247 if (dev->srCache[i].object == obj &&
4248 dev->srCache[i].dirty) {
4250 || dev->srCache[i].chunkId <
4252 cache = &dev->srCache[i];
4253 lowest = cache->chunkId;
4258 if (cache && !cache->locked) {
4259 /* Write it out and free it up */
4262 yaffs_WriteChunkDataToObject(cache->object,
4268 cache->object = NULL;
4271 } while (cache && chunkWritten > 0);
4274 /* Hoosterman, disk full while writing cache out. */
4275 T(YAFFS_TRACE_ERROR,
4276 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
4283 /*yaffs_FlushEntireDeviceCache(dev)
4288 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
4291 int nCaches = dev->param.nShortOpCaches;
4294 /* Find a dirty object in the cache and flush it...
4295 * until there are no further dirty objects.
4299 for (i = 0; i < nCaches && !obj; i++) {
4300 if (dev->srCache[i].object &&
4301 dev->srCache[i].dirty)
4302 obj = dev->srCache[i].object;
4306 yaffs_FlushFilesChunkCache(obj);
4313 /* Grab us a cache chunk for use.
4314 * First look for an empty one.
4315 * Then look for the least recently used non-dirty one.
4316 * Then look for the least recently used dirty one...., flush and look again.
4318 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
4322 if (dev->param.nShortOpCaches > 0) {
4323 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4324 if (!dev->srCache[i].object)
4325 return &dev->srCache[i];
4332 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
4334 yaffs_ChunkCache *cache;
4335 yaffs_Object *theObj;
4340 if (dev->param.nShortOpCaches > 0) {
4341 /* Try find a non-dirty one... */
4343 cache = yaffs_GrabChunkCacheWorker(dev);
4346 /* They were all dirty, find the last recently used object and flush
4347 * its cache, then find again.
4348 * NB what's here is not very accurate, we actually flush the object
4349 * the last recently used page.
4352 /* With locking we can't assume we can use entry zero */
4359 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4360 if (dev->srCache[i].object &&
4361 !dev->srCache[i].locked &&
4362 (dev->srCache[i].lastUse < usage || !cache)) {
4363 usage = dev->srCache[i].lastUse;
4364 theObj = dev->srCache[i].object;
4365 cache = &dev->srCache[i];
4370 if (!cache || cache->dirty) {
4371 /* Flush and try again */
4372 yaffs_FlushFilesChunkCache(theObj);
4373 cache = yaffs_GrabChunkCacheWorker(dev);
4383 /* Find a cached chunk */
4384 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj,
4387 yaffs_Device *dev = obj->myDev;
4389 if (dev->param.nShortOpCaches > 0) {
4390 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4391 if (dev->srCache[i].object == obj &&
4392 dev->srCache[i].chunkId == chunkId) {
4395 return &dev->srCache[i];
4402 /* Mark the chunk for the least recently used algorithym */
4403 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache,
4407 if (dev->param.nShortOpCaches > 0) {
4408 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4409 /* Reset the cache usages */
4411 for (i = 1; i < dev->param.nShortOpCaches; i++)
4412 dev->srCache[i].lastUse = 0;
4419 cache->lastUse = dev->srLastUse;
4426 /* Invalidate a single cache page.
4427 * Do this when a whole page gets written,
4428 * ie the short cache for this page is no longer valid.
4430 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
4432 if (object->myDev->param.nShortOpCaches > 0) {
4433 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4436 cache->object = NULL;
4440 /* Invalidate all the cache pages associated with this object
4441 * Do this whenever ther file is deleted or resized.
4443 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
4446 yaffs_Device *dev = in->myDev;
4448 if (dev->param.nShortOpCaches > 0) {
4449 /* Invalidate it. */
4450 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4451 if (dev->srCache[i].object == in)
4452 dev->srCache[i].object = NULL;
4457 /*--------------------- Checkpointing --------------------*/
4460 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev, int head)
4462 yaffs_CheckpointValidity cp;
4464 memset(&cp, 0, sizeof(cp));
4466 cp.structType = sizeof(cp);
4467 cp.magic = YAFFS_MAGIC;
4468 cp.version = YAFFS_CHECKPOINT_VERSION;
4469 cp.head = (head) ? 1 : 0;
4471 return (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp)) ?
4475 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4477 yaffs_CheckpointValidity cp;
4480 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4483 ok = (cp.structType == sizeof(cp)) &&
4484 (cp.magic == YAFFS_MAGIC) &&
4485 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4486 (cp.head == ((head) ? 1 : 0));
4490 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4493 cp->nErasedBlocks = dev->nErasedBlocks;
4494 cp->allocationBlock = dev->allocationBlock;
4495 cp->allocationPage = dev->allocationPage;
4496 cp->nFreeChunks = dev->nFreeChunks;
4498 cp->nDeletedFiles = dev->nDeletedFiles;
4499 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4500 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4501 cp->sequenceNumber = dev->sequenceNumber;
4505 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4506 yaffs_CheckpointDevice *cp)
4508 dev->nErasedBlocks = cp->nErasedBlocks;
4509 dev->allocationBlock = cp->allocationBlock;
4510 dev->allocationPage = cp->allocationPage;
4511 dev->nFreeChunks = cp->nFreeChunks;
4513 dev->nDeletedFiles = cp->nDeletedFiles;
4514 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4515 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4516 dev->sequenceNumber = cp->sequenceNumber;
4520 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4522 yaffs_CheckpointDevice cp;
4524 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4528 /* Write device runtime values*/
4529 yaffs_DeviceToCheckpointDevice(&cp, dev);
4530 cp.structType = sizeof(cp);
4532 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4534 /* Write block info */
4536 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4537 ok = (yaffs_CheckpointWrite(dev, dev->blockInfo, nBytes) == nBytes);
4540 /* Write chunk bits */
4542 nBytes = nBlocks * dev->chunkBitmapStride;
4543 ok = (yaffs_CheckpointWrite(dev, dev->chunkBits, nBytes) == nBytes);
4549 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4551 yaffs_CheckpointDevice cp;
4553 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4557 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4561 if (cp.structType != sizeof(cp))
4565 yaffs_CheckpointDeviceToDevice(dev, &cp);
4567 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4569 ok = (yaffs_CheckpointRead(dev, dev->blockInfo, nBytes) == nBytes);
4573 nBytes = nBlocks * dev->chunkBitmapStride;
4575 ok = (yaffs_CheckpointRead(dev, dev->chunkBits, nBytes) == nBytes);
4580 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4584 cp->objectId = obj->objectId;
4585 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4586 cp->hdrChunk = obj->hdrChunk;
4587 cp->variantType = obj->variantType;
4588 cp->deleted = obj->deleted;
4589 cp->softDeleted = obj->softDeleted;
4590 cp->unlinked = obj->unlinked;
4591 cp->fake = obj->fake;
4592 cp->renameAllowed = obj->renameAllowed;
4593 cp->unlinkAllowed = obj->unlinkAllowed;
4594 cp->serial = obj->serial;
4595 cp->nDataChunks = obj->nDataChunks;
4597 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4598 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4599 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4600 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4603 static int yaffs_CheckpointObjectToObject(yaffs_Object *obj, yaffs_CheckpointObject *cp)
4606 yaffs_Object *parent;
4608 if (obj->variantType != cp->variantType) {
4609 T(YAFFS_TRACE_ERROR, (TSTR("Checkpoint read object %d type %d "
4610 TCONT("chunk %d does not match existing object type %d")
4611 TENDSTR), cp->objectId, cp->variantType, cp->hdrChunk,
4616 obj->objectId = cp->objectId;
4619 parent = yaffs_FindOrCreateObjectByNumber(
4622 YAFFS_OBJECT_TYPE_DIRECTORY);
4627 if (parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4628 T(YAFFS_TRACE_ALWAYS, (TSTR("Checkpoint read object %d parent %d type %d"
4629 TCONT(" chunk %d Parent type, %d, not directory")
4631 cp->objectId, cp->parentId, cp->variantType,
4632 cp->hdrChunk, parent->variantType));
4635 yaffs_AddObjectToDirectory(parent, obj);
4638 obj->hdrChunk = cp->hdrChunk;
4639 obj->variantType = cp->variantType;
4640 obj->deleted = cp->deleted;
4641 obj->softDeleted = cp->softDeleted;
4642 obj->unlinked = cp->unlinked;
4643 obj->fake = cp->fake;
4644 obj->renameAllowed = cp->renameAllowed;
4645 obj->unlinkAllowed = cp->unlinkAllowed;
4646 obj->serial = cp->serial;
4647 obj->nDataChunks = cp->nDataChunks;
4649 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4650 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4651 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4652 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4654 if (obj->hdrChunk > 0)
4655 obj->lazyLoaded = 1;
4661 static int yaffs_CheckpointTnodeWorker(yaffs_Object *in, yaffs_Tnode *tn,
4662 __u32 level, int chunkOffset)
4665 yaffs_Device *dev = in->myDev;
4667 int tnodeSize = yaffs_CalcTnodeSize(dev);
4672 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
4673 if (tn->internal[i]) {
4674 ok = yaffs_CheckpointTnodeWorker(in,
4677 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4680 } else if (level == 0) {
4681 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4682 ok = (yaffs_CheckpointWrite(dev, &baseOffset, sizeof(baseOffset)) == sizeof(baseOffset));
4684 ok = (yaffs_CheckpointWrite(dev, tn, tnodeSize) == tnodeSize);
4692 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4694 __u32 endMarker = ~0;
4697 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4698 ok = yaffs_CheckpointTnodeWorker(obj,
4699 obj->variant.fileVariant.top,
4700 obj->variant.fileVariant.topLevel,
4703 ok = (yaffs_CheckpointWrite(obj->myDev, &endMarker, sizeof(endMarker)) ==
4710 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4714 yaffs_Device *dev = obj->myDev;
4715 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4718 int tnodeSize = yaffs_CalcTnodeSize(dev);
4720 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4722 while (ok && (~baseChunk)) {
4724 /* Read level 0 tnode */
4727 tn = yaffs_GetTnodeRaw(dev);
4729 ok = (yaffs_CheckpointRead(dev, tn, tnodeSize) == tnodeSize);
4734 ok = yaffs_AddOrFindLevel0Tnode(dev,
4740 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4744 T(YAFFS_TRACE_CHECKPOINT, (
4745 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4746 nread, baseChunk, ok));
4752 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4755 yaffs_CheckpointObject cp;
4758 struct ylist_head *lh;
4761 /* Iterate through the objects in each hash entry,
4762 * dumping them to the checkpointing stream.
4765 for (i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++) {
4766 ylist_for_each(lh, &dev->objectBucket[i].list) {
4768 obj = ylist_entry(lh, yaffs_Object, hashLink);
4769 if (!obj->deferedFree) {
4770 yaffs_ObjectToCheckpointObject(&cp, obj);
4771 cp.structType = sizeof(cp);
4773 T(YAFFS_TRACE_CHECKPOINT, (
4774 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %p" TENDSTR),
4775 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk, obj));
4777 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4779 if (ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4780 ok = yaffs_WriteCheckpointTnodes(obj);
4786 /* Dump end of list */
4787 memset(&cp, 0xFF, sizeof(yaffs_CheckpointObject));
4788 cp.structType = sizeof(cp);
4791 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4796 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4799 yaffs_CheckpointObject cp;
4802 yaffs_Object *hardList = NULL;
4804 while (ok && !done) {
4805 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4806 if (cp.structType != sizeof(cp)) {
4807 T(YAFFS_TRACE_CHECKPOINT, (TSTR("struct size %d instead of %d ok %d"TENDSTR),
4808 cp.structType, (int)sizeof(cp), ok));
4812 T(YAFFS_TRACE_CHECKPOINT, (TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4813 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk));
4815 if (ok && cp.objectId == ~0)
4818 obj = yaffs_FindOrCreateObjectByNumber(dev, cp.objectId, cp.variantType);
4820 ok = yaffs_CheckpointObjectToObject(obj, &cp);
4823 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4824 ok = yaffs_ReadCheckpointTnodes(obj);
4825 } else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4826 obj->hardLinks.next =
4827 (struct ylist_head *) hardList;
4836 yaffs_HardlinkFixup(dev, hardList);
4841 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4843 __u32 checkpointSum;
4846 yaffs_GetCheckpointSum(dev, &checkpointSum);
4848 ok = (yaffs_CheckpointWrite(dev, &checkpointSum, sizeof(checkpointSum)) == sizeof(checkpointSum));
4856 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4858 __u32 checkpointSum0;
4859 __u32 checkpointSum1;
4862 yaffs_GetCheckpointSum(dev, &checkpointSum0);
4864 ok = (yaffs_CheckpointRead(dev, &checkpointSum1, sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4869 if (checkpointSum0 != checkpointSum1)
4876 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4880 if (dev->param.skipCheckpointWrite || !dev->param.isYaffs2) {
4881 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint write" TENDSTR)));
4886 ok = yaffs_CheckpointOpen(dev, 1);
4889 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4890 ok = yaffs_WriteCheckpointValidityMarker(dev, 1);
4893 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint device" TENDSTR)));
4894 ok = yaffs_WriteCheckpointDevice(dev);
4897 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint objects" TENDSTR)));
4898 ok = yaffs_WriteCheckpointObjects(dev);
4901 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4902 ok = yaffs_WriteCheckpointValidityMarker(dev, 0);
4906 ok = yaffs_WriteCheckpointSum(dev);
4908 if (!yaffs_CheckpointClose(dev))
4912 dev->isCheckpointed = 1;
4914 dev->isCheckpointed = 0;
4916 return dev->isCheckpointed;
4919 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4923 if (dev->param.skipCheckpointRead || !dev->param.isYaffs2) {
4924 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint read" TENDSTR)));
4929 ok = yaffs_CheckpointOpen(dev, 0); /* open for read */
4932 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4933 ok = yaffs_ReadCheckpointValidityMarker(dev, 1);
4936 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint device" TENDSTR)));
4937 ok = yaffs_ReadCheckpointDevice(dev);
4940 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint objects" TENDSTR)));
4941 ok = yaffs_ReadCheckpointObjects(dev);
4944 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4945 ok = yaffs_ReadCheckpointValidityMarker(dev, 0);
4949 ok = yaffs_ReadCheckpointSum(dev);
4950 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint checksum %d" TENDSTR), ok));
4953 if (!yaffs_CheckpointClose(dev))
4957 dev->isCheckpointed = 1;
4959 dev->isCheckpointed = 0;
4965 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4967 if (dev->isCheckpointed ||
4968 dev->blocksInCheckpoint > 0) {
4969 dev->isCheckpointed = 0;
4970 yaffs_CheckpointInvalidateStream(dev);
4972 if (dev->param.markSuperBlockDirty)
4973 dev->param.markSuperBlockDirty(dev);
4977 int yaffs_CheckpointSave(yaffs_Device *dev)
4980 T(YAFFS_TRACE_CHECKPOINT, (TSTR("save entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4982 yaffs_VerifyObjects(dev);
4983 yaffs_VerifyBlocks(dev);
4984 yaffs_VerifyFreeChunks(dev);
4986 if (!dev->isCheckpointed) {
4987 yaffs_InvalidateCheckpoint(dev);
4988 yaffs_WriteCheckpointData(dev);
4991 T(YAFFS_TRACE_ALWAYS, (TSTR("save exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4993 return dev->isCheckpointed;
4996 int yaffs_CheckpointRestore(yaffs_Device *dev)
4999 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
5001 retval = yaffs_ReadCheckpointData(dev);
5003 if (dev->isCheckpointed) {
5004 yaffs_VerifyObjects(dev);
5005 yaffs_VerifyBlocks(dev);
5006 yaffs_VerifyFreeChunks(dev);
5009 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
5014 /*--------------------- File read/write ------------------------
5015 * Read and write have very similar structures.
5016 * In general the read/write has three parts to it
5017 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
5018 * Some complete chunks
5019 * An incomplete chunk to end off with
5021 * Curve-balls: the first chunk might also be the last chunk.
5024 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 *buffer, loff_t offset,
5033 yaffs_ChunkCache *cache;
5040 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
5041 /* start = offset % dev->nDataBytesPerChunk; */
5042 yaffs_AddrToChunk(dev, offset, &chunk, &start);
5045 /* OK now check for the curveball where the start and end are in
5048 if ((start + n) < dev->nDataBytesPerChunk)
5051 nToCopy = dev->nDataBytesPerChunk - start;
5053 cache = yaffs_FindChunkCache(in, chunk);
5055 /* If the chunk is already in the cache or it is less than a whole chunk
5056 * or we're using inband tags then use the cache (if there is caching)
5057 * else bypass the cache.
5059 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
5060 if (dev->param.nShortOpCaches > 0) {
5062 /* If we can't find the data in the cache, then load it up. */
5065 cache = yaffs_GrabChunkCache(in->myDev);
5067 cache->chunkId = chunk;
5070 yaffs_ReadChunkDataFromObject(in, chunk,
5076 yaffs_UseChunkCache(dev, cache, 0);
5081 memcpy(buffer, &cache->data[start], nToCopy);
5085 /* Read into the local buffer then copy..*/
5088 yaffs_GetTempBuffer(dev, __LINE__);
5089 yaffs_ReadChunkDataFromObject(in, chunk,
5092 memcpy(buffer, &localBuffer[start], nToCopy);
5095 yaffs_ReleaseTempBuffer(dev, localBuffer,
5101 /* A full chunk. Read directly into the supplied buffer. */
5102 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
5116 int yaffs_DoWriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
5117 int nBytes, int writeThrough)
5126 int startOfWrite = offset;
5127 int chunkWritten = 0;
5135 while (n > 0 && chunkWritten >= 0) {
5136 yaffs_AddrToChunk(dev, offset, &chunk, &start);
5138 if (chunk * dev->nDataBytesPerChunk + start != offset ||
5139 start >= dev->nDataBytesPerChunk) {
5140 T(YAFFS_TRACE_ERROR, (
5141 TSTR("AddrToChunk of offset %d gives chunk %d start %d"
5143 (int)offset, chunk, start));
5145 chunk++; /* File pos to chunk in file offset */
5147 /* OK now check for the curveball where the start and end are in
5151 if ((start + n) < dev->nDataBytesPerChunk) {
5154 /* Now folks, to calculate how many bytes to write back....
5155 * If we're overwriting and not writing to then end of file then
5156 * we need to write back as much as was there before.
5159 chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
5161 if (chunkStart > in->variant.fileVariant.fileSize)
5162 nBytesRead = 0; /* Past end of file */
5164 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
5166 if (nBytesRead > dev->nDataBytesPerChunk)
5167 nBytesRead = dev->nDataBytesPerChunk;
5171 (start + n)) ? nBytesRead : (start + n);
5173 if (nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
5177 nToCopy = dev->nDataBytesPerChunk - start;
5178 nToWriteBack = dev->nDataBytesPerChunk;
5181 if (nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
5182 /* An incomplete start or end chunk (or maybe both start and end chunk),
5183 * or we're using inband tags, so we want to use the cache buffers.
5185 if (dev->param.nShortOpCaches > 0) {
5186 yaffs_ChunkCache *cache;
5187 /* If we can't find the data in the cache, then load the cache */
5188 cache = yaffs_FindChunkCache(in, chunk);
5191 && yaffs_CheckSpaceForAllocation(dev, 1)) {
5192 cache = yaffs_GrabChunkCache(dev);
5194 cache->chunkId = chunk;
5197 yaffs_ReadChunkDataFromObject(in, chunk,
5201 !yaffs_CheckSpaceForAllocation(dev, 1)) {
5202 /* Drop the cache if it was a read cache item and
5203 * no space check has been made for it.
5209 yaffs_UseChunkCache(dev, cache, 1);
5213 memcpy(&cache->data[start], buffer,
5218 cache->nBytes = nToWriteBack;
5222 yaffs_WriteChunkDataToObject
5225 cache->data, cache->nBytes,
5231 chunkWritten = -1; /* fail the write */
5234 /* An incomplete start or end chunk (or maybe both start and end chunk)
5235 * Read into the local buffer then copy, then copy over and write back.
5239 yaffs_GetTempBuffer(dev, __LINE__);
5241 yaffs_ReadChunkDataFromObject(in, chunk,
5246 memcpy(&localBuffer[start], buffer, nToCopy);
5249 yaffs_WriteChunkDataToObject(in, chunk,
5254 yaffs_ReleaseTempBuffer(dev, localBuffer,
5260 /* A full chunk. Write directly from the supplied buffer. */
5265 yaffs_WriteChunkDataToObject(in, chunk, buffer,
5266 dev->nDataBytesPerChunk,
5269 /* Since we've overwritten the cached data, we better invalidate it. */
5270 yaffs_InvalidateChunkCache(in, chunk);
5273 if (chunkWritten >= 0) {
5282 /* Update file object */
5284 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
5285 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
5292 int yaffs_WriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
5293 int nBytes, int writeThrough)
5295 yaffs_HandleHole(in,offset);
5296 return yaffs_DoWriteDataToFile(in,buffer,offset,nBytes,writeThrough);
5301 /* ---------------------- File resizing stuff ------------------ */
5303 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
5306 yaffs_Device *dev = in->myDev;
5307 int oldFileSize = in->variant.fileVariant.fileSize;
5309 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
5311 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
5312 dev->nDataBytesPerChunk;
5316 /* Delete backwards so that we don't end up with holes if
5317 * power is lost part-way through the operation.
5319 for (i = lastDel; i >= startDel; i--) {
5320 /* NB this could be optimised somewhat,
5321 * eg. could retrieve the tags and write them without
5322 * using yaffs_DeleteChunk
5325 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5328 (dev->internalStartBlock * dev->param.nChunksPerBlock)
5330 ((dev->internalEndBlock +
5331 1) * dev->param.nChunksPerBlock)) {
5332 T(YAFFS_TRACE_ALWAYS,
5333 (TSTR("Found daft chunkId %d for %d" TENDSTR),
5337 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5345 static void yaffs_ResizeDown( yaffs_Object *obj, loff_t newSize)
5348 __u32 newSizeOfPartialChunk;
5349 yaffs_Device *dev = obj->myDev;
5351 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5353 yaffs_PruneResizedChunks(obj, newSize);
5355 if (newSizeOfPartialChunk != 0) {
5356 int lastChunk = 1 + newFullChunks;
5357 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5359 /* Got to read and rewrite the last chunk with its new size and zero pad */
5360 yaffs_ReadChunkDataFromObject(obj, lastChunk, localBuffer);
5361 memset(localBuffer + newSizeOfPartialChunk, 0,
5362 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5364 yaffs_WriteChunkDataToObject(obj, lastChunk, localBuffer,
5365 newSizeOfPartialChunk, 1);
5367 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5370 obj->variant.fileVariant.fileSize = newSize;
5372 yaffs_PruneFileStructure(dev, &obj->variant.fileVariant);
5376 static int yaffs_HandleHole(yaffs_Object *obj, loff_t newSize)
5378 /* if newsSize > oldFileSize.
5379 * We're going to be writing a hole.
5380 * If the hole is small then write zeros otherwise write a start of hole marker.
5387 int result = YAFFS_OK;
5388 yaffs_Device *dev = NULL;
5390 __u8 *localBuffer = NULL;
5392 int smallIncreaseOk = 0;
5397 if(obj->variantType != YAFFS_OBJECT_TYPE_FILE)
5402 /* Bail out if not yaffs2 mode */
5403 if(!dev->param.isYaffs2)
5406 oldFileSize = obj->variant.fileVariant.fileSize;
5408 if (newSize <= oldFileSize)
5411 increase = newSize - oldFileSize;
5413 if(increase < YAFFS_SMALL_HOLE_THRESHOLD * dev->nDataBytesPerChunk &&
5414 yaffs_CheckSpaceForAllocation(dev, YAFFS_SMALL_HOLE_THRESHOLD + 1))
5420 localBuffer= yaffs_GetTempBuffer(dev, __LINE__);
5423 /* fill hole with zero bytes */
5424 int pos = oldFileSize;
5427 memset(localBuffer,0,dev->nDataBytesPerChunk);
5428 smallIncreaseOk = 1;
5430 while(increase > 0 && smallIncreaseOk){
5431 thisWrite = increase;
5432 if(thisWrite > dev->nDataBytesPerChunk)
5433 thisWrite = dev->nDataBytesPerChunk;
5434 written = yaffs_DoWriteDataToFile(obj,localBuffer,pos,thisWrite,0);
5435 if(written == thisWrite){
5437 increase -= thisWrite;
5439 smallIncreaseOk = 0;
5442 yaffs_ReleaseTempBuffer(dev,localBuffer,__LINE__);
5444 /* If we were out of space then reverse any chunks we've added */
5445 if(!smallIncreaseOk)
5446 yaffs_ResizeDown(obj, oldFileSize);
5449 if (!smallIncreaseOk &&
5451 obj->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5452 obj->parent->objectId != YAFFS_OBJECTID_DELETED){
5453 /* Write a hole start header with the old file size */
5454 yaffs_UpdateObjectHeader(obj, NULL, 0,1,0);
5461 int yaffs_ResizeFile(yaffs_Object *in, loff_t newSize)
5463 yaffs_Device *dev = in->myDev;
5464 int oldFileSize = in->variant.fileVariant.fileSize;
5466 yaffs_FlushFilesChunkCache(in);
5467 yaffs_InvalidateWholeChunkCache(in);
5469 yaffs_CheckGarbageCollection(dev,0);
5471 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
5474 if (newSize == oldFileSize)
5477 if(newSize > oldFileSize){
5478 yaffs_HandleHole(in,newSize);
5479 in->variant.fileVariant.fileSize = newSize;
5481 /* newSize < oldFileSize */
5482 yaffs_ResizeDown(in, newSize);
5485 /* Write a new object header to reflect the resize.
5486 * show we've shrunk the file, if need be
5487 * Do this only if the file is not in the deleted directories
5488 * and is not shadowed.
5492 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5493 in->parent->objectId != YAFFS_OBJECTID_DELETED)
5494 yaffs_UpdateObjectHeader(in, NULL, 0,0,0);
5500 loff_t yaffs_GetFileSize(yaffs_Object *obj)
5502 YCHAR *alias = NULL;
5503 obj = yaffs_GetEquivalentObject(obj);
5505 switch (obj->variantType) {
5506 case YAFFS_OBJECT_TYPE_FILE:
5507 return obj->variant.fileVariant.fileSize;
5508 case YAFFS_OBJECT_TYPE_SYMLINK:
5509 alias = obj->variant.symLinkVariant.alias;
5512 return yaffs_strnlen(alias,YAFFS_MAX_ALIAS_LENGTH);
5520 int yaffs_FlushFile(yaffs_Object *in, int updateTime, int dataSync)
5524 yaffs_FlushFilesChunkCache(in);
5525 if(dataSync) /* Only sync data */
5529 #ifdef CONFIG_YAFFS_WINCE
5530 yfsd_WinFileTimeNow(in->win_mtime);
5533 in->yst_mtime = Y_CURRENT_TIME;
5538 retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5539 0) ? YAFFS_OK : YAFFS_FAIL;
5549 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
5552 /* First off, invalidate the file's data in the cache, without flushing. */
5553 yaffs_InvalidateWholeChunkCache(in);
5555 if (in->myDev->param.isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5556 /* Move to the unlinked directory so we have a record that it was deleted. */
5557 yaffs_ChangeObjectName(in, in->myDev->deletedDir, _Y("deleted"), 0, 0);
5561 yaffs_RemoveObjectFromDirectory(in);
5562 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5565 yaffs_FreeObject(in);
5570 /* yaffs_DeleteFile deletes the whole file data
5571 * and the inode associated with the file.
5572 * It does not delete the links associated with the file.
5574 static int yaffs_UnlinkFileIfNeeded(yaffs_Object *in)
5578 int immediateDeletion = 0;
5579 yaffs_Device *dev = in->myDev;
5582 immediateDeletion = 1;
5584 if (immediateDeletion) {
5586 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5587 _Y("deleted"), 0, 0);
5588 T(YAFFS_TRACE_TRACING,
5589 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5592 in->myDev->nDeletedFiles++;
5593 if (dev->param.disableSoftDelete || dev->param.isYaffs2)
5594 yaffs_ResizeFile(in, 0);
5595 yaffs_SoftDeleteFile(in);
5598 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5599 _Y("unlinked"), 0, 0);
5606 int yaffs_DeleteFile(yaffs_Object *in)
5608 int retVal = YAFFS_OK;
5609 int deleted = in->deleted;
5610 yaffs_Device *dev = in->myDev;
5612 if (dev->param.disableSoftDelete || dev->param.isYaffs2)
5613 yaffs_ResizeFile(in, 0);
5615 if (in->nDataChunks > 0) {
5616 /* Use soft deletion if there is data in the file.
5617 * That won't be the case if it has been resized to zero.
5620 retVal = yaffs_UnlinkFileIfNeeded(in);
5622 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5625 in->myDev->nDeletedFiles++;
5626 yaffs_SoftDeleteFile(in);
5628 return deleted ? YAFFS_OK : YAFFS_FAIL;
5630 /* The file has no data chunks so we toss it immediately */
5631 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5632 in->variant.fileVariant.top = NULL;
5633 yaffs_DoGenericObjectDeletion(in);
5639 static int yaffs_IsNonEmptyDirectory(yaffs_Object *obj)
5641 return (obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) &&
5642 !(ylist_empty(&obj->variant.directoryVariant.children));
5645 static int yaffs_DeleteDirectory(yaffs_Object *obj)
5647 /* First check that the directory is empty. */
5648 if (yaffs_IsNonEmptyDirectory(obj))
5651 return yaffs_DoGenericObjectDeletion(obj);
5654 static int yaffs_DeleteSymLink(yaffs_Object *in)
5656 if(in->variant.symLinkVariant.alias)
5657 YFREE(in->variant.symLinkVariant.alias);
5658 in->variant.symLinkVariant.alias=NULL;
5660 return yaffs_DoGenericObjectDeletion(in);
5663 static int yaffs_DeleteHardLink(yaffs_Object *in)
5665 /* remove this hardlink from the list assocaited with the equivalent
5668 ylist_del_init(&in->hardLinks);
5669 return yaffs_DoGenericObjectDeletion(in);
5672 int yaffs_DeleteObject(yaffs_Object *obj)
5675 switch (obj->variantType) {
5676 case YAFFS_OBJECT_TYPE_FILE:
5677 retVal = yaffs_DeleteFile(obj);
5679 case YAFFS_OBJECT_TYPE_DIRECTORY:
5680 if(!ylist_empty(&obj->variant.directoryVariant.dirty)){
5681 T(YAFFS_TRACE_BACKGROUND, (TSTR("Remove object %d from dirty directories" TENDSTR),obj->objectId));
5682 ylist_del_init(&obj->variant.directoryVariant.dirty);
5684 return yaffs_DeleteDirectory(obj);
5686 case YAFFS_OBJECT_TYPE_SYMLINK:
5687 retVal = yaffs_DeleteSymLink(obj);
5689 case YAFFS_OBJECT_TYPE_HARDLINK:
5690 retVal = yaffs_DeleteHardLink(obj);
5692 case YAFFS_OBJECT_TYPE_SPECIAL:
5693 retVal = yaffs_DoGenericObjectDeletion(obj);
5695 case YAFFS_OBJECT_TYPE_UNKNOWN:
5697 break; /* should not happen. */
5703 static int yaffs_UnlinkWorker(yaffs_Object *obj)
5706 int immediateDeletion = 0;
5709 immediateDeletion = 1;
5712 yaffs_UpdateParent(obj->parent);
5714 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5715 return yaffs_DeleteHardLink(obj);
5716 } else if (!ylist_empty(&obj->hardLinks)) {
5717 /* Curve ball: We're unlinking an object that has a hardlink.
5719 * This problem arises because we are not strictly following
5720 * The Linux link/inode model.
5722 * We can't really delete the object.
5723 * Instead, we do the following:
5724 * - Select a hardlink.
5725 * - Unhook it from the hard links
5726 * - Move it from its parent directory (so that the rename can work)
5727 * - Rename the object to the hardlink's name.
5728 * - Delete the hardlink
5732 yaffs_Object *parent;
5734 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5736 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5738 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5739 parent = hl->parent;
5741 ylist_del_init(&hl->hardLinks);
5743 yaffs_AddObjectToDirectory(obj->myDev->unlinkedDir, hl);
5745 retVal = yaffs_ChangeObjectName(obj,parent, name, 0, 0);
5747 if (retVal == YAFFS_OK)
5748 retVal = yaffs_DoGenericObjectDeletion(hl);
5752 } else if (immediateDeletion) {
5753 switch (obj->variantType) {
5754 case YAFFS_OBJECT_TYPE_FILE:
5755 return yaffs_DeleteFile(obj);
5757 case YAFFS_OBJECT_TYPE_DIRECTORY:
5758 ylist_del_init(&obj->variant.directoryVariant.dirty);
5759 return yaffs_DeleteDirectory(obj);
5761 case YAFFS_OBJECT_TYPE_SYMLINK:
5762 return yaffs_DeleteSymLink(obj);
5764 case YAFFS_OBJECT_TYPE_SPECIAL:
5765 return yaffs_DoGenericObjectDeletion(obj);
5767 case YAFFS_OBJECT_TYPE_HARDLINK:
5768 case YAFFS_OBJECT_TYPE_UNKNOWN:
5772 } else if(yaffs_IsNonEmptyDirectory(obj))
5775 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
5776 _Y("unlinked"), 0, 0);
5780 static int yaffs_UnlinkObject(yaffs_Object *obj)
5783 if (obj && obj->unlinkAllowed)
5784 return yaffs_UnlinkWorker(obj);
5789 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
5793 obj = yaffs_FindObjectByName(dir, name);
5794 return yaffs_UnlinkObject(obj);
5797 /*----------------------- Initialisation Scanning ---------------------- */
5799 static void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
5800 int backwardScanning)
5804 if (!backwardScanning) {
5805 /* Handle YAFFS1 forward scanning case
5806 * For YAFFS1 we always do the deletion
5810 /* Handle YAFFS2 case (backward scanning)
5811 * If the shadowed object exists then ignore.
5813 obj = yaffs_FindObjectByNumber(dev, objId);
5818 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5819 * We put it in unlinked dir to be cleaned up after the scanning
5822 yaffs_FindOrCreateObjectByNumber(dev, objId,
5823 YAFFS_OBJECT_TYPE_FILE);
5826 obj->isShadowed = 1;
5827 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5828 obj->variant.fileVariant.shrinkSize = 0;
5829 obj->valid = 1; /* So that we don't read any other info for this file */
5839 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5846 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5848 in = yaffs_FindObjectByNumber(dev,
5849 hl->variant.hardLinkVariant.
5850 equivalentObjectId);
5853 /* Add the hardlink pointers */
5854 hl->variant.hardLinkVariant.equivalentObject = in;
5855 ylist_add(&hl->hardLinks, &in->hardLinks);
5857 /* Todo Need to report/handle this better.
5858 * Got a problem... hardlink to a non-existant object
5860 hl->variant.hardLinkVariant.equivalentObject = NULL;
5861 YINIT_LIST_HEAD(&hl->hardLinks);
5871 static int ybicmp(const void *a, const void *b)
5873 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5874 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5875 register int ablock = ((yaffs_BlockIndex *)a)->block;
5876 register int bblock = ((yaffs_BlockIndex *)b)->block;
5878 return ablock - bblock;
5884 struct yaffs_ShadowFixerStruct {
5887 struct yaffs_ShadowFixerStruct *next;
5891 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5894 * Sort out state of unlinked and deleted objects after scanning.
5896 struct ylist_head *i;
5897 struct ylist_head *n;
5900 /* Soft delete all the unlinked files */
5901 ylist_for_each_safe(i, n,
5902 &dev->unlinkedDir->variant.directoryVariant.children) {
5904 l = ylist_entry(i, yaffs_Object, siblings);
5905 yaffs_DeleteObject(l);
5909 ylist_for_each_safe(i, n,
5910 &dev->deletedDir->variant.directoryVariant.children) {
5912 l = ylist_entry(i, yaffs_Object, siblings);
5913 yaffs_DeleteObject(l);
5920 * This code iterates through all the objects making sure that they are rooted.
5921 * Any unrooted objects are re-rooted in lost+found.
5922 * An object needs to be in one of:
5923 * - Directly under deleted, unlinked
5924 * - Directly or indirectly under root.
5927 * This code assumes that we don't ever change the current relationships between
5929 * rootDir->parent == unlinkedDir->parent == deletedDir->parent == NULL
5930 * lostNfound->parent == rootDir
5932 * This fixes the problem where directories might have inadvertently been deleted
5933 * leaving the object "hanging" without being rooted in the directory tree.
5936 static int yaffs_HasNULLParent(yaffs_Device *dev, yaffs_Object *obj)
5938 return (obj == dev->deletedDir ||
5939 obj == dev->unlinkedDir||
5940 obj == dev->rootDir);
5943 static void yaffs_FixHangingObjects(yaffs_Device *dev)
5946 yaffs_Object *parent;
5948 struct ylist_head *lh;
5949 struct ylist_head *n;
5954 /* Iterate through the objects in each hash entry,
5955 * looking at each object.
5956 * Make sure it is rooted.
5959 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
5960 ylist_for_each_safe(lh, n, &dev->objectBucket[i].list) {
5962 obj = ylist_entry(lh, yaffs_Object, hashLink);
5963 parent= obj->parent;
5965 if(yaffs_HasNULLParent(dev,obj)){
5966 /* These directories are not hanging */
5969 else if(!parent || parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5971 else if(yaffs_HasNULLParent(dev,parent))
5975 * Need to follow the parent chain to see if it is hanging.
5980 while(parent != dev->rootDir &&
5982 parent->parent->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
5984 parent = parent->parent;
5987 if(parent != dev->rootDir)
5992 (TSTR("Hanging object %d moved to lost and found" TENDSTR),
5994 yaffs_AddObjectToDirectory(dev->lostNFoundDir,obj);
6003 * Delete directory contents for cleaning up lost and found.
6005 static void yaffs_DeleteDirectoryContents(yaffs_Object *dir)
6008 struct ylist_head *lh;
6009 struct ylist_head *n;
6011 if(dir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
6014 ylist_for_each_safe(lh, n, &dir->variant.directoryVariant.children) {
6016 obj = ylist_entry(lh, yaffs_Object, siblings);
6017 if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
6018 yaffs_DeleteDirectoryContents(obj);
6021 (TSTR("Deleting lost_found object %d" TENDSTR),
6024 /* Need to use UnlinkObject since Delete would not handle
6025 * hardlinked objects correctly.
6027 yaffs_UnlinkObject(obj);
6033 static void yaffs_EmptyLostAndFound(yaffs_Device *dev)
6035 yaffs_DeleteDirectoryContents(dev->lostNFoundDir);
6038 static int yaffs_Scan(yaffs_Device *dev)
6040 yaffs_ExtendedTags tags;
6050 yaffs_BlockState state;
6051 yaffs_Object *hardList = NULL;
6052 yaffs_BlockInfo *bi;
6053 __u32 sequenceNumber;
6054 yaffs_ObjectHeader *oh;
6056 yaffs_Object *parent;
6058 int alloc_failed = 0;
6060 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
6068 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
6069 dev->internalStartBlock, dev->internalEndBlock));
6071 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6073 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6075 /* Scan all the blocks to determine their state */
6076 bi = dev->blockInfo;
6077 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6078 yaffs_ClearChunkBits(dev, blk);
6080 bi->softDeletions = 0;
6082 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6084 bi->blockState = state;
6085 bi->sequenceNumber = sequenceNumber;
6087 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6088 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6090 T(YAFFS_TRACE_SCAN_DEBUG,
6091 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6092 state, sequenceNumber));
6094 if (state == YAFFS_BLOCK_STATE_DEAD) {
6095 T(YAFFS_TRACE_BAD_BLOCKS,
6096 (TSTR("block %d is bad" TENDSTR), blk));
6097 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6098 T(YAFFS_TRACE_SCAN_DEBUG,
6099 (TSTR("Block empty " TENDSTR)));
6100 dev->nErasedBlocks++;
6101 dev->nFreeChunks += dev->param.nChunksPerBlock;
6106 startIterator = dev->internalStartBlock;
6107 endIterator = dev->internalEndBlock;
6109 /* For each block.... */
6110 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
6117 blk = blockIterator;
6119 bi = yaffs_GetBlockInfo(dev, blk);
6120 state = bi->blockState;
6124 /* For each chunk in each block that needs scanning....*/
6125 for (c = 0; !alloc_failed && c < dev->param.nChunksPerBlock &&
6126 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
6127 /* Read the tags and decide what to do */
6128 chunk = blk * dev->param.nChunksPerBlock + c;
6130 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6133 /* Let's have a good look at this chunk... */
6135 if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
6141 /*T((" %d %d deleted\n",blk,c)); */
6142 } else if (!tags.chunkUsed) {
6143 /* An unassigned chunk in the block
6144 * This means that either the block is empty or
6145 * this is the one being allocated from
6149 /* We're looking at the first chunk in the block so the block is unused */
6150 state = YAFFS_BLOCK_STATE_EMPTY;
6151 dev->nErasedBlocks++;
6153 /* this is the block being allocated from */
6156 (" Allocating from %d %d" TENDSTR),
6158 state = YAFFS_BLOCK_STATE_ALLOCATING;
6159 dev->allocationBlock = blk;
6160 dev->allocationPage = c;
6161 dev->allocationBlockFinder = blk;
6162 /* Set block finder here to encourage the allocator to go forth from here. */
6166 dev->nFreeChunks += (dev->param.nChunksPerBlock - c);
6167 } else if (tags.chunkId > 0) {
6168 /* chunkId > 0 so it is a data chunk... */
6169 unsigned int endpos;
6171 yaffs_SetChunkBit(dev, blk, c);
6174 in = yaffs_FindOrCreateObjectByNumber(dev,
6177 YAFFS_OBJECT_TYPE_FILE);
6178 /* PutChunkIntoFile checks for a clash (two data chunks with
6179 * the same chunkId).
6186 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, 1))
6191 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
6194 in->variantType == YAFFS_OBJECT_TYPE_FILE
6195 && in->variant.fileVariant.scannedFileSize <
6197 in->variant.fileVariant.
6198 scannedFileSize = endpos;
6199 if (!dev->param.useHeaderFileSize) {
6200 in->variant.fileVariant.
6202 in->variant.fileVariant.
6207 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
6209 /* chunkId == 0, so it is an ObjectHeader.
6210 * Thus, we read in the object header and make the object
6212 yaffs_SetChunkBit(dev, blk, c);
6215 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
6219 oh = (yaffs_ObjectHeader *) chunkData;
6221 in = yaffs_FindObjectByNumber(dev,
6223 if (in && in->variantType != oh->type) {
6224 /* This should not happen, but somehow
6225 * Wev'e ended up with an objectId that has been reused but not yet
6226 * deleted, and worse still it has changed type. Delete the old object.
6229 yaffs_DeleteObject(in);
6234 in = yaffs_FindOrCreateObjectByNumber(dev,
6242 if (in && oh->shadowsObject > 0) {
6244 struct yaffs_ShadowFixerStruct *fixer;
6245 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
6247 fixer->next = shadowFixerList;
6248 shadowFixerList = fixer;
6249 fixer->objectId = tags.objectId;
6250 fixer->shadowedId = oh->shadowsObject;
6255 if (in && in->valid) {
6256 /* We have already filled this one. We have a duplicate and need to resolve it. */
6258 unsigned existingSerial = in->serial;
6259 unsigned newSerial = tags.serialNumber;
6261 if (((existingSerial + 1) & 3) == newSerial) {
6262 /* Use new one - destroy the exisiting one */
6263 yaffs_DeleteChunk(dev,
6268 /* Use existing - destroy this one. */
6269 yaffs_DeleteChunk(dev, chunk, 1,
6274 if (in && !in->valid &&
6275 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6276 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
6277 /* We only load some info, don't fiddle with directory structure */
6279 in->variantType = oh->type;
6281 in->yst_mode = oh->yst_mode;
6282 #ifdef CONFIG_YAFFS_WINCE
6283 in->win_atime[0] = oh->win_atime[0];
6284 in->win_ctime[0] = oh->win_ctime[0];
6285 in->win_mtime[0] = oh->win_mtime[0];
6286 in->win_atime[1] = oh->win_atime[1];
6287 in->win_ctime[1] = oh->win_ctime[1];
6288 in->win_mtime[1] = oh->win_mtime[1];
6290 in->yst_uid = oh->yst_uid;
6291 in->yst_gid = oh->yst_gid;
6292 in->yst_atime = oh->yst_atime;
6293 in->yst_mtime = oh->yst_mtime;
6294 in->yst_ctime = oh->yst_ctime;
6295 in->yst_rdev = oh->yst_rdev;
6297 in->hdrChunk = chunk;
6298 in->serial = tags.serialNumber;
6300 } else if (in && !in->valid) {
6301 /* we need to load this info */
6304 in->variantType = oh->type;
6306 in->yst_mode = oh->yst_mode;
6307 #ifdef CONFIG_YAFFS_WINCE
6308 in->win_atime[0] = oh->win_atime[0];
6309 in->win_ctime[0] = oh->win_ctime[0];
6310 in->win_mtime[0] = oh->win_mtime[0];
6311 in->win_atime[1] = oh->win_atime[1];
6312 in->win_ctime[1] = oh->win_ctime[1];
6313 in->win_mtime[1] = oh->win_mtime[1];
6315 in->yst_uid = oh->yst_uid;
6316 in->yst_gid = oh->yst_gid;
6317 in->yst_atime = oh->yst_atime;
6318 in->yst_mtime = oh->yst_mtime;
6319 in->yst_ctime = oh->yst_ctime;
6320 in->yst_rdev = oh->yst_rdev;
6322 in->hdrChunk = chunk;
6323 in->serial = tags.serialNumber;
6325 yaffs_SetObjectName(in, oh->name);
6328 /* directory stuff...
6333 yaffs_FindOrCreateObjectByNumber
6334 (dev, oh->parentObjectId,
6335 YAFFS_OBJECT_TYPE_DIRECTORY);
6338 if (parent && parent->variantType ==
6339 YAFFS_OBJECT_TYPE_UNKNOWN) {
6340 /* Set up as a directory */
6341 parent->variantType =
6342 YAFFS_OBJECT_TYPE_DIRECTORY;
6343 YINIT_LIST_HEAD(&parent->variant.
6346 } else if (!parent || parent->variantType !=
6347 YAFFS_OBJECT_TYPE_DIRECTORY) {
6348 /* Hoosterman, another problem....
6349 * We're trying to use a non-directory as a directory
6352 T(YAFFS_TRACE_ERROR,
6354 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6356 parent = dev->lostNFoundDir;
6359 yaffs_AddObjectToDirectory(parent, in);
6361 if (0 && (parent == dev->deletedDir ||
6362 parent == dev->unlinkedDir)) {
6363 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
6364 dev->nDeletedFiles++;
6366 /* Note re hardlinks.
6367 * Since we might scan a hardlink before its equivalent object is scanned
6368 * we put them all in a list.
6369 * After scanning is complete, we should have all the objects, so we run through this
6370 * list and fix up all the chains.
6373 switch (in->variantType) {
6374 case YAFFS_OBJECT_TYPE_UNKNOWN:
6375 /* Todo got a problem */
6377 case YAFFS_OBJECT_TYPE_FILE:
6378 if (dev->param.useHeaderFileSize)
6380 in->variant.fileVariant.
6385 case YAFFS_OBJECT_TYPE_HARDLINK:
6386 in->variant.hardLinkVariant.
6387 equivalentObjectId =
6388 oh->equivalentObjectId;
6389 in->hardLinks.next =
6390 (struct ylist_head *)
6394 case YAFFS_OBJECT_TYPE_DIRECTORY:
6397 case YAFFS_OBJECT_TYPE_SPECIAL:
6400 case YAFFS_OBJECT_TYPE_SYMLINK:
6401 in->variant.symLinkVariant.alias =
6402 yaffs_CloneString(oh->alias);
6403 if (!in->variant.symLinkVariant.alias)
6412 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6413 /* If we got this far while scanning, then the block is fully allocated.*/
6414 state = YAFFS_BLOCK_STATE_FULL;
6417 if (state == YAFFS_BLOCK_STATE_ALLOCATING) {
6418 /* If the block was partially allocated then treat it as fully allocated.*/
6419 state = YAFFS_BLOCK_STATE_FULL;
6420 dev->allocationBlock = -1;
6423 bi->blockState = state;
6425 /* Now let's see if it was dirty */
6426 if (bi->pagesInUse == 0 &&
6427 !bi->hasShrinkHeader &&
6428 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6429 yaffs_BlockBecameDirty(dev, blk);
6435 /* Ok, we've done all the scanning.
6436 * Fix up the hard link chains.
6437 * We should now have scanned all the objects, now it's time to add these
6441 yaffs_HardlinkFixup(dev, hardList);
6443 /* Fix up any shadowed objects */
6445 struct yaffs_ShadowFixerStruct *fixer;
6448 while (shadowFixerList) {
6449 fixer = shadowFixerList;
6450 shadowFixerList = fixer->next;
6451 /* Complete the rename transaction by deleting the shadowed object
6452 * then setting the object header to unshadowed.
6454 obj = yaffs_FindObjectByNumber(dev, fixer->shadowedId);
6456 yaffs_DeleteObject(obj);
6458 obj = yaffs_FindObjectByNumber(dev, fixer->objectId);
6461 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6467 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6472 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
6478 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
6481 yaffs_ObjectHeader *oh;
6483 yaffs_ExtendedTags tags;
6485 int alloc_failed = 0;
6493 T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
6495 in->lazyLoaded ? "not yet" : "already"));
6498 if (in->lazyLoaded && in->hdrChunk > 0) {
6500 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6502 result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
6503 oh = (yaffs_ObjectHeader *) chunkData;
6505 in->yst_mode = oh->yst_mode;
6506 #ifdef CONFIG_YAFFS_WINCE
6507 in->win_atime[0] = oh->win_atime[0];
6508 in->win_ctime[0] = oh->win_ctime[0];
6509 in->win_mtime[0] = oh->win_mtime[0];
6510 in->win_atime[1] = oh->win_atime[1];
6511 in->win_ctime[1] = oh->win_ctime[1];
6512 in->win_mtime[1] = oh->win_mtime[1];
6514 in->yst_uid = oh->yst_uid;
6515 in->yst_gid = oh->yst_gid;
6516 in->yst_atime = oh->yst_atime;
6517 in->yst_mtime = oh->yst_mtime;
6518 in->yst_ctime = oh->yst_ctime;
6519 in->yst_rdev = oh->yst_rdev;
6522 yaffs_SetObjectName(in, oh->name);
6524 if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6525 in->variant.symLinkVariant.alias =
6526 yaffs_CloneString(oh->alias);
6527 if (!in->variant.symLinkVariant.alias)
6528 alloc_failed = 1; /* Not returned to caller */
6531 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6535 static int yaffs_ScanBackwards(yaffs_Device *dev)
6537 yaffs_ExtendedTags tags;
6542 int nBlocksToScan = 0;
6548 yaffs_BlockState state;
6549 yaffs_Object *hardList = NULL;
6550 yaffs_BlockInfo *bi;
6551 __u32 sequenceNumber;
6552 yaffs_ObjectHeader *oh;
6554 yaffs_Object *parent;
6555 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6561 int foundChunksInBlock;
6562 int equivalentObjectId;
6563 int alloc_failed = 0;
6566 yaffs_BlockIndex *blockIndex = NULL;
6567 int altBlockIndex = 0;
6569 if (!dev->param.isYaffs2) {
6571 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6577 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
6578 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6581 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6583 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6586 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6592 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6596 dev->blocksInCheckpoint = 0;
6598 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6600 /* Scan all the blocks to determine their state */
6601 bi = dev->blockInfo;
6602 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6603 yaffs_ClearChunkBits(dev, blk);
6605 bi->softDeletions = 0;
6607 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6609 bi->blockState = state;
6610 bi->sequenceNumber = sequenceNumber;
6612 if (bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6613 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6614 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6615 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6617 T(YAFFS_TRACE_SCAN_DEBUG,
6618 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6619 state, sequenceNumber));
6622 if (state == YAFFS_BLOCK_STATE_CHECKPOINT) {
6623 dev->blocksInCheckpoint++;
6625 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6626 T(YAFFS_TRACE_BAD_BLOCKS,
6627 (TSTR("block %d is bad" TENDSTR), blk));
6628 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6629 T(YAFFS_TRACE_SCAN_DEBUG,
6630 (TSTR("Block empty " TENDSTR)));
6631 dev->nErasedBlocks++;
6632 dev->nFreeChunks += dev->param.nChunksPerBlock;
6633 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6635 /* Determine the highest sequence number */
6636 if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6637 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6639 blockIndex[nBlocksToScan].seq = sequenceNumber;
6640 blockIndex[nBlocksToScan].block = blk;
6644 if (sequenceNumber >= dev->sequenceNumber)
6645 dev->sequenceNumber = sequenceNumber;
6647 /* TODO: Nasty sequence number! */
6650 ("Block scanning block %d has bad sequence number %d"
6651 TENDSTR), blk, sequenceNumber));
6659 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6665 /* Sort the blocks */
6666 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6668 /* Use qsort now. */
6669 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6673 /* Dungy old bubble sort... */
6675 yaffs_BlockIndex temp;
6679 for (i = 0; i < nBlocksToScan; i++)
6680 for (j = i + 1; j < nBlocksToScan; j++)
6681 if (blockIndex[i].seq > blockIndex[j].seq) {
6682 temp = blockIndex[j];
6683 blockIndex[j] = blockIndex[i];
6684 blockIndex[i] = temp;
6691 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6693 /* Now scan the blocks looking at the data. */
6695 endIterator = nBlocksToScan - 1;
6696 T(YAFFS_TRACE_SCAN_DEBUG,
6697 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6699 /* For each block.... backwards */
6700 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6702 /* Cooperative multitasking! This loop can run for so
6703 long that watchdog timers expire. */
6706 /* get the block to scan in the correct order */
6707 blk = blockIndex[blockIterator].block;
6709 bi = yaffs_GetBlockInfo(dev, blk);
6712 state = bi->blockState;
6716 /* For each chunk in each block that needs scanning.... */
6717 foundChunksInBlock = 0;
6718 for (c = dev->param.nChunksPerBlock - 1;
6719 !alloc_failed && c >= 0 &&
6720 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6721 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6722 /* Scan backwards...
6723 * Read the tags and decide what to do
6726 chunk = blk * dev->param.nChunksPerBlock + c;
6728 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6731 /* Let's have a good look at this chunk... */
6733 if (!tags.chunkUsed) {
6734 /* An unassigned chunk in the block.
6735 * If there are used chunks after this one, then
6736 * it is a chunk that was skipped due to failing the erased
6737 * check. Just skip it so that it can be deleted.
6738 * But, more typically, We get here when this is an unallocated
6739 * chunk and his means that either the block is empty or
6740 * this is the one being allocated from
6743 if (foundChunksInBlock) {
6744 /* This is a chunk that was skipped due to failing the erased check */
6745 } else if (c == 0) {
6746 /* We're looking at the first chunk in the block so the block is unused */
6747 state = YAFFS_BLOCK_STATE_EMPTY;
6748 dev->nErasedBlocks++;
6750 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6751 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6752 if (dev->sequenceNumber == bi->sequenceNumber) {
6753 /* this is the block being allocated from */
6757 (" Allocating from %d %d"
6760 state = YAFFS_BLOCK_STATE_ALLOCATING;
6761 dev->allocationBlock = blk;
6762 dev->allocationPage = c;
6763 dev->allocationBlockFinder = blk;
6765 /* This is a partially written block that is not
6766 * the current allocation block.
6770 (TSTR("Partially written block %d detected" TENDSTR),
6778 } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED) {
6780 (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
6785 } else if (tags.chunkId > 0) {
6786 /* chunkId > 0 so it is a data chunk... */
6787 unsigned int endpos;
6789 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6791 foundChunksInBlock = 1;
6794 yaffs_SetChunkBit(dev, blk, c);
6797 in = yaffs_FindOrCreateObjectByNumber(dev,
6800 YAFFS_OBJECT_TYPE_FILE);
6807 in->variantType == YAFFS_OBJECT_TYPE_FILE
6808 && chunkBase < in->variant.fileVariant.shrinkSize) {
6809 /* This has not been invalidated by a resize */
6810 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, -1)) {
6814 /* File size is calculated by looking at the data chunks if we have not
6815 * seen an object header yet. Stop this practice once we find an object header.
6817 endpos = chunkBase + tags.byteCount;
6819 if (!in->valid && /* have not got an object header yet */
6820 in->variant.fileVariant.scannedFileSize < endpos) {
6821 in->variant.fileVariant.scannedFileSize = endpos;
6822 in->variant.fileVariant.fileSize = endpos;
6826 /* This chunk has been invalidated by a resize, or a past file deletion
6827 * so delete the chunk*/
6828 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6832 /* chunkId == 0, so it is an ObjectHeader.
6833 * Thus, we read in the object header and make the object
6835 foundChunksInBlock = 1;
6837 yaffs_SetChunkBit(dev, blk, c);
6843 if (tags.extraHeaderInfoAvailable) {
6844 in = yaffs_FindOrCreateObjectByNumber(dev,
6846 tags.extraObjectType);
6852 (!in->valid && dev->param.disableLazyLoad) ||
6853 tags.extraShadows ||
6855 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6856 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))) {
6858 /* If we don't have valid info then we need to read the chunk
6859 * TODO In future we can probably defer reading the chunk and
6860 * living with invalid data until needed.
6863 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6868 oh = (yaffs_ObjectHeader *) chunkData;
6870 if (dev->param.inbandTags) {
6871 /* Fix up the header if they got corrupted by inband tags */
6872 oh->shadowsObject = oh->inbandShadowsObject;
6873 oh->isShrink = oh->inbandIsShrink;
6877 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6885 /* TODO Hoosterman we have a problem! */
6886 T(YAFFS_TRACE_ERROR,
6888 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6889 TENDSTR), tags.objectId, chunk));
6894 /* We have already filled this one.
6895 * We have a duplicate that will be discarded, but
6896 * we first have to suck out resize info if it is a file.
6899 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6901 oh->type == YAFFS_OBJECT_TYPE_FILE) ||
6902 (tags.extraHeaderInfoAvailable &&
6903 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))) {
6905 (oh) ? oh->fileSize : tags.
6907 __u32 parentObjectId =
6909 parentObjectId : tags.
6910 extraParentObjectId;
6914 (oh) ? oh->isShrink : tags.
6915 extraIsShrinkHeader;
6917 /* If it is deleted (unlinked at start also means deleted)
6918 * we treat the file size as being zeroed at this point.
6920 if (parentObjectId ==
6921 YAFFS_OBJECTID_DELETED
6922 || parentObjectId ==
6923 YAFFS_OBJECTID_UNLINKED) {
6928 if (isShrink && in->variant.fileVariant.shrinkSize > thisSize)
6929 in->variant.fileVariant.shrinkSize = thisSize;
6932 bi->hasShrinkHeader = 1;
6935 /* Use existing - destroy this one. */
6936 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6940 if (!in->valid && in->variantType !=
6941 (oh ? oh->type : tags.extraObjectType))
6942 T(YAFFS_TRACE_ERROR, (
6943 TSTR("yaffs tragedy: Bad object type, "
6944 TCONT("%d != %d, for object %d at chunk ")
6945 TCONT("%d during scan")
6947 oh->type : tags.extraObjectType,
6948 in->variantType, tags.objectId,
6952 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6954 YAFFS_OBJECTID_LOSTNFOUND)) {
6955 /* We only load some info, don't fiddle with directory structure */
6959 in->variantType = oh->type;
6961 in->yst_mode = oh->yst_mode;
6962 #ifdef CONFIG_YAFFS_WINCE
6963 in->win_atime[0] = oh->win_atime[0];
6964 in->win_ctime[0] = oh->win_ctime[0];
6965 in->win_mtime[0] = oh->win_mtime[0];
6966 in->win_atime[1] = oh->win_atime[1];
6967 in->win_ctime[1] = oh->win_ctime[1];
6968 in->win_mtime[1] = oh->win_mtime[1];
6970 in->yst_uid = oh->yst_uid;
6971 in->yst_gid = oh->yst_gid;
6972 in->yst_atime = oh->yst_atime;
6973 in->yst_mtime = oh->yst_mtime;
6974 in->yst_ctime = oh->yst_ctime;
6975 in->yst_rdev = oh->yst_rdev;
6979 in->variantType = tags.extraObjectType;
6983 in->hdrChunk = chunk;
6985 } else if (!in->valid) {
6986 /* we need to load this info */
6989 in->hdrChunk = chunk;
6992 in->variantType = oh->type;
6994 in->yst_mode = oh->yst_mode;
6995 #ifdef CONFIG_YAFFS_WINCE
6996 in->win_atime[0] = oh->win_atime[0];
6997 in->win_ctime[0] = oh->win_ctime[0];
6998 in->win_mtime[0] = oh->win_mtime[0];
6999 in->win_atime[1] = oh->win_atime[1];
7000 in->win_ctime[1] = oh->win_ctime[1];
7001 in->win_mtime[1] = oh->win_mtime[1];
7003 in->yst_uid = oh->yst_uid;
7004 in->yst_gid = oh->yst_gid;
7005 in->yst_atime = oh->yst_atime;
7006 in->yst_mtime = oh->yst_mtime;
7007 in->yst_ctime = oh->yst_ctime;
7008 in->yst_rdev = oh->yst_rdev;
7011 if (oh->shadowsObject > 0)
7012 yaffs_HandleShadowedObject(dev,
7019 yaffs_SetObjectName(in, oh->name);
7021 yaffs_FindOrCreateObjectByNumber
7022 (dev, oh->parentObjectId,
7023 YAFFS_OBJECT_TYPE_DIRECTORY);
7025 fileSize = oh->fileSize;
7026 isShrink = oh->isShrink;
7027 equivalentObjectId = oh->equivalentObjectId;
7030 in->variantType = tags.extraObjectType;
7032 yaffs_FindOrCreateObjectByNumber
7033 (dev, tags.extraParentObjectId,
7034 YAFFS_OBJECT_TYPE_DIRECTORY);
7035 fileSize = tags.extraFileLength;
7036 isShrink = tags.extraIsShrinkHeader;
7037 equivalentObjectId = tags.extraEquivalentObjectId;
7046 /* directory stuff...
7050 if (parent && parent->variantType ==
7051 YAFFS_OBJECT_TYPE_UNKNOWN) {
7052 /* Set up as a directory */
7053 parent->variantType =
7054 YAFFS_OBJECT_TYPE_DIRECTORY;
7055 YINIT_LIST_HEAD(&parent->variant.
7058 } else if (!parent || parent->variantType !=
7059 YAFFS_OBJECT_TYPE_DIRECTORY) {
7060 /* Hoosterman, another problem....
7061 * We're trying to use a non-directory as a directory
7064 T(YAFFS_TRACE_ERROR,
7066 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
7068 parent = dev->lostNFoundDir;
7071 yaffs_AddObjectToDirectory(parent, in);
7073 itsUnlinked = (parent == dev->deletedDir) ||
7074 (parent == dev->unlinkedDir);
7077 /* Mark the block as having a shrinkHeader */
7078 bi->hasShrinkHeader = 1;
7081 /* Note re hardlinks.
7082 * Since we might scan a hardlink before its equivalent object is scanned
7083 * we put them all in a list.
7084 * After scanning is complete, we should have all the objects, so we run
7085 * through this list and fix up all the chains.
7088 switch (in->variantType) {
7089 case YAFFS_OBJECT_TYPE_UNKNOWN:
7090 /* Todo got a problem */
7092 case YAFFS_OBJECT_TYPE_FILE:
7094 if (in->variant.fileVariant.
7095 scannedFileSize < fileSize) {
7096 /* This covers the case where the file size is greater
7097 * than where the data is
7098 * This will happen if the file is resized to be larger
7099 * than its current data extents.
7101 in->variant.fileVariant.fileSize = fileSize;
7102 in->variant.fileVariant.scannedFileSize = fileSize;
7105 if (in->variant.fileVariant.shrinkSize > fileSize)
7106 in->variant.fileVariant.shrinkSize = fileSize;
7110 case YAFFS_OBJECT_TYPE_HARDLINK:
7112 in->variant.hardLinkVariant.equivalentObjectId =
7114 in->hardLinks.next =
7115 (struct ylist_head *) hardList;
7119 case YAFFS_OBJECT_TYPE_DIRECTORY:
7122 case YAFFS_OBJECT_TYPE_SPECIAL:
7125 case YAFFS_OBJECT_TYPE_SYMLINK:
7127 in->variant.symLinkVariant.alias =
7128 yaffs_CloneString(oh->alias);
7129 if (!in->variant.symLinkVariant.alias)
7139 } /* End of scanning for each chunk */
7141 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
7142 /* If we got this far while scanning, then the block is fully allocated. */
7143 state = YAFFS_BLOCK_STATE_FULL;
7147 bi->blockState = state;
7149 /* Now let's see if it was dirty */
7150 if (bi->pagesInUse == 0 &&
7151 !bi->hasShrinkHeader &&
7152 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
7153 yaffs_BlockBecameDirty(dev, blk);
7158 yaffs_SkipRestOfBlock(dev);
7161 YFREE_ALT(blockIndex);
7165 /* Ok, we've done all the scanning.
7166 * Fix up the hard link chains.
7167 * We should now have scanned all the objects, now it's time to add these
7170 yaffs_HardlinkFixup(dev, hardList);
7173 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
7178 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
7183 /*------------------------------ Directory Functions ----------------------------- */
7185 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
7187 struct ylist_head *lh;
7188 yaffs_Object *listObj;
7193 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
7198 if (yaffs_SkipVerification(obj->myDev))
7202 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
7207 if (obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7208 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
7212 /* Iterate through the objects in each hash entry */
7214 ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
7216 listObj = ylist_entry(lh, yaffs_Object, siblings);
7217 yaffs_VerifyObject(listObj);
7224 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR), count));
7229 static void yaffs_VerifyDirectory(yaffs_Object *directory)
7231 struct ylist_head *lh;
7232 yaffs_Object *listObj;
7239 if (yaffs_SkipFullVerification(directory->myDev))
7242 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7243 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR), directory->variantType));
7247 /* Iterate through the objects in each hash entry */
7249 ylist_for_each(lh, &directory->variant.directoryVariant.children) {
7251 listObj = ylist_entry(lh, yaffs_Object, siblings);
7252 if (listObj->parent != directory) {
7253 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR), listObj->parent));
7256 yaffs_VerifyObjectInDirectory(listObj);
7262 *yaffs_UpdateParent() handles fixing a directories mtime and ctime when a new
7263 * link (ie. name) is created or deleted in the directory.
7266 * create dir/a : update dir's mtime/ctime
7267 * rm dir/a: update dir's mtime/ctime
7268 * modify dir/a: don't update dir's mtimme/ctime
7270 * This can be handled immediately or defered. Defering helps reduce the number
7271 * of updates when many files in a directory are changed within a brief period.
7273 * If the directory updating is defered then yaffs_UpdateDirtyDirecories must be
7274 * called periodically.
7277 static void yaffs_UpdateParent(yaffs_Object *obj)
7285 obj->yst_mtime = obj->yst_ctime = Y_CURRENT_TIME;
7286 if(dev->param.deferDirectoryUpdate){
7287 struct ylist_head *link = &obj->variant.directoryVariant.dirty;
7289 if(ylist_empty(link)){
7290 ylist_add(link,&dev->dirtyDirectories);
7291 T(YAFFS_TRACE_BACKGROUND, (TSTR("Added object %d to dirty directories" TENDSTR),obj->objectId));
7295 yaffs_UpdateObjectHeader(obj,NULL,0,0,0);
7298 void yaffs_UpdateDirtyDirectories(yaffs_Device *dev)
7300 struct ylist_head *link;
7302 yaffs_DirectoryStructure *dS;
7303 yaffs_ObjectVariant *oV;
7305 T(YAFFS_TRACE_BACKGROUND, (TSTR("Update dirty directories" TENDSTR)));
7307 while(!ylist_empty(&dev->dirtyDirectories)){
7308 link = dev->dirtyDirectories.next;
7309 ylist_del_init(link);
7311 dS=ylist_entry(link,yaffs_DirectoryStructure,dirty);
7312 oV = ylist_entry(dS,yaffs_ObjectVariant,directoryVariant);
7313 obj = ylist_entry(oV,yaffs_Object,variant);
7315 T(YAFFS_TRACE_BACKGROUND, (TSTR("Update directory %d" TENDSTR), obj->objectId));
7318 yaffs_UpdateObjectHeader(obj,NULL,0,0,0);
7322 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
7324 yaffs_Device *dev = obj->myDev;
7325 yaffs_Object *parent;
7327 yaffs_VerifyObjectInDirectory(obj);
7328 parent = obj->parent;
7330 yaffs_VerifyDirectory(parent);
7332 if (dev && dev->param.removeObjectCallback)
7333 dev->param.removeObjectCallback(obj);
7336 ylist_del_init(&obj->siblings);
7339 yaffs_VerifyDirectory(parent);
7342 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
7346 T(YAFFS_TRACE_ALWAYS,
7348 ("tragedy: Trying to add an object to a null pointer directory"
7353 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7354 T(YAFFS_TRACE_ALWAYS,
7356 ("tragedy: Trying to add an object to a non-directory"
7361 if (obj->siblings.prev == NULL) {
7362 /* Not initialised */
7367 yaffs_VerifyDirectory(directory);
7369 yaffs_RemoveObjectFromDirectory(obj);
7373 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
7374 obj->parent = directory;
7376 if (directory == obj->myDev->unlinkedDir
7377 || directory == obj->myDev->deletedDir) {
7379 obj->myDev->nUnlinkedFiles++;
7380 obj->renameAllowed = 0;
7383 yaffs_VerifyDirectory(directory);
7384 yaffs_VerifyObjectInDirectory(obj);
7387 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
7392 struct ylist_head *i;
7393 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
7401 T(YAFFS_TRACE_ALWAYS,
7403 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7408 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7409 T(YAFFS_TRACE_ALWAYS,
7411 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7415 sum = yaffs_CalcNameSum(name);
7417 ylist_for_each(i, &directory->variant.directoryVariant.children) {
7419 l = ylist_entry(i, yaffs_Object, siblings);
7421 if (l->parent != directory)
7424 yaffs_CheckObjectDetailsLoaded(l);
7426 /* Special case for lost-n-found */
7427 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7428 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
7430 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
7431 /* LostnFound chunk called Objxxx
7434 yaffs_GetObjectName(l, buffer,
7435 YAFFS_MAX_NAME_LENGTH + 1);
7436 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
7447 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
7448 int (*fn) (yaffs_Object *))
7450 struct ylist_head *i;
7454 T(YAFFS_TRACE_ALWAYS,
7456 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7461 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7462 T(YAFFS_TRACE_ALWAYS,
7464 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7469 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
7471 l = ylist_entry(i, yaffs_Object, siblings);
7482 /* GetEquivalentObject dereferences any hard links to get to the
7486 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
7488 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
7489 /* We want the object id of the equivalent object, not this one */
7490 obj = obj->variant.hardLinkVariant.equivalentObject;
7491 yaffs_CheckObjectDetailsLoaded(obj);
7496 int yaffs_GetObjectName(yaffs_Object *obj, YCHAR *name, int buffSize)
7498 memset(name, 0, buffSize * sizeof(YCHAR));
7500 yaffs_CheckObjectDetailsLoaded(obj);
7502 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7503 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
7504 } else if (obj->hdrChunk <= 0) {
7506 YCHAR numString[20];
7507 YCHAR *x = &numString[19];
7508 unsigned v = obj->objectId;
7512 *x = '0' + (v % 10);
7515 /* make up a name */
7516 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
7517 yaffs_strcat(locName, x);
7518 yaffs_strncpy(name, locName, buffSize - 1);
7521 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
7522 else if (obj->shortName[0])
7523 yaffs_strncpy(name, obj->shortName,YAFFS_SHORT_NAME_LENGTH+1);
7527 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
7529 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
7531 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
7533 if (obj->hdrChunk > 0) {
7534 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
7535 obj->hdrChunk, buffer,
7538 yaffs_strncpy(name, oh->name, buffSize - 1);
7541 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
7544 return yaffs_strnlen(name,buffSize-1);
7547 int yaffs_GetObjectFileLength(yaffs_Object *obj)
7549 /* Dereference any hard linking */
7550 obj = yaffs_GetEquivalentObject(obj);
7552 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
7553 return obj->variant.fileVariant.fileSize;
7554 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
7555 if(!obj->variant.symLinkVariant.alias)
7557 return yaffs_strnlen(obj->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
7559 /* Only a directory should drop through to here */
7560 return obj->myDev->nDataBytesPerChunk;
7564 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
7567 struct ylist_head *i;
7570 count++; /* the object itself */
7572 ylist_for_each(i, &obj->hardLinks)
7573 count++; /* add the hard links; */
7578 int yaffs_GetObjectInode(yaffs_Object *obj)
7580 obj = yaffs_GetEquivalentObject(obj);
7582 return obj->objectId;
7585 unsigned yaffs_GetObjectType(yaffs_Object *obj)
7587 obj = yaffs_GetEquivalentObject(obj);
7589 switch (obj->variantType) {
7590 case YAFFS_OBJECT_TYPE_FILE:
7593 case YAFFS_OBJECT_TYPE_DIRECTORY:
7596 case YAFFS_OBJECT_TYPE_SYMLINK:
7599 case YAFFS_OBJECT_TYPE_HARDLINK:
7602 case YAFFS_OBJECT_TYPE_SPECIAL:
7603 if (S_ISFIFO(obj->yst_mode))
7605 if (S_ISCHR(obj->yst_mode))
7607 if (S_ISBLK(obj->yst_mode))
7609 if (S_ISSOCK(obj->yst_mode))
7617 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
7619 obj = yaffs_GetEquivalentObject(obj);
7620 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
7621 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7623 return yaffs_CloneString(_Y(""));
7626 #ifndef CONFIG_YAFFS_WINCE
7628 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
7630 unsigned int valid = attr->ia_valid;
7632 if (valid & ATTR_MODE)
7633 obj->yst_mode = attr->ia_mode;
7634 if (valid & ATTR_UID)
7635 obj->yst_uid = attr->ia_uid;
7636 if (valid & ATTR_GID)
7637 obj->yst_gid = attr->ia_gid;
7639 if (valid & ATTR_ATIME)
7640 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7641 if (valid & ATTR_CTIME)
7642 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7643 if (valid & ATTR_MTIME)
7644 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7646 if (valid & ATTR_SIZE)
7647 yaffs_ResizeFile(obj, attr->ia_size);
7649 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7654 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
7656 unsigned int valid = 0;
7658 attr->ia_mode = obj->yst_mode;
7660 attr->ia_uid = obj->yst_uid;
7662 attr->ia_gid = obj->yst_gid;
7665 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7666 valid |= ATTR_ATIME;
7667 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7668 valid |= ATTR_CTIME;
7669 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7670 valid |= ATTR_MTIME;
7672 attr->ia_size = yaffs_GetFileSize(obj);
7675 attr->ia_valid = valid;
7683 int yaffs_DumpObject(yaffs_Object *obj)
7687 yaffs_GetObjectName(obj, name, YAFFS_MAX_NAME_LENGTH + 1);
7689 T(YAFFS_TRACE_ALWAYS,
7691 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7692 " chunk %d type %d size %d\n"
7693 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7694 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7695 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7701 /*---------------------------- Initialisation code -------------------------------------- */
7703 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
7706 /* Common functions, gotta have */
7707 if (!dev->param.eraseBlockInNAND || !dev->param.initialiseNAND)
7710 #ifdef CONFIG_YAFFS_YAFFS2
7712 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7713 if (dev->param.writeChunkWithTagsToNAND &&
7714 dev->param.readChunkWithTagsFromNAND &&
7715 !dev->param.writeChunkToNAND &&
7716 !dev->param.readChunkFromNAND &&
7717 dev->param.markNANDBlockBad &&
7718 dev->param.queryNANDBlock)
7722 /* Can use the "spare" style interface for yaffs1 */
7723 if (!dev->param.isYaffs2 &&
7724 !dev->param.writeChunkWithTagsToNAND &&
7725 !dev->param.readChunkWithTagsFromNAND &&
7726 dev->param.writeChunkToNAND &&
7727 dev->param.readChunkFromNAND &&
7728 !dev->param.markNANDBlockBad &&
7729 !dev->param.queryNANDBlock)
7736 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7738 /* Initialise the unlinked, deleted, root and lost and found directories */
7740 dev->lostNFoundDir = dev->rootDir = NULL;
7741 dev->unlinkedDir = dev->deletedDir = NULL;
7744 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7747 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7750 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7751 YAFFS_ROOT_MODE | S_IFDIR);
7752 dev->lostNFoundDir =
7753 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7754 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7756 if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
7757 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7764 int yaffs_GutsInitialise(yaffs_Device *dev)
7766 int init_failed = 0;
7770 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7772 /* Check stuff that must be set */
7775 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7779 dev->internalStartBlock = dev->param.startBlock;
7780 dev->internalEndBlock = dev->param.endBlock;
7781 dev->blockOffset = 0;
7782 dev->chunkOffset = 0;
7783 dev->nFreeChunks = 0;
7787 if (dev->param.startBlock == 0) {
7788 dev->internalStartBlock = dev->param.startBlock + 1;
7789 dev->internalEndBlock = dev->param.endBlock + 1;
7790 dev->blockOffset = 1;
7791 dev->chunkOffset = dev->param.nChunksPerBlock;
7794 /* Check geometry parameters. */
7796 if ((!dev->param.inbandTags && dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 1024) ||
7797 (!dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 512) ||
7798 (dev->param.inbandTags && !dev->param.isYaffs2) ||
7799 dev->param.nChunksPerBlock < 2 ||
7800 dev->param.nReservedBlocks < 2 ||
7801 dev->internalStartBlock <= 0 ||
7802 dev->internalEndBlock <= 0 ||
7803 dev->internalEndBlock <= (dev->internalStartBlock + dev->param.nReservedBlocks + 2)) { /* otherwise it is too small */
7804 T(YAFFS_TRACE_ALWAYS,
7806 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7807 TENDSTR), dev->param.totalBytesPerChunk, dev->param.isYaffs2 ? "2" : "", dev->param.inbandTags));
7811 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7812 T(YAFFS_TRACE_ALWAYS,
7813 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7817 /* Sort out space for inband tags, if required */
7818 if (dev->param.inbandTags)
7819 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7821 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk;
7823 /* Got the right mix of functions? */
7824 if (!yaffs_CheckDevFunctions(dev)) {
7825 /* Function missing */
7826 T(YAFFS_TRACE_ALWAYS,
7828 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7833 /* This is really a compilation check. */
7834 if (!yaffs_CheckStructures()) {
7835 T(YAFFS_TRACE_ALWAYS,
7836 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7840 if (dev->isMounted) {
7841 T(YAFFS_TRACE_ALWAYS,
7842 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7846 /* Finished with most checks. One or two more checks happen later on too. */
7850 /* OK now calculate a few things for the device */
7853 * Calculate all the chunk size manipulation numbers:
7855 x = dev->nDataBytesPerChunk;
7856 /* We always use dev->chunkShift and dev->chunkDiv */
7857 dev->chunkShift = Shifts(x);
7858 x >>= dev->chunkShift;
7860 /* We only use chunk mask if chunkDiv is 1 */
7861 dev->chunkMask = (1<<dev->chunkShift) - 1;
7864 * Calculate chunkGroupBits.
7865 * We need to find the next power of 2 > than internalEndBlock
7868 x = dev->param.nChunksPerBlock * (dev->internalEndBlock + 1);
7872 /* Set up tnode width if wide tnodes are enabled. */
7873 if (!dev->param.wideTnodesDisabled) {
7874 /* bits must be even so that we end up with 32-bit words */
7878 dev->tnodeWidth = 16;
7880 dev->tnodeWidth = bits;
7882 dev->tnodeWidth = 16;
7884 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7886 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7887 * so if the bitwidth of the
7888 * chunk range we're using is greater than 16 we need
7889 * to figure out chunk shift and chunkGroupSize
7892 if (bits <= dev->tnodeWidth)
7893 dev->chunkGroupBits = 0;
7895 dev->chunkGroupBits = bits - dev->tnodeWidth;
7898 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7900 if (dev->param.nChunksPerBlock < dev->chunkGroupSize) {
7901 /* We have a problem because the soft delete won't work if
7902 * the chunk group size > chunks per block.
7903 * This can be remedied by using larger "virtual blocks".
7905 T(YAFFS_TRACE_ALWAYS,
7906 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7911 /* OK, we've finished verifying the device, lets continue with initialisation */
7913 /* More device initialisation */
7915 dev->passiveGCs = 0;
7916 dev->oldestDirtyGCs = 0;
7917 dev->backgroundGCs = 0;
7918 dev->gcBlockFinder = 0;
7919 dev->bufferedBlock = -1;
7920 dev->doingBufferedBlockRewrite = 0;
7921 dev->nDeletedFiles = 0;
7922 dev->nBackgroundDeletions = 0;
7923 dev->nUnlinkedFiles = 0;
7925 dev->eccUnfixed = 0;
7926 dev->tagsEccFixed = 0;
7927 dev->tagsEccUnfixed = 0;
7928 dev->nErasureFailures = 0;
7929 dev->nErasedBlocks = 0;
7931 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7932 YINIT_LIST_HEAD(&dev->dirtyDirectories);
7933 dev->oldestDirtySequence = 0;
7934 dev->oldestDirtyBlock = 0;
7936 /* Initialise temporary buffers and caches. */
7937 if (!yaffs_InitialiseTempBuffers(dev))
7940 dev->srCache = NULL;
7941 dev->gcCleanupList = NULL;
7945 dev->param.nShortOpCaches > 0) {
7948 int srCacheBytes = dev->param.nShortOpCaches * sizeof(yaffs_ChunkCache);
7950 if (dev->param.nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
7951 dev->param.nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7953 dev->srCache = YMALLOC(srCacheBytes);
7955 buf = (__u8 *) dev->srCache;
7958 memset(dev->srCache, 0, srCacheBytes);
7960 for (i = 0; i < dev->param.nShortOpCaches && buf; i++) {
7961 dev->srCache[i].object = NULL;
7962 dev->srCache[i].lastUse = 0;
7963 dev->srCache[i].dirty = 0;
7964 dev->srCache[i].data = buf = YMALLOC_DMA(dev->param.totalBytesPerChunk);
7975 dev->gcCleanupList = YMALLOC(dev->param.nChunksPerBlock * sizeof(__u32));
7976 if (!dev->gcCleanupList)
7980 if (dev->param.isYaffs2)
7981 dev->param.useHeaderFileSize = 1;
7983 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7986 yaffs_InitialiseTnodes(dev);
7987 yaffs_InitialiseObjects(dev);
7989 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7994 /* Now scan the flash. */
7995 if (dev->param.isYaffs2) {
7996 if (yaffs_CheckpointRestore(dev)) {
7997 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7998 T(YAFFS_TRACE_ALWAYS,
7999 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
8002 /* Clean up the mess caused by an aborted checkpoint load
8003 * and scan backwards.
8005 yaffs_DeinitialiseBlocks(dev);
8006 yaffs_DeinitialiseTnodes(dev);
8007 yaffs_DeinitialiseObjects(dev);
8010 dev->nErasedBlocks = 0;
8011 dev->nFreeChunks = 0;
8012 dev->allocationBlock = -1;
8013 dev->allocationPage = -1;
8014 dev->nDeletedFiles = 0;
8015 dev->nUnlinkedFiles = 0;
8016 dev->nBackgroundDeletions = 0;
8018 if (!init_failed && !yaffs_InitialiseBlocks(dev))
8021 yaffs_InitialiseTnodes(dev);
8022 yaffs_InitialiseObjects(dev);
8024 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
8027 if (!init_failed && !yaffs_ScanBackwards(dev))
8030 } else if (!yaffs_Scan(dev))
8033 yaffs_StripDeletedObjects(dev);
8034 yaffs_FixHangingObjects(dev);
8035 if(dev->param.emptyLostAndFound)
8036 yaffs_EmptyLostAndFound(dev);
8040 /* Clean up the mess */
8041 T(YAFFS_TRACE_TRACING,
8042 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
8044 yaffs_Deinitialise(dev);
8048 /* Zero out stats */
8049 dev->nPageReads = 0;
8050 dev->nPageWrites = 0;
8051 dev->nBlockErasures = 0;
8053 dev->nRetriedWrites = 0;
8055 dev->nRetiredBlocks = 0;
8057 yaffs_VerifyFreeChunks(dev);
8058 yaffs_VerifyBlocks(dev);
8060 /* Clean up any aborted checkpoint data */
8061 if(!dev->isCheckpointed && dev->blocksInCheckpoint > 0)
8062 yaffs_InvalidateCheckpoint(dev);
8064 T(YAFFS_TRACE_TRACING,
8065 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
8070 void yaffs_Deinitialise(yaffs_Device *dev)
8072 if (dev->isMounted) {
8075 yaffs_DeinitialiseBlocks(dev);
8076 yaffs_DeinitialiseTnodes(dev);
8077 yaffs_DeinitialiseObjects(dev);
8078 if (dev->param.nShortOpCaches > 0 &&
8081 for (i = 0; i < dev->param.nShortOpCaches; i++) {
8082 if (dev->srCache[i].data)
8083 YFREE(dev->srCache[i].data);
8084 dev->srCache[i].data = NULL;
8087 YFREE(dev->srCache);
8088 dev->srCache = NULL;
8091 YFREE(dev->gcCleanupList);
8093 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
8094 YFREE(dev->tempBuffer[i].buffer);
8098 if (dev->param.deinitialiseNAND)
8099 dev->param.deinitialiseNAND(dev);
8103 static int yaffs_CountFreeChunks(yaffs_Device *dev)
8108 yaffs_BlockInfo *blk;
8110 blk = dev->blockInfo;
8111 for (b = dev->internalStartBlock; b <= dev->internalEndBlock; b++) {
8112 switch (blk->blockState) {
8113 case YAFFS_BLOCK_STATE_EMPTY:
8114 case YAFFS_BLOCK_STATE_ALLOCATING:
8115 case YAFFS_BLOCK_STATE_COLLECTING:
8116 case YAFFS_BLOCK_STATE_FULL:
8118 (dev->param.nChunksPerBlock - blk->pagesInUse +
8119 blk->softDeletions);
8130 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
8132 /* This is what we report to the outside world */
8135 int nDirtyCacheChunks;
8136 int blocksForCheckpoint;
8140 nFree = dev->nFreeChunks;
8142 nFree = yaffs_CountFreeChunks(dev);
8145 nFree += dev->nDeletedFiles;
8147 /* Now count the number of dirty chunks in the cache and subtract those */
8149 for (nDirtyCacheChunks = 0, i = 0; i < dev->param.nShortOpCaches; i++) {
8150 if (dev->srCache[i].dirty)
8151 nDirtyCacheChunks++;
8154 nFree -= nDirtyCacheChunks;
8156 nFree -= ((dev->param.nReservedBlocks + 1) * dev->param.nChunksPerBlock);
8158 /* Now we figure out how much to reserve for the checkpoint and report that... */
8159 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
8160 if (blocksForCheckpoint < 0)
8161 blocksForCheckpoint = 0;
8163 nFree -= (blocksForCheckpoint * dev->param.nChunksPerBlock);
8172 static int yaffs_freeVerificationFailures;
8174 static void yaffs_VerifyFreeChunks(yaffs_Device *dev)
8179 if (yaffs_SkipVerification(dev))
8182 counted = yaffs_CountFreeChunks(dev);
8184 difference = dev->nFreeChunks - counted;
8187 T(YAFFS_TRACE_ALWAYS,
8188 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
8189 dev->nFreeChunks, counted, difference));
8190 yaffs_freeVerificationFailures++;
8194 /*---------------------------------------- YAFFS test code ----------------------*/
8196 #define yaffs_CheckStruct(structure, syze, name) \
8198 if (sizeof(structure) != syze) { \
8199 T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
8200 name, syze, (int) sizeof(structure))); \
8201 return YAFFS_FAIL; \
8205 static int yaffs_CheckStructures(void)
8207 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
8208 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
8209 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
8210 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
8211 /* yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode"); */
8213 #ifndef CONFIG_YAFFS_WINCE
8214 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");