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
36 #define YAFFS_SMALL_HOLE_THRESHOLD 3
38 #include "yaffs_ecc.h"
41 /* Robustification (if it ever comes about...) */
42 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND);
43 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
45 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
47 const yaffs_ExtendedTags *tags);
48 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
49 const yaffs_ExtendedTags *tags);
51 /* Other local prototypes */
52 static void yaffs_UpdateParent(yaffs_Object *obj);
53 static int yaffs_UnlinkObject(yaffs_Object *obj);
54 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
56 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
58 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev,
60 yaffs_ExtendedTags *tags,
62 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
63 int chunkInNAND, int inScan);
65 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
66 yaffs_ObjectType type);
67 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
69 static int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name,
70 int force, int isShrink, int shadows);
71 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
72 static int yaffs_CheckStructures(void);
73 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
74 int chunkOffset, int *limit);
75 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
77 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev, int blockNo);
80 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
83 static int yaffs_UnlinkWorker(yaffs_Object *obj);
85 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
88 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
89 yaffs_BlockInfo **blockUsedPtr);
91 static void yaffs_VerifyFreeChunks(yaffs_Device *dev);
93 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
95 static void yaffs_VerifyDirectory(yaffs_Object *directory);
97 static int yaffs_CheckFileSanity(yaffs_Object *in);
99 #define yaffs_CheckFileSanity(in)
102 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
103 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
105 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
107 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
108 yaffs_ExtendedTags *tags);
110 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
112 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
113 yaffs_FileStructure *fStruct,
116 static int yaffs_HandleHole(yaffs_Object *obj, loff_t newSize);
117 static void yaffs_SkipRestOfBlock(yaffs_Device *dev);
118 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
121 yaffs_ExtendedTags *tags);
123 /* Function to calculate chunk and offset */
125 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut,
131 chunk = (__u32)(addr >> dev->chunkShift);
133 if (dev->chunkDiv == 1) {
134 /* easy power of 2 case */
135 offset = (__u32)(addr & dev->chunkMask);
137 /* Non power-of-2 case */
141 chunk /= dev->chunkDiv;
143 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
144 offset = (__u32)(addr - chunkBase);
151 /* Function to return the number of shifts for a power of 2 greater than or
152 * equal to the given number
153 * Note we don't try to cater for all possible numbers and this does not have to
154 * be hellishly efficient.
157 static __u32 ShiftsGE(__u32 x)
162 nShifts = extraBits = 0;
177 /* Function to return the number of shifts to get a 1 in bit 0
180 static __u32 Shifts(__u32 x)
200 * Temporary buffer manipulations.
203 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
206 __u8 *buf = (__u8 *)1;
208 memset(dev->tempBuffer, 0, sizeof(dev->tempBuffer));
210 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
211 dev->tempBuffer[i].line = 0; /* not in use */
212 dev->tempBuffer[i].buffer = buf =
213 YMALLOC_DMA(dev->param.totalBytesPerChunk);
216 return buf ? YAFFS_OK : YAFFS_FAIL;
219 __u8 *yaffs_GetTempBuffer(yaffs_Device *dev, int lineNo)
224 if (dev->tempInUse > dev->maxTemp)
225 dev->maxTemp = dev->tempInUse;
227 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
228 if (dev->tempBuffer[i].line == 0) {
229 dev->tempBuffer[i].line = lineNo;
230 if ((i + 1) > dev->maxTemp) {
231 dev->maxTemp = i + 1;
232 for (j = 0; j <= i; j++)
233 dev->tempBuffer[j].maxLine =
234 dev->tempBuffer[j].line;
237 return dev->tempBuffer[i].buffer;
241 T(YAFFS_TRACE_BUFFERS,
242 (TSTR("Out of temp buffers at line %d, other held by lines:"),
244 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
245 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
247 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
250 * If we got here then we have to allocate an unmanaged one
254 dev->unmanagedTempAllocations++;
255 return YMALLOC(dev->nDataBytesPerChunk);
259 void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer,
266 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
267 if (dev->tempBuffer[i].buffer == buffer) {
268 dev->tempBuffer[i].line = 0;
274 /* assume it is an unmanaged one. */
275 T(YAFFS_TRACE_BUFFERS,
276 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
279 dev->unmanagedTempDeallocations++;
285 * Determine if we have a managed buffer.
287 int yaffs_IsManagedTempBuffer(yaffs_Device *dev, const __u8 *buffer)
291 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
292 if (dev->tempBuffer[i].buffer == buffer)
296 for (i = 0; i < dev->param.nShortOpCaches; i++) {
297 if (dev->srCache[i].data == buffer)
301 if (buffer == dev->checkpointBuffer)
304 T(YAFFS_TRACE_ALWAYS,
305 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
312 * Chunk bitmap manipulations
315 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
317 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
319 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
323 return dev->chunkBits +
324 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
327 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
329 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
330 chunk < 0 || chunk >= dev->param.nChunksPerBlock) {
332 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),
338 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device *dev, int blk)
340 __u8 *blkBits = yaffs_BlockBits(dev, blk);
342 memset(blkBits, 0, dev->chunkBitmapStride);
345 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device *dev, int blk, int chunk)
347 __u8 *blkBits = yaffs_BlockBits(dev, blk);
349 yaffs_VerifyChunkBitId(dev, blk, chunk);
351 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
354 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device *dev, int blk, int chunk)
356 __u8 *blkBits = yaffs_BlockBits(dev, blk);
358 yaffs_VerifyChunkBitId(dev, blk, chunk);
360 blkBits[chunk / 8] |= (1 << (chunk & 7));
363 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device *dev, int blk, int chunk)
365 __u8 *blkBits = yaffs_BlockBits(dev, blk);
366 yaffs_VerifyChunkBitId(dev, blk, chunk);
368 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
371 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device *dev, int blk)
373 __u8 *blkBits = yaffs_BlockBits(dev, blk);
375 for (i = 0; i < dev->chunkBitmapStride; i++) {
383 static int yaffs_CountChunkBits(yaffs_Device *dev, int blk)
385 __u8 *blkBits = yaffs_BlockBits(dev, blk);
388 for (i = 0; i < dev->chunkBitmapStride; i++) {
405 static int yaffs_SkipVerification(yaffs_Device *dev)
408 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
411 static int yaffs_SkipFullVerification(yaffs_Device *dev)
414 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
417 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
420 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
423 static const char *blockStateName[] = {
436 static void yaffs_VerifyBlock(yaffs_Device *dev, yaffs_BlockInfo *bi, int n)
441 if (yaffs_SkipVerification(dev))
444 /* Report illegal runtime states */
445 if (bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
446 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has undefined state %d"TENDSTR), n, bi->blockState));
448 switch (bi->blockState) {
449 case YAFFS_BLOCK_STATE_UNKNOWN:
450 case YAFFS_BLOCK_STATE_SCANNING:
451 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
452 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has bad run-state %s"TENDSTR),
453 n, blockStateName[bi->blockState]));
456 /* Check pages in use and soft deletions are legal */
458 actuallyUsed = bi->pagesInUse - bi->softDeletions;
460 if (bi->pagesInUse < 0 || bi->pagesInUse > dev->param.nChunksPerBlock ||
461 bi->softDeletions < 0 || bi->softDeletions > dev->param.nChunksPerBlock ||
462 actuallyUsed < 0 || actuallyUsed > dev->param.nChunksPerBlock)
463 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
464 n, bi->pagesInUse, bi->softDeletions));
467 /* Check chunk bitmap legal */
468 inUse = yaffs_CountChunkBits(dev, n);
469 if (inUse != bi->pagesInUse)
470 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
471 n, bi->pagesInUse, inUse));
473 /* Check that the sequence number is valid.
474 * Ten million is legal, but is very unlikely
476 if (dev->param.isYaffs2 &&
477 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
478 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000))
479 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has suspect sequence number of %d"TENDSTR),
480 n, bi->sequenceNumber));
483 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev, yaffs_BlockInfo *bi,
486 yaffs_VerifyBlock(dev, bi, n);
488 /* After collection the block should be in the erased state */
489 /* This will need to change if we do partial gc */
491 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
492 bi->blockState != YAFFS_BLOCK_STATE_EMPTY) {
493 T(YAFFS_TRACE_ERROR, (TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
498 static void yaffs_VerifyBlocks(yaffs_Device *dev)
501 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
502 int nIllegalBlockStates = 0;
504 if (yaffs_SkipVerification(dev))
507 memset(nBlocksPerState, 0, sizeof(nBlocksPerState));
509 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
510 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, i);
511 yaffs_VerifyBlock(dev, bi, i);
513 if (bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
514 nBlocksPerState[bi->blockState]++;
516 nIllegalBlockStates++;
519 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
520 T(YAFFS_TRACE_VERIFY, (TSTR("Block summary"TENDSTR)));
522 T(YAFFS_TRACE_VERIFY, (TSTR("%d blocks have illegal states"TENDSTR), nIllegalBlockStates));
523 if (nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
524 T(YAFFS_TRACE_VERIFY, (TSTR("Too many allocating blocks"TENDSTR)));
526 for (i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
527 T(YAFFS_TRACE_VERIFY,
528 (TSTR("%s %d blocks"TENDSTR),
529 blockStateName[i], nBlocksPerState[i]));
531 if (dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
532 T(YAFFS_TRACE_VERIFY,
533 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
534 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
536 if (dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
537 T(YAFFS_TRACE_VERIFY,
538 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
539 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
541 if (nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
542 T(YAFFS_TRACE_VERIFY,
543 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
544 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
546 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
551 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
552 * case those tests will not be performed.
554 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
556 if (obj && yaffs_SkipVerification(obj->myDev))
559 if (!(tags && obj && oh)) {
560 T(YAFFS_TRACE_VERIFY,
561 (TSTR("Verifying object header tags %p obj %p oh %p"TENDSTR),
566 if (oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
567 oh->type > YAFFS_OBJECT_TYPE_MAX)
568 T(YAFFS_TRACE_VERIFY,
569 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
570 tags->objectId, oh->type));
572 if (tags->objectId != obj->objectId)
573 T(YAFFS_TRACE_VERIFY,
574 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
575 tags->objectId, obj->objectId));
579 * Check that the object's parent ids match if parentCheck requested.
581 * Tests do not apply to the root object.
584 if (parentCheck && tags->objectId > 1 && !obj->parent)
585 T(YAFFS_TRACE_VERIFY,
586 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
587 tags->objectId, oh->parentObjectId));
589 if (parentCheck && obj->parent &&
590 oh->parentObjectId != obj->parent->objectId &&
591 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
592 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
593 T(YAFFS_TRACE_VERIFY,
594 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
595 tags->objectId, oh->parentObjectId, obj->parent->objectId));
597 if (tags->objectId > 1 && oh->name[0] == 0) /* Null name */
598 T(YAFFS_TRACE_VERIFY,
599 (TSTR("Obj %d header name is NULL"TENDSTR),
602 if (tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
603 T(YAFFS_TRACE_VERIFY,
604 (TSTR("Obj %d header name is 0xFF"TENDSTR),
610 static int yaffs_VerifyTnodeWorker(yaffs_Object *obj, yaffs_Tnode *tn,
611 __u32 level, int chunkOffset)
614 yaffs_Device *dev = obj->myDev;
620 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
621 if (tn->internal[i]) {
622 ok = yaffs_VerifyTnodeWorker(obj,
625 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
628 } else if (level == 0) {
629 yaffs_ExtendedTags tags;
630 __u32 objectId = obj->objectId;
632 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
634 for (i = 0; i < YAFFS_NTNODES_LEVEL0; i++) {
635 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
638 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
639 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
640 if (tags.objectId != objectId || tags.chunkId != chunkOffset) {
641 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
642 objectId, chunkOffset, theChunk,
643 tags.objectId, tags.chunkId));
656 static void yaffs_VerifyFile(yaffs_Object *obj)
658 int requiredTallness;
664 yaffs_ExtendedTags tags;
671 if (yaffs_SkipVerification(obj->myDev))
675 objectId = obj->objectId;
677 /* Check file size is consistent with tnode depth */
678 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
679 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
680 requiredTallness = 0;
682 x >>= YAFFS_TNODES_INTERNAL_BITS;
686 actualTallness = obj->variant.fileVariant.topLevel;
688 /* Check that the chunks in the tnode tree are all correct.
689 * We do this by scanning through the tnode tree and
690 * checking the tags for every chunk match.
693 if (yaffs_SkipNANDVerification(dev))
696 for (i = 1; i <= lastChunk; i++) {
697 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant, i);
700 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
702 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
703 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
704 if (tags.objectId != objectId || tags.chunkId != i) {
705 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
706 objectId, i, theChunk,
707 tags.objectId, tags.chunkId));
715 static void yaffs_VerifyHardLink(yaffs_Object *obj)
717 if (obj && yaffs_SkipVerification(obj->myDev))
720 /* Verify sane equivalent object */
723 static void yaffs_VerifySymlink(yaffs_Object *obj)
725 if (obj && yaffs_SkipVerification(obj->myDev))
728 /* Verify symlink string */
731 static void yaffs_VerifySpecial(yaffs_Object *obj)
733 if (obj && yaffs_SkipVerification(obj->myDev))
737 static void yaffs_VerifyObject(yaffs_Object *obj)
746 __u32 chunkShouldNotBeDeleted;
752 if (obj->beingCreated)
757 if (yaffs_SkipVerification(dev))
760 /* Check sane object header chunk */
762 chunkMin = dev->internalStartBlock * dev->param.nChunksPerBlock;
763 chunkMax = (dev->internalEndBlock+1) * dev->param.nChunksPerBlock - 1;
765 chunkInRange = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
766 chunkIdOk = chunkInRange || (obj->hdrChunk == 0);
767 chunkValid = chunkInRange &&
768 yaffs_CheckChunkBit(dev,
769 obj->hdrChunk / dev->param.nChunksPerBlock,
770 obj->hdrChunk % dev->param.nChunksPerBlock);
771 chunkShouldNotBeDeleted = chunkInRange && !chunkValid;
774 (!chunkIdOk || chunkShouldNotBeDeleted)) {
775 T(YAFFS_TRACE_VERIFY,
776 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
777 obj->objectId, obj->hdrChunk,
778 chunkIdOk ? "" : ",out of range",
779 chunkShouldNotBeDeleted ? ",marked as deleted" : ""));
782 if (chunkValid && !yaffs_SkipNANDVerification(dev)) {
783 yaffs_ExtendedTags tags;
784 yaffs_ObjectHeader *oh;
785 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
787 oh = (yaffs_ObjectHeader *)buffer;
789 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk, buffer,
792 yaffs_VerifyObjectHeader(obj, oh, &tags, 1);
794 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
797 /* Verify it has a parent */
798 if (obj && !obj->fake &&
799 (!obj->parent || obj->parent->myDev != dev)) {
800 T(YAFFS_TRACE_VERIFY,
801 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
802 obj->objectId, obj->parent));
805 /* Verify parent is a directory */
806 if (obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
807 T(YAFFS_TRACE_VERIFY,
808 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
809 obj->objectId, obj->parent->variantType));
812 switch (obj->variantType) {
813 case YAFFS_OBJECT_TYPE_FILE:
814 yaffs_VerifyFile(obj);
816 case YAFFS_OBJECT_TYPE_SYMLINK:
817 yaffs_VerifySymlink(obj);
819 case YAFFS_OBJECT_TYPE_DIRECTORY:
820 yaffs_VerifyDirectory(obj);
822 case YAFFS_OBJECT_TYPE_HARDLINK:
823 yaffs_VerifyHardLink(obj);
825 case YAFFS_OBJECT_TYPE_SPECIAL:
826 yaffs_VerifySpecial(obj);
828 case YAFFS_OBJECT_TYPE_UNKNOWN:
830 T(YAFFS_TRACE_VERIFY,
831 (TSTR("Obj %d has illegaltype %d"TENDSTR),
832 obj->objectId, obj->variantType));
837 static void yaffs_VerifyObjects(yaffs_Device *dev)
841 struct ylist_head *lh;
843 if (yaffs_SkipVerification(dev))
846 /* Iterate through the objects in each hash entry */
848 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
849 ylist_for_each(lh, &dev->objectBucket[i].list) {
851 obj = ylist_entry(lh, yaffs_Object, hashLink);
852 yaffs_VerifyObject(obj);
860 * Simple hash function. Needs to have a reasonable spread
863 static Y_INLINE int yaffs_HashFunction(int n)
866 return n % YAFFS_NOBJECT_BUCKETS;
870 * Access functions to useful fake objects.
871 * Note that root might have a presence in NAND if permissions are set.
874 yaffs_Object *yaffs_Root(yaffs_Device *dev)
879 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
881 return dev->lostNFoundDir;
886 * Erased NAND checking functions
889 int yaffs_CheckFF(__u8 *buffer, int nBytes)
891 /* Horrible, slow implementation */
900 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
903 int retval = YAFFS_OK;
904 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
905 yaffs_ExtendedTags tags;
908 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
910 if (tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
913 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
914 T(YAFFS_TRACE_NANDACCESS,
915 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
919 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
926 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
929 yaffs_ExtendedTags *tags)
931 int retval = YAFFS_OK;
932 yaffs_ExtendedTags tempTags;
933 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
936 result = yaffs_ReadChunkWithTagsFromNAND(dev,chunkInNAND,buffer,&tempTags);
937 if(memcmp(buffer,data,dev->nDataBytesPerChunk) ||
938 tempTags.objectId != tags->objectId ||
939 tempTags.chunkId != tags->chunkId ||
940 tempTags.byteCount != tags->byteCount)
943 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
948 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
950 yaffs_ExtendedTags *tags,
957 yaffs_InvalidateCheckpoint(dev);
960 yaffs_BlockInfo *bi = 0;
963 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
969 /* First check this chunk is erased, if it needs
970 * checking. The checking policy (unless forced
971 * always on) is as follows:
973 * Check the first page we try to write in a block.
974 * If the check passes then we don't need to check any
975 * more. If the check fails, we check again...
976 * If the block has been erased, we don't need to check.
978 * However, if the block has been prioritised for gc,
979 * then we think there might be something odd about
980 * this block and stop using it.
982 * Rationale: We should only ever see chunks that have
983 * not been erased if there was a partially written
984 * chunk due to power loss. This checking policy should
985 * catch that case with very few checks and thus save a
986 * lot of checks that are most likely not needed.
989 * If an erase check fails or the write fails we skip the
993 /* let's give it a try */
996 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
997 bi->skipErasedCheck = 0;
999 if (!bi->skipErasedCheck) {
1000 erasedOk = yaffs_CheckChunkErased(dev, chunk);
1001 if (erasedOk != YAFFS_OK) {
1002 T(YAFFS_TRACE_ERROR,
1003 (TSTR("**>> yaffs chunk %d was not erased"
1006 /* If not erased, delete this one,
1007 * skip rest of block and
1008 * try another chunk */
1009 yaffs_DeleteChunk(dev,chunk,1,__LINE__);
1010 yaffs_SkipRestOfBlock(dev);
1015 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
1018 if(!bi->skipErasedCheck)
1019 writeOk = yaffs_VerifyChunkWritten(dev, chunk, data, tags);
1021 if (writeOk != YAFFS_OK) {
1022 /* Clean up aborted write, skip to next block and
1023 * try another chunk */
1024 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
1028 bi->skipErasedCheck = 1;
1030 /* Copy the data into the robustification buffer */
1031 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1033 } while (writeOk != YAFFS_OK &&
1034 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1040 T(YAFFS_TRACE_ERROR,
1041 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1044 dev->nRetriedWrites += (attempts - 1);
1052 * Oldest Dirty Sequence Number handling.
1055 /* yaffs_CalcOldestDirtySequence()
1056 * yaffs_FindOldestDirtySequence()
1057 * Calculate the oldest dirty sequence number if we don't know it.
1059 static void yaffs_CalcOldestDirtySequence(yaffs_Device *dev)
1063 unsigned blockNo = 0;
1066 if(!dev->param.isYaffs2)
1069 /* Find the oldest dirty sequence number. */
1070 seq = dev->sequenceNumber + 1;
1072 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
1073 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
1074 (b->pagesInUse - b->softDeletions) < dev->param.nChunksPerBlock &&
1075 b->sequenceNumber < seq) {
1076 seq = b->sequenceNumber;
1083 dev->oldestDirtySequence = seq;
1084 dev->oldestDirtyBlock = blockNo;
1090 static void yaffs_FindOldestDirtySequence(yaffs_Device *dev)
1092 if(dev->param.isYaffs2 && !dev->oldestDirtySequence)
1093 yaffs_CalcOldestDirtySequence(dev);
1097 * yaffs_ClearOldestDirtySequence()
1098 * Called when a block is erased or marked bad. (ie. when its sequenceNumber
1099 * becomes invalid). If the value matches the oldest then we clear
1100 * dev->oldestDirtySequence to force its recomputation.
1102 static void yaffs_ClearOldestDirtySequence(yaffs_Device *dev, yaffs_BlockInfo *bi)
1105 if(!dev->param.isYaffs2)
1108 if(!bi || bi->sequenceNumber == dev->oldestDirtySequence){
1109 dev->oldestDirtySequence = 0;
1110 dev->oldestDirtyBlock = 0;
1115 * yaffs_UpdateOldestDirtySequence()
1116 * Update the oldest dirty sequence number whenever we dirty a block.
1117 * Only do this if the oldestDirtySequence is actually being tracked.
1119 static void yaffs_UpdateOldestDirtySequence(yaffs_Device *dev, unsigned blockNo, yaffs_BlockInfo *bi)
1121 if(dev->param.isYaffs2 && dev->oldestDirtySequence){
1122 if(dev->oldestDirtySequence > bi->sequenceNumber){
1123 dev->oldestDirtySequence = bi->sequenceNumber;
1124 dev->oldestDirtyBlock = blockNo;
1130 * Block retiring for handling a broken block.
1133 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND)
1135 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1137 yaffs_InvalidateCheckpoint(dev);
1139 yaffs_ClearOldestDirtySequence(dev,bi);
1141 if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
1142 if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
1143 T(YAFFS_TRACE_ALWAYS, (TSTR(
1144 "yaffs: Failed to mark bad and erase block %d"
1145 TENDSTR), blockInNAND));
1147 yaffs_ExtendedTags tags;
1148 int chunkId = blockInNAND * dev->param.nChunksPerBlock;
1150 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
1152 memset(buffer, 0xff, dev->nDataBytesPerChunk);
1153 yaffs_InitialiseTags(&tags);
1154 tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
1155 if (dev->param.writeChunkWithTagsToNAND(dev, chunkId -
1156 dev->chunkOffset, buffer, &tags) != YAFFS_OK)
1157 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
1158 TCONT("write bad block marker to block %d")
1159 TENDSTR), blockInNAND));
1161 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
1165 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1166 bi->gcPrioritise = 0;
1167 bi->needsRetiring = 0;
1169 dev->nRetiredBlocks++;
1173 * Functions for robustisizing TODO
1177 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
1179 const yaffs_ExtendedTags *tags)
1182 chunkInNAND=chunkInNAND;
1187 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
1188 const yaffs_ExtendedTags *tags)
1191 chunkInNAND=chunkInNAND;
1195 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1197 if (!bi->gcPrioritise) {
1198 bi->gcPrioritise = 1;
1199 dev->hasPendingPrioritisedGCs = 1;
1200 bi->chunkErrorStrikes++;
1202 if (bi->chunkErrorStrikes > 3) {
1203 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1204 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1210 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
1213 int blockInNAND = chunkInNAND / dev->param.nChunksPerBlock;
1214 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1216 yaffs_HandleChunkError(dev, bi);
1219 /* Was an actual write failure, so mark the block for retirement */
1220 bi->needsRetiring = 1;
1221 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1222 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1225 /* Delete the chunk */
1226 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1227 yaffs_SkipRestOfBlock(dev);
1231 /*---------------- Name handling functions ------------*/
1233 static __u16 yaffs_CalcNameSum(const YCHAR *name)
1238 const YUCHAR *bname = (const YUCHAR *) name;
1240 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1242 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1243 sum += yaffs_toupper(*bname) * i;
1245 sum += (*bname) * i;
1254 static void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
1256 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1257 memset(obj->shortName, 0, sizeof(YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1258 if (name && yaffs_strnlen(name,YAFFS_SHORT_NAME_LENGTH+1) <= YAFFS_SHORT_NAME_LENGTH)
1259 yaffs_strcpy(obj->shortName, name);
1261 obj->shortName[0] = _Y('\0');
1263 obj->sum = yaffs_CalcNameSum(name);
1266 /*-------------------- TNODES -------------------
1268 * List of spare tnodes
1269 * The list is hooked together using the first pointer
1273 /* yaffs_CreateTnodes creates a bunch more tnodes and
1274 * adds them to the tnode free list.
1275 * Don't use this function directly
1277 static Y_INLINE int yaffs_CalcTnodeSize(yaffs_Device *dev)
1280 /* Calculate the tnode size in bytes for variable width tnode support.
1281 * Must be a multiple of 32-bits */
1282 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1284 if (tnodeSize < sizeof(yaffs_Tnode))
1285 tnodeSize = sizeof(yaffs_Tnode);
1289 static int yaffs_CreateTnodes(yaffs_Device *dev, int nTnodes)
1292 int tnodeSize = yaffs_CalcTnodeSize(dev);
1293 yaffs_Tnode *newTnodes;
1297 yaffs_TnodeList *tnl;
1303 /* make these things */
1305 newTnodes = YMALLOC(nTnodes * tnodeSize);
1306 mem = (__u8 *)newTnodes;
1309 T(YAFFS_TRACE_ERROR,
1310 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1314 /* Hook them into the free list */
1316 for (i = 0; i < nTnodes - 1; i++) {
1317 newTnodes[i].internal[0] = &newTnodes[i + 1];
1318 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1319 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1323 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1324 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1325 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1327 dev->freeTnodes = newTnodes;
1329 /* New hookup for wide tnodes */
1330 for (i = 0; i < nTnodes - 1; i++) {
1331 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1332 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1333 curr->internal[0] = next;
1336 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1337 curr->internal[0] = dev->freeTnodes;
1338 dev->freeTnodes = (yaffs_Tnode *)mem;
1343 dev->nFreeTnodes += nTnodes;
1344 dev->nTnodesCreated += nTnodes;
1346 /* Now add this bunch of tnodes to a list for freeing up.
1347 * NB If we can't add this to the management list it isn't fatal
1348 * but it just means we can't free this bunch of tnodes later.
1351 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1353 T(YAFFS_TRACE_ERROR,
1355 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1358 tnl->tnodes = newTnodes;
1359 tnl->next = dev->allocatedTnodeList;
1360 dev->allocatedTnodeList = tnl;
1363 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1368 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1370 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device *dev)
1372 yaffs_Tnode *tn = NULL;
1374 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1375 tn = YMALLOC(yaffs_CalcTnodeSize(dev));
1377 dev->nTnodesCreated++;
1379 /* If there are none left make more */
1380 if (!dev->freeTnodes)
1381 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1383 if (dev->freeTnodes) {
1384 tn = dev->freeTnodes;
1385 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1386 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1387 /* Hoosterman, this thing looks like it isn't in the list */
1388 T(YAFFS_TRACE_ALWAYS,
1389 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1392 dev->freeTnodes = dev->freeTnodes->internal[0];
1396 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1401 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
1403 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1404 int tnodeSize = yaffs_CalcTnodeSize(dev);
1407 memset(tn, 0, tnodeSize);
1412 /* FreeTnode frees up a tnode and puts it back on the free list */
1413 static void yaffs_FreeTnode(yaffs_Device *dev, yaffs_Tnode *tn)
1416 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1418 dev->nTnodesCreated--;
1420 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1421 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1422 /* Hoosterman, this thing looks like it is already in the list */
1423 T(YAFFS_TRACE_ALWAYS,
1424 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1426 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1428 tn->internal[0] = dev->freeTnodes;
1429 dev->freeTnodes = tn;
1433 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1436 static void yaffs_DeinitialiseTnodes(yaffs_Device *dev)
1438 /* Free the list of allocated tnodes */
1439 yaffs_TnodeList *tmp;
1441 while (dev->allocatedTnodeList) {
1442 tmp = dev->allocatedTnodeList->next;
1444 YFREE(dev->allocatedTnodeList->tnodes);
1445 YFREE(dev->allocatedTnodeList);
1446 dev->allocatedTnodeList = tmp;
1450 dev->freeTnodes = NULL;
1451 dev->nFreeTnodes = 0;
1452 dev->nTnodesCreated = 0;
1455 static void yaffs_InitialiseTnodes(yaffs_Device *dev)
1457 dev->allocatedTnodeList = NULL;
1458 dev->freeTnodes = NULL;
1459 dev->nFreeTnodes = 0;
1460 dev->nTnodesCreated = 0;
1464 void yaffs_LoadLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
1467 __u32 *map = (__u32 *)tn;
1473 pos &= YAFFS_TNODES_LEVEL0_MASK;
1474 val >>= dev->chunkGroupBits;
1476 bitInMap = pos * dev->tnodeWidth;
1477 wordInMap = bitInMap / 32;
1478 bitInWord = bitInMap & (32 - 1);
1480 mask = dev->tnodeMask << bitInWord;
1482 map[wordInMap] &= ~mask;
1483 map[wordInMap] |= (mask & (val << bitInWord));
1485 if (dev->tnodeWidth > (32 - bitInWord)) {
1486 bitInWord = (32 - bitInWord);
1488 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1489 map[wordInMap] &= ~mask;
1490 map[wordInMap] |= (mask & (val >> bitInWord));
1494 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
1497 __u32 *map = (__u32 *)tn;
1503 pos &= YAFFS_TNODES_LEVEL0_MASK;
1505 bitInMap = pos * dev->tnodeWidth;
1506 wordInMap = bitInMap / 32;
1507 bitInWord = bitInMap & (32 - 1);
1509 val = map[wordInMap] >> bitInWord;
1511 if (dev->tnodeWidth > (32 - bitInWord)) {
1512 bitInWord = (32 - bitInWord);
1514 val |= (map[wordInMap] << bitInWord);
1517 val &= dev->tnodeMask;
1518 val <<= dev->chunkGroupBits;
1523 /* ------------------- End of individual tnode manipulation -----------------*/
1525 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1526 * The look up tree is represented by the top tnode and the number of topLevel
1527 * in the tree. 0 means only the level 0 tnode is in the tree.
1530 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1531 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
1532 yaffs_FileStructure *fStruct,
1535 yaffs_Tnode *tn = fStruct->top;
1537 int requiredTallness;
1538 int level = fStruct->topLevel;
1542 /* Check sane level and chunk Id */
1543 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
1546 if (chunkId > YAFFS_MAX_CHUNK_ID)
1549 /* First check we're tall enough (ie enough topLevel) */
1551 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1552 requiredTallness = 0;
1554 i >>= YAFFS_TNODES_INTERNAL_BITS;
1558 if (requiredTallness > fStruct->topLevel)
1559 return NULL; /* Not tall enough, so we can't find it */
1561 /* Traverse down to level 0 */
1562 while (level > 0 && tn) {
1563 tn = tn->internal[(chunkId >>
1564 (YAFFS_TNODES_LEVEL0_BITS +
1566 YAFFS_TNODES_INTERNAL_BITS)) &
1567 YAFFS_TNODES_INTERNAL_MASK];
1574 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1575 * This happens in two steps:
1576 * 1. If the tree isn't tall enough, then make it taller.
1577 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1579 * Used when modifying the tree.
1581 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1582 * be plugged into the ttree.
1585 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
1586 yaffs_FileStructure *fStruct,
1588 yaffs_Tnode *passedTn)
1590 int requiredTallness;
1598 /* Check sane level and page Id */
1599 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
1602 if (chunkId > YAFFS_MAX_CHUNK_ID)
1605 /* First check we're tall enough (ie enough topLevel) */
1607 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1608 requiredTallness = 0;
1610 x >>= YAFFS_TNODES_INTERNAL_BITS;
1615 if (requiredTallness > fStruct->topLevel) {
1616 /* Not tall enough, gotta make the tree taller */
1617 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1619 tn = yaffs_GetTnode(dev);
1622 tn->internal[0] = fStruct->top;
1624 fStruct->topLevel++;
1626 T(YAFFS_TRACE_ERROR,
1627 (TSTR("yaffs: no more tnodes" TENDSTR)));
1633 /* Traverse down to level 0, adding anything we need */
1635 l = fStruct->topLevel;
1639 while (l > 0 && tn) {
1641 (YAFFS_TNODES_LEVEL0_BITS +
1642 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1643 YAFFS_TNODES_INTERNAL_MASK;
1646 if ((l > 1) && !tn->internal[x]) {
1647 /* Add missing non-level-zero tnode */
1648 tn->internal[x] = yaffs_GetTnode(dev);
1649 if(!tn->internal[x])
1651 } else if (l == 1) {
1652 /* Looking from level 1 at level 0 */
1654 /* If we already have one, then release it.*/
1655 if (tn->internal[x])
1656 yaffs_FreeTnode(dev, tn->internal[x]);
1657 tn->internal[x] = passedTn;
1659 } else if (!tn->internal[x]) {
1660 /* Don't have one, none passed in */
1661 tn->internal[x] = yaffs_GetTnode(dev);
1662 if(!tn->internal[x])
1667 tn = tn->internal[x];
1671 /* top is level 0 */
1673 memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1674 yaffs_FreeTnode(dev, passedTn);
1681 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
1682 yaffs_ExtendedTags *tags, int objectId,
1687 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1688 if (yaffs_CheckChunkBit(dev, theChunk / dev->param.nChunksPerBlock,
1689 theChunk % dev->param.nChunksPerBlock)) {
1691 if(dev->chunkGroupSize == 1)
1694 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1696 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1708 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1709 * chunks and tnodes in the file
1710 * Returns 1 if the tree was deleted.
1711 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1714 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
1715 int chunkOffset, int *limit)
1720 yaffs_ExtendedTags tags;
1722 yaffs_Device *dev = in->myDev;
1728 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1730 if (tn->internal[i]) {
1731 if (limit && (*limit) < 0) {
1735 yaffs_DeleteWorker(in,
1743 YAFFS_TNODES_INTERNAL_BITS)
1748 yaffs_FreeTnode(dev,
1751 tn->internal[i] = NULL;
1755 return (allDone) ? 1 : 0;
1756 } else if (level == 0) {
1759 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1761 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1764 chunkInInode = (chunkOffset <<
1765 YAFFS_TNODES_LEVEL0_BITS) + i;
1768 yaffs_FindChunkInGroup(dev,
1774 if (foundChunk > 0) {
1775 yaffs_DeleteChunk(dev,
1780 *limit = *limit - 1;
1787 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1791 return (i < 0) ? 1 : 0;
1801 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1803 yaffs_BlockInfo *theBlock;
1806 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1808 blockNo = chunk / dev->param.nChunksPerBlock;
1809 theBlock = yaffs_GetBlockInfo(dev, blockNo);
1811 theBlock->softDeletions++;
1813 yaffs_UpdateOldestDirtySequence(dev, blockNo, theBlock);
1817 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1818 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1820 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1823 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1824 __u32 level, int chunkOffset)
1829 yaffs_Device *dev = in->myDev;
1834 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1836 if (tn->internal[i]) {
1838 yaffs_SoftDeleteWorker(in,
1844 YAFFS_TNODES_INTERNAL_BITS)
1847 yaffs_FreeTnode(dev,
1850 tn->internal[i] = NULL;
1852 /* Hoosterman... how could this happen? */
1856 return (allDone) ? 1 : 0;
1857 } else if (level == 0) {
1859 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1860 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1862 /* Note this does not find the real chunk, only the chunk group.
1863 * We make an assumption that a chunk group is not larger than
1866 yaffs_SoftDeleteChunk(dev, theChunk);
1867 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1881 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1884 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1885 if (obj->nDataChunks <= 0) {
1886 /* Empty file with no duplicate object headers, just delete it immediately */
1887 yaffs_FreeTnode(obj->myDev,
1888 obj->variant.fileVariant.top);
1889 obj->variant.fileVariant.top = NULL;
1890 T(YAFFS_TRACE_TRACING,
1891 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1893 yaffs_DoGenericObjectDeletion(obj);
1895 yaffs_SoftDeleteWorker(obj,
1896 obj->variant.fileVariant.top,
1897 obj->variant.fileVariant.
1899 obj->softDeleted = 1;
1904 /* Pruning removes any part of the file structure tree that is beyond the
1905 * bounds of the file (ie that does not point to chunks).
1907 * A file should only get pruned when its size is reduced.
1909 * Before pruning, the chunks must be pulled from the tree and the
1910 * level 0 tnode entries must be zeroed out.
1911 * Could also use this for file deletion, but that's probably better handled
1912 * by a special case.
1914 * This function is recursive. For levels > 0 the function is called again on
1915 * any sub-tree. For level == 0 we just check if the sub-tree has data.
1916 * If there is no data in a subtree then it is pruned.
1919 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1920 __u32 level, int del0)
1929 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1930 if (tn->internal[i]) {
1932 yaffs_PruneWorker(dev, tn->internal[i],
1934 (i == 0) ? del0 : 1);
1937 if (tn->internal[i])
1941 int tnodeSize_u32 = yaffs_CalcTnodeSize(dev)/sizeof(__u32);
1942 __u32 *map = (__u32 *)tn;
1944 for(i = 0; !hasData && i < tnodeSize_u32; i++){
1950 if (hasData == 0 && del0) {
1951 /* Free and return NULL */
1953 yaffs_FreeTnode(dev, tn);
1963 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1964 yaffs_FileStructure *fStruct)
1971 if (fStruct->topLevel > 0) {
1973 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1975 /* Now we have a tree with all the non-zero branches NULL but the height
1976 * is the same as it was.
1977 * Let's see if we can trim internal tnodes to shorten the tree.
1978 * We can do this if only the 0th element in the tnode is in use
1979 * (ie all the non-zero are NULL)
1982 while (fStruct->topLevel && !done) {
1986 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1987 if (tn->internal[i])
1992 fStruct->top = tn->internal[0];
1993 fStruct->topLevel--;
1994 yaffs_FreeTnode(dev, tn);
2004 /*-------------------- End of File Structure functions.-------------------*/
2006 /* yaffs_CreateFreeObjects creates a bunch more objects and
2007 * adds them to the object free list.
2009 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
2012 yaffs_Object *newObjects;
2013 yaffs_ObjectList *list;
2018 /* make these things */
2019 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
2020 list = YMALLOC(sizeof(yaffs_ObjectList));
2022 if (!newObjects || !list) {
2031 T(YAFFS_TRACE_ALLOCATE,
2032 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
2036 /* Hook them into the free list */
2037 for (i = 0; i < nObjects - 1; i++) {
2038 newObjects[i].siblings.next =
2039 (struct ylist_head *)(&newObjects[i + 1]);
2042 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
2043 dev->freeObjects = newObjects;
2044 dev->nFreeObjects += nObjects;
2045 dev->nObjectsCreated += nObjects;
2047 /* Now add this bunch of Objects to a list for freeing up. */
2049 list->objects = newObjects;
2050 list->next = dev->allocatedObjectList;
2051 dev->allocatedObjectList = list;
2057 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
2058 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
2060 yaffs_Object *tn = NULL;
2062 #ifdef CONFIG_YAFFS_VALGRIND_TEST
2063 tn = YMALLOC(sizeof(yaffs_Object));
2065 dev->nObjectsCreated++;
2067 /* If there are none left make more */
2068 if (!dev->freeObjects)
2069 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
2071 if (dev->freeObjects) {
2072 tn = dev->freeObjects;
2074 (yaffs_Object *) (dev->freeObjects->siblings.next);
2075 dev->nFreeObjects--;
2079 /* Now sweeten it up... */
2081 memset(tn, 0, sizeof(yaffs_Object));
2082 tn->beingCreated = 1;
2086 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
2087 YINIT_LIST_HEAD(&(tn->hardLinks));
2088 YINIT_LIST_HEAD(&(tn->hashLink));
2089 YINIT_LIST_HEAD(&tn->siblings);
2092 /* Now make the directory sane */
2094 tn->parent = dev->rootDir;
2095 ylist_add(&(tn->siblings), &dev->rootDir->variant.directoryVariant.children);
2098 /* Add it to the lost and found directory.
2099 * NB Can't put root or lostNFound in lostNFound so
2100 * check if lostNFound exists first
2102 if (dev->lostNFoundDir)
2103 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
2105 tn->beingCreated = 0;
2108 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2113 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
2118 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
2120 obj->fake = 1; /* it is fake so it might have no NAND presence... */
2121 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
2122 obj->unlinkAllowed = 0; /* ... or unlink it */
2125 obj->yst_mode = mode;
2127 obj->hdrChunk = 0; /* Not a valid chunk. */
2134 static void yaffs_UnhashObject(yaffs_Object *tn)
2137 yaffs_Device *dev = tn->myDev;
2139 /* If it is still linked into the bucket list, free from the list */
2140 if (!ylist_empty(&tn->hashLink)) {
2141 ylist_del_init(&tn->hashLink);
2142 bucket = yaffs_HashFunction(tn->objectId);
2143 dev->objectBucket[bucket].count--;
2147 /* FreeObject frees up a Object and puts it back on the free list */
2148 static void yaffs_FreeObject(yaffs_Object *tn)
2150 yaffs_Device *dev = tn->myDev;
2152 T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), tn, tn->myInode));
2158 if (!ylist_empty(&tn->siblings))
2163 /* We're still hooked up to a cached inode.
2164 * Don't delete now, but mark for later deletion
2166 tn->deferedFree = 1;
2170 yaffs_UnhashObject(tn);
2172 #ifdef CONFIG_YAFFS_VALGRIND_TEST
2174 dev->nObjectsCreated--;
2177 /* Link into the free list. */
2178 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2179 dev->freeObjects = tn;
2180 dev->nFreeObjects++;
2182 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2186 void yaffs_HandleDeferedFree(yaffs_Object *obj)
2188 if (obj->deferedFree)
2189 yaffs_FreeObject(obj);
2193 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
2195 /* Free the list of allocated Objects */
2197 yaffs_ObjectList *tmp;
2199 while (dev->allocatedObjectList) {
2200 tmp = dev->allocatedObjectList->next;
2201 YFREE(dev->allocatedObjectList->objects);
2202 YFREE(dev->allocatedObjectList);
2204 dev->allocatedObjectList = tmp;
2207 dev->freeObjects = NULL;
2208 dev->nFreeObjects = 0;
2209 dev->nObjectsCreated = 0;
2212 static void yaffs_InitialiseObjects(yaffs_Device *dev)
2216 dev->allocatedObjectList = NULL;
2217 dev->freeObjects = NULL;
2218 dev->nFreeObjects = 0;
2220 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2221 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2222 dev->objectBucket[i].count = 0;
2226 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
2230 int lowest = 999999;
2233 /* Search for the shortest list or one that
2237 for (i = 0; i < 10 && lowest > 4; i++) {
2238 dev->bucketFinder++;
2239 dev->bucketFinder %= YAFFS_NOBJECT_BUCKETS;
2240 if (dev->objectBucket[dev->bucketFinder].count < lowest) {
2241 lowest = dev->objectBucket[dev->bucketFinder].count;
2242 l = dev->bucketFinder;
2250 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
2252 int bucket = yaffs_FindNiceObjectBucket(dev);
2254 /* Now find an object value that has not already been taken
2255 * by scanning the list.
2259 struct ylist_head *i;
2261 __u32 n = (__u32) bucket;
2263 /* yaffs_CheckObjectHashSanity(); */
2267 n += YAFFS_NOBJECT_BUCKETS;
2268 if (1 || dev->objectBucket[bucket].count > 0) {
2269 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2270 /* If there is already one in the list */
2271 if (i && ylist_entry(i, yaffs_Object,
2272 hashLink)->objectId == n) {
2282 static void yaffs_HashObject(yaffs_Object *in)
2284 int bucket = yaffs_HashFunction(in->objectId);
2285 yaffs_Device *dev = in->myDev;
2287 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2288 dev->objectBucket[bucket].count++;
2291 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
2293 int bucket = yaffs_HashFunction(number);
2294 struct ylist_head *i;
2297 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2298 /* Look if it is in the list */
2300 in = ylist_entry(i, yaffs_Object, hashLink);
2301 if (in->objectId == number) {
2303 /* Don't tell the VFS about this one if it is defered free */
2304 if (in->deferedFree)
2315 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
2316 yaffs_ObjectType type)
2318 yaffs_Object *theObject=NULL;
2319 yaffs_Tnode *tn = NULL;
2322 number = yaffs_CreateNewObjectNumber(dev);
2324 if (type == YAFFS_OBJECT_TYPE_FILE) {
2325 tn = yaffs_GetTnode(dev);
2330 theObject = yaffs_AllocateEmptyObject(dev);
2333 yaffs_FreeTnode(dev,tn);
2339 theObject->fake = 0;
2340 theObject->renameAllowed = 1;
2341 theObject->unlinkAllowed = 1;
2342 theObject->objectId = number;
2343 yaffs_HashObject(theObject);
2344 theObject->variantType = type;
2345 #ifdef CONFIG_YAFFS_WINCE
2346 yfsd_WinFileTimeNow(theObject->win_atime);
2347 theObject->win_ctime[0] = theObject->win_mtime[0] =
2348 theObject->win_atime[0];
2349 theObject->win_ctime[1] = theObject->win_mtime[1] =
2350 theObject->win_atime[1];
2354 theObject->yst_atime = theObject->yst_mtime =
2355 theObject->yst_ctime = Y_CURRENT_TIME;
2358 case YAFFS_OBJECT_TYPE_FILE:
2359 theObject->variant.fileVariant.fileSize = 0;
2360 theObject->variant.fileVariant.scannedFileSize = 0;
2361 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2362 theObject->variant.fileVariant.topLevel = 0;
2363 theObject->variant.fileVariant.top = tn;
2365 case YAFFS_OBJECT_TYPE_DIRECTORY:
2366 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2368 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2371 case YAFFS_OBJECT_TYPE_SYMLINK:
2372 case YAFFS_OBJECT_TYPE_HARDLINK:
2373 case YAFFS_OBJECT_TYPE_SPECIAL:
2374 /* No action required */
2376 case YAFFS_OBJECT_TYPE_UNKNOWN:
2377 /* todo this should not happen */
2385 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
2387 yaffs_ObjectType type)
2389 yaffs_Object *theObject = NULL;
2392 theObject = yaffs_FindObjectByNumber(dev, number);
2395 theObject = yaffs_CreateNewObject(dev, number, type);
2402 static YCHAR *yaffs_CloneString(const YCHAR *str)
2404 YCHAR *newStr = NULL;
2410 len = yaffs_strnlen(str,YAFFS_MAX_ALIAS_LENGTH);
2411 newStr = YMALLOC((len + 1) * sizeof(YCHAR));
2413 yaffs_strncpy(newStr, str,len);
2421 * Mknod (create) a new object.
2422 * equivalentObject only has meaning for a hard link;
2423 * aliasString only has meaning for a symlink.
2424 * rdev only has meaning for devices (a subset of special objects)
2427 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2428 yaffs_Object *parent,
2433 yaffs_Object *equivalentObject,
2434 const YCHAR *aliasString, __u32 rdev)
2439 yaffs_Device *dev = parent->myDev;
2441 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2442 if (yaffs_FindObjectByName(parent, name))
2445 if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2446 str = yaffs_CloneString(aliasString);
2451 in = yaffs_CreateNewObject(dev, -1, type);
2466 in->variantType = type;
2468 in->yst_mode = mode;
2470 #ifdef CONFIG_YAFFS_WINCE
2471 yfsd_WinFileTimeNow(in->win_atime);
2472 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2473 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2476 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2478 in->yst_rdev = rdev;
2482 in->nDataChunks = 0;
2484 yaffs_SetObjectName(in, name);
2487 yaffs_AddObjectToDirectory(parent, in);
2489 in->myDev = parent->myDev;
2492 case YAFFS_OBJECT_TYPE_SYMLINK:
2493 in->variant.symLinkVariant.alias = str;
2495 case YAFFS_OBJECT_TYPE_HARDLINK:
2496 in->variant.hardLinkVariant.equivalentObject =
2498 in->variant.hardLinkVariant.equivalentObjectId =
2499 equivalentObject->objectId;
2500 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2502 case YAFFS_OBJECT_TYPE_FILE:
2503 case YAFFS_OBJECT_TYPE_DIRECTORY:
2504 case YAFFS_OBJECT_TYPE_SPECIAL:
2505 case YAFFS_OBJECT_TYPE_UNKNOWN:
2510 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2511 /* Could not create the object header, fail the creation */
2512 yaffs_DeleteObject(in);
2516 yaffs_UpdateParent(parent);
2522 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
2523 __u32 mode, __u32 uid, __u32 gid)
2525 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2526 uid, gid, NULL, NULL, 0);
2529 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
2530 __u32 mode, __u32 uid, __u32 gid)
2532 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2533 mode, uid, gid, NULL, NULL, 0);
2536 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
2537 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2539 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2540 uid, gid, NULL, NULL, rdev);
2543 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
2544 __u32 mode, __u32 uid, __u32 gid,
2547 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2548 uid, gid, NULL, alias, 0);
2551 /* yaffs_Link returns the object id of the equivalent object.*/
2552 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
2553 yaffs_Object *equivalentObject)
2555 /* Get the real object in case we were fed a hard link as an equivalent object */
2556 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2558 if (yaffs_MknodObject
2559 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2560 equivalentObject, NULL, 0)) {
2561 return equivalentObject;
2568 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
2569 const YCHAR *newName, int force, int shadows)
2574 yaffs_Object *existingTarget;
2577 newDir = obj->parent; /* use the old directory */
2579 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2580 T(YAFFS_TRACE_ALWAYS,
2582 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2587 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2588 if (obj->myDev->param.isYaffs2)
2589 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2591 unlinkOp = (newDir == obj->myDev->unlinkedDir
2592 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2594 deleteOp = (newDir == obj->myDev->deletedDir);
2596 existingTarget = yaffs_FindObjectByName(newDir, newName);
2598 /* If the object is a file going into the unlinked directory,
2599 * then it is OK to just stuff it in since duplicate names are allowed.
2600 * else only proceed if the new name does not exist and if we're putting
2601 * it into a directory.
2608 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2609 yaffs_SetObjectName(obj, newName);
2612 yaffs_AddObjectToDirectory(newDir, obj);
2617 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2618 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows) >= 0)
2625 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
2626 yaffs_Object *newDir, const YCHAR *newName)
2628 yaffs_Object *obj = NULL;
2629 yaffs_Object *existingTarget = NULL;
2635 if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2637 if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2640 dev = oldDir->myDev;
2642 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2643 /* Special case for case insemsitive systems (eg. WinCE).
2644 * While look-up is case insensitive, the name isn't.
2645 * Therefore we might want to change x.txt to X.txt
2647 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
2651 if(yaffs_strnlen(newName,YAFFS_MAX_NAME_LENGTH+1) > YAFFS_MAX_NAME_LENGTH)
2655 obj = yaffs_FindObjectByName(oldDir, oldName);
2657 if (obj && obj->renameAllowed) {
2659 /* Now do the handling for an existing target, if there is one */
2661 existingTarget = yaffs_FindObjectByName(newDir, newName);
2662 if (existingTarget &&
2663 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2664 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2665 /* There is a target that is a non-empty directory, so we fail */
2666 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2667 } else if (existingTarget && existingTarget != obj) {
2668 /* Nuke the target first, using shadowing,
2669 * but only if it isn't the same object.
2671 * Note we must disable gc otherwise it can mess up the shadowing.
2675 yaffs_ChangeObjectName(obj, newDir, newName, force,
2676 existingTarget->objectId);
2677 existingTarget->isShadowed = 1;
2678 yaffs_UnlinkObject(existingTarget);
2682 result = yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2684 yaffs_UpdateParent(oldDir);
2685 if(newDir != oldDir)
2686 yaffs_UpdateParent(newDir);
2693 /*------------------------- Block Management and Page Allocation ----------------*/
2695 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
2697 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2699 dev->blockInfo = NULL;
2700 dev->chunkBits = NULL;
2702 dev->allocationBlock = -1; /* force it to get a new one */
2704 /* If the first allocation strategy fails, thry the alternate one */
2705 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2706 if (!dev->blockInfo) {
2707 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2708 dev->blockInfoAlt = 1;
2710 dev->blockInfoAlt = 0;
2712 if (dev->blockInfo) {
2713 /* Set up dynamic blockinfo stuff. */
2714 dev->chunkBitmapStride = (dev->param.nChunksPerBlock + 7) / 8; /* round up bytes */
2715 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2716 if (!dev->chunkBits) {
2717 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2718 dev->chunkBitsAlt = 1;
2720 dev->chunkBitsAlt = 0;
2723 if (dev->blockInfo && dev->chunkBits) {
2724 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2725 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2732 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2734 if (dev->blockInfoAlt && dev->blockInfo)
2735 YFREE_ALT(dev->blockInfo);
2736 else if (dev->blockInfo)
2737 YFREE(dev->blockInfo);
2739 dev->blockInfoAlt = 0;
2741 dev->blockInfo = NULL;
2743 if (dev->chunkBitsAlt && dev->chunkBits)
2744 YFREE_ALT(dev->chunkBits);
2745 else if (dev->chunkBits)
2746 YFREE(dev->chunkBits);
2747 dev->chunkBitsAlt = 0;
2748 dev->chunkBits = NULL;
2751 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
2752 yaffs_BlockInfo *bi)
2755 if (!dev->param.isYaffs2)
2756 return 1; /* disqualification only applies to yaffs2. */
2758 if (!bi->hasShrinkHeader)
2759 return 1; /* can gc */
2761 yaffs_FindOldestDirtySequence(dev);
2763 /* Can't do gc of this block if there are any blocks older than this one that have
2766 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2770 * yaffs_FindRefreshBlock()
2771 * periodically finds the oldest full block by sequence number for refreshing.
2774 static __u32 yaffs_FindRefreshBlock(yaffs_Device *dev)
2779 __u32 oldestSequence = 0;
2781 yaffs_BlockInfo *bi;
2784 * If refresh period < 10 then refreshing is disabled.
2786 if(dev->param.refreshPeriod < 10 ||
2787 !dev->param.isYaffs2)
2791 * Fix broken values.
2793 if(dev->refreshSkip > dev->param.refreshPeriod)
2794 dev->refreshSkip = dev->param.refreshPeriod;
2796 if(dev->refreshSkip > 0)
2800 * Refresh skip is now zero.
2801 * We'll do a refresh this time around....
2802 * Update the refresh skip and find the oldest block.
2804 dev->refreshSkip = dev->param.refreshPeriod;
2805 dev->refreshCount++;
2806 bi = dev->blockInfo;
2807 for (b = dev->internalStartBlock; b <=dev->internalEndBlock; b++){
2809 if (bi->blockState == YAFFS_BLOCK_STATE_FULL){
2812 bi->sequenceNumber < oldestSequence){
2814 oldestSequence = bi->sequenceNumber;
2822 (TSTR("GC refresh count %d selected block %d with sequenceNumber %d" TENDSTR),
2823 dev->refreshCount, oldest, oldestSequence));
2830 static void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
2832 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2836 /* If the block is still healthy erase it and mark as clean.
2837 * If the block has had a data failure, then retire it.
2840 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2841 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2842 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2844 yaffs_ClearOldestDirtySequence(dev,bi);
2846 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2848 /* If this is the block being garbage collected then stop gc'ing this block */
2849 if(blockNo == dev->gcBlock)
2852 /* If this block is currently the best candidate for gc then drop as a candidate */
2853 if(blockNo == dev->gcDirtiest){
2854 dev->gcDirtiest = 0;
2855 dev->gcPagesInUse = 0;
2858 if (!bi->needsRetiring) {
2859 yaffs_InvalidateCheckpoint(dev);
2860 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2862 dev->nErasureFailures++;
2863 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2864 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2869 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2871 for (i = 0; i < dev->param.nChunksPerBlock; i++) {
2872 if (!yaffs_CheckChunkErased
2873 (dev, blockNo * dev->param.nChunksPerBlock + i)) {
2874 T(YAFFS_TRACE_ERROR,
2876 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2877 TENDSTR), blockNo, i));
2883 /* Clean it up... */
2884 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2885 bi->sequenceNumber = 0;
2886 dev->nErasedBlocks++;
2888 bi->softDeletions = 0;
2889 bi->hasShrinkHeader = 0;
2890 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2891 bi->gcPrioritise = 0;
2892 yaffs_ClearChunkBits(dev, blockNo);
2894 T(YAFFS_TRACE_ERASE,
2895 (TSTR("Erased block %d" TENDSTR), blockNo));
2897 dev->nFreeChunks -= dev->param.nChunksPerBlock; /* We lost a block of free space */
2899 yaffs_RetireBlock(dev, blockNo);
2900 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2901 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2905 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2909 yaffs_BlockInfo *bi;
2911 if (dev->nErasedBlocks < 1) {
2912 /* Hoosterman we've got a problem.
2913 * Can't get space to gc
2915 T(YAFFS_TRACE_ERROR,
2916 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2921 /* Find an empty block. */
2923 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2924 dev->allocationBlockFinder++;
2925 if (dev->allocationBlockFinder < dev->internalStartBlock
2926 || dev->allocationBlockFinder > dev->internalEndBlock) {
2927 dev->allocationBlockFinder = dev->internalStartBlock;
2930 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2932 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2933 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2934 dev->sequenceNumber++;
2935 bi->sequenceNumber = dev->sequenceNumber;
2936 dev->nErasedBlocks--;
2937 T(YAFFS_TRACE_ALLOCATE,
2938 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2939 dev->allocationBlockFinder, dev->sequenceNumber,
2940 dev->nErasedBlocks));
2941 return dev->allocationBlockFinder;
2945 T(YAFFS_TRACE_ALWAYS,
2947 ("yaffs tragedy: no more erased blocks, but there should have been %d"
2948 TENDSTR), dev->nErasedBlocks));
2955 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2957 if (!dev->nCheckpointBlocksRequired &&
2958 dev->param.isYaffs2) {
2959 /* Not a valid value so recalculate */
2962 int devBlocks = (dev->param.endBlock - dev->param.startBlock + 1);
2963 int tnodeSize = yaffs_CalcTnodeSize(dev);
2965 nBytes += sizeof(yaffs_CheckpointValidity);
2966 nBytes += sizeof(yaffs_CheckpointDevice);
2967 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2968 nBytes += devBlocks * dev->chunkBitmapStride;
2969 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2970 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2971 nBytes += sizeof(yaffs_CheckpointValidity);
2972 nBytes += sizeof(__u32); /* checksum*/
2974 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2976 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->param.nChunksPerBlock)) + 3;
2978 dev->nCheckpointBlocksRequired = nBlocks;
2981 return dev->nCheckpointBlocksRequired;
2985 * Check if there's space to allocate...
2986 * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2988 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev, int nChunks)
2991 int reservedBlocks = dev->param.nReservedBlocks;
2992 int checkpointBlocks;
2994 if (dev->param.isYaffs2) {
2995 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
2996 dev->blocksInCheckpoint;
2997 if (checkpointBlocks < 0)
2998 checkpointBlocks = 0;
3000 checkpointBlocks = 0;
3003 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->param.nChunksPerBlock);
3005 return (dev->nFreeChunks > (reservedChunks + nChunks));
3008 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
3009 yaffs_BlockInfo **blockUsedPtr)
3012 yaffs_BlockInfo *bi;
3014 if (dev->allocationBlock < 0) {
3015 /* Get next block to allocate off */
3016 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
3017 dev->allocationPage = 0;
3020 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev, 1)) {
3021 /* Not enough space to allocate unless we're allowed to use the reserve. */
3025 if (dev->nErasedBlocks < dev->param.nReservedBlocks
3026 && dev->allocationPage == 0) {
3027 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
3030 /* Next page please.... */
3031 if (dev->allocationBlock >= 0) {
3032 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3034 retVal = (dev->allocationBlock * dev->param.nChunksPerBlock) +
3035 dev->allocationPage;
3037 yaffs_SetChunkBit(dev, dev->allocationBlock,
3038 dev->allocationPage);
3040 dev->allocationPage++;
3044 /* If the block is full set the state to full */
3045 if (dev->allocationPage >= dev->param.nChunksPerBlock) {
3046 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3047 dev->allocationBlock = -1;
3056 T(YAFFS_TRACE_ERROR,
3057 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
3062 static int yaffs_GetErasedChunks(yaffs_Device *dev)
3066 n = dev->nErasedBlocks * dev->param.nChunksPerBlock;
3068 if (dev->allocationBlock > 0)
3069 n += (dev->param.nChunksPerBlock - dev->allocationPage);
3076 * yaffs_SkipRestOfBlock() skips over the rest of the allocation block
3077 * if we don't want to write to it.
3079 static void yaffs_SkipRestOfBlock(yaffs_Device *dev)
3081 if(dev->allocationBlock > 0){
3082 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3083 if(bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING){
3084 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3085 dev->allocationBlock = -1;
3091 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
3097 int retVal = YAFFS_OK;
3100 int isCheckpointBlock;
3104 int chunksBefore = yaffs_GetErasedChunks(dev);
3107 yaffs_ExtendedTags tags;
3109 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3111 yaffs_Object *object;
3113 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3116 T(YAFFS_TRACE_TRACING,
3117 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3120 bi->hasShrinkHeader,
3123 /*yaffs_VerifyFreeChunks(dev); */
3125 if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
3126 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3128 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
3132 if (isCheckpointBlock ||
3133 !yaffs_StillSomeChunkBits(dev, block)) {
3134 T(YAFFS_TRACE_TRACING,
3136 ("Collecting block %d that has no chunks in use" TENDSTR),
3138 yaffs_BlockBecameDirty(dev, block);
3141 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3143 yaffs_VerifyBlock(dev, bi, block);
3145 maxCopies = (wholeBlock) ? dev->param.nChunksPerBlock : 5;
3146 oldChunk = block * dev->param.nChunksPerBlock + dev->gcChunk;
3148 for (/* init already done */;
3149 retVal == YAFFS_OK &&
3150 dev->gcChunk < dev->param.nChunksPerBlock &&
3151 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
3153 dev->gcChunk++, oldChunk++) {
3154 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3156 /* This page is in use and might need to be copied off */
3162 yaffs_InitialiseTags(&tags);
3164 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3168 yaffs_FindObjectByNumber(dev,
3171 T(YAFFS_TRACE_GC_DETAIL,
3173 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3174 dev->gcChunk, tags.objectId, tags.chunkId,
3177 if (object && !yaffs_SkipVerification(dev)) {
3178 if (tags.chunkId == 0)
3179 matchingChunk = object->hdrChunk;
3180 else if (object->softDeleted)
3181 matchingChunk = oldChunk; /* Defeat the test */
3183 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
3185 if (oldChunk != matchingChunk)
3186 T(YAFFS_TRACE_ERROR,
3187 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3188 oldChunk, matchingChunk, tags.objectId, tags.chunkId));
3193 T(YAFFS_TRACE_ERROR,
3195 ("page %d in gc has no object: %d %d %d "
3197 tags.objectId, tags.chunkId, tags.byteCount));
3202 object->softDeleted &&
3203 tags.chunkId != 0) {
3204 /* Data chunk in a soft deleted file, throw it away
3205 * It's a soft deleted data chunk,
3206 * No need to copy this, just forget about it and
3207 * fix up the object.
3210 /* Free chunks already includes softdeleted chunks.
3211 * How ever this chunk is going to soon be really deleted
3212 * which will increment free chunks.
3213 * We have to decrement free chunks so this works out properly.
3217 object->nDataChunks--;
3219 if (object->nDataChunks <= 0) {
3220 /* remeber to clean up the object */
3221 dev->gcCleanupList[cleanups] =
3227 /* Todo object && object->deleted && object->nDataChunks == 0 */
3228 /* Deleted object header with no data chunks.
3229 * Can be discarded and the file deleted.
3231 object->hdrChunk = 0;
3232 yaffs_FreeTnode(object->myDev,
3235 object->variant.fileVariant.top = NULL;
3236 yaffs_DoGenericObjectDeletion(object);
3238 } else if (object) {
3239 /* It's either a data chunk in a live file or
3240 * an ObjectHeader, so we're interested in it.
3241 * NB Need to keep the ObjectHeaders of deleted files
3242 * until the whole file has been deleted off
3244 tags.serialNumber++;
3248 if (tags.chunkId == 0) {
3249 /* It is an object Id,
3250 * We need to nuke the shrinkheader flags first
3251 * Also need to clean up shadowing.
3252 * We no longer want the shrinkHeader flag since its work is done
3253 * and if it is left in place it will mess up scanning.
3256 yaffs_ObjectHeader *oh;
3257 oh = (yaffs_ObjectHeader *)buffer;
3260 tags.extraIsShrinkHeader = 0;
3262 oh->shadowsObject = 0;
3263 oh->inbandShadowsObject = 0;
3264 tags.extraShadows = 0;
3266 /* Update file size */
3267 if(object->variantType == YAFFS_OBJECT_TYPE_FILE){
3268 oh->fileSize = object->variant.fileVariant.fileSize;
3269 tags.extraFileLength = oh->fileSize;
3272 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
3274 yaffs_WriteNewChunkWithTagsToNAND(dev,(__u8 *) oh, &tags, 1);
3277 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3280 retVal = YAFFS_FAIL;
3283 /* Ok, now fix up the Tnodes etc. */
3285 if (tags.chunkId == 0) {
3287 object->hdrChunk = newChunk;
3288 object->serial = tags.serialNumber;
3290 /* It's a data chunk */
3292 ok = yaffs_PutChunkIntoFile
3300 if (retVal == YAFFS_OK)
3301 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3306 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3309 /* Do any required cleanups */
3310 for (i = 0; i < cleanups; i++) {
3311 /* Time to delete the file too */
3313 yaffs_FindObjectByNumber(dev,
3314 dev->gcCleanupList[i]);
3316 yaffs_FreeTnode(dev,
3317 object->variant.fileVariant.
3319 object->variant.fileVariant.top = NULL;
3322 ("yaffs: About to finally delete object %d"
3323 TENDSTR), object->objectId));
3324 yaffs_DoGenericObjectDeletion(object);
3325 object->myDev->nDeletedFiles--;
3332 yaffs_VerifyCollectedBlock(dev, bi, block);
3336 if (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3338 * The gc did not complete. Set block state back to FULL
3339 * because checkpointing does not restore gc.
3341 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3343 /* The gc completed. */
3344 chunksAfter = yaffs_GetErasedChunks(dev);
3345 if (chunksBefore >= chunksAfter) {
3348 ("gc did not increase free chunks before %d after %d"
3349 TENDSTR), chunksBefore, chunksAfter));
3361 * FindBlockForgarbageCollection is used to select the dirtiest block (or close enough)
3362 * for garbage collection.
3365 static unsigned yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
3371 unsigned selected = 0;
3372 int prioritised = 0;
3373 int prioritisedExists = 0;
3374 yaffs_BlockInfo *bi;
3377 /* First let's see if we need to grab a prioritised block */
3378 if (dev->hasPendingPrioritisedGCs && !aggressive) {
3379 dev->gcDirtiest = 0;
3380 bi = dev->blockInfo;
3381 for (i = dev->internalStartBlock;
3382 i <= dev->internalEndBlock && !selected;
3385 if (bi->gcPrioritise) {
3386 prioritisedExists = 1;
3387 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
3388 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
3397 * If there is a prioritised block and none was selected then
3398 * this happened because there is at least one old dirty block gumming
3399 * up the works. Let's gc the oldest dirty block.
3402 if(prioritisedExists &&
3404 dev->oldestDirtyBlock > 0)
3405 selected = dev->oldestDirtyBlock;
3407 if (!prioritisedExists) /* None found, so we can clear this */
3408 dev->hasPendingPrioritisedGCs = 0;
3411 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
3413 * else (we're doing a leasurely gc), then we only bother to do this if the
3414 * block has only a few pages in use.
3419 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
3421 threshold = dev->param.nChunksPerBlock;
3422 iterations = nBlocks;
3424 int maxThreshold = dev->param.nChunksPerBlock/2;
3425 threshold = background ?
3426 (dev->gcNotDone + 2) * 2 : 0;
3427 if(threshold <YAFFS_GC_PASSIVE_THRESHOLD)
3428 threshold = YAFFS_GC_PASSIVE_THRESHOLD;
3429 if(threshold > maxThreshold)
3430 threshold = maxThreshold;
3432 iterations = nBlocks / 16 + 1;
3433 if (iterations > 100)
3439 (dev->gcDirtiest < 1 ||
3440 dev->gcPagesInUse > YAFFS_GC_GOOD_ENOUGH);
3442 dev->gcBlockFinder++;
3443 if (dev->gcBlockFinder < dev->internalStartBlock ||
3444 dev->gcBlockFinder > dev->internalEndBlock)
3445 dev->gcBlockFinder = dev->internalStartBlock;
3447 bi = yaffs_GetBlockInfo(dev, dev->gcBlockFinder);
3449 pagesUsed = bi->pagesInUse - bi->softDeletions;
3451 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
3452 pagesUsed < dev->param.nChunksPerBlock &&
3453 (dev->gcDirtiest < 1 || pagesUsed < dev->gcPagesInUse) &&
3454 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
3455 dev->gcDirtiest = dev->gcBlockFinder;
3456 dev->gcPagesInUse = pagesUsed;
3460 if(dev->gcDirtiest > 0 && dev->gcPagesInUse <= threshold)
3461 selected = dev->gcDirtiest;
3465 * If nothing has been selected for a while, try selecting the oldest dirty
3466 * because that's gumming up the works.
3469 if(!selected && dev->param.isYaffs2 &&
3470 dev->gcNotDone >= ( background ? 10 : 20)){
3471 yaffs_FindOldestDirtySequence(dev);
3472 if(dev->oldestDirtyBlock > 0) {
3473 selected = dev->oldestDirtyBlock;
3474 dev->gcDirtiest = selected;
3475 dev->oldestDirtyGCs++;
3476 bi = yaffs_GetBlockInfo(dev, selected);
3477 dev->gcPagesInUse = bi->pagesInUse - bi->softDeletions;
3484 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR),
3486 dev->param.nChunksPerBlock - dev->gcPagesInUse,
3490 dev->backgroundGCs++;
3491 dev->gcDirtiest = 0;
3492 dev->gcPagesInUse = 0;
3494 if(dev->refreshSkip > 0)
3499 (TSTR("GC none: finder %d skip %d threshold %d dirtiest %d using %d oldest %d%s" TENDSTR),
3500 dev->gcBlockFinder, dev->gcNotDone,
3502 dev->gcDirtiest, dev->gcPagesInUse,
3503 dev->oldestDirtyBlock,
3504 background ? " bg" : ""));
3510 /* New garbage collector
3511 * If we're very low on erased blocks then we do aggressive garbage collection
3512 * otherwise we do "leasurely" garbage collection.
3513 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3514 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3516 * The idea is to help clear out space in a more spread-out manner.
3517 * Dunno if it really does anything useful.
3519 static int yaffs_CheckGarbageCollection(yaffs_Device *dev, int background)
3522 int gcOk = YAFFS_OK;
3528 int checkpointBlockAdjust;
3530 if(dev->param.gcControl &&
3531 (dev->param.gcControl(dev) & 1) == 0)
3534 if (dev->gcDisable) {
3535 /* Bail out so we don't get recursive gc */
3539 /* This loop should pass the first time.
3540 * We'll only see looping here if the collection does not increase space.
3546 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3547 if (checkpointBlockAdjust < 0)
3548 checkpointBlockAdjust = 0;
3550 minErased = dev->param.nReservedBlocks + checkpointBlockAdjust + 1;
3551 erasedChunks = dev->nErasedBlocks * dev->param.nChunksPerBlock;
3553 /* If we need a block soon then do aggressive gc.*/
3554 if (dev->nErasedBlocks < minErased)
3557 if(dev->gcSkip > 20)
3559 if(erasedChunks < dev->nFreeChunks/2 ||
3571 /* If we don't already have a block being gc'd then see if we should start another */
3573 if (dev->gcBlock < 1 && !aggressive) {
3574 dev->gcBlock = yaffs_FindRefreshBlock(dev);
3577 if (dev->gcBlock < 1) {
3578 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive, background);
3582 if (dev->gcBlock > 0) {
3589 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3590 dev->nErasedBlocks, aggressive));
3592 gcOk = yaffs_GarbageCollectBlock(dev, dev->gcBlock, aggressive);
3595 if (dev->nErasedBlocks < (dev->param.nReservedBlocks) && dev->gcBlock > 0) {
3598 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3599 TENDSTR), dev->nErasedBlocks, maxTries, dev->gcBlock));
3601 } while ((dev->nErasedBlocks < dev->param.nReservedBlocks) &&
3602 (dev->gcBlock > 0) &&
3605 return aggressive ? gcOk : YAFFS_OK;
3609 * yaffs_BackgroundGarbageCollect()
3610 * Garbage collects. Intended to be called from a background thread.
3611 * Returns non-zero if at least half the free chunks are erased.
3613 int yaffs_BackgroundGarbageCollect(yaffs_Device *dev, unsigned urgency)
3615 int erasedChunks = dev->nErasedBlocks * dev->param.nChunksPerBlock;
3617 T(YAFFS_TRACE_BACKGROUND, (TSTR("Background gc %u" TENDSTR),urgency));
3619 yaffs_CheckGarbageCollection(dev, 1);
3620 return erasedChunks > dev->nFreeChunks/2;
3623 /*------------------------- TAGS --------------------------------*/
3625 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
3628 return (tags->chunkId == chunkInObject &&
3629 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3634 /*-------------------- Data file manipulation -----------------*/
3636 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
3637 yaffs_ExtendedTags *tags)
3639 /*Get the Tnode, then get the level 0 offset chunk offset */
3642 yaffs_ExtendedTags localTags;
3645 yaffs_Device *dev = in->myDev;
3648 /* Passed a NULL, so use our own tags space */
3652 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3655 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3658 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3664 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
3665 yaffs_ExtendedTags *tags)
3667 /* Get the Tnode, then get the level 0 offset chunk offset */
3670 yaffs_ExtendedTags localTags;
3672 yaffs_Device *dev = in->myDev;
3676 /* Passed a NULL, so use our own tags space */
3680 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3684 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3687 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3690 /* Delete the entry in the filestructure (if found) */
3692 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, 0);
3698 #ifdef YAFFS_PARANOID
3700 static int yaffs_CheckFileSanity(yaffs_Object *in)
3708 yaffs_Tags localTags;
3709 yaffs_Tags *tags = &localTags;
3713 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3716 objId = in->objectId;
3717 fSize = in->variant.fileVariant.fileSize;
3719 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3721 for (chunk = 1; chunk <= nChunks; chunk++) {
3722 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3727 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunk);
3729 if (yaffs_CheckChunkBits
3730 (dev, theChunk / dev->param.nChunksPerBlock,
3731 theChunk % dev->param.nChunksPerBlock)) {
3733 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3737 (tags, in->objectId, chunk, chunkDeleted)) {
3747 /* T(("No level 0 found for %d\n", chunk)); */
3751 return failed ? YAFFS_FAIL : YAFFS_OK;
3756 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
3757 int chunkInNAND, int inScan)
3759 /* NB inScan is zero unless scanning.
3760 * For forward scanning, inScan is > 0;
3761 * for backward scanning inScan is < 0
3763 * chunkInNAND = 0 is a dummy insert to make sure the tnodes are there.
3767 yaffs_Device *dev = in->myDev;
3769 yaffs_ExtendedTags existingTags;
3770 yaffs_ExtendedTags newTags;
3771 unsigned existingSerial, newSerial;
3773 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3774 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3775 * If it is not during Scanning then something went wrong!
3778 T(YAFFS_TRACE_ERROR,
3780 ("yaffs tragedy:attempt to put data chunk into a non-file"
3785 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3789 tn = yaffs_AddOrFindLevel0Tnode(dev,
3790 &in->variant.fileVariant,
3797 /* Dummy insert, bail now */
3800 existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3803 /* If we're scanning then we need to test for duplicates
3804 * NB This does not need to be efficient since it should only ever
3805 * happen when the power fails during a write, then only one
3806 * chunk should ever be affected.
3808 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3809 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3812 if (existingChunk > 0) {
3813 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3814 * thus we have to do a FindChunkInFile to get the real chunk id.
3816 * We have a duplicate now we need to decide which one to use:
3818 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3819 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3820 * YAFFS1: Get both sets of tags and compare serial numbers.
3824 /* Only do this for forward scanning */
3825 yaffs_ReadChunkWithTagsFromNAND(dev,
3829 /* Do a proper find */
3831 yaffs_FindChunkInFile(in, chunkInInode,
3835 if (existingChunk <= 0) {
3836 /*Hoosterman - how did this happen? */
3838 T(YAFFS_TRACE_ERROR,
3840 ("yaffs tragedy: existing chunk < 0 in scan"
3845 /* NB The deleted flags should be false, otherwise the chunks will
3846 * not be loaded during a scan
3850 newSerial = newTags.serialNumber;
3851 existingSerial = existingTags.serialNumber;
3855 (in->myDev->param.isYaffs2 ||
3856 existingChunk <= 0 ||
3857 ((existingSerial + 1) & 3) == newSerial)) {
3858 /* Forward scanning.
3860 * Delete the old one and drop through to update the tnode
3862 yaffs_DeleteChunk(dev, existingChunk, 1,
3865 /* Backward scanning or we want to use the existing one
3867 * Delete the new one and return early so that the tnode isn't changed
3869 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3877 if (existingChunk == 0)
3880 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
3885 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
3888 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3890 if (chunkInNAND >= 0)
3891 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3894 T(YAFFS_TRACE_NANDACCESS,
3895 (TSTR("Chunk %d not found zero instead" TENDSTR),
3897 /* get sane (zero) data if you read a hole */
3898 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3904 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
3908 yaffs_ExtendedTags tags;
3909 yaffs_BlockInfo *bi;
3915 block = chunkId / dev->param.nChunksPerBlock;
3916 page = chunkId % dev->param.nChunksPerBlock;
3919 if (!yaffs_CheckChunkBit(dev, block, page))
3920 T(YAFFS_TRACE_VERIFY,
3921 (TSTR("Deleting invalid chunk %d"TENDSTR),
3924 bi = yaffs_GetBlockInfo(dev, block);
3926 yaffs_UpdateOldestDirtySequence(dev, block, bi);
3928 T(YAFFS_TRACE_DELETION,
3929 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3932 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->param.isYaffs2) {
3934 yaffs_InitialiseTags(&tags);
3936 tags.chunkDeleted = 1;
3938 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3939 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3941 dev->nUnmarkedDeletions++;
3944 /* Pull out of the management area.
3945 * If the whole block became dirty, this will kick off an erasure.
3947 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3948 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3949 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3950 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3953 yaffs_ClearChunkBit(dev, block, page);
3957 if (bi->pagesInUse == 0 &&
3958 !bi->hasShrinkHeader &&
3959 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3960 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3961 yaffs_BlockBecameDirty(dev, block);
3968 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
3969 const __u8 *buffer, int nBytes,
3972 /* Find old chunk Need to do this to get serial number
3973 * Write new one and patch into tree.
3974 * Invalidate old tags.
3978 yaffs_ExtendedTags prevTags;
3981 yaffs_ExtendedTags newTags;
3983 yaffs_Device *dev = in->myDev;
3985 yaffs_CheckGarbageCollection(dev,0);
3987 /* Get the previous chunk at this location in the file if it exists.
3988 * If it does not exist then put a zero into the tree. This creates
3989 * the tnode now, rather than later when it is harder to clean up.
3991 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3992 if(prevChunkId < 1 &&
3993 !yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0))
3996 /* Set up new tags */
3997 yaffs_InitialiseTags(&newTags);
3999 newTags.chunkId = chunkInInode;
4000 newTags.objectId = in->objectId;
4001 newTags.serialNumber =
4002 (prevChunkId > 0) ? prevTags.serialNumber + 1 : 1;
4003 newTags.byteCount = nBytes;
4005 if (nBytes < 1 || nBytes > dev->param.totalBytesPerChunk) {
4006 T(YAFFS_TRACE_ERROR,
4007 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
4013 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
4016 if (newChunkId > 0) {
4017 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
4019 if (prevChunkId > 0)
4020 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
4022 yaffs_CheckFileSanity(in);
4028 /* UpdateObjectHeader updates the header on NAND for an object.
4029 * If name is not NULL, then that new name is used.
4031 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
4032 int isShrink, int shadows)
4035 yaffs_BlockInfo *bi;
4037 yaffs_Device *dev = in->myDev;
4044 yaffs_ExtendedTags newTags;
4045 yaffs_ExtendedTags oldTags;
4046 YCHAR *alias = NULL;
4048 __u8 *buffer = NULL;
4049 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
4051 yaffs_ObjectHeader *oh = NULL;
4053 yaffs_strcpy(oldName, _Y("silly old name"));
4057 in == dev->rootDir || /* The rootDir should also be saved */
4060 yaffs_CheckGarbageCollection(dev,0);
4061 yaffs_CheckObjectDetailsLoaded(in);
4063 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
4064 oh = (yaffs_ObjectHeader *) buffer;
4066 prevChunkId = in->hdrChunk;
4068 if (prevChunkId > 0) {
4069 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
4072 yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
4074 memcpy(oldName, oh->name, sizeof(oh->name));
4077 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
4079 oh->type = in->variantType;
4080 oh->yst_mode = in->yst_mode;
4081 oh->shadowsObject = oh->inbandShadowsObject = shadows;
4083 #ifdef CONFIG_YAFFS_WINCE
4084 oh->win_atime[0] = in->win_atime[0];
4085 oh->win_ctime[0] = in->win_ctime[0];
4086 oh->win_mtime[0] = in->win_mtime[0];
4087 oh->win_atime[1] = in->win_atime[1];
4088 oh->win_ctime[1] = in->win_ctime[1];
4089 oh->win_mtime[1] = in->win_mtime[1];
4091 oh->yst_uid = in->yst_uid;
4092 oh->yst_gid = in->yst_gid;
4093 oh->yst_atime = in->yst_atime;
4094 oh->yst_mtime = in->yst_mtime;
4095 oh->yst_ctime = in->yst_ctime;
4096 oh->yst_rdev = in->yst_rdev;
4099 oh->parentObjectId = in->parent->objectId;
4101 oh->parentObjectId = 0;
4103 if (name && *name) {
4104 memset(oh->name, 0, sizeof(oh->name));
4105 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
4106 } else if (prevChunkId > 0)
4107 memcpy(oh->name, oldName, sizeof(oh->name));
4109 memset(oh->name, 0, sizeof(oh->name));
4111 oh->isShrink = isShrink;
4113 switch (in->variantType) {
4114 case YAFFS_OBJECT_TYPE_UNKNOWN:
4115 /* Should not happen */
4117 case YAFFS_OBJECT_TYPE_FILE:
4119 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
4120 || oh->parentObjectId ==
4121 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
4122 fileVariant.fileSize;
4124 case YAFFS_OBJECT_TYPE_HARDLINK:
4125 oh->equivalentObjectId =
4126 in->variant.hardLinkVariant.equivalentObjectId;
4128 case YAFFS_OBJECT_TYPE_SPECIAL:
4131 case YAFFS_OBJECT_TYPE_DIRECTORY:
4134 case YAFFS_OBJECT_TYPE_SYMLINK:
4135 alias = in->variant.symLinkVariant.alias;
4137 alias = _Y("no alias");
4138 yaffs_strncpy(oh->alias,
4140 YAFFS_MAX_ALIAS_LENGTH);
4141 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
4146 yaffs_InitialiseTags(&newTags);
4148 newTags.chunkId = 0;
4149 newTags.objectId = in->objectId;
4150 newTags.serialNumber = in->serial;
4152 /* Add extra info for file header */
4154 newTags.extraHeaderInfoAvailable = 1;
4155 newTags.extraParentObjectId = oh->parentObjectId;
4156 newTags.extraFileLength = oh->fileSize;
4157 newTags.extraIsShrinkHeader = oh->isShrink;
4158 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
4159 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
4160 newTags.extraObjectType = in->variantType;
4162 yaffs_VerifyObjectHeader(in, oh, &newTags, 1);
4164 /* Create new chunk in NAND */
4166 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
4167 (prevChunkId > 0) ? 1 : 0);
4169 if (newChunkId >= 0) {
4171 in->hdrChunk = newChunkId;
4173 if (prevChunkId > 0) {
4174 yaffs_DeleteChunk(dev, prevChunkId, 1,
4178 if (!yaffs_ObjectHasCachedWriteData(in))
4181 /* If this was a shrink, then mark the block that the chunk lives on */
4183 bi = yaffs_GetBlockInfo(in->myDev,
4184 newChunkId / in->myDev->param.nChunksPerBlock);
4185 bi->hasShrinkHeader = 1;
4190 retVal = newChunkId;
4195 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
4200 /*------------------------ Short Operations Cache ----------------------------------------
4201 * In many situations where there is no high level buffering (eg WinCE) a lot of
4202 * reads might be short sequential reads, and a lot of writes may be short
4203 * sequential writes. eg. scanning/writing a jpeg file.
4204 * In these cases, a short read/write cache can provide a huge perfomance benefit
4205 * with dumb-as-a-rock code.
4206 * In Linux, the page cache provides read buffering aand the short op cache provides write
4209 * There are a limited number (~10) of cache chunks per device so that we don't
4210 * need a very intelligent search.
4213 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
4215 yaffs_Device *dev = obj->myDev;
4217 yaffs_ChunkCache *cache;
4218 int nCaches = obj->myDev->param.nShortOpCaches;
4220 for (i = 0; i < nCaches; i++) {
4221 cache = &dev->srCache[i];
4222 if (cache->object == obj &&
4231 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
4233 yaffs_Device *dev = obj->myDev;
4234 int lowest = -99; /* Stop compiler whining. */
4236 yaffs_ChunkCache *cache;
4237 int chunkWritten = 0;
4238 int nCaches = obj->myDev->param.nShortOpCaches;
4244 /* Find the dirty cache for this object with the lowest chunk id. */
4245 for (i = 0; i < nCaches; i++) {
4246 if (dev->srCache[i].object == obj &&
4247 dev->srCache[i].dirty) {
4249 || dev->srCache[i].chunkId <
4251 cache = &dev->srCache[i];
4252 lowest = cache->chunkId;
4257 if (cache && !cache->locked) {
4258 /* Write it out and free it up */
4261 yaffs_WriteChunkDataToObject(cache->object,
4267 cache->object = NULL;
4270 } while (cache && chunkWritten > 0);
4273 /* Hoosterman, disk full while writing cache out. */
4274 T(YAFFS_TRACE_ERROR,
4275 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
4282 /*yaffs_FlushEntireDeviceCache(dev)
4287 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
4290 int nCaches = dev->param.nShortOpCaches;
4293 /* Find a dirty object in the cache and flush it...
4294 * until there are no further dirty objects.
4298 for (i = 0; i < nCaches && !obj; i++) {
4299 if (dev->srCache[i].object &&
4300 dev->srCache[i].dirty)
4301 obj = dev->srCache[i].object;
4305 yaffs_FlushFilesChunkCache(obj);
4312 /* Grab us a cache chunk for use.
4313 * First look for an empty one.
4314 * Then look for the least recently used non-dirty one.
4315 * Then look for the least recently used dirty one...., flush and look again.
4317 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
4321 if (dev->param.nShortOpCaches > 0) {
4322 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4323 if (!dev->srCache[i].object)
4324 return &dev->srCache[i];
4331 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
4333 yaffs_ChunkCache *cache;
4334 yaffs_Object *theObj;
4339 if (dev->param.nShortOpCaches > 0) {
4340 /* Try find a non-dirty one... */
4342 cache = yaffs_GrabChunkCacheWorker(dev);
4345 /* They were all dirty, find the last recently used object and flush
4346 * its cache, then find again.
4347 * NB what's here is not very accurate, we actually flush the object
4348 * the last recently used page.
4351 /* With locking we can't assume we can use entry zero */
4358 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4359 if (dev->srCache[i].object &&
4360 !dev->srCache[i].locked &&
4361 (dev->srCache[i].lastUse < usage || !cache)) {
4362 usage = dev->srCache[i].lastUse;
4363 theObj = dev->srCache[i].object;
4364 cache = &dev->srCache[i];
4369 if (!cache || cache->dirty) {
4370 /* Flush and try again */
4371 yaffs_FlushFilesChunkCache(theObj);
4372 cache = yaffs_GrabChunkCacheWorker(dev);
4382 /* Find a cached chunk */
4383 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj,
4386 yaffs_Device *dev = obj->myDev;
4388 if (dev->param.nShortOpCaches > 0) {
4389 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4390 if (dev->srCache[i].object == obj &&
4391 dev->srCache[i].chunkId == chunkId) {
4394 return &dev->srCache[i];
4401 /* Mark the chunk for the least recently used algorithym */
4402 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache,
4406 if (dev->param.nShortOpCaches > 0) {
4407 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4408 /* Reset the cache usages */
4410 for (i = 1; i < dev->param.nShortOpCaches; i++)
4411 dev->srCache[i].lastUse = 0;
4418 cache->lastUse = dev->srLastUse;
4425 /* Invalidate a single cache page.
4426 * Do this when a whole page gets written,
4427 * ie the short cache for this page is no longer valid.
4429 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
4431 if (object->myDev->param.nShortOpCaches > 0) {
4432 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4435 cache->object = NULL;
4439 /* Invalidate all the cache pages associated with this object
4440 * Do this whenever ther file is deleted or resized.
4442 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
4445 yaffs_Device *dev = in->myDev;
4447 if (dev->param.nShortOpCaches > 0) {
4448 /* Invalidate it. */
4449 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4450 if (dev->srCache[i].object == in)
4451 dev->srCache[i].object = NULL;
4456 /*--------------------- Checkpointing --------------------*/
4459 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev, int head)
4461 yaffs_CheckpointValidity cp;
4463 memset(&cp, 0, sizeof(cp));
4465 cp.structType = sizeof(cp);
4466 cp.magic = YAFFS_MAGIC;
4467 cp.version = YAFFS_CHECKPOINT_VERSION;
4468 cp.head = (head) ? 1 : 0;
4470 return (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp)) ?
4474 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4476 yaffs_CheckpointValidity cp;
4479 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4482 ok = (cp.structType == sizeof(cp)) &&
4483 (cp.magic == YAFFS_MAGIC) &&
4484 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4485 (cp.head == ((head) ? 1 : 0));
4489 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4492 cp->nErasedBlocks = dev->nErasedBlocks;
4493 cp->allocationBlock = dev->allocationBlock;
4494 cp->allocationPage = dev->allocationPage;
4495 cp->nFreeChunks = dev->nFreeChunks;
4497 cp->nDeletedFiles = dev->nDeletedFiles;
4498 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4499 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4500 cp->sequenceNumber = dev->sequenceNumber;
4504 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4505 yaffs_CheckpointDevice *cp)
4507 dev->nErasedBlocks = cp->nErasedBlocks;
4508 dev->allocationBlock = cp->allocationBlock;
4509 dev->allocationPage = cp->allocationPage;
4510 dev->nFreeChunks = cp->nFreeChunks;
4512 dev->nDeletedFiles = cp->nDeletedFiles;
4513 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4514 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4515 dev->sequenceNumber = cp->sequenceNumber;
4519 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4521 yaffs_CheckpointDevice cp;
4523 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4527 /* Write device runtime values*/
4528 yaffs_DeviceToCheckpointDevice(&cp, dev);
4529 cp.structType = sizeof(cp);
4531 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4533 /* Write block info */
4535 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4536 ok = (yaffs_CheckpointWrite(dev, dev->blockInfo, nBytes) == nBytes);
4539 /* Write chunk bits */
4541 nBytes = nBlocks * dev->chunkBitmapStride;
4542 ok = (yaffs_CheckpointWrite(dev, dev->chunkBits, nBytes) == nBytes);
4548 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4550 yaffs_CheckpointDevice cp;
4552 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4556 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4560 if (cp.structType != sizeof(cp))
4564 yaffs_CheckpointDeviceToDevice(dev, &cp);
4566 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4568 ok = (yaffs_CheckpointRead(dev, dev->blockInfo, nBytes) == nBytes);
4572 nBytes = nBlocks * dev->chunkBitmapStride;
4574 ok = (yaffs_CheckpointRead(dev, dev->chunkBits, nBytes) == nBytes);
4579 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4583 cp->objectId = obj->objectId;
4584 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4585 cp->hdrChunk = obj->hdrChunk;
4586 cp->variantType = obj->variantType;
4587 cp->deleted = obj->deleted;
4588 cp->softDeleted = obj->softDeleted;
4589 cp->unlinked = obj->unlinked;
4590 cp->fake = obj->fake;
4591 cp->renameAllowed = obj->renameAllowed;
4592 cp->unlinkAllowed = obj->unlinkAllowed;
4593 cp->serial = obj->serial;
4594 cp->nDataChunks = obj->nDataChunks;
4596 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4597 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4598 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4599 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4602 static int yaffs_CheckpointObjectToObject(yaffs_Object *obj, yaffs_CheckpointObject *cp)
4605 yaffs_Object *parent;
4607 if (obj->variantType != cp->variantType) {
4608 T(YAFFS_TRACE_ERROR, (TSTR("Checkpoint read object %d type %d "
4609 TCONT("chunk %d does not match existing object type %d")
4610 TENDSTR), cp->objectId, cp->variantType, cp->hdrChunk,
4615 obj->objectId = cp->objectId;
4618 parent = yaffs_FindOrCreateObjectByNumber(
4621 YAFFS_OBJECT_TYPE_DIRECTORY);
4626 if (parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4627 T(YAFFS_TRACE_ALWAYS, (TSTR("Checkpoint read object %d parent %d type %d"
4628 TCONT(" chunk %d Parent type, %d, not directory")
4630 cp->objectId, cp->parentId, cp->variantType,
4631 cp->hdrChunk, parent->variantType));
4634 yaffs_AddObjectToDirectory(parent, obj);
4637 obj->hdrChunk = cp->hdrChunk;
4638 obj->variantType = cp->variantType;
4639 obj->deleted = cp->deleted;
4640 obj->softDeleted = cp->softDeleted;
4641 obj->unlinked = cp->unlinked;
4642 obj->fake = cp->fake;
4643 obj->renameAllowed = cp->renameAllowed;
4644 obj->unlinkAllowed = cp->unlinkAllowed;
4645 obj->serial = cp->serial;
4646 obj->nDataChunks = cp->nDataChunks;
4648 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4649 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4650 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4651 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4653 if (obj->hdrChunk > 0)
4654 obj->lazyLoaded = 1;
4660 static int yaffs_CheckpointTnodeWorker(yaffs_Object *in, yaffs_Tnode *tn,
4661 __u32 level, int chunkOffset)
4664 yaffs_Device *dev = in->myDev;
4666 int tnodeSize = yaffs_CalcTnodeSize(dev);
4671 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
4672 if (tn->internal[i]) {
4673 ok = yaffs_CheckpointTnodeWorker(in,
4676 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4679 } else if (level == 0) {
4680 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4681 ok = (yaffs_CheckpointWrite(dev, &baseOffset, sizeof(baseOffset)) == sizeof(baseOffset));
4683 ok = (yaffs_CheckpointWrite(dev, tn, tnodeSize) == tnodeSize);
4691 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4693 __u32 endMarker = ~0;
4696 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4697 ok = yaffs_CheckpointTnodeWorker(obj,
4698 obj->variant.fileVariant.top,
4699 obj->variant.fileVariant.topLevel,
4702 ok = (yaffs_CheckpointWrite(obj->myDev, &endMarker, sizeof(endMarker)) ==
4709 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4713 yaffs_Device *dev = obj->myDev;
4714 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4717 int tnodeSize = yaffs_CalcTnodeSize(dev);
4719 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4721 while (ok && (~baseChunk)) {
4723 /* Read level 0 tnode */
4726 tn = yaffs_GetTnodeRaw(dev);
4728 ok = (yaffs_CheckpointRead(dev, tn, tnodeSize) == tnodeSize);
4733 ok = yaffs_AddOrFindLevel0Tnode(dev,
4739 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4743 T(YAFFS_TRACE_CHECKPOINT, (
4744 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4745 nread, baseChunk, ok));
4751 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4754 yaffs_CheckpointObject cp;
4757 struct ylist_head *lh;
4760 /* Iterate through the objects in each hash entry,
4761 * dumping them to the checkpointing stream.
4764 for (i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++) {
4765 ylist_for_each(lh, &dev->objectBucket[i].list) {
4767 obj = ylist_entry(lh, yaffs_Object, hashLink);
4768 if (!obj->deferedFree) {
4769 yaffs_ObjectToCheckpointObject(&cp, obj);
4770 cp.structType = sizeof(cp);
4772 T(YAFFS_TRACE_CHECKPOINT, (
4773 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %p" TENDSTR),
4774 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk, obj));
4776 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4778 if (ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4779 ok = yaffs_WriteCheckpointTnodes(obj);
4785 /* Dump end of list */
4786 memset(&cp, 0xFF, sizeof(yaffs_CheckpointObject));
4787 cp.structType = sizeof(cp);
4790 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4795 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4798 yaffs_CheckpointObject cp;
4801 yaffs_Object *hardList = NULL;
4803 while (ok && !done) {
4804 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4805 if (cp.structType != sizeof(cp)) {
4806 T(YAFFS_TRACE_CHECKPOINT, (TSTR("struct size %d instead of %d ok %d"TENDSTR),
4807 cp.structType, (int)sizeof(cp), ok));
4811 T(YAFFS_TRACE_CHECKPOINT, (TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4812 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk));
4814 if (ok && cp.objectId == ~0)
4817 obj = yaffs_FindOrCreateObjectByNumber(dev, cp.objectId, cp.variantType);
4819 ok = yaffs_CheckpointObjectToObject(obj, &cp);
4822 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4823 ok = yaffs_ReadCheckpointTnodes(obj);
4824 } else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4825 obj->hardLinks.next =
4826 (struct ylist_head *) hardList;
4835 yaffs_HardlinkFixup(dev, hardList);
4840 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4842 __u32 checkpointSum;
4845 yaffs_GetCheckpointSum(dev, &checkpointSum);
4847 ok = (yaffs_CheckpointWrite(dev, &checkpointSum, sizeof(checkpointSum)) == sizeof(checkpointSum));
4855 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4857 __u32 checkpointSum0;
4858 __u32 checkpointSum1;
4861 yaffs_GetCheckpointSum(dev, &checkpointSum0);
4863 ok = (yaffs_CheckpointRead(dev, &checkpointSum1, sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4868 if (checkpointSum0 != checkpointSum1)
4875 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4879 if (dev->param.skipCheckpointWrite || !dev->param.isYaffs2) {
4880 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint write" TENDSTR)));
4885 ok = yaffs_CheckpointOpen(dev, 1);
4888 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4889 ok = yaffs_WriteCheckpointValidityMarker(dev, 1);
4892 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint device" TENDSTR)));
4893 ok = yaffs_WriteCheckpointDevice(dev);
4896 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint objects" TENDSTR)));
4897 ok = yaffs_WriteCheckpointObjects(dev);
4900 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4901 ok = yaffs_WriteCheckpointValidityMarker(dev, 0);
4905 ok = yaffs_WriteCheckpointSum(dev);
4907 if (!yaffs_CheckpointClose(dev))
4911 dev->isCheckpointed = 1;
4913 dev->isCheckpointed = 0;
4915 return dev->isCheckpointed;
4918 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4922 if (dev->param.skipCheckpointRead || !dev->param.isYaffs2) {
4923 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint read" TENDSTR)));
4928 ok = yaffs_CheckpointOpen(dev, 0); /* open for read */
4931 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4932 ok = yaffs_ReadCheckpointValidityMarker(dev, 1);
4935 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint device" TENDSTR)));
4936 ok = yaffs_ReadCheckpointDevice(dev);
4939 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint objects" TENDSTR)));
4940 ok = yaffs_ReadCheckpointObjects(dev);
4943 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4944 ok = yaffs_ReadCheckpointValidityMarker(dev, 0);
4948 ok = yaffs_ReadCheckpointSum(dev);
4949 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint checksum %d" TENDSTR), ok));
4952 if (!yaffs_CheckpointClose(dev))
4956 dev->isCheckpointed = 1;
4958 dev->isCheckpointed = 0;
4964 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4966 if (dev->isCheckpointed ||
4967 dev->blocksInCheckpoint > 0) {
4968 dev->isCheckpointed = 0;
4969 yaffs_CheckpointInvalidateStream(dev);
4971 if (dev->param.markSuperBlockDirty)
4972 dev->param.markSuperBlockDirty(dev);
4976 int yaffs_CheckpointSave(yaffs_Device *dev)
4979 T(YAFFS_TRACE_CHECKPOINT, (TSTR("save entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4981 yaffs_VerifyObjects(dev);
4982 yaffs_VerifyBlocks(dev);
4983 yaffs_VerifyFreeChunks(dev);
4985 if (!dev->isCheckpointed) {
4986 yaffs_InvalidateCheckpoint(dev);
4987 yaffs_WriteCheckpointData(dev);
4990 T(YAFFS_TRACE_ALWAYS, (TSTR("save exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4992 return dev->isCheckpointed;
4995 int yaffs_CheckpointRestore(yaffs_Device *dev)
4998 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
5000 retval = yaffs_ReadCheckpointData(dev);
5002 if (dev->isCheckpointed) {
5003 yaffs_VerifyObjects(dev);
5004 yaffs_VerifyBlocks(dev);
5005 yaffs_VerifyFreeChunks(dev);
5008 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
5013 /*--------------------- File read/write ------------------------
5014 * Read and write have very similar structures.
5015 * In general the read/write has three parts to it
5016 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
5017 * Some complete chunks
5018 * An incomplete chunk to end off with
5020 * Curve-balls: the first chunk might also be the last chunk.
5023 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 *buffer, loff_t offset,
5032 yaffs_ChunkCache *cache;
5039 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
5040 /* start = offset % dev->nDataBytesPerChunk; */
5041 yaffs_AddrToChunk(dev, offset, &chunk, &start);
5044 /* OK now check for the curveball where the start and end are in
5047 if ((start + n) < dev->nDataBytesPerChunk)
5050 nToCopy = dev->nDataBytesPerChunk - start;
5052 cache = yaffs_FindChunkCache(in, chunk);
5054 /* If the chunk is already in the cache or it is less than a whole chunk
5055 * or we're using inband tags then use the cache (if there is caching)
5056 * else bypass the cache.
5058 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
5059 if (dev->param.nShortOpCaches > 0) {
5061 /* If we can't find the data in the cache, then load it up. */
5064 cache = yaffs_GrabChunkCache(in->myDev);
5066 cache->chunkId = chunk;
5069 yaffs_ReadChunkDataFromObject(in, chunk,
5075 yaffs_UseChunkCache(dev, cache, 0);
5080 memcpy(buffer, &cache->data[start], nToCopy);
5084 /* Read into the local buffer then copy..*/
5087 yaffs_GetTempBuffer(dev, __LINE__);
5088 yaffs_ReadChunkDataFromObject(in, chunk,
5091 memcpy(buffer, &localBuffer[start], nToCopy);
5094 yaffs_ReleaseTempBuffer(dev, localBuffer,
5100 /* A full chunk. Read directly into the supplied buffer. */
5101 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
5115 int yaffs_DoWriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
5116 int nBytes, int writeThrough)
5125 int startOfWrite = offset;
5126 int chunkWritten = 0;
5134 while (n > 0 && chunkWritten >= 0) {
5135 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
5136 /* start = offset % dev->nDataBytesPerChunk; */
5137 yaffs_AddrToChunk(dev, offset, &chunk, &start);
5139 if (chunk * dev->nDataBytesPerChunk + start != offset ||
5140 start >= dev->nDataBytesPerChunk) {
5141 T(YAFFS_TRACE_ERROR, (
5142 TSTR("AddrToChunk of offset %d gives chunk %d start %d"
5144 (int)offset, chunk, start));
5148 /* OK now check for the curveball where the start and end are in
5152 if ((start + n) < dev->nDataBytesPerChunk) {
5155 /* Now folks, to calculate how many bytes to write back....
5156 * If we're overwriting and not writing to then end of file then
5157 * we need to write back as much as was there before.
5160 chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
5162 if (chunkStart > in->variant.fileVariant.fileSize)
5163 nBytesRead = 0; /* Past end of file */
5165 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
5167 if (nBytesRead > dev->nDataBytesPerChunk)
5168 nBytesRead = dev->nDataBytesPerChunk;
5172 (start + n)) ? nBytesRead : (start + n);
5174 if (nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
5178 nToCopy = dev->nDataBytesPerChunk - start;
5179 nToWriteBack = dev->nDataBytesPerChunk;
5182 if (nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
5183 /* An incomplete start or end chunk (or maybe both start and end chunk),
5184 * or we're using inband tags, so we want to use the cache buffers.
5186 if (dev->param.nShortOpCaches > 0) {
5187 yaffs_ChunkCache *cache;
5188 /* If we can't find the data in the cache, then load the cache */
5189 cache = yaffs_FindChunkCache(in, chunk);
5192 && yaffs_CheckSpaceForAllocation(dev, 1)) {
5193 cache = yaffs_GrabChunkCache(dev);
5195 cache->chunkId = chunk;
5198 yaffs_ReadChunkDataFromObject(in, chunk,
5202 !yaffs_CheckSpaceForAllocation(dev, 1)) {
5203 /* Drop the cache if it was a read cache item and
5204 * no space check has been made for it.
5210 yaffs_UseChunkCache(dev, cache, 1);
5214 memcpy(&cache->data[start], buffer,
5219 cache->nBytes = nToWriteBack;
5223 yaffs_WriteChunkDataToObject
5226 cache->data, cache->nBytes,
5232 chunkWritten = -1; /* fail the write */
5235 /* An incomplete start or end chunk (or maybe both start and end chunk)
5236 * Read into the local buffer then copy, then copy over and write back.
5240 yaffs_GetTempBuffer(dev, __LINE__);
5242 yaffs_ReadChunkDataFromObject(in, chunk,
5247 memcpy(&localBuffer[start], buffer, nToCopy);
5250 yaffs_WriteChunkDataToObject(in, chunk,
5255 yaffs_ReleaseTempBuffer(dev, localBuffer,
5261 /* A full chunk. Write directly from the supplied buffer. */
5266 yaffs_WriteChunkDataToObject(in, chunk, buffer,
5267 dev->nDataBytesPerChunk,
5270 /* Since we've overwritten the cached data, we better invalidate it. */
5271 yaffs_InvalidateChunkCache(in, chunk);
5274 if (chunkWritten >= 0) {
5283 /* Update file object */
5285 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
5286 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
5293 int yaffs_WriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
5294 int nBytes, int writeThrough)
5296 yaffs_HandleHole(in,offset);
5297 return yaffs_DoWriteDataToFile(in,buffer,offset,nBytes,writeThrough);
5302 /* ---------------------- File resizing stuff ------------------ */
5304 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
5307 yaffs_Device *dev = in->myDev;
5308 int oldFileSize = in->variant.fileVariant.fileSize;
5310 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
5312 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
5313 dev->nDataBytesPerChunk;
5317 /* Delete backwards so that we don't end up with holes if
5318 * power is lost part-way through the operation.
5320 for (i = lastDel; i >= startDel; i--) {
5321 /* NB this could be optimised somewhat,
5322 * eg. could retrieve the tags and write them without
5323 * using yaffs_DeleteChunk
5326 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5329 (dev->internalStartBlock * dev->param.nChunksPerBlock)
5331 ((dev->internalEndBlock +
5332 1) * dev->param.nChunksPerBlock)) {
5333 T(YAFFS_TRACE_ALWAYS,
5334 (TSTR("Found daft chunkId %d for %d" TENDSTR),
5338 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5346 static void yaffs_ResizeDown( yaffs_Object *obj, loff_t newSize)
5349 __u32 newSizeOfPartialChunk;
5350 yaffs_Device *dev = obj->myDev;
5352 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5354 yaffs_PruneResizedChunks(obj, newSize);
5356 if (newSizeOfPartialChunk != 0) {
5357 int lastChunk = 1 + newFullChunks;
5358 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5360 /* Got to read and rewrite the last chunk with its new size and zero pad */
5361 yaffs_ReadChunkDataFromObject(obj, lastChunk, localBuffer);
5362 memset(localBuffer + newSizeOfPartialChunk, 0,
5363 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5365 yaffs_WriteChunkDataToObject(obj, lastChunk, localBuffer,
5366 newSizeOfPartialChunk, 1);
5368 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5371 obj->variant.fileVariant.fileSize = newSize;
5373 yaffs_PruneFileStructure(dev, &obj->variant.fileVariant);
5377 static int yaffs_HandleHole(yaffs_Object *obj, loff_t newSize)
5379 /* if newsSize > oldFileSize.
5380 * We're going to be writing a hole.
5381 * If the hole is small then write zeros otherwise write a start of hole marker.
5388 int result = YAFFS_OK;
5389 yaffs_Device *dev = NULL;
5391 __u8 *localBuffer = NULL;
5393 int smallIncreaseOk = 0;
5398 if(obj->variantType != YAFFS_OBJECT_TYPE_FILE)
5403 /* Bail out if not yaffs2 mode */
5404 if(!dev->param.isYaffs2)
5407 oldFileSize = obj->variant.fileVariant.fileSize;
5409 if (newSize <= oldFileSize)
5412 increase = newSize - oldFileSize;
5414 if(increase < YAFFS_SMALL_HOLE_THRESHOLD * dev->nDataBytesPerChunk &&
5415 yaffs_CheckSpaceForAllocation(dev, YAFFS_SMALL_HOLE_THRESHOLD + 1))
5421 localBuffer= yaffs_GetTempBuffer(dev, __LINE__);
5424 /* fill hole with zero bytes */
5425 int pos = oldFileSize;
5428 memset(localBuffer,0,dev->nDataBytesPerChunk);
5429 smallIncreaseOk = 1;
5431 while(increase > 0 && smallIncreaseOk){
5432 thisWrite = increase;
5433 if(thisWrite > dev->nDataBytesPerChunk)
5434 thisWrite = dev->nDataBytesPerChunk;
5435 written = yaffs_DoWriteDataToFile(obj,localBuffer,pos,thisWrite,0);
5436 if(written == thisWrite){
5438 increase -= thisWrite;
5440 smallIncreaseOk = 0;
5443 yaffs_ReleaseTempBuffer(dev,localBuffer,__LINE__);
5445 /* If we were out of space then reverse any chunks we've added */
5446 if(!smallIncreaseOk)
5447 yaffs_ResizeDown(obj, oldFileSize);
5450 if (!smallIncreaseOk &&
5452 obj->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5453 obj->parent->objectId != YAFFS_OBJECTID_DELETED){
5454 /* Write a hole start header with the old file size */
5455 yaffs_UpdateObjectHeader(obj, NULL, 0,1,0);
5462 int yaffs_ResizeFile(yaffs_Object *in, loff_t newSize)
5464 yaffs_Device *dev = in->myDev;
5465 int oldFileSize = in->variant.fileVariant.fileSize;
5467 yaffs_FlushFilesChunkCache(in);
5468 yaffs_InvalidateWholeChunkCache(in);
5470 yaffs_CheckGarbageCollection(dev,0);
5472 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
5475 if (newSize == oldFileSize)
5478 if(newSize > oldFileSize){
5479 yaffs_HandleHole(in,newSize);
5480 in->variant.fileVariant.fileSize = newSize;
5482 /* newSize < oldFileSize */
5483 yaffs_ResizeDown(in, newSize);
5486 /* Write a new object header to reflect the resize.
5487 * show we've shrunk the file, if need be
5488 * Do this only if the file is not in the deleted directories
5489 * and is not shadowed.
5493 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5494 in->parent->objectId != YAFFS_OBJECTID_DELETED)
5495 yaffs_UpdateObjectHeader(in, NULL, 0,0,0);
5501 loff_t yaffs_GetFileSize(yaffs_Object *obj)
5503 YCHAR *alias = NULL;
5504 obj = yaffs_GetEquivalentObject(obj);
5506 switch (obj->variantType) {
5507 case YAFFS_OBJECT_TYPE_FILE:
5508 return obj->variant.fileVariant.fileSize;
5509 case YAFFS_OBJECT_TYPE_SYMLINK:
5510 alias = obj->variant.symLinkVariant.alias;
5513 return yaffs_strnlen(alias,YAFFS_MAX_ALIAS_LENGTH);
5521 int yaffs_FlushFile(yaffs_Object *in, int updateTime, int dataSync)
5525 yaffs_FlushFilesChunkCache(in);
5526 if(dataSync) /* Only sync data */
5530 #ifdef CONFIG_YAFFS_WINCE
5531 yfsd_WinFileTimeNow(in->win_mtime);
5534 in->yst_mtime = Y_CURRENT_TIME;
5539 retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5540 0) ? YAFFS_OK : YAFFS_FAIL;
5550 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
5553 /* First off, invalidate the file's data in the cache, without flushing. */
5554 yaffs_InvalidateWholeChunkCache(in);
5556 if (in->myDev->param.isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5557 /* Move to the unlinked directory so we have a record that it was deleted. */
5558 yaffs_ChangeObjectName(in, in->myDev->deletedDir, _Y("deleted"), 0, 0);
5562 yaffs_RemoveObjectFromDirectory(in);
5563 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5566 yaffs_FreeObject(in);
5571 /* yaffs_DeleteFile deletes the whole file data
5572 * and the inode associated with the file.
5573 * It does not delete the links associated with the file.
5575 static int yaffs_UnlinkFileIfNeeded(yaffs_Object *in)
5579 int immediateDeletion = 0;
5580 yaffs_Device *dev = in->myDev;
5583 immediateDeletion = 1;
5585 if (immediateDeletion) {
5587 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5588 _Y("deleted"), 0, 0);
5589 T(YAFFS_TRACE_TRACING,
5590 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5593 in->myDev->nDeletedFiles++;
5594 if (dev->param.disableSoftDelete || dev->param.isYaffs2)
5595 yaffs_ResizeFile(in, 0);
5596 yaffs_SoftDeleteFile(in);
5599 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5600 _Y("unlinked"), 0, 0);
5607 int yaffs_DeleteFile(yaffs_Object *in)
5609 int retVal = YAFFS_OK;
5610 int deleted = in->deleted;
5611 yaffs_Device *dev = in->myDev;
5613 if (dev->param.disableSoftDelete || dev->param.isYaffs2)
5614 yaffs_ResizeFile(in, 0);
5616 if (in->nDataChunks > 0) {
5617 /* Use soft deletion if there is data in the file.
5618 * That won't be the case if it has been resized to zero.
5621 retVal = yaffs_UnlinkFileIfNeeded(in);
5623 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5626 in->myDev->nDeletedFiles++;
5627 yaffs_SoftDeleteFile(in);
5629 return deleted ? YAFFS_OK : YAFFS_FAIL;
5631 /* The file has no data chunks so we toss it immediately */
5632 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5633 in->variant.fileVariant.top = NULL;
5634 yaffs_DoGenericObjectDeletion(in);
5640 static int yaffs_IsNonEmptyDirectory(yaffs_Object *obj)
5642 return (obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) &&
5643 !(ylist_empty(&obj->variant.directoryVariant.children));
5646 static int yaffs_DeleteDirectory(yaffs_Object *obj)
5648 /* First check that the directory is empty. */
5649 if (yaffs_IsNonEmptyDirectory(obj))
5652 return yaffs_DoGenericObjectDeletion(obj);
5655 static int yaffs_DeleteSymLink(yaffs_Object *in)
5657 if(in->variant.symLinkVariant.alias)
5658 YFREE(in->variant.symLinkVariant.alias);
5659 in->variant.symLinkVariant.alias=NULL;
5661 return yaffs_DoGenericObjectDeletion(in);
5664 static int yaffs_DeleteHardLink(yaffs_Object *in)
5666 /* remove this hardlink from the list assocaited with the equivalent
5669 ylist_del_init(&in->hardLinks);
5670 return yaffs_DoGenericObjectDeletion(in);
5673 int yaffs_DeleteObject(yaffs_Object *obj)
5676 switch (obj->variantType) {
5677 case YAFFS_OBJECT_TYPE_FILE:
5678 retVal = yaffs_DeleteFile(obj);
5680 case YAFFS_OBJECT_TYPE_DIRECTORY:
5681 if(!ylist_empty(&obj->variant.directoryVariant.dirty)){
5682 T(YAFFS_TRACE_BACKGROUND, (TSTR("Remove object %d from dirty directories" TENDSTR),obj->objectId));
5683 ylist_del_init(&obj->variant.directoryVariant.dirty);
5685 return yaffs_DeleteDirectory(obj);
5687 case YAFFS_OBJECT_TYPE_SYMLINK:
5688 retVal = yaffs_DeleteSymLink(obj);
5690 case YAFFS_OBJECT_TYPE_HARDLINK:
5691 retVal = yaffs_DeleteHardLink(obj);
5693 case YAFFS_OBJECT_TYPE_SPECIAL:
5694 retVal = yaffs_DoGenericObjectDeletion(obj);
5696 case YAFFS_OBJECT_TYPE_UNKNOWN:
5698 break; /* should not happen. */
5704 static int yaffs_UnlinkWorker(yaffs_Object *obj)
5707 int immediateDeletion = 0;
5710 immediateDeletion = 1;
5713 yaffs_UpdateParent(obj->parent);
5715 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5716 return yaffs_DeleteHardLink(obj);
5717 } else if (!ylist_empty(&obj->hardLinks)) {
5718 /* Curve ball: We're unlinking an object that has a hardlink.
5720 * This problem arises because we are not strictly following
5721 * The Linux link/inode model.
5723 * We can't really delete the object.
5724 * Instead, we do the following:
5725 * - Select a hardlink.
5726 * - Unhook it from the hard links
5727 * - Move it from its parent directory (so that the rename can work)
5728 * - Rename the object to the hardlink's name.
5729 * - Delete the hardlink
5733 yaffs_Object *parent;
5735 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5737 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5739 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5740 parent = hl->parent;
5742 ylist_del_init(&hl->hardLinks);
5744 yaffs_AddObjectToDirectory(obj->myDev->unlinkedDir, hl);
5746 retVal = yaffs_ChangeObjectName(obj,parent, name, 0, 0);
5748 if (retVal == YAFFS_OK)
5749 retVal = yaffs_DoGenericObjectDeletion(hl);
5753 } else if (immediateDeletion) {
5754 switch (obj->variantType) {
5755 case YAFFS_OBJECT_TYPE_FILE:
5756 return yaffs_DeleteFile(obj);
5758 case YAFFS_OBJECT_TYPE_DIRECTORY:
5759 ylist_del_init(&obj->variant.directoryVariant.dirty);
5760 return yaffs_DeleteDirectory(obj);
5762 case YAFFS_OBJECT_TYPE_SYMLINK:
5763 return yaffs_DeleteSymLink(obj);
5765 case YAFFS_OBJECT_TYPE_SPECIAL:
5766 return yaffs_DoGenericObjectDeletion(obj);
5768 case YAFFS_OBJECT_TYPE_HARDLINK:
5769 case YAFFS_OBJECT_TYPE_UNKNOWN:
5773 } else if(yaffs_IsNonEmptyDirectory(obj))
5776 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
5777 _Y("unlinked"), 0, 0);
5781 static int yaffs_UnlinkObject(yaffs_Object *obj)
5784 if (obj && obj->unlinkAllowed)
5785 return yaffs_UnlinkWorker(obj);
5790 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
5794 obj = yaffs_FindObjectByName(dir, name);
5795 return yaffs_UnlinkObject(obj);
5798 /*----------------------- Initialisation Scanning ---------------------- */
5800 static void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
5801 int backwardScanning)
5805 if (!backwardScanning) {
5806 /* Handle YAFFS1 forward scanning case
5807 * For YAFFS1 we always do the deletion
5811 /* Handle YAFFS2 case (backward scanning)
5812 * If the shadowed object exists then ignore.
5814 obj = yaffs_FindObjectByNumber(dev, objId);
5819 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5820 * We put it in unlinked dir to be cleaned up after the scanning
5823 yaffs_FindOrCreateObjectByNumber(dev, objId,
5824 YAFFS_OBJECT_TYPE_FILE);
5827 obj->isShadowed = 1;
5828 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5829 obj->variant.fileVariant.shrinkSize = 0;
5830 obj->valid = 1; /* So that we don't read any other info for this file */
5840 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5847 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5849 in = yaffs_FindObjectByNumber(dev,
5850 hl->variant.hardLinkVariant.
5851 equivalentObjectId);
5854 /* Add the hardlink pointers */
5855 hl->variant.hardLinkVariant.equivalentObject = in;
5856 ylist_add(&hl->hardLinks, &in->hardLinks);
5858 /* Todo Need to report/handle this better.
5859 * Got a problem... hardlink to a non-existant object
5861 hl->variant.hardLinkVariant.equivalentObject = NULL;
5862 YINIT_LIST_HEAD(&hl->hardLinks);
5872 static int ybicmp(const void *a, const void *b)
5874 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5875 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5876 register int ablock = ((yaffs_BlockIndex *)a)->block;
5877 register int bblock = ((yaffs_BlockIndex *)b)->block;
5879 return ablock - bblock;
5885 struct yaffs_ShadowFixerStruct {
5888 struct yaffs_ShadowFixerStruct *next;
5892 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5895 * Sort out state of unlinked and deleted objects after scanning.
5897 struct ylist_head *i;
5898 struct ylist_head *n;
5901 /* Soft delete all the unlinked files */
5902 ylist_for_each_safe(i, n,
5903 &dev->unlinkedDir->variant.directoryVariant.children) {
5905 l = ylist_entry(i, yaffs_Object, siblings);
5906 yaffs_DeleteObject(l);
5910 ylist_for_each_safe(i, n,
5911 &dev->deletedDir->variant.directoryVariant.children) {
5913 l = ylist_entry(i, yaffs_Object, siblings);
5914 yaffs_DeleteObject(l);
5921 * This code iterates through all the objects making sure that they are rooted.
5922 * Any unrooted objects are re-rooted in lost+found.
5923 * An object needs to be in one of:
5924 * - Directly under deleted, unlinked
5925 * - Directly or indirectly under root.
5928 * This code assumes that we don't ever change the current relationships between
5930 * rootDir->parent == unlinkedDir->parent == deletedDir->parent == NULL
5931 * lostNfound->parent == rootDir
5933 * This fixes the problem where directories might have inadvertently been deleted
5934 * leaving the object "hanging" without being rooted in the directory tree.
5937 static int yaffs_HasNULLParent(yaffs_Device *dev, yaffs_Object *obj)
5939 return (obj == dev->deletedDir ||
5940 obj == dev->unlinkedDir||
5941 obj == dev->rootDir);
5944 static void yaffs_FixHangingObjects(yaffs_Device *dev)
5947 yaffs_Object *parent;
5949 struct ylist_head *lh;
5950 struct ylist_head *n;
5955 /* Iterate through the objects in each hash entry,
5956 * looking at each object.
5957 * Make sure it is rooted.
5960 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
5961 ylist_for_each_safe(lh, n, &dev->objectBucket[i].list) {
5963 obj = ylist_entry(lh, yaffs_Object, hashLink);
5964 parent= obj->parent;
5966 if(yaffs_HasNULLParent(dev,obj)){
5967 /* These directories are not hanging */
5970 else if(!parent || parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5972 else if(yaffs_HasNULLParent(dev,parent))
5976 * Need to follow the parent chain to see if it is hanging.
5981 while(parent != dev->rootDir &&
5983 parent->parent->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
5985 parent = parent->parent;
5988 if(parent != dev->rootDir)
5993 (TSTR("Hanging object %d moved to lost and found" TENDSTR),
5995 yaffs_AddObjectToDirectory(dev->lostNFoundDir,obj);
6004 * Delete directory contents for cleaning up lost and found.
6006 static void yaffs_DeleteDirectoryContents(yaffs_Object *dir)
6009 struct ylist_head *lh;
6010 struct ylist_head *n;
6012 if(dir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
6015 ylist_for_each_safe(lh, n, &dir->variant.directoryVariant.children) {
6017 obj = ylist_entry(lh, yaffs_Object, siblings);
6018 if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
6019 yaffs_DeleteDirectoryContents(obj);
6022 (TSTR("Deleting lost_found object %d" TENDSTR),
6025 /* Need to use UnlinkObject since Delete would not handle
6026 * hardlinked objects correctly.
6028 yaffs_UnlinkObject(obj);
6034 static void yaffs_EmptyLostAndFound(yaffs_Device *dev)
6036 yaffs_DeleteDirectoryContents(dev->lostNFoundDir);
6039 static int yaffs_Scan(yaffs_Device *dev)
6041 yaffs_ExtendedTags tags;
6051 yaffs_BlockState state;
6052 yaffs_Object *hardList = NULL;
6053 yaffs_BlockInfo *bi;
6054 __u32 sequenceNumber;
6055 yaffs_ObjectHeader *oh;
6057 yaffs_Object *parent;
6059 int alloc_failed = 0;
6061 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
6069 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
6070 dev->internalStartBlock, dev->internalEndBlock));
6072 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6074 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6076 /* Scan all the blocks to determine their state */
6077 bi = dev->blockInfo;
6078 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6079 yaffs_ClearChunkBits(dev, blk);
6081 bi->softDeletions = 0;
6083 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6085 bi->blockState = state;
6086 bi->sequenceNumber = sequenceNumber;
6088 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6089 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6091 T(YAFFS_TRACE_SCAN_DEBUG,
6092 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6093 state, sequenceNumber));
6095 if (state == YAFFS_BLOCK_STATE_DEAD) {
6096 T(YAFFS_TRACE_BAD_BLOCKS,
6097 (TSTR("block %d is bad" TENDSTR), blk));
6098 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6099 T(YAFFS_TRACE_SCAN_DEBUG,
6100 (TSTR("Block empty " TENDSTR)));
6101 dev->nErasedBlocks++;
6102 dev->nFreeChunks += dev->param.nChunksPerBlock;
6107 startIterator = dev->internalStartBlock;
6108 endIterator = dev->internalEndBlock;
6110 /* For each block.... */
6111 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
6118 blk = blockIterator;
6120 bi = yaffs_GetBlockInfo(dev, blk);
6121 state = bi->blockState;
6125 /* For each chunk in each block that needs scanning....*/
6126 for (c = 0; !alloc_failed && c < dev->param.nChunksPerBlock &&
6127 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
6128 /* Read the tags and decide what to do */
6129 chunk = blk * dev->param.nChunksPerBlock + c;
6131 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6134 /* Let's have a good look at this chunk... */
6136 if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
6142 /*T((" %d %d deleted\n",blk,c)); */
6143 } else if (!tags.chunkUsed) {
6144 /* An unassigned chunk in the block
6145 * This means that either the block is empty or
6146 * this is the one being allocated from
6150 /* We're looking at the first chunk in the block so the block is unused */
6151 state = YAFFS_BLOCK_STATE_EMPTY;
6152 dev->nErasedBlocks++;
6154 /* this is the block being allocated from */
6157 (" Allocating from %d %d" TENDSTR),
6159 state = YAFFS_BLOCK_STATE_ALLOCATING;
6160 dev->allocationBlock = blk;
6161 dev->allocationPage = c;
6162 dev->allocationBlockFinder = blk;
6163 /* Set block finder here to encourage the allocator to go forth from here. */
6167 dev->nFreeChunks += (dev->param.nChunksPerBlock - c);
6168 } else if (tags.chunkId > 0) {
6169 /* chunkId > 0 so it is a data chunk... */
6170 unsigned int endpos;
6172 yaffs_SetChunkBit(dev, blk, c);
6175 in = yaffs_FindOrCreateObjectByNumber(dev,
6178 YAFFS_OBJECT_TYPE_FILE);
6179 /* PutChunkIntoFile checks for a clash (two data chunks with
6180 * the same chunkId).
6187 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, 1))
6192 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
6195 in->variantType == YAFFS_OBJECT_TYPE_FILE
6196 && in->variant.fileVariant.scannedFileSize <
6198 in->variant.fileVariant.
6199 scannedFileSize = endpos;
6200 if (!dev->param.useHeaderFileSize) {
6201 in->variant.fileVariant.
6203 in->variant.fileVariant.
6208 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
6210 /* chunkId == 0, so it is an ObjectHeader.
6211 * Thus, we read in the object header and make the object
6213 yaffs_SetChunkBit(dev, blk, c);
6216 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
6220 oh = (yaffs_ObjectHeader *) chunkData;
6222 in = yaffs_FindObjectByNumber(dev,
6224 if (in && in->variantType != oh->type) {
6225 /* This should not happen, but somehow
6226 * Wev'e ended up with an objectId that has been reused but not yet
6227 * deleted, and worse still it has changed type. Delete the old object.
6230 yaffs_DeleteObject(in);
6235 in = yaffs_FindOrCreateObjectByNumber(dev,
6243 if (in && oh->shadowsObject > 0) {
6245 struct yaffs_ShadowFixerStruct *fixer;
6246 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
6248 fixer->next = shadowFixerList;
6249 shadowFixerList = fixer;
6250 fixer->objectId = tags.objectId;
6251 fixer->shadowedId = oh->shadowsObject;
6256 if (in && in->valid) {
6257 /* We have already filled this one. We have a duplicate and need to resolve it. */
6259 unsigned existingSerial = in->serial;
6260 unsigned newSerial = tags.serialNumber;
6262 if (((existingSerial + 1) & 3) == newSerial) {
6263 /* Use new one - destroy the exisiting one */
6264 yaffs_DeleteChunk(dev,
6269 /* Use existing - destroy this one. */
6270 yaffs_DeleteChunk(dev, chunk, 1,
6275 if (in && !in->valid &&
6276 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6277 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
6278 /* We only load some info, don't fiddle with directory structure */
6280 in->variantType = oh->type;
6282 in->yst_mode = oh->yst_mode;
6283 #ifdef CONFIG_YAFFS_WINCE
6284 in->win_atime[0] = oh->win_atime[0];
6285 in->win_ctime[0] = oh->win_ctime[0];
6286 in->win_mtime[0] = oh->win_mtime[0];
6287 in->win_atime[1] = oh->win_atime[1];
6288 in->win_ctime[1] = oh->win_ctime[1];
6289 in->win_mtime[1] = oh->win_mtime[1];
6291 in->yst_uid = oh->yst_uid;
6292 in->yst_gid = oh->yst_gid;
6293 in->yst_atime = oh->yst_atime;
6294 in->yst_mtime = oh->yst_mtime;
6295 in->yst_ctime = oh->yst_ctime;
6296 in->yst_rdev = oh->yst_rdev;
6298 in->hdrChunk = chunk;
6299 in->serial = tags.serialNumber;
6301 } else if (in && !in->valid) {
6302 /* we need to load this info */
6305 in->variantType = oh->type;
6307 in->yst_mode = oh->yst_mode;
6308 #ifdef CONFIG_YAFFS_WINCE
6309 in->win_atime[0] = oh->win_atime[0];
6310 in->win_ctime[0] = oh->win_ctime[0];
6311 in->win_mtime[0] = oh->win_mtime[0];
6312 in->win_atime[1] = oh->win_atime[1];
6313 in->win_ctime[1] = oh->win_ctime[1];
6314 in->win_mtime[1] = oh->win_mtime[1];
6316 in->yst_uid = oh->yst_uid;
6317 in->yst_gid = oh->yst_gid;
6318 in->yst_atime = oh->yst_atime;
6319 in->yst_mtime = oh->yst_mtime;
6320 in->yst_ctime = oh->yst_ctime;
6321 in->yst_rdev = oh->yst_rdev;
6323 in->hdrChunk = chunk;
6324 in->serial = tags.serialNumber;
6326 yaffs_SetObjectName(in, oh->name);
6329 /* directory stuff...
6334 yaffs_FindOrCreateObjectByNumber
6335 (dev, oh->parentObjectId,
6336 YAFFS_OBJECT_TYPE_DIRECTORY);
6339 if (parent && parent->variantType ==
6340 YAFFS_OBJECT_TYPE_UNKNOWN) {
6341 /* Set up as a directory */
6342 parent->variantType =
6343 YAFFS_OBJECT_TYPE_DIRECTORY;
6344 YINIT_LIST_HEAD(&parent->variant.
6347 } else if (!parent || parent->variantType !=
6348 YAFFS_OBJECT_TYPE_DIRECTORY) {
6349 /* Hoosterman, another problem....
6350 * We're trying to use a non-directory as a directory
6353 T(YAFFS_TRACE_ERROR,
6355 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6357 parent = dev->lostNFoundDir;
6360 yaffs_AddObjectToDirectory(parent, in);
6362 if (0 && (parent == dev->deletedDir ||
6363 parent == dev->unlinkedDir)) {
6364 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
6365 dev->nDeletedFiles++;
6367 /* Note re hardlinks.
6368 * Since we might scan a hardlink before its equivalent object is scanned
6369 * we put them all in a list.
6370 * After scanning is complete, we should have all the objects, so we run through this
6371 * list and fix up all the chains.
6374 switch (in->variantType) {
6375 case YAFFS_OBJECT_TYPE_UNKNOWN:
6376 /* Todo got a problem */
6378 case YAFFS_OBJECT_TYPE_FILE:
6379 if (dev->param.useHeaderFileSize)
6381 in->variant.fileVariant.
6386 case YAFFS_OBJECT_TYPE_HARDLINK:
6387 in->variant.hardLinkVariant.
6388 equivalentObjectId =
6389 oh->equivalentObjectId;
6390 in->hardLinks.next =
6391 (struct ylist_head *)
6395 case YAFFS_OBJECT_TYPE_DIRECTORY:
6398 case YAFFS_OBJECT_TYPE_SPECIAL:
6401 case YAFFS_OBJECT_TYPE_SYMLINK:
6402 in->variant.symLinkVariant.alias =
6403 yaffs_CloneString(oh->alias);
6404 if (!in->variant.symLinkVariant.alias)
6413 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6414 /* If we got this far while scanning, then the block is fully allocated.*/
6415 state = YAFFS_BLOCK_STATE_FULL;
6418 if (state == YAFFS_BLOCK_STATE_ALLOCATING) {
6419 /* If the block was partially allocated then treat it as fully allocated.*/
6420 state = YAFFS_BLOCK_STATE_FULL;
6421 dev->allocationBlock = -1;
6424 bi->blockState = state;
6426 /* Now let's see if it was dirty */
6427 if (bi->pagesInUse == 0 &&
6428 !bi->hasShrinkHeader &&
6429 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6430 yaffs_BlockBecameDirty(dev, blk);
6436 /* Ok, we've done all the scanning.
6437 * Fix up the hard link chains.
6438 * We should now have scanned all the objects, now it's time to add these
6442 yaffs_HardlinkFixup(dev, hardList);
6444 /* Fix up any shadowed objects */
6446 struct yaffs_ShadowFixerStruct *fixer;
6449 while (shadowFixerList) {
6450 fixer = shadowFixerList;
6451 shadowFixerList = fixer->next;
6452 /* Complete the rename transaction by deleting the shadowed object
6453 * then setting the object header to unshadowed.
6455 obj = yaffs_FindObjectByNumber(dev, fixer->shadowedId);
6457 yaffs_DeleteObject(obj);
6459 obj = yaffs_FindObjectByNumber(dev, fixer->objectId);
6462 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6468 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6473 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
6479 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
6482 yaffs_ObjectHeader *oh;
6484 yaffs_ExtendedTags tags;
6486 int alloc_failed = 0;
6494 T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
6496 in->lazyLoaded ? "not yet" : "already"));
6499 if (in->lazyLoaded && in->hdrChunk > 0) {
6501 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6503 result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
6504 oh = (yaffs_ObjectHeader *) chunkData;
6506 in->yst_mode = oh->yst_mode;
6507 #ifdef CONFIG_YAFFS_WINCE
6508 in->win_atime[0] = oh->win_atime[0];
6509 in->win_ctime[0] = oh->win_ctime[0];
6510 in->win_mtime[0] = oh->win_mtime[0];
6511 in->win_atime[1] = oh->win_atime[1];
6512 in->win_ctime[1] = oh->win_ctime[1];
6513 in->win_mtime[1] = oh->win_mtime[1];
6515 in->yst_uid = oh->yst_uid;
6516 in->yst_gid = oh->yst_gid;
6517 in->yst_atime = oh->yst_atime;
6518 in->yst_mtime = oh->yst_mtime;
6519 in->yst_ctime = oh->yst_ctime;
6520 in->yst_rdev = oh->yst_rdev;
6523 yaffs_SetObjectName(in, oh->name);
6525 if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6526 in->variant.symLinkVariant.alias =
6527 yaffs_CloneString(oh->alias);
6528 if (!in->variant.symLinkVariant.alias)
6529 alloc_failed = 1; /* Not returned to caller */
6532 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6536 static int yaffs_ScanBackwards(yaffs_Device *dev)
6538 yaffs_ExtendedTags tags;
6543 int nBlocksToScan = 0;
6549 yaffs_BlockState state;
6550 yaffs_Object *hardList = NULL;
6551 yaffs_BlockInfo *bi;
6552 __u32 sequenceNumber;
6553 yaffs_ObjectHeader *oh;
6555 yaffs_Object *parent;
6556 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6562 int foundChunksInBlock;
6563 int equivalentObjectId;
6564 int alloc_failed = 0;
6567 yaffs_BlockIndex *blockIndex = NULL;
6568 int altBlockIndex = 0;
6570 if (!dev->param.isYaffs2) {
6572 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6578 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
6579 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6582 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6584 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6587 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6593 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6597 dev->blocksInCheckpoint = 0;
6599 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6601 /* Scan all the blocks to determine their state */
6602 bi = dev->blockInfo;
6603 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6604 yaffs_ClearChunkBits(dev, blk);
6606 bi->softDeletions = 0;
6608 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6610 bi->blockState = state;
6611 bi->sequenceNumber = sequenceNumber;
6613 if (bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6614 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6615 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6616 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6618 T(YAFFS_TRACE_SCAN_DEBUG,
6619 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6620 state, sequenceNumber));
6623 if (state == YAFFS_BLOCK_STATE_CHECKPOINT) {
6624 dev->blocksInCheckpoint++;
6626 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6627 T(YAFFS_TRACE_BAD_BLOCKS,
6628 (TSTR("block %d is bad" TENDSTR), blk));
6629 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6630 T(YAFFS_TRACE_SCAN_DEBUG,
6631 (TSTR("Block empty " TENDSTR)));
6632 dev->nErasedBlocks++;
6633 dev->nFreeChunks += dev->param.nChunksPerBlock;
6634 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6636 /* Determine the highest sequence number */
6637 if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6638 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6640 blockIndex[nBlocksToScan].seq = sequenceNumber;
6641 blockIndex[nBlocksToScan].block = blk;
6645 if (sequenceNumber >= dev->sequenceNumber)
6646 dev->sequenceNumber = sequenceNumber;
6648 /* TODO: Nasty sequence number! */
6651 ("Block scanning block %d has bad sequence number %d"
6652 TENDSTR), blk, sequenceNumber));
6660 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6666 /* Sort the blocks */
6667 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6669 /* Use qsort now. */
6670 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6674 /* Dungy old bubble sort... */
6676 yaffs_BlockIndex temp;
6680 for (i = 0; i < nBlocksToScan; i++)
6681 for (j = i + 1; j < nBlocksToScan; j++)
6682 if (blockIndex[i].seq > blockIndex[j].seq) {
6683 temp = blockIndex[j];
6684 blockIndex[j] = blockIndex[i];
6685 blockIndex[i] = temp;
6692 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6694 /* Now scan the blocks looking at the data. */
6696 endIterator = nBlocksToScan - 1;
6697 T(YAFFS_TRACE_SCAN_DEBUG,
6698 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6700 /* For each block.... backwards */
6701 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6703 /* Cooperative multitasking! This loop can run for so
6704 long that watchdog timers expire. */
6707 /* get the block to scan in the correct order */
6708 blk = blockIndex[blockIterator].block;
6710 bi = yaffs_GetBlockInfo(dev, blk);
6713 state = bi->blockState;
6717 /* For each chunk in each block that needs scanning.... */
6718 foundChunksInBlock = 0;
6719 for (c = dev->param.nChunksPerBlock - 1;
6720 !alloc_failed && c >= 0 &&
6721 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6722 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6723 /* Scan backwards...
6724 * Read the tags and decide what to do
6727 chunk = blk * dev->param.nChunksPerBlock + c;
6729 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6732 /* Let's have a good look at this chunk... */
6734 if (!tags.chunkUsed) {
6735 /* An unassigned chunk in the block.
6736 * If there are used chunks after this one, then
6737 * it is a chunk that was skipped due to failing the erased
6738 * check. Just skip it so that it can be deleted.
6739 * But, more typically, We get here when this is an unallocated
6740 * chunk and his means that either the block is empty or
6741 * this is the one being allocated from
6744 if (foundChunksInBlock) {
6745 /* This is a chunk that was skipped due to failing the erased check */
6746 } else if (c == 0) {
6747 /* We're looking at the first chunk in the block so the block is unused */
6748 state = YAFFS_BLOCK_STATE_EMPTY;
6749 dev->nErasedBlocks++;
6751 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6752 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6753 if (dev->sequenceNumber == bi->sequenceNumber) {
6754 /* this is the block being allocated from */
6758 (" Allocating from %d %d"
6761 state = YAFFS_BLOCK_STATE_ALLOCATING;
6762 dev->allocationBlock = blk;
6763 dev->allocationPage = c;
6764 dev->allocationBlockFinder = blk;
6766 /* This is a partially written block that is not
6767 * the current allocation block.
6771 (TSTR("Partially written block %d detected" TENDSTR),
6779 } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED) {
6781 (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
6786 } else if (tags.chunkId > 0) {
6787 /* chunkId > 0 so it is a data chunk... */
6788 unsigned int endpos;
6790 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6792 foundChunksInBlock = 1;
6795 yaffs_SetChunkBit(dev, blk, c);
6798 in = yaffs_FindOrCreateObjectByNumber(dev,
6801 YAFFS_OBJECT_TYPE_FILE);
6808 in->variantType == YAFFS_OBJECT_TYPE_FILE
6809 && chunkBase < in->variant.fileVariant.shrinkSize) {
6810 /* This has not been invalidated by a resize */
6811 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, -1)) {
6815 /* File size is calculated by looking at the data chunks if we have not
6816 * seen an object header yet. Stop this practice once we find an object header.
6818 endpos = chunkBase + tags.byteCount;
6820 if (!in->valid && /* have not got an object header yet */
6821 in->variant.fileVariant.scannedFileSize < endpos) {
6822 in->variant.fileVariant.scannedFileSize = endpos;
6823 in->variant.fileVariant.fileSize = endpos;
6827 /* This chunk has been invalidated by a resize, or a past file deletion
6828 * so delete the chunk*/
6829 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6833 /* chunkId == 0, so it is an ObjectHeader.
6834 * Thus, we read in the object header and make the object
6836 foundChunksInBlock = 1;
6838 yaffs_SetChunkBit(dev, blk, c);
6844 if (tags.extraHeaderInfoAvailable) {
6845 in = yaffs_FindOrCreateObjectByNumber(dev,
6847 tags.extraObjectType);
6853 (!in->valid && dev->param.disableLazyLoad) ||
6854 tags.extraShadows ||
6856 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6857 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))) {
6859 /* If we don't have valid info then we need to read the chunk
6860 * TODO In future we can probably defer reading the chunk and
6861 * living with invalid data until needed.
6864 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6869 oh = (yaffs_ObjectHeader *) chunkData;
6871 if (dev->param.inbandTags) {
6872 /* Fix up the header if they got corrupted by inband tags */
6873 oh->shadowsObject = oh->inbandShadowsObject;
6874 oh->isShrink = oh->inbandIsShrink;
6878 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6886 /* TODO Hoosterman we have a problem! */
6887 T(YAFFS_TRACE_ERROR,
6889 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6890 TENDSTR), tags.objectId, chunk));
6895 /* We have already filled this one.
6896 * We have a duplicate that will be discarded, but
6897 * we first have to suck out resize info if it is a file.
6900 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6902 oh->type == YAFFS_OBJECT_TYPE_FILE) ||
6903 (tags.extraHeaderInfoAvailable &&
6904 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))) {
6906 (oh) ? oh->fileSize : tags.
6908 __u32 parentObjectId =
6910 parentObjectId : tags.
6911 extraParentObjectId;
6915 (oh) ? oh->isShrink : tags.
6916 extraIsShrinkHeader;
6918 /* If it is deleted (unlinked at start also means deleted)
6919 * we treat the file size as being zeroed at this point.
6921 if (parentObjectId ==
6922 YAFFS_OBJECTID_DELETED
6923 || parentObjectId ==
6924 YAFFS_OBJECTID_UNLINKED) {
6929 if (isShrink && in->variant.fileVariant.shrinkSize > thisSize)
6930 in->variant.fileVariant.shrinkSize = thisSize;
6933 bi->hasShrinkHeader = 1;
6936 /* Use existing - destroy this one. */
6937 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6941 if (!in->valid && in->variantType !=
6942 (oh ? oh->type : tags.extraObjectType))
6943 T(YAFFS_TRACE_ERROR, (
6944 TSTR("yaffs tragedy: Bad object type, "
6945 TCONT("%d != %d, for object %d at chunk ")
6946 TCONT("%d during scan")
6948 oh->type : tags.extraObjectType,
6949 in->variantType, tags.objectId,
6953 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6955 YAFFS_OBJECTID_LOSTNFOUND)) {
6956 /* We only load some info, don't fiddle with directory structure */
6960 in->variantType = oh->type;
6962 in->yst_mode = oh->yst_mode;
6963 #ifdef CONFIG_YAFFS_WINCE
6964 in->win_atime[0] = oh->win_atime[0];
6965 in->win_ctime[0] = oh->win_ctime[0];
6966 in->win_mtime[0] = oh->win_mtime[0];
6967 in->win_atime[1] = oh->win_atime[1];
6968 in->win_ctime[1] = oh->win_ctime[1];
6969 in->win_mtime[1] = oh->win_mtime[1];
6971 in->yst_uid = oh->yst_uid;
6972 in->yst_gid = oh->yst_gid;
6973 in->yst_atime = oh->yst_atime;
6974 in->yst_mtime = oh->yst_mtime;
6975 in->yst_ctime = oh->yst_ctime;
6976 in->yst_rdev = oh->yst_rdev;
6980 in->variantType = tags.extraObjectType;
6984 in->hdrChunk = chunk;
6986 } else if (!in->valid) {
6987 /* we need to load this info */
6990 in->hdrChunk = chunk;
6993 in->variantType = oh->type;
6995 in->yst_mode = oh->yst_mode;
6996 #ifdef CONFIG_YAFFS_WINCE
6997 in->win_atime[0] = oh->win_atime[0];
6998 in->win_ctime[0] = oh->win_ctime[0];
6999 in->win_mtime[0] = oh->win_mtime[0];
7000 in->win_atime[1] = oh->win_atime[1];
7001 in->win_ctime[1] = oh->win_ctime[1];
7002 in->win_mtime[1] = oh->win_mtime[1];
7004 in->yst_uid = oh->yst_uid;
7005 in->yst_gid = oh->yst_gid;
7006 in->yst_atime = oh->yst_atime;
7007 in->yst_mtime = oh->yst_mtime;
7008 in->yst_ctime = oh->yst_ctime;
7009 in->yst_rdev = oh->yst_rdev;
7012 if (oh->shadowsObject > 0)
7013 yaffs_HandleShadowedObject(dev,
7020 yaffs_SetObjectName(in, oh->name);
7022 yaffs_FindOrCreateObjectByNumber
7023 (dev, oh->parentObjectId,
7024 YAFFS_OBJECT_TYPE_DIRECTORY);
7026 fileSize = oh->fileSize;
7027 isShrink = oh->isShrink;
7028 equivalentObjectId = oh->equivalentObjectId;
7031 in->variantType = tags.extraObjectType;
7033 yaffs_FindOrCreateObjectByNumber
7034 (dev, tags.extraParentObjectId,
7035 YAFFS_OBJECT_TYPE_DIRECTORY);
7036 fileSize = tags.extraFileLength;
7037 isShrink = tags.extraIsShrinkHeader;
7038 equivalentObjectId = tags.extraEquivalentObjectId;
7047 /* directory stuff...
7051 if (parent && parent->variantType ==
7052 YAFFS_OBJECT_TYPE_UNKNOWN) {
7053 /* Set up as a directory */
7054 parent->variantType =
7055 YAFFS_OBJECT_TYPE_DIRECTORY;
7056 YINIT_LIST_HEAD(&parent->variant.
7059 } else if (!parent || parent->variantType !=
7060 YAFFS_OBJECT_TYPE_DIRECTORY) {
7061 /* Hoosterman, another problem....
7062 * We're trying to use a non-directory as a directory
7065 T(YAFFS_TRACE_ERROR,
7067 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
7069 parent = dev->lostNFoundDir;
7072 yaffs_AddObjectToDirectory(parent, in);
7074 itsUnlinked = (parent == dev->deletedDir) ||
7075 (parent == dev->unlinkedDir);
7078 /* Mark the block as having a shrinkHeader */
7079 bi->hasShrinkHeader = 1;
7082 /* Note re hardlinks.
7083 * Since we might scan a hardlink before its equivalent object is scanned
7084 * we put them all in a list.
7085 * After scanning is complete, we should have all the objects, so we run
7086 * through this list and fix up all the chains.
7089 switch (in->variantType) {
7090 case YAFFS_OBJECT_TYPE_UNKNOWN:
7091 /* Todo got a problem */
7093 case YAFFS_OBJECT_TYPE_FILE:
7095 if (in->variant.fileVariant.
7096 scannedFileSize < fileSize) {
7097 /* This covers the case where the file size is greater
7098 * than where the data is
7099 * This will happen if the file is resized to be larger
7100 * than its current data extents.
7102 in->variant.fileVariant.fileSize = fileSize;
7103 in->variant.fileVariant.scannedFileSize = fileSize;
7106 if (in->variant.fileVariant.shrinkSize > fileSize)
7107 in->variant.fileVariant.shrinkSize = fileSize;
7111 case YAFFS_OBJECT_TYPE_HARDLINK:
7113 in->variant.hardLinkVariant.equivalentObjectId =
7115 in->hardLinks.next =
7116 (struct ylist_head *) hardList;
7120 case YAFFS_OBJECT_TYPE_DIRECTORY:
7123 case YAFFS_OBJECT_TYPE_SPECIAL:
7126 case YAFFS_OBJECT_TYPE_SYMLINK:
7128 in->variant.symLinkVariant.alias =
7129 yaffs_CloneString(oh->alias);
7130 if (!in->variant.symLinkVariant.alias)
7140 } /* End of scanning for each chunk */
7142 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
7143 /* If we got this far while scanning, then the block is fully allocated. */
7144 state = YAFFS_BLOCK_STATE_FULL;
7148 bi->blockState = state;
7150 /* Now let's see if it was dirty */
7151 if (bi->pagesInUse == 0 &&
7152 !bi->hasShrinkHeader &&
7153 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
7154 yaffs_BlockBecameDirty(dev, blk);
7159 yaffs_SkipRestOfBlock(dev);
7162 YFREE_ALT(blockIndex);
7166 /* Ok, we've done all the scanning.
7167 * Fix up the hard link chains.
7168 * We should now have scanned all the objects, now it's time to add these
7171 yaffs_HardlinkFixup(dev, hardList);
7174 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
7179 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
7184 /*------------------------------ Directory Functions ----------------------------- */
7186 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
7188 struct ylist_head *lh;
7189 yaffs_Object *listObj;
7194 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
7199 if (yaffs_SkipVerification(obj->myDev))
7203 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
7208 if (obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7209 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
7213 /* Iterate through the objects in each hash entry */
7215 ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
7217 listObj = ylist_entry(lh, yaffs_Object, siblings);
7218 yaffs_VerifyObject(listObj);
7225 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR), count));
7230 static void yaffs_VerifyDirectory(yaffs_Object *directory)
7232 struct ylist_head *lh;
7233 yaffs_Object *listObj;
7240 if (yaffs_SkipFullVerification(directory->myDev))
7243 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7244 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR), directory->variantType));
7248 /* Iterate through the objects in each hash entry */
7250 ylist_for_each(lh, &directory->variant.directoryVariant.children) {
7252 listObj = ylist_entry(lh, yaffs_Object, siblings);
7253 if (listObj->parent != directory) {
7254 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR), listObj->parent));
7257 yaffs_VerifyObjectInDirectory(listObj);
7263 *yaffs_UpdateParent() handles fixing a directories mtime and ctime when a new
7264 * link (ie. name) is created or deleted in the directory.
7267 * create dir/a : update dir's mtime/ctime
7268 * rm dir/a: update dir's mtime/ctime
7269 * modify dir/a: don't update dir's mtimme/ctime
7271 * This can be handled immediately or defered. Defering helps reduce the number
7272 * of updates when many files in a directory are changed within a brief period.
7274 * If the directory updating is defered then yaffs_UpdateDirtyDirecories must be
7275 * called periodically.
7278 static void yaffs_UpdateParent(yaffs_Object *obj)
7286 obj->yst_mtime = obj->yst_ctime = Y_CURRENT_TIME;
7287 if(dev->param.deferDirectoryUpdate){
7288 struct ylist_head *link = &obj->variant.directoryVariant.dirty;
7290 if(ylist_empty(link)){
7291 ylist_add(link,&dev->dirtyDirectories);
7292 T(YAFFS_TRACE_BACKGROUND, (TSTR("Added object %d to dirty directories" TENDSTR),obj->objectId));
7296 yaffs_UpdateObjectHeader(obj,NULL,0,0,0);
7299 void yaffs_UpdateDirtyDirectories(yaffs_Device *dev)
7301 struct ylist_head *link;
7303 yaffs_DirectoryStructure *dS;
7304 yaffs_ObjectVariant *oV;
7306 T(YAFFS_TRACE_BACKGROUND, (TSTR("Update dirty directories" TENDSTR)));
7308 while(!ylist_empty(&dev->dirtyDirectories)){
7309 link = dev->dirtyDirectories.next;
7310 ylist_del_init(link);
7312 dS=ylist_entry(link,yaffs_DirectoryStructure,dirty);
7313 oV = ylist_entry(dS,yaffs_ObjectVariant,directoryVariant);
7314 obj = ylist_entry(oV,yaffs_Object,variant);
7316 T(YAFFS_TRACE_BACKGROUND, (TSTR("Update directory %d" TENDSTR), obj->objectId));
7319 yaffs_UpdateObjectHeader(obj,NULL,0,0,0);
7323 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
7325 yaffs_Device *dev = obj->myDev;
7326 yaffs_Object *parent;
7328 yaffs_VerifyObjectInDirectory(obj);
7329 parent = obj->parent;
7331 yaffs_VerifyDirectory(parent);
7333 if (dev && dev->param.removeObjectCallback)
7334 dev->param.removeObjectCallback(obj);
7337 ylist_del_init(&obj->siblings);
7340 yaffs_VerifyDirectory(parent);
7343 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
7347 T(YAFFS_TRACE_ALWAYS,
7349 ("tragedy: Trying to add an object to a null pointer directory"
7354 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7355 T(YAFFS_TRACE_ALWAYS,
7357 ("tragedy: Trying to add an object to a non-directory"
7362 if (obj->siblings.prev == NULL) {
7363 /* Not initialised */
7368 yaffs_VerifyDirectory(directory);
7370 yaffs_RemoveObjectFromDirectory(obj);
7374 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
7375 obj->parent = directory;
7377 if (directory == obj->myDev->unlinkedDir
7378 || directory == obj->myDev->deletedDir) {
7380 obj->myDev->nUnlinkedFiles++;
7381 obj->renameAllowed = 0;
7384 yaffs_VerifyDirectory(directory);
7385 yaffs_VerifyObjectInDirectory(obj);
7388 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
7393 struct ylist_head *i;
7394 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
7402 T(YAFFS_TRACE_ALWAYS,
7404 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7409 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7410 T(YAFFS_TRACE_ALWAYS,
7412 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7416 sum = yaffs_CalcNameSum(name);
7418 ylist_for_each(i, &directory->variant.directoryVariant.children) {
7420 l = ylist_entry(i, yaffs_Object, siblings);
7422 if (l->parent != directory)
7425 yaffs_CheckObjectDetailsLoaded(l);
7427 /* Special case for lost-n-found */
7428 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7429 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
7431 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
7432 /* LostnFound chunk called Objxxx
7435 yaffs_GetObjectName(l, buffer,
7436 YAFFS_MAX_NAME_LENGTH + 1);
7437 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
7448 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
7449 int (*fn) (yaffs_Object *))
7451 struct ylist_head *i;
7455 T(YAFFS_TRACE_ALWAYS,
7457 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7462 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7463 T(YAFFS_TRACE_ALWAYS,
7465 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7470 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
7472 l = ylist_entry(i, yaffs_Object, siblings);
7483 /* GetEquivalentObject dereferences any hard links to get to the
7487 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
7489 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
7490 /* We want the object id of the equivalent object, not this one */
7491 obj = obj->variant.hardLinkVariant.equivalentObject;
7492 yaffs_CheckObjectDetailsLoaded(obj);
7497 int yaffs_GetObjectName(yaffs_Object *obj, YCHAR *name, int buffSize)
7499 memset(name, 0, buffSize * sizeof(YCHAR));
7501 yaffs_CheckObjectDetailsLoaded(obj);
7503 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7504 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
7505 } else if (obj->hdrChunk <= 0) {
7507 YCHAR numString[20];
7508 YCHAR *x = &numString[19];
7509 unsigned v = obj->objectId;
7513 *x = '0' + (v % 10);
7516 /* make up a name */
7517 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
7518 yaffs_strcat(locName, x);
7519 yaffs_strncpy(name, locName, buffSize - 1);
7522 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
7523 else if (obj->shortName[0])
7524 yaffs_strncpy(name, obj->shortName,YAFFS_SHORT_NAME_LENGTH+1);
7528 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
7530 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
7532 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
7534 if (obj->hdrChunk > 0) {
7535 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
7536 obj->hdrChunk, buffer,
7539 yaffs_strncpy(name, oh->name, buffSize - 1);
7542 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
7545 return yaffs_strnlen(name,buffSize-1);
7548 int yaffs_GetObjectFileLength(yaffs_Object *obj)
7550 /* Dereference any hard linking */
7551 obj = yaffs_GetEquivalentObject(obj);
7553 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
7554 return obj->variant.fileVariant.fileSize;
7555 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
7556 if(!obj->variant.symLinkVariant.alias)
7558 return yaffs_strnlen(obj->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
7560 /* Only a directory should drop through to here */
7561 return obj->myDev->nDataBytesPerChunk;
7565 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
7568 struct ylist_head *i;
7571 count++; /* the object itself */
7573 ylist_for_each(i, &obj->hardLinks)
7574 count++; /* add the hard links; */
7579 int yaffs_GetObjectInode(yaffs_Object *obj)
7581 obj = yaffs_GetEquivalentObject(obj);
7583 return obj->objectId;
7586 unsigned yaffs_GetObjectType(yaffs_Object *obj)
7588 obj = yaffs_GetEquivalentObject(obj);
7590 switch (obj->variantType) {
7591 case YAFFS_OBJECT_TYPE_FILE:
7594 case YAFFS_OBJECT_TYPE_DIRECTORY:
7597 case YAFFS_OBJECT_TYPE_SYMLINK:
7600 case YAFFS_OBJECT_TYPE_HARDLINK:
7603 case YAFFS_OBJECT_TYPE_SPECIAL:
7604 if (S_ISFIFO(obj->yst_mode))
7606 if (S_ISCHR(obj->yst_mode))
7608 if (S_ISBLK(obj->yst_mode))
7610 if (S_ISSOCK(obj->yst_mode))
7618 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
7620 obj = yaffs_GetEquivalentObject(obj);
7621 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
7622 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7624 return yaffs_CloneString(_Y(""));
7627 #ifndef CONFIG_YAFFS_WINCE
7629 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
7631 unsigned int valid = attr->ia_valid;
7633 if (valid & ATTR_MODE)
7634 obj->yst_mode = attr->ia_mode;
7635 if (valid & ATTR_UID)
7636 obj->yst_uid = attr->ia_uid;
7637 if (valid & ATTR_GID)
7638 obj->yst_gid = attr->ia_gid;
7640 if (valid & ATTR_ATIME)
7641 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7642 if (valid & ATTR_CTIME)
7643 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7644 if (valid & ATTR_MTIME)
7645 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7647 if (valid & ATTR_SIZE)
7648 yaffs_ResizeFile(obj, attr->ia_size);
7650 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7655 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
7657 unsigned int valid = 0;
7659 attr->ia_mode = obj->yst_mode;
7661 attr->ia_uid = obj->yst_uid;
7663 attr->ia_gid = obj->yst_gid;
7666 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7667 valid |= ATTR_ATIME;
7668 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7669 valid |= ATTR_CTIME;
7670 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7671 valid |= ATTR_MTIME;
7673 attr->ia_size = yaffs_GetFileSize(obj);
7676 attr->ia_valid = valid;
7684 int yaffs_DumpObject(yaffs_Object *obj)
7688 yaffs_GetObjectName(obj, name, YAFFS_MAX_NAME_LENGTH + 1);
7690 T(YAFFS_TRACE_ALWAYS,
7692 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7693 " chunk %d type %d size %d\n"
7694 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7695 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7696 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7702 /*---------------------------- Initialisation code -------------------------------------- */
7704 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
7707 /* Common functions, gotta have */
7708 if (!dev->param.eraseBlockInNAND || !dev->param.initialiseNAND)
7711 #ifdef CONFIG_YAFFS_YAFFS2
7713 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7714 if (dev->param.writeChunkWithTagsToNAND &&
7715 dev->param.readChunkWithTagsFromNAND &&
7716 !dev->param.writeChunkToNAND &&
7717 !dev->param.readChunkFromNAND &&
7718 dev->param.markNANDBlockBad &&
7719 dev->param.queryNANDBlock)
7723 /* Can use the "spare" style interface for yaffs1 */
7724 if (!dev->param.isYaffs2 &&
7725 !dev->param.writeChunkWithTagsToNAND &&
7726 !dev->param.readChunkWithTagsFromNAND &&
7727 dev->param.writeChunkToNAND &&
7728 dev->param.readChunkFromNAND &&
7729 !dev->param.markNANDBlockBad &&
7730 !dev->param.queryNANDBlock)
7737 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7739 /* Initialise the unlinked, deleted, root and lost and found directories */
7741 dev->lostNFoundDir = dev->rootDir = NULL;
7742 dev->unlinkedDir = dev->deletedDir = NULL;
7745 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7748 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7751 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7752 YAFFS_ROOT_MODE | S_IFDIR);
7753 dev->lostNFoundDir =
7754 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7755 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7757 if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
7758 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7765 int yaffs_GutsInitialise(yaffs_Device *dev)
7767 int init_failed = 0;
7771 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7773 /* Check stuff that must be set */
7776 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7780 dev->internalStartBlock = dev->param.startBlock;
7781 dev->internalEndBlock = dev->param.endBlock;
7782 dev->blockOffset = 0;
7783 dev->chunkOffset = 0;
7784 dev->nFreeChunks = 0;
7788 if (dev->param.startBlock == 0) {
7789 dev->internalStartBlock = dev->param.startBlock + 1;
7790 dev->internalEndBlock = dev->param.endBlock + 1;
7791 dev->blockOffset = 1;
7792 dev->chunkOffset = dev->param.nChunksPerBlock;
7795 /* Check geometry parameters. */
7797 if ((!dev->param.inbandTags && dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 1024) ||
7798 (!dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 512) ||
7799 (dev->param.inbandTags && !dev->param.isYaffs2) ||
7800 dev->param.nChunksPerBlock < 2 ||
7801 dev->param.nReservedBlocks < 2 ||
7802 dev->internalStartBlock <= 0 ||
7803 dev->internalEndBlock <= 0 ||
7804 dev->internalEndBlock <= (dev->internalStartBlock + dev->param.nReservedBlocks + 2)) { /* otherwise it is too small */
7805 T(YAFFS_TRACE_ALWAYS,
7807 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7808 TENDSTR), dev->param.totalBytesPerChunk, dev->param.isYaffs2 ? "2" : "", dev->param.inbandTags));
7812 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7813 T(YAFFS_TRACE_ALWAYS,
7814 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7818 /* Sort out space for inband tags, if required */
7819 if (dev->param.inbandTags)
7820 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7822 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk;
7824 /* Got the right mix of functions? */
7825 if (!yaffs_CheckDevFunctions(dev)) {
7826 /* Function missing */
7827 T(YAFFS_TRACE_ALWAYS,
7829 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7834 /* This is really a compilation check. */
7835 if (!yaffs_CheckStructures()) {
7836 T(YAFFS_TRACE_ALWAYS,
7837 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7841 if (dev->isMounted) {
7842 T(YAFFS_TRACE_ALWAYS,
7843 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7847 /* Finished with most checks. One or two more checks happen later on too. */
7851 /* OK now calculate a few things for the device */
7854 * Calculate all the chunk size manipulation numbers:
7856 x = dev->nDataBytesPerChunk;
7857 /* We always use dev->chunkShift and dev->chunkDiv */
7858 dev->chunkShift = Shifts(x);
7859 x >>= dev->chunkShift;
7861 /* We only use chunk mask if chunkDiv is 1 */
7862 dev->chunkMask = (1<<dev->chunkShift) - 1;
7865 * Calculate chunkGroupBits.
7866 * We need to find the next power of 2 > than internalEndBlock
7869 x = dev->param.nChunksPerBlock * (dev->internalEndBlock + 1);
7873 /* Set up tnode width if wide tnodes are enabled. */
7874 if (!dev->param.wideTnodesDisabled) {
7875 /* bits must be even so that we end up with 32-bit words */
7879 dev->tnodeWidth = 16;
7881 dev->tnodeWidth = bits;
7883 dev->tnodeWidth = 16;
7885 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7887 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7888 * so if the bitwidth of the
7889 * chunk range we're using is greater than 16 we need
7890 * to figure out chunk shift and chunkGroupSize
7893 if (bits <= dev->tnodeWidth)
7894 dev->chunkGroupBits = 0;
7896 dev->chunkGroupBits = bits - dev->tnodeWidth;
7899 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7901 if (dev->param.nChunksPerBlock < dev->chunkGroupSize) {
7902 /* We have a problem because the soft delete won't work if
7903 * the chunk group size > chunks per block.
7904 * This can be remedied by using larger "virtual blocks".
7906 T(YAFFS_TRACE_ALWAYS,
7907 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7912 /* OK, we've finished verifying the device, lets continue with initialisation */
7914 /* More device initialisation */
7916 dev->passiveGCs = 0;
7917 dev->oldestDirtyGCs = 0;
7918 dev->backgroundGCs = 0;
7919 dev->gcBlockFinder = 0;
7920 dev->bufferedBlock = -1;
7921 dev->doingBufferedBlockRewrite = 0;
7922 dev->nDeletedFiles = 0;
7923 dev->nBackgroundDeletions = 0;
7924 dev->nUnlinkedFiles = 0;
7926 dev->eccUnfixed = 0;
7927 dev->tagsEccFixed = 0;
7928 dev->tagsEccUnfixed = 0;
7929 dev->nErasureFailures = 0;
7930 dev->nErasedBlocks = 0;
7932 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7933 YINIT_LIST_HEAD(&dev->dirtyDirectories);
7934 dev->oldestDirtySequence = 0;
7935 dev->oldestDirtyBlock = 0;
7937 /* Initialise temporary buffers and caches. */
7938 if (!yaffs_InitialiseTempBuffers(dev))
7941 dev->srCache = NULL;
7942 dev->gcCleanupList = NULL;
7946 dev->param.nShortOpCaches > 0) {
7949 int srCacheBytes = dev->param.nShortOpCaches * sizeof(yaffs_ChunkCache);
7951 if (dev->param.nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
7952 dev->param.nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7954 dev->srCache = YMALLOC(srCacheBytes);
7956 buf = (__u8 *) dev->srCache;
7959 memset(dev->srCache, 0, srCacheBytes);
7961 for (i = 0; i < dev->param.nShortOpCaches && buf; i++) {
7962 dev->srCache[i].object = NULL;
7963 dev->srCache[i].lastUse = 0;
7964 dev->srCache[i].dirty = 0;
7965 dev->srCache[i].data = buf = YMALLOC_DMA(dev->param.totalBytesPerChunk);
7976 dev->gcCleanupList = YMALLOC(dev->param.nChunksPerBlock * sizeof(__u32));
7977 if (!dev->gcCleanupList)
7981 if (dev->param.isYaffs2)
7982 dev->param.useHeaderFileSize = 1;
7984 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7987 yaffs_InitialiseTnodes(dev);
7988 yaffs_InitialiseObjects(dev);
7990 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7995 /* Now scan the flash. */
7996 if (dev->param.isYaffs2) {
7997 if (yaffs_CheckpointRestore(dev)) {
7998 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7999 T(YAFFS_TRACE_ALWAYS,
8000 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
8003 /* Clean up the mess caused by an aborted checkpoint load
8004 * and scan backwards.
8006 yaffs_DeinitialiseBlocks(dev);
8007 yaffs_DeinitialiseTnodes(dev);
8008 yaffs_DeinitialiseObjects(dev);
8011 dev->nErasedBlocks = 0;
8012 dev->nFreeChunks = 0;
8013 dev->allocationBlock = -1;
8014 dev->allocationPage = -1;
8015 dev->nDeletedFiles = 0;
8016 dev->nUnlinkedFiles = 0;
8017 dev->nBackgroundDeletions = 0;
8019 if (!init_failed && !yaffs_InitialiseBlocks(dev))
8022 yaffs_InitialiseTnodes(dev);
8023 yaffs_InitialiseObjects(dev);
8025 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
8028 if (!init_failed && !yaffs_ScanBackwards(dev))
8031 } else if (!yaffs_Scan(dev))
8034 yaffs_StripDeletedObjects(dev);
8035 yaffs_FixHangingObjects(dev);
8036 if(dev->param.emptyLostAndFound)
8037 yaffs_EmptyLostAndFound(dev);
8041 /* Clean up the mess */
8042 T(YAFFS_TRACE_TRACING,
8043 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
8045 yaffs_Deinitialise(dev);
8049 /* Zero out stats */
8050 dev->nPageReads = 0;
8051 dev->nPageWrites = 0;
8052 dev->nBlockErasures = 0;
8054 dev->nRetriedWrites = 0;
8056 dev->nRetiredBlocks = 0;
8058 yaffs_VerifyFreeChunks(dev);
8059 yaffs_VerifyBlocks(dev);
8061 /* Clean up any aborted checkpoint data */
8062 if(!dev->isCheckpointed && dev->blocksInCheckpoint > 0)
8063 yaffs_InvalidateCheckpoint(dev);
8065 T(YAFFS_TRACE_TRACING,
8066 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
8071 void yaffs_Deinitialise(yaffs_Device *dev)
8073 if (dev->isMounted) {
8076 yaffs_DeinitialiseBlocks(dev);
8077 yaffs_DeinitialiseTnodes(dev);
8078 yaffs_DeinitialiseObjects(dev);
8079 if (dev->param.nShortOpCaches > 0 &&
8082 for (i = 0; i < dev->param.nShortOpCaches; i++) {
8083 if (dev->srCache[i].data)
8084 YFREE(dev->srCache[i].data);
8085 dev->srCache[i].data = NULL;
8088 YFREE(dev->srCache);
8089 dev->srCache = NULL;
8092 YFREE(dev->gcCleanupList);
8094 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
8095 YFREE(dev->tempBuffer[i].buffer);
8099 if (dev->param.deinitialiseNAND)
8100 dev->param.deinitialiseNAND(dev);
8104 static int yaffs_CountFreeChunks(yaffs_Device *dev)
8109 yaffs_BlockInfo *blk;
8111 blk = dev->blockInfo;
8112 for (b = dev->internalStartBlock; b <= dev->internalEndBlock; b++) {
8113 switch (blk->blockState) {
8114 case YAFFS_BLOCK_STATE_EMPTY:
8115 case YAFFS_BLOCK_STATE_ALLOCATING:
8116 case YAFFS_BLOCK_STATE_COLLECTING:
8117 case YAFFS_BLOCK_STATE_FULL:
8119 (dev->param.nChunksPerBlock - blk->pagesInUse +
8120 blk->softDeletions);
8131 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
8133 /* This is what we report to the outside world */
8136 int nDirtyCacheChunks;
8137 int blocksForCheckpoint;
8141 nFree = dev->nFreeChunks;
8143 nFree = yaffs_CountFreeChunks(dev);
8146 nFree += dev->nDeletedFiles;
8148 /* Now count the number of dirty chunks in the cache and subtract those */
8150 for (nDirtyCacheChunks = 0, i = 0; i < dev->param.nShortOpCaches; i++) {
8151 if (dev->srCache[i].dirty)
8152 nDirtyCacheChunks++;
8155 nFree -= nDirtyCacheChunks;
8157 nFree -= ((dev->param.nReservedBlocks + 1) * dev->param.nChunksPerBlock);
8159 /* Now we figure out how much to reserve for the checkpoint and report that... */
8160 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
8161 if (blocksForCheckpoint < 0)
8162 blocksForCheckpoint = 0;
8164 nFree -= (blocksForCheckpoint * dev->param.nChunksPerBlock);
8173 static int yaffs_freeVerificationFailures;
8175 static void yaffs_VerifyFreeChunks(yaffs_Device *dev)
8180 if (yaffs_SkipVerification(dev))
8183 counted = yaffs_CountFreeChunks(dev);
8185 difference = dev->nFreeChunks - counted;
8188 T(YAFFS_TRACE_ALWAYS,
8189 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
8190 dev->nFreeChunks, counted, difference));
8191 yaffs_freeVerificationFailures++;
8195 /*---------------------------------------- YAFFS test code ----------------------*/
8197 #define yaffs_CheckStruct(structure, syze, name) \
8199 if (sizeof(structure) != syze) { \
8200 T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
8201 name, syze, (int) sizeof(structure))); \
8202 return YAFFS_FAIL; \
8206 static int yaffs_CheckStructures(void)
8208 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
8209 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
8210 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
8211 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
8212 /* yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode"); */
8214 #ifndef CONFIG_YAFFS_WINCE
8215 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");