2 * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
4 * Copyright (C) 2002-2010 Aleph One Ltd.
5 * for Toby Churchill Ltd and Brightstar Engineering
7 * Created by Charles Manning <charles@aleph1.co.uk>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2 as
11 * published by the Free Software Foundation.
14 #include "yaffs_trace.h"
16 #include "yaffsinterface.h"
17 #include "yaffs_guts.h"
18 #include "yaffs_tagsvalidity.h"
19 #include "yaffs_getblockinfo.h"
21 #include "yaffs_tagscompat.h"
22 #ifndef CONFIG_YAFFS_USE_OWN_SORT
23 #include "yaffs_qsort.h"
25 #include "yaffs_nand.h"
27 #include "yaffs_checkptrw.h"
29 #include "yaffs_nand.h"
30 #include "yaffs_packedtags2.h"
33 /* Note YAFFS_GC_GOOD_ENOUGH must be <= YAFFS_GC_PASSIVE_THRESHOLD */
34 #define YAFFS_GC_GOOD_ENOUGH 2
35 #define YAFFS_GC_PASSIVE_THRESHOLD 4
37 #define YAFFS_SMALL_HOLE_THRESHOLD 3
40 * Checkpoints are really no benefit on very small partitions.
42 * To save space on small partitions don't bother with checkpoints unless
43 * the partition is at least this big.
45 #define YAFFS_CHECKPOINT_MIN_BLOCKS 60
47 #include "yaffs_ecc.h"
50 /* Robustification (if it ever comes about...) */
51 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND);
52 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
54 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
56 const yaffs_ExtendedTags *tags);
57 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
58 const yaffs_ExtendedTags *tags);
60 /* Other local prototypes */
61 static void yaffs_UpdateParent(yaffs_Object *obj);
62 static int yaffs_UnlinkObject(yaffs_Object *obj);
63 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
65 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
67 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev,
69 yaffs_ExtendedTags *tags,
71 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
72 int chunkInNAND, int inScan);
74 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
75 yaffs_ObjectType type);
76 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
78 static int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name,
79 int force, int isShrink, int shadows);
80 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
81 static int yaffs_CheckStructures(void);
82 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
83 int chunkOffset, int *limit);
84 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
86 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev, int blockNo);
89 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
92 static int yaffs_UnlinkWorker(yaffs_Object *obj);
94 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
97 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
98 yaffs_BlockInfo **blockUsedPtr);
100 static void yaffs_VerifyFreeChunks(yaffs_Device *dev);
102 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
104 static void yaffs_VerifyDirectory(yaffs_Object *directory);
105 #ifdef YAFFS_PARANOID
106 static int yaffs_CheckFileSanity(yaffs_Object *in);
108 #define yaffs_CheckFileSanity(in)
111 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
112 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
114 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
116 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
117 yaffs_ExtendedTags *tags);
119 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
121 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
122 yaffs_FileStructure *fStruct,
125 static int yaffs_HandleHole(yaffs_Object *obj, loff_t newSize);
126 static void yaffs_SkipRestOfBlock(yaffs_Device *dev);
127 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
130 yaffs_ExtendedTags *tags);
132 /* Function to calculate chunk and offset */
134 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut,
140 chunk = (__u32)(addr >> dev->chunkShift);
142 if (dev->chunkDiv == 1) {
143 /* easy power of 2 case */
144 offset = (__u32)(addr & dev->chunkMask);
146 /* Non power-of-2 case */
150 chunk /= dev->chunkDiv;
152 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
153 offset = (__u32)(addr - chunkBase);
160 /* Function to return the number of shifts for a power of 2 greater than or
161 * equal to the given number
162 * Note we don't try to cater for all possible numbers and this does not have to
163 * be hellishly efficient.
166 static __u32 ShiftsGE(__u32 x)
171 nShifts = extraBits = 0;
186 /* Function to return the number of shifts to get a 1 in bit 0
189 static __u32 Shifts(__u32 x)
209 * Temporary buffer manipulations.
212 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
215 __u8 *buf = (__u8 *)1;
217 memset(dev->tempBuffer, 0, sizeof(dev->tempBuffer));
219 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
220 dev->tempBuffer[i].line = 0; /* not in use */
221 dev->tempBuffer[i].buffer = buf =
222 YMALLOC_DMA(dev->param.totalBytesPerChunk);
225 return buf ? YAFFS_OK : YAFFS_FAIL;
228 __u8 *yaffs_GetTempBuffer(yaffs_Device *dev, int lineNo)
233 if (dev->tempInUse > dev->maxTemp)
234 dev->maxTemp = dev->tempInUse;
236 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
237 if (dev->tempBuffer[i].line == 0) {
238 dev->tempBuffer[i].line = lineNo;
239 if ((i + 1) > dev->maxTemp) {
240 dev->maxTemp = i + 1;
241 for (j = 0; j <= i; j++)
242 dev->tempBuffer[j].maxLine =
243 dev->tempBuffer[j].line;
246 return dev->tempBuffer[i].buffer;
250 T(YAFFS_TRACE_BUFFERS,
251 (TSTR("Out of temp buffers at line %d, other held by lines:"),
253 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
254 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
256 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
259 * If we got here then we have to allocate an unmanaged one
263 dev->unmanagedTempAllocations++;
264 return YMALLOC(dev->nDataBytesPerChunk);
268 void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer,
275 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
276 if (dev->tempBuffer[i].buffer == buffer) {
277 dev->tempBuffer[i].line = 0;
283 /* assume it is an unmanaged one. */
284 T(YAFFS_TRACE_BUFFERS,
285 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
288 dev->unmanagedTempDeallocations++;
294 * Determine if we have a managed buffer.
296 int yaffs_IsManagedTempBuffer(yaffs_Device *dev, const __u8 *buffer)
300 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
301 if (dev->tempBuffer[i].buffer == buffer)
305 for (i = 0; i < dev->param.nShortOpCaches; i++) {
306 if (dev->srCache[i].data == buffer)
310 if (buffer == dev->checkpointBuffer)
313 T(YAFFS_TRACE_ALWAYS,
314 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
321 * Chunk bitmap manipulations
324 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
326 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
328 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
332 return dev->chunkBits +
333 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
336 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
338 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
339 chunk < 0 || chunk >= dev->param.nChunksPerBlock) {
341 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),
347 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device *dev, int blk)
349 __u8 *blkBits = yaffs_BlockBits(dev, blk);
351 memset(blkBits, 0, dev->chunkBitmapStride);
354 static Y_INLINE void yaffs_ClearChunkBit(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 void yaffs_SetChunkBit(yaffs_Device *dev, int blk, int chunk)
365 __u8 *blkBits = yaffs_BlockBits(dev, blk);
367 yaffs_VerifyChunkBitId(dev, blk, chunk);
369 blkBits[chunk / 8] |= (1 << (chunk & 7));
372 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device *dev, int blk, int chunk)
374 __u8 *blkBits = yaffs_BlockBits(dev, blk);
375 yaffs_VerifyChunkBitId(dev, blk, chunk);
377 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
380 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device *dev, int blk)
382 __u8 *blkBits = yaffs_BlockBits(dev, blk);
384 for (i = 0; i < dev->chunkBitmapStride; i++) {
392 static int yaffs_CountChunkBits(yaffs_Device *dev, int blk)
394 __u8 *blkBits = yaffs_BlockBits(dev, blk);
397 for (i = 0; i < dev->chunkBitmapStride; i++) {
414 static int yaffs_SkipVerification(yaffs_Device *dev)
417 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
420 static int yaffs_SkipFullVerification(yaffs_Device *dev)
423 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
426 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
429 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
432 static const char *blockStateName[] = {
445 static void yaffs_VerifyBlock(yaffs_Device *dev, yaffs_BlockInfo *bi, int n)
450 if (yaffs_SkipVerification(dev))
453 /* Report illegal runtime states */
454 if (bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
455 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has undefined state %d"TENDSTR), n, bi->blockState));
457 switch (bi->blockState) {
458 case YAFFS_BLOCK_STATE_UNKNOWN:
459 case YAFFS_BLOCK_STATE_SCANNING:
460 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
461 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has bad run-state %s"TENDSTR),
462 n, blockStateName[bi->blockState]));
465 /* Check pages in use and soft deletions are legal */
467 actuallyUsed = bi->pagesInUse - bi->softDeletions;
469 if (bi->pagesInUse < 0 || bi->pagesInUse > dev->param.nChunksPerBlock ||
470 bi->softDeletions < 0 || bi->softDeletions > dev->param.nChunksPerBlock ||
471 actuallyUsed < 0 || actuallyUsed > dev->param.nChunksPerBlock)
472 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
473 n, bi->pagesInUse, bi->softDeletions));
476 /* Check chunk bitmap legal */
477 inUse = yaffs_CountChunkBits(dev, n);
478 if (inUse != bi->pagesInUse)
479 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
480 n, bi->pagesInUse, inUse));
482 /* Check that the sequence number is valid.
483 * Ten million is legal, but is very unlikely
485 if (dev->param.isYaffs2 &&
486 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
487 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000))
488 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has suspect sequence number of %d"TENDSTR),
489 n, bi->sequenceNumber));
492 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev, yaffs_BlockInfo *bi,
495 yaffs_VerifyBlock(dev, bi, n);
497 /* After collection the block should be in the erased state */
498 /* This will need to change if we do partial gc */
500 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
501 bi->blockState != YAFFS_BLOCK_STATE_EMPTY) {
502 T(YAFFS_TRACE_ERROR, (TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
507 static void yaffs_VerifyBlocks(yaffs_Device *dev)
510 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
511 int nIllegalBlockStates = 0;
513 if (yaffs_SkipVerification(dev))
516 memset(nBlocksPerState, 0, sizeof(nBlocksPerState));
518 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
519 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, i);
520 yaffs_VerifyBlock(dev, bi, i);
522 if (bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
523 nBlocksPerState[bi->blockState]++;
525 nIllegalBlockStates++;
528 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
529 T(YAFFS_TRACE_VERIFY, (TSTR("Block summary"TENDSTR)));
531 T(YAFFS_TRACE_VERIFY, (TSTR("%d blocks have illegal states"TENDSTR), nIllegalBlockStates));
532 if (nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
533 T(YAFFS_TRACE_VERIFY, (TSTR("Too many allocating blocks"TENDSTR)));
535 for (i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
536 T(YAFFS_TRACE_VERIFY,
537 (TSTR("%s %d blocks"TENDSTR),
538 blockStateName[i], nBlocksPerState[i]));
540 if (dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
541 T(YAFFS_TRACE_VERIFY,
542 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
543 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
545 if (dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
546 T(YAFFS_TRACE_VERIFY,
547 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
548 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
550 if (nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
551 T(YAFFS_TRACE_VERIFY,
552 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
553 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
555 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
560 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
561 * case those tests will not be performed.
563 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
565 if (obj && yaffs_SkipVerification(obj->myDev))
568 if (!(tags && obj && oh)) {
569 T(YAFFS_TRACE_VERIFY,
570 (TSTR("Verifying object header tags %p obj %p oh %p"TENDSTR),
575 if (oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
576 oh->type > YAFFS_OBJECT_TYPE_MAX)
577 T(YAFFS_TRACE_VERIFY,
578 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
579 tags->objectId, oh->type));
581 if (tags->objectId != obj->objectId)
582 T(YAFFS_TRACE_VERIFY,
583 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
584 tags->objectId, obj->objectId));
588 * Check that the object's parent ids match if parentCheck requested.
590 * Tests do not apply to the root object.
593 if (parentCheck && tags->objectId > 1 && !obj->parent)
594 T(YAFFS_TRACE_VERIFY,
595 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
596 tags->objectId, oh->parentObjectId));
598 if (parentCheck && obj->parent &&
599 oh->parentObjectId != obj->parent->objectId &&
600 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
601 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
602 T(YAFFS_TRACE_VERIFY,
603 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
604 tags->objectId, oh->parentObjectId, obj->parent->objectId));
606 if (tags->objectId > 1 && oh->name[0] == 0) /* Null name */
607 T(YAFFS_TRACE_VERIFY,
608 (TSTR("Obj %d header name is NULL"TENDSTR),
611 if (tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
612 T(YAFFS_TRACE_VERIFY,
613 (TSTR("Obj %d header name is 0xFF"TENDSTR),
619 static int yaffs_VerifyTnodeWorker(yaffs_Object *obj, yaffs_Tnode *tn,
620 __u32 level, int chunkOffset)
623 yaffs_Device *dev = obj->myDev;
629 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
630 if (tn->internal[i]) {
631 ok = yaffs_VerifyTnodeWorker(obj,
634 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
637 } else if (level == 0) {
638 yaffs_ExtendedTags tags;
639 __u32 objectId = obj->objectId;
641 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
643 for (i = 0; i < YAFFS_NTNODES_LEVEL0; i++) {
644 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
647 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
648 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
649 if (tags.objectId != objectId || tags.chunkId != chunkOffset) {
650 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
651 objectId, chunkOffset, theChunk,
652 tags.objectId, tags.chunkId));
665 static void yaffs_VerifyFile(yaffs_Object *obj)
667 int requiredTallness;
673 yaffs_ExtendedTags tags;
680 if (yaffs_SkipVerification(obj->myDev))
684 objectId = obj->objectId;
686 /* Check file size is consistent with tnode depth */
687 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
688 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
689 requiredTallness = 0;
691 x >>= YAFFS_TNODES_INTERNAL_BITS;
695 actualTallness = obj->variant.fileVariant.topLevel;
697 /* Check that the chunks in the tnode tree are all correct.
698 * We do this by scanning through the tnode tree and
699 * checking the tags for every chunk match.
702 if (yaffs_SkipNANDVerification(dev))
705 for (i = 1; i <= lastChunk; i++) {
706 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant, i);
709 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
711 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
712 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
713 if (tags.objectId != objectId || tags.chunkId != i) {
714 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
715 objectId, i, theChunk,
716 tags.objectId, tags.chunkId));
724 static void yaffs_VerifyHardLink(yaffs_Object *obj)
726 if (obj && yaffs_SkipVerification(obj->myDev))
729 /* Verify sane equivalent object */
732 static void yaffs_VerifySymlink(yaffs_Object *obj)
734 if (obj && yaffs_SkipVerification(obj->myDev))
737 /* Verify symlink string */
740 static void yaffs_VerifySpecial(yaffs_Object *obj)
742 if (obj && yaffs_SkipVerification(obj->myDev))
746 static void yaffs_VerifyObject(yaffs_Object *obj)
755 __u32 chunkShouldNotBeDeleted;
761 if (obj->beingCreated)
766 if (yaffs_SkipVerification(dev))
769 /* Check sane object header chunk */
771 chunkMin = dev->internalStartBlock * dev->param.nChunksPerBlock;
772 chunkMax = (dev->internalEndBlock+1) * dev->param.nChunksPerBlock - 1;
774 chunkInRange = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
775 chunkIdOk = chunkInRange || (obj->hdrChunk == 0);
776 chunkValid = chunkInRange &&
777 yaffs_CheckChunkBit(dev,
778 obj->hdrChunk / dev->param.nChunksPerBlock,
779 obj->hdrChunk % dev->param.nChunksPerBlock);
780 chunkShouldNotBeDeleted = chunkInRange && !chunkValid;
783 (!chunkIdOk || chunkShouldNotBeDeleted)) {
784 T(YAFFS_TRACE_VERIFY,
785 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
786 obj->objectId, obj->hdrChunk,
787 chunkIdOk ? "" : ",out of range",
788 chunkShouldNotBeDeleted ? ",marked as deleted" : ""));
791 if (chunkValid && !yaffs_SkipNANDVerification(dev)) {
792 yaffs_ExtendedTags tags;
793 yaffs_ObjectHeader *oh;
794 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
796 oh = (yaffs_ObjectHeader *)buffer;
798 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk, buffer,
801 yaffs_VerifyObjectHeader(obj, oh, &tags, 1);
803 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
806 /* Verify it has a parent */
807 if (obj && !obj->fake &&
808 (!obj->parent || obj->parent->myDev != dev)) {
809 T(YAFFS_TRACE_VERIFY,
810 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
811 obj->objectId, obj->parent));
814 /* Verify parent is a directory */
815 if (obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
816 T(YAFFS_TRACE_VERIFY,
817 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
818 obj->objectId, obj->parent->variantType));
821 switch (obj->variantType) {
822 case YAFFS_OBJECT_TYPE_FILE:
823 yaffs_VerifyFile(obj);
825 case YAFFS_OBJECT_TYPE_SYMLINK:
826 yaffs_VerifySymlink(obj);
828 case YAFFS_OBJECT_TYPE_DIRECTORY:
829 yaffs_VerifyDirectory(obj);
831 case YAFFS_OBJECT_TYPE_HARDLINK:
832 yaffs_VerifyHardLink(obj);
834 case YAFFS_OBJECT_TYPE_SPECIAL:
835 yaffs_VerifySpecial(obj);
837 case YAFFS_OBJECT_TYPE_UNKNOWN:
839 T(YAFFS_TRACE_VERIFY,
840 (TSTR("Obj %d has illegaltype %d"TENDSTR),
841 obj->objectId, obj->variantType));
846 static void yaffs_VerifyObjects(yaffs_Device *dev)
850 struct ylist_head *lh;
852 if (yaffs_SkipVerification(dev))
855 /* Iterate through the objects in each hash entry */
857 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
858 ylist_for_each(lh, &dev->objectBucket[i].list) {
860 obj = ylist_entry(lh, yaffs_Object, hashLink);
861 yaffs_VerifyObject(obj);
869 * Simple hash function. Needs to have a reasonable spread
872 static Y_INLINE int yaffs_HashFunction(int n)
875 return n % YAFFS_NOBJECT_BUCKETS;
879 * Access functions to useful fake objects.
880 * Note that root might have a presence in NAND if permissions are set.
883 yaffs_Object *yaffs_Root(yaffs_Device *dev)
888 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
890 return dev->lostNFoundDir;
895 * Erased NAND checking functions
898 int yaffs_CheckFF(__u8 *buffer, int nBytes)
900 /* Horrible, slow implementation */
909 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
912 int retval = YAFFS_OK;
913 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
914 yaffs_ExtendedTags tags;
917 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
919 if (tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
922 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
923 T(YAFFS_TRACE_NANDACCESS,
924 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
928 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
935 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
938 yaffs_ExtendedTags *tags)
940 int retval = YAFFS_OK;
941 yaffs_ExtendedTags tempTags;
942 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
945 result = yaffs_ReadChunkWithTagsFromNAND(dev,chunkInNAND,buffer,&tempTags);
946 if(memcmp(buffer,data,dev->nDataBytesPerChunk) ||
947 tempTags.objectId != tags->objectId ||
948 tempTags.chunkId != tags->chunkId ||
949 tempTags.byteCount != tags->byteCount)
952 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
957 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
959 yaffs_ExtendedTags *tags,
966 yaffs_InvalidateCheckpoint(dev);
969 yaffs_BlockInfo *bi = 0;
972 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
978 /* First check this chunk is erased, if it needs
979 * checking. The checking policy (unless forced
980 * always on) is as follows:
982 * Check the first page we try to write in a block.
983 * If the check passes then we don't need to check any
984 * more. If the check fails, we check again...
985 * If the block has been erased, we don't need to check.
987 * However, if the block has been prioritised for gc,
988 * then we think there might be something odd about
989 * this block and stop using it.
991 * Rationale: We should only ever see chunks that have
992 * not been erased if there was a partially written
993 * chunk due to power loss. This checking policy should
994 * catch that case with very few checks and thus save a
995 * lot of checks that are most likely not needed.
998 * If an erase check fails or the write fails we skip the
1002 /* let's give it a try */
1005 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
1006 bi->skipErasedCheck = 0;
1008 if (!bi->skipErasedCheck) {
1009 erasedOk = yaffs_CheckChunkErased(dev, chunk);
1010 if (erasedOk != YAFFS_OK) {
1011 T(YAFFS_TRACE_ERROR,
1012 (TSTR("**>> yaffs chunk %d was not erased"
1015 /* If not erased, delete this one,
1016 * skip rest of block and
1017 * try another chunk */
1018 yaffs_DeleteChunk(dev,chunk,1,__LINE__);
1019 yaffs_SkipRestOfBlock(dev);
1024 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
1027 if(!bi->skipErasedCheck)
1028 writeOk = yaffs_VerifyChunkWritten(dev, chunk, data, tags);
1030 if (writeOk != YAFFS_OK) {
1031 /* Clean up aborted write, skip to next block and
1032 * try another chunk */
1033 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
1037 bi->skipErasedCheck = 1;
1039 /* Copy the data into the robustification buffer */
1040 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1042 } while (writeOk != YAFFS_OK &&
1043 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1049 T(YAFFS_TRACE_ERROR,
1050 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1053 dev->nRetriedWrites += (attempts - 1);
1061 * Oldest Dirty Sequence Number handling.
1064 /* yaffs_CalcOldestDirtySequence()
1065 * yaffs_FindOldestDirtySequence()
1066 * Calculate the oldest dirty sequence number if we don't know it.
1068 static void yaffs_CalcOldestDirtySequence(yaffs_Device *dev)
1072 unsigned blockNo = 0;
1075 if(!dev->param.isYaffs2)
1078 /* Find the oldest dirty sequence number. */
1079 seq = dev->sequenceNumber + 1;
1081 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
1082 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
1083 (b->pagesInUse - b->softDeletions) < dev->param.nChunksPerBlock &&
1084 b->sequenceNumber < seq) {
1085 seq = b->sequenceNumber;
1092 dev->oldestDirtySequence = seq;
1093 dev->oldestDirtyBlock = blockNo;
1099 static void yaffs_FindOldestDirtySequence(yaffs_Device *dev)
1101 if(dev->param.isYaffs2 && !dev->oldestDirtySequence)
1102 yaffs_CalcOldestDirtySequence(dev);
1106 * yaffs_ClearOldestDirtySequence()
1107 * Called when a block is erased or marked bad. (ie. when its sequenceNumber
1108 * becomes invalid). If the value matches the oldest then we clear
1109 * dev->oldestDirtySequence to force its recomputation.
1111 static void yaffs_ClearOldestDirtySequence(yaffs_Device *dev, yaffs_BlockInfo *bi)
1114 if(!dev->param.isYaffs2)
1117 if(!bi || bi->sequenceNumber == dev->oldestDirtySequence){
1118 dev->oldestDirtySequence = 0;
1119 dev->oldestDirtyBlock = 0;
1124 * yaffs_UpdateOldestDirtySequence()
1125 * Update the oldest dirty sequence number whenever we dirty a block.
1126 * Only do this if the oldestDirtySequence is actually being tracked.
1128 static void yaffs_UpdateOldestDirtySequence(yaffs_Device *dev, unsigned blockNo, yaffs_BlockInfo *bi)
1130 if(dev->param.isYaffs2 && dev->oldestDirtySequence){
1131 if(dev->oldestDirtySequence > bi->sequenceNumber){
1132 dev->oldestDirtySequence = bi->sequenceNumber;
1133 dev->oldestDirtyBlock = blockNo;
1139 * Block retiring for handling a broken block.
1142 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND)
1144 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1146 yaffs_InvalidateCheckpoint(dev);
1148 yaffs_ClearOldestDirtySequence(dev,bi);
1150 if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
1151 if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
1152 T(YAFFS_TRACE_ALWAYS, (TSTR(
1153 "yaffs: Failed to mark bad and erase block %d"
1154 TENDSTR), blockInNAND));
1156 yaffs_ExtendedTags tags;
1157 int chunkId = blockInNAND * dev->param.nChunksPerBlock;
1159 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
1161 memset(buffer, 0xff, dev->nDataBytesPerChunk);
1162 yaffs_InitialiseTags(&tags);
1163 tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
1164 if (dev->param.writeChunkWithTagsToNAND(dev, chunkId -
1165 dev->chunkOffset, buffer, &tags) != YAFFS_OK)
1166 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
1167 TCONT("write bad block marker to block %d")
1168 TENDSTR), blockInNAND));
1170 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
1174 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1175 bi->gcPrioritise = 0;
1176 bi->needsRetiring = 0;
1178 dev->nRetiredBlocks++;
1182 * Functions for robustisizing TODO
1186 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
1188 const yaffs_ExtendedTags *tags)
1191 chunkInNAND=chunkInNAND;
1196 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
1197 const yaffs_ExtendedTags *tags)
1200 chunkInNAND=chunkInNAND;
1204 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1206 if (!bi->gcPrioritise) {
1207 bi->gcPrioritise = 1;
1208 dev->hasPendingPrioritisedGCs = 1;
1209 bi->chunkErrorStrikes++;
1211 if (bi->chunkErrorStrikes > 3) {
1212 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1213 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1219 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
1222 int blockInNAND = chunkInNAND / dev->param.nChunksPerBlock;
1223 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1225 yaffs_HandleChunkError(dev, bi);
1228 /* Was an actual write failure, so mark the block for retirement */
1229 bi->needsRetiring = 1;
1230 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1231 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1234 /* Delete the chunk */
1235 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1236 yaffs_SkipRestOfBlock(dev);
1240 /*---------------- Name handling functions ------------*/
1242 static __u16 yaffs_CalcNameSum(const YCHAR *name)
1247 const YUCHAR *bname = (const YUCHAR *) name;
1249 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1251 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1252 sum += yaffs_toupper(*bname) * i;
1254 sum += (*bname) * i;
1263 static void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
1265 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1266 memset(obj->shortName, 0, sizeof(YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1267 if (name && yaffs_strnlen(name,YAFFS_SHORT_NAME_LENGTH+1) <= YAFFS_SHORT_NAME_LENGTH)
1268 yaffs_strcpy(obj->shortName, name);
1270 obj->shortName[0] = _Y('\0');
1272 obj->sum = yaffs_CalcNameSum(name);
1275 /*-------------------- TNODES -------------------
1277 * List of spare tnodes
1278 * The list is hooked together using the first pointer
1282 /* yaffs_CreateTnodes creates a bunch more tnodes and
1283 * adds them to the tnode free list.
1284 * Don't use this function directly
1286 static Y_INLINE int yaffs_CalcTnodeSize(yaffs_Device *dev)
1289 /* Calculate the tnode size in bytes for variable width tnode support.
1290 * Must be a multiple of 32-bits */
1291 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1293 if (tnodeSize < sizeof(yaffs_Tnode))
1294 tnodeSize = sizeof(yaffs_Tnode);
1298 static int yaffs_CreateTnodes(yaffs_Device *dev, int nTnodes)
1301 int tnodeSize = yaffs_CalcTnodeSize(dev);
1302 yaffs_Tnode *newTnodes;
1306 yaffs_TnodeList *tnl;
1312 /* make these things */
1314 newTnodes = YMALLOC(nTnodes * tnodeSize);
1315 mem = (__u8 *)newTnodes;
1318 T(YAFFS_TRACE_ERROR,
1319 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1323 /* Hook them into the free list */
1325 for (i = 0; i < nTnodes - 1; i++) {
1326 newTnodes[i].internal[0] = &newTnodes[i + 1];
1327 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1328 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1332 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1333 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1334 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1336 dev->freeTnodes = newTnodes;
1338 /* New hookup for wide tnodes */
1339 for (i = 0; i < nTnodes - 1; i++) {
1340 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1341 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1342 curr->internal[0] = next;
1345 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1346 curr->internal[0] = dev->freeTnodes;
1347 dev->freeTnodes = (yaffs_Tnode *)mem;
1352 dev->nFreeTnodes += nTnodes;
1353 dev->nTnodesCreated += nTnodes;
1355 /* Now add this bunch of tnodes to a list for freeing up.
1356 * NB If we can't add this to the management list it isn't fatal
1357 * but it just means we can't free this bunch of tnodes later.
1360 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1362 T(YAFFS_TRACE_ERROR,
1364 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1367 tnl->tnodes = newTnodes;
1368 tnl->next = dev->allocatedTnodeList;
1369 dev->allocatedTnodeList = tnl;
1372 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1377 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1379 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device *dev)
1381 yaffs_Tnode *tn = NULL;
1383 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1384 tn = YMALLOC(yaffs_CalcTnodeSize(dev));
1386 dev->nTnodesCreated++;
1388 /* If there are none left make more */
1389 if (!dev->freeTnodes)
1390 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1392 if (dev->freeTnodes) {
1393 tn = dev->freeTnodes;
1394 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1395 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1396 /* Hoosterman, this thing looks like it isn't in the list */
1397 T(YAFFS_TRACE_ALWAYS,
1398 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1401 dev->freeTnodes = dev->freeTnodes->internal[0];
1405 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1410 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
1412 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1413 int tnodeSize = yaffs_CalcTnodeSize(dev);
1416 memset(tn, 0, tnodeSize);
1421 /* FreeTnode frees up a tnode and puts it back on the free list */
1422 static void yaffs_FreeTnode(yaffs_Device *dev, yaffs_Tnode *tn)
1425 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1427 dev->nTnodesCreated--;
1429 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1430 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1431 /* Hoosterman, this thing looks like it is already in the list */
1432 T(YAFFS_TRACE_ALWAYS,
1433 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1435 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1437 tn->internal[0] = dev->freeTnodes;
1438 dev->freeTnodes = tn;
1442 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1445 static void yaffs_DeinitialiseTnodes(yaffs_Device *dev)
1447 /* Free the list of allocated tnodes */
1448 yaffs_TnodeList *tmp;
1450 while (dev->allocatedTnodeList) {
1451 tmp = dev->allocatedTnodeList->next;
1453 YFREE(dev->allocatedTnodeList->tnodes);
1454 YFREE(dev->allocatedTnodeList);
1455 dev->allocatedTnodeList = tmp;
1459 dev->freeTnodes = NULL;
1460 dev->nFreeTnodes = 0;
1461 dev->nTnodesCreated = 0;
1464 static void yaffs_InitialiseTnodes(yaffs_Device *dev)
1466 dev->allocatedTnodeList = NULL;
1467 dev->freeTnodes = NULL;
1468 dev->nFreeTnodes = 0;
1469 dev->nTnodesCreated = 0;
1473 void yaffs_LoadLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
1476 __u32 *map = (__u32 *)tn;
1482 pos &= YAFFS_TNODES_LEVEL0_MASK;
1483 val >>= dev->chunkGroupBits;
1485 bitInMap = pos * dev->tnodeWidth;
1486 wordInMap = bitInMap / 32;
1487 bitInWord = bitInMap & (32 - 1);
1489 mask = dev->tnodeMask << bitInWord;
1491 map[wordInMap] &= ~mask;
1492 map[wordInMap] |= (mask & (val << bitInWord));
1494 if (dev->tnodeWidth > (32 - bitInWord)) {
1495 bitInWord = (32 - bitInWord);
1497 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1498 map[wordInMap] &= ~mask;
1499 map[wordInMap] |= (mask & (val >> bitInWord));
1503 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
1506 __u32 *map = (__u32 *)tn;
1512 pos &= YAFFS_TNODES_LEVEL0_MASK;
1514 bitInMap = pos * dev->tnodeWidth;
1515 wordInMap = bitInMap / 32;
1516 bitInWord = bitInMap & (32 - 1);
1518 val = map[wordInMap] >> bitInWord;
1520 if (dev->tnodeWidth > (32 - bitInWord)) {
1521 bitInWord = (32 - bitInWord);
1523 val |= (map[wordInMap] << bitInWord);
1526 val &= dev->tnodeMask;
1527 val <<= dev->chunkGroupBits;
1532 /* ------------------- End of individual tnode manipulation -----------------*/
1534 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1535 * The look up tree is represented by the top tnode and the number of topLevel
1536 * in the tree. 0 means only the level 0 tnode is in the tree.
1539 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1540 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
1541 yaffs_FileStructure *fStruct,
1544 yaffs_Tnode *tn = fStruct->top;
1546 int requiredTallness;
1547 int level = fStruct->topLevel;
1551 /* Check sane level and chunk Id */
1552 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
1555 if (chunkId > YAFFS_MAX_CHUNK_ID)
1558 /* First check we're tall enough (ie enough topLevel) */
1560 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1561 requiredTallness = 0;
1563 i >>= YAFFS_TNODES_INTERNAL_BITS;
1567 if (requiredTallness > fStruct->topLevel)
1568 return NULL; /* Not tall enough, so we can't find it */
1570 /* Traverse down to level 0 */
1571 while (level > 0 && tn) {
1572 tn = tn->internal[(chunkId >>
1573 (YAFFS_TNODES_LEVEL0_BITS +
1575 YAFFS_TNODES_INTERNAL_BITS)) &
1576 YAFFS_TNODES_INTERNAL_MASK];
1583 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1584 * This happens in two steps:
1585 * 1. If the tree isn't tall enough, then make it taller.
1586 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1588 * Used when modifying the tree.
1590 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1591 * be plugged into the ttree.
1594 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
1595 yaffs_FileStructure *fStruct,
1597 yaffs_Tnode *passedTn)
1599 int requiredTallness;
1607 /* Check sane level and page Id */
1608 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
1611 if (chunkId > YAFFS_MAX_CHUNK_ID)
1614 /* First check we're tall enough (ie enough topLevel) */
1616 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1617 requiredTallness = 0;
1619 x >>= YAFFS_TNODES_INTERNAL_BITS;
1624 if (requiredTallness > fStruct->topLevel) {
1625 /* Not tall enough, gotta make the tree taller */
1626 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1628 tn = yaffs_GetTnode(dev);
1631 tn->internal[0] = fStruct->top;
1633 fStruct->topLevel++;
1635 T(YAFFS_TRACE_ERROR,
1636 (TSTR("yaffs: no more tnodes" TENDSTR)));
1642 /* Traverse down to level 0, adding anything we need */
1644 l = fStruct->topLevel;
1648 while (l > 0 && tn) {
1650 (YAFFS_TNODES_LEVEL0_BITS +
1651 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1652 YAFFS_TNODES_INTERNAL_MASK;
1655 if ((l > 1) && !tn->internal[x]) {
1656 /* Add missing non-level-zero tnode */
1657 tn->internal[x] = yaffs_GetTnode(dev);
1658 if(!tn->internal[x])
1660 } else if (l == 1) {
1661 /* Looking from level 1 at level 0 */
1663 /* If we already have one, then release it.*/
1664 if (tn->internal[x])
1665 yaffs_FreeTnode(dev, tn->internal[x]);
1666 tn->internal[x] = passedTn;
1668 } else if (!tn->internal[x]) {
1669 /* Don't have one, none passed in */
1670 tn->internal[x] = yaffs_GetTnode(dev);
1671 if(!tn->internal[x])
1676 tn = tn->internal[x];
1680 /* top is level 0 */
1682 memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1683 yaffs_FreeTnode(dev, passedTn);
1690 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
1691 yaffs_ExtendedTags *tags, int objectId,
1696 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1697 if (yaffs_CheckChunkBit(dev, theChunk / dev->param.nChunksPerBlock,
1698 theChunk % dev->param.nChunksPerBlock)) {
1700 if(dev->chunkGroupSize == 1)
1703 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1705 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1717 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1718 * chunks and tnodes in the file
1719 * Returns 1 if the tree was deleted.
1720 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1723 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
1724 int chunkOffset, int *limit)
1729 yaffs_ExtendedTags tags;
1731 yaffs_Device *dev = in->myDev;
1737 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1739 if (tn->internal[i]) {
1740 if (limit && (*limit) < 0) {
1744 yaffs_DeleteWorker(in,
1752 YAFFS_TNODES_INTERNAL_BITS)
1757 yaffs_FreeTnode(dev,
1760 tn->internal[i] = NULL;
1764 return (allDone) ? 1 : 0;
1765 } else if (level == 0) {
1768 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1770 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1773 chunkInInode = (chunkOffset <<
1774 YAFFS_TNODES_LEVEL0_BITS) + i;
1777 yaffs_FindChunkInGroup(dev,
1783 if (foundChunk > 0) {
1784 yaffs_DeleteChunk(dev,
1789 *limit = *limit - 1;
1796 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1800 return (i < 0) ? 1 : 0;
1810 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1812 yaffs_BlockInfo *theBlock;
1815 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1817 blockNo = chunk / dev->param.nChunksPerBlock;
1818 theBlock = yaffs_GetBlockInfo(dev, blockNo);
1820 theBlock->softDeletions++;
1822 yaffs_UpdateOldestDirtySequence(dev, blockNo, theBlock);
1826 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1827 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1829 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1832 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1833 __u32 level, int chunkOffset)
1838 yaffs_Device *dev = in->myDev;
1843 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1845 if (tn->internal[i]) {
1847 yaffs_SoftDeleteWorker(in,
1853 YAFFS_TNODES_INTERNAL_BITS)
1856 yaffs_FreeTnode(dev,
1859 tn->internal[i] = NULL;
1861 /* Hoosterman... how could this happen? */
1865 return (allDone) ? 1 : 0;
1866 } else if (level == 0) {
1868 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1869 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1871 /* Note this does not find the real chunk, only the chunk group.
1872 * We make an assumption that a chunk group is not larger than
1875 yaffs_SoftDeleteChunk(dev, theChunk);
1876 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1890 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1893 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1894 if (obj->nDataChunks <= 0) {
1895 /* Empty file with no duplicate object headers, just delete it immediately */
1896 yaffs_FreeTnode(obj->myDev,
1897 obj->variant.fileVariant.top);
1898 obj->variant.fileVariant.top = NULL;
1899 T(YAFFS_TRACE_TRACING,
1900 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1902 yaffs_DoGenericObjectDeletion(obj);
1904 yaffs_SoftDeleteWorker(obj,
1905 obj->variant.fileVariant.top,
1906 obj->variant.fileVariant.
1908 obj->softDeleted = 1;
1913 /* Pruning removes any part of the file structure tree that is beyond the
1914 * bounds of the file (ie that does not point to chunks).
1916 * A file should only get pruned when its size is reduced.
1918 * Before pruning, the chunks must be pulled from the tree and the
1919 * level 0 tnode entries must be zeroed out.
1920 * Could also use this for file deletion, but that's probably better handled
1921 * by a special case.
1923 * This function is recursive. For levels > 0 the function is called again on
1924 * any sub-tree. For level == 0 we just check if the sub-tree has data.
1925 * If there is no data in a subtree then it is pruned.
1928 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1929 __u32 level, int del0)
1938 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1939 if (tn->internal[i]) {
1941 yaffs_PruneWorker(dev, tn->internal[i],
1943 (i == 0) ? del0 : 1);
1946 if (tn->internal[i])
1950 int tnodeSize_u32 = yaffs_CalcTnodeSize(dev)/sizeof(__u32);
1951 __u32 *map = (__u32 *)tn;
1953 for(i = 0; !hasData && i < tnodeSize_u32; i++){
1959 if (hasData == 0 && del0) {
1960 /* Free and return NULL */
1962 yaffs_FreeTnode(dev, tn);
1972 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1973 yaffs_FileStructure *fStruct)
1980 if (fStruct->topLevel > 0) {
1982 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1984 /* Now we have a tree with all the non-zero branches NULL but the height
1985 * is the same as it was.
1986 * Let's see if we can trim internal tnodes to shorten the tree.
1987 * We can do this if only the 0th element in the tnode is in use
1988 * (ie all the non-zero are NULL)
1991 while (fStruct->topLevel && !done) {
1995 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1996 if (tn->internal[i])
2001 fStruct->top = tn->internal[0];
2002 fStruct->topLevel--;
2003 yaffs_FreeTnode(dev, tn);
2013 /*-------------------- End of File Structure functions.-------------------*/
2015 /* yaffs_CreateFreeObjects creates a bunch more objects and
2016 * adds them to the object free list.
2018 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
2021 yaffs_Object *newObjects;
2022 yaffs_ObjectList *list;
2027 /* make these things */
2028 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
2029 list = YMALLOC(sizeof(yaffs_ObjectList));
2031 if (!newObjects || !list) {
2040 T(YAFFS_TRACE_ALLOCATE,
2041 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
2045 /* Hook them into the free list */
2046 for (i = 0; i < nObjects - 1; i++) {
2047 newObjects[i].siblings.next =
2048 (struct ylist_head *)(&newObjects[i + 1]);
2051 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
2052 dev->freeObjects = newObjects;
2053 dev->nFreeObjects += nObjects;
2054 dev->nObjectsCreated += nObjects;
2056 /* Now add this bunch of Objects to a list for freeing up. */
2058 list->objects = newObjects;
2059 list->next = dev->allocatedObjectList;
2060 dev->allocatedObjectList = list;
2066 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
2067 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
2069 yaffs_Object *tn = NULL;
2071 #ifdef CONFIG_YAFFS_VALGRIND_TEST
2072 tn = YMALLOC(sizeof(yaffs_Object));
2074 dev->nObjectsCreated++;
2076 /* If there are none left make more */
2077 if (!dev->freeObjects)
2078 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
2080 if (dev->freeObjects) {
2081 tn = dev->freeObjects;
2083 (yaffs_Object *) (dev->freeObjects->siblings.next);
2084 dev->nFreeObjects--;
2088 /* Now sweeten it up... */
2090 memset(tn, 0, sizeof(yaffs_Object));
2091 tn->beingCreated = 1;
2095 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
2096 YINIT_LIST_HEAD(&(tn->hardLinks));
2097 YINIT_LIST_HEAD(&(tn->hashLink));
2098 YINIT_LIST_HEAD(&tn->siblings);
2101 /* Now make the directory sane */
2103 tn->parent = dev->rootDir;
2104 ylist_add(&(tn->siblings), &dev->rootDir->variant.directoryVariant.children);
2107 /* Add it to the lost and found directory.
2108 * NB Can't put root or lostNFound in lostNFound so
2109 * check if lostNFound exists first
2111 if (dev->lostNFoundDir)
2112 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
2114 tn->beingCreated = 0;
2117 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2122 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
2127 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
2129 obj->fake = 1; /* it is fake so it might have no NAND presence... */
2130 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
2131 obj->unlinkAllowed = 0; /* ... or unlink it */
2134 obj->yst_mode = mode;
2136 obj->hdrChunk = 0; /* Not a valid chunk. */
2143 static void yaffs_UnhashObject(yaffs_Object *tn)
2146 yaffs_Device *dev = tn->myDev;
2148 /* If it is still linked into the bucket list, free from the list */
2149 if (!ylist_empty(&tn->hashLink)) {
2150 ylist_del_init(&tn->hashLink);
2151 bucket = yaffs_HashFunction(tn->objectId);
2152 dev->objectBucket[bucket].count--;
2156 /* FreeObject frees up a Object and puts it back on the free list */
2157 static void yaffs_FreeObject(yaffs_Object *tn)
2159 yaffs_Device *dev = tn->myDev;
2161 T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), tn, tn->myInode));
2167 if (!ylist_empty(&tn->siblings))
2172 /* We're still hooked up to a cached inode.
2173 * Don't delete now, but mark for later deletion
2175 tn->deferedFree = 1;
2179 yaffs_UnhashObject(tn);
2181 #ifdef CONFIG_YAFFS_VALGRIND_TEST
2183 dev->nObjectsCreated--;
2186 /* Link into the free list. */
2187 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2188 dev->freeObjects = tn;
2189 dev->nFreeObjects++;
2191 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2195 void yaffs_HandleDeferedFree(yaffs_Object *obj)
2197 if (obj->deferedFree)
2198 yaffs_FreeObject(obj);
2202 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
2204 /* Free the list of allocated Objects */
2206 yaffs_ObjectList *tmp;
2208 while (dev->allocatedObjectList) {
2209 tmp = dev->allocatedObjectList->next;
2210 YFREE(dev->allocatedObjectList->objects);
2211 YFREE(dev->allocatedObjectList);
2213 dev->allocatedObjectList = tmp;
2216 dev->freeObjects = NULL;
2217 dev->nFreeObjects = 0;
2218 dev->nObjectsCreated = 0;
2221 static void yaffs_InitialiseObjects(yaffs_Device *dev)
2225 dev->allocatedObjectList = NULL;
2226 dev->freeObjects = NULL;
2227 dev->nFreeObjects = 0;
2229 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2230 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2231 dev->objectBucket[i].count = 0;
2235 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
2239 int lowest = 999999;
2242 /* Search for the shortest list or one that
2246 for (i = 0; i < 10 && lowest > 4; i++) {
2247 dev->bucketFinder++;
2248 dev->bucketFinder %= YAFFS_NOBJECT_BUCKETS;
2249 if (dev->objectBucket[dev->bucketFinder].count < lowest) {
2250 lowest = dev->objectBucket[dev->bucketFinder].count;
2251 l = dev->bucketFinder;
2259 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
2261 int bucket = yaffs_FindNiceObjectBucket(dev);
2263 /* Now find an object value that has not already been taken
2264 * by scanning the list.
2268 struct ylist_head *i;
2270 __u32 n = (__u32) bucket;
2272 /* yaffs_CheckObjectHashSanity(); */
2276 n += YAFFS_NOBJECT_BUCKETS;
2277 if (1 || dev->objectBucket[bucket].count > 0) {
2278 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2279 /* If there is already one in the list */
2280 if (i && ylist_entry(i, yaffs_Object,
2281 hashLink)->objectId == n) {
2291 static void yaffs_HashObject(yaffs_Object *in)
2293 int bucket = yaffs_HashFunction(in->objectId);
2294 yaffs_Device *dev = in->myDev;
2296 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2297 dev->objectBucket[bucket].count++;
2300 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
2302 int bucket = yaffs_HashFunction(number);
2303 struct ylist_head *i;
2306 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2307 /* Look if it is in the list */
2309 in = ylist_entry(i, yaffs_Object, hashLink);
2310 if (in->objectId == number) {
2312 /* Don't tell the VFS about this one if it is defered free */
2313 if (in->deferedFree)
2324 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
2325 yaffs_ObjectType type)
2327 yaffs_Object *theObject=NULL;
2328 yaffs_Tnode *tn = NULL;
2331 number = yaffs_CreateNewObjectNumber(dev);
2333 if (type == YAFFS_OBJECT_TYPE_FILE) {
2334 tn = yaffs_GetTnode(dev);
2339 theObject = yaffs_AllocateEmptyObject(dev);
2342 yaffs_FreeTnode(dev,tn);
2348 theObject->fake = 0;
2349 theObject->renameAllowed = 1;
2350 theObject->unlinkAllowed = 1;
2351 theObject->objectId = number;
2352 yaffs_HashObject(theObject);
2353 theObject->variantType = type;
2354 #ifdef CONFIG_YAFFS_WINCE
2355 yfsd_WinFileTimeNow(theObject->win_atime);
2356 theObject->win_ctime[0] = theObject->win_mtime[0] =
2357 theObject->win_atime[0];
2358 theObject->win_ctime[1] = theObject->win_mtime[1] =
2359 theObject->win_atime[1];
2363 theObject->yst_atime = theObject->yst_mtime =
2364 theObject->yst_ctime = Y_CURRENT_TIME;
2367 case YAFFS_OBJECT_TYPE_FILE:
2368 theObject->variant.fileVariant.fileSize = 0;
2369 theObject->variant.fileVariant.scannedFileSize = 0;
2370 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2371 theObject->variant.fileVariant.topLevel = 0;
2372 theObject->variant.fileVariant.top = tn;
2374 case YAFFS_OBJECT_TYPE_DIRECTORY:
2375 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2377 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2380 case YAFFS_OBJECT_TYPE_SYMLINK:
2381 case YAFFS_OBJECT_TYPE_HARDLINK:
2382 case YAFFS_OBJECT_TYPE_SPECIAL:
2383 /* No action required */
2385 case YAFFS_OBJECT_TYPE_UNKNOWN:
2386 /* todo this should not happen */
2394 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
2396 yaffs_ObjectType type)
2398 yaffs_Object *theObject = NULL;
2401 theObject = yaffs_FindObjectByNumber(dev, number);
2404 theObject = yaffs_CreateNewObject(dev, number, type);
2411 static YCHAR *yaffs_CloneString(const YCHAR *str)
2413 YCHAR *newStr = NULL;
2419 len = yaffs_strnlen(str,YAFFS_MAX_ALIAS_LENGTH);
2420 newStr = YMALLOC((len + 1) * sizeof(YCHAR));
2422 yaffs_strncpy(newStr, str,len);
2430 * Mknod (create) a new object.
2431 * equivalentObject only has meaning for a hard link;
2432 * aliasString only has meaning for a symlink.
2433 * rdev only has meaning for devices (a subset of special objects)
2436 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2437 yaffs_Object *parent,
2442 yaffs_Object *equivalentObject,
2443 const YCHAR *aliasString, __u32 rdev)
2448 yaffs_Device *dev = parent->myDev;
2450 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2451 if (yaffs_FindObjectByName(parent, name))
2454 if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2455 str = yaffs_CloneString(aliasString);
2460 in = yaffs_CreateNewObject(dev, -1, type);
2475 in->variantType = type;
2477 in->yst_mode = mode;
2479 #ifdef CONFIG_YAFFS_WINCE
2480 yfsd_WinFileTimeNow(in->win_atime);
2481 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2482 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2485 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2487 in->yst_rdev = rdev;
2491 in->nDataChunks = 0;
2493 yaffs_SetObjectName(in, name);
2496 yaffs_AddObjectToDirectory(parent, in);
2498 in->myDev = parent->myDev;
2501 case YAFFS_OBJECT_TYPE_SYMLINK:
2502 in->variant.symLinkVariant.alias = str;
2504 case YAFFS_OBJECT_TYPE_HARDLINK:
2505 in->variant.hardLinkVariant.equivalentObject =
2507 in->variant.hardLinkVariant.equivalentObjectId =
2508 equivalentObject->objectId;
2509 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2511 case YAFFS_OBJECT_TYPE_FILE:
2512 case YAFFS_OBJECT_TYPE_DIRECTORY:
2513 case YAFFS_OBJECT_TYPE_SPECIAL:
2514 case YAFFS_OBJECT_TYPE_UNKNOWN:
2519 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2520 /* Could not create the object header, fail the creation */
2521 yaffs_DeleteObject(in);
2525 yaffs_UpdateParent(parent);
2531 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
2532 __u32 mode, __u32 uid, __u32 gid)
2534 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2535 uid, gid, NULL, NULL, 0);
2538 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
2539 __u32 mode, __u32 uid, __u32 gid)
2541 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2542 mode, uid, gid, NULL, NULL, 0);
2545 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
2546 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2548 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2549 uid, gid, NULL, NULL, rdev);
2552 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
2553 __u32 mode, __u32 uid, __u32 gid,
2556 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2557 uid, gid, NULL, alias, 0);
2560 /* yaffs_Link returns the object id of the equivalent object.*/
2561 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
2562 yaffs_Object *equivalentObject)
2564 /* Get the real object in case we were fed a hard link as an equivalent object */
2565 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2567 if (yaffs_MknodObject
2568 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2569 equivalentObject, NULL, 0)) {
2570 return equivalentObject;
2577 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
2578 const YCHAR *newName, int force, int shadows)
2583 yaffs_Object *existingTarget;
2586 newDir = obj->parent; /* use the old directory */
2588 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2589 T(YAFFS_TRACE_ALWAYS,
2591 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2596 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2597 if (obj->myDev->param.isYaffs2)
2598 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2600 unlinkOp = (newDir == obj->myDev->unlinkedDir
2601 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2603 deleteOp = (newDir == obj->myDev->deletedDir);
2605 existingTarget = yaffs_FindObjectByName(newDir, newName);
2607 /* If the object is a file going into the unlinked directory,
2608 * then it is OK to just stuff it in since duplicate names are allowed.
2609 * else only proceed if the new name does not exist and if we're putting
2610 * it into a directory.
2617 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2618 yaffs_SetObjectName(obj, newName);
2621 yaffs_AddObjectToDirectory(newDir, obj);
2626 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2627 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows) >= 0)
2634 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
2635 yaffs_Object *newDir, const YCHAR *newName)
2637 yaffs_Object *obj = NULL;
2638 yaffs_Object *existingTarget = NULL;
2644 if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2646 if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2649 dev = oldDir->myDev;
2651 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2652 /* Special case for case insemsitive systems (eg. WinCE).
2653 * While look-up is case insensitive, the name isn't.
2654 * Therefore we might want to change x.txt to X.txt
2656 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
2660 if(yaffs_strnlen(newName,YAFFS_MAX_NAME_LENGTH+1) > YAFFS_MAX_NAME_LENGTH)
2664 obj = yaffs_FindObjectByName(oldDir, oldName);
2666 if (obj && obj->renameAllowed) {
2668 /* Now do the handling for an existing target, if there is one */
2670 existingTarget = yaffs_FindObjectByName(newDir, newName);
2671 if (existingTarget &&
2672 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2673 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2674 /* There is a target that is a non-empty directory, so we fail */
2675 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2676 } else if (existingTarget && existingTarget != obj) {
2677 /* Nuke the target first, using shadowing,
2678 * but only if it isn't the same object.
2680 * Note we must disable gc otherwise it can mess up the shadowing.
2684 yaffs_ChangeObjectName(obj, newDir, newName, force,
2685 existingTarget->objectId);
2686 existingTarget->isShadowed = 1;
2687 yaffs_UnlinkObject(existingTarget);
2691 result = yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2693 yaffs_UpdateParent(oldDir);
2694 if(newDir != oldDir)
2695 yaffs_UpdateParent(newDir);
2702 /*------------------------- Block Management and Page Allocation ----------------*/
2704 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
2706 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2708 dev->blockInfo = NULL;
2709 dev->chunkBits = NULL;
2711 dev->allocationBlock = -1; /* force it to get a new one */
2713 /* If the first allocation strategy fails, thry the alternate one */
2714 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2715 if (!dev->blockInfo) {
2716 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2717 dev->blockInfoAlt = 1;
2719 dev->blockInfoAlt = 0;
2721 if (dev->blockInfo) {
2722 /* Set up dynamic blockinfo stuff. */
2723 dev->chunkBitmapStride = (dev->param.nChunksPerBlock + 7) / 8; /* round up bytes */
2724 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2725 if (!dev->chunkBits) {
2726 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2727 dev->chunkBitsAlt = 1;
2729 dev->chunkBitsAlt = 0;
2732 if (dev->blockInfo && dev->chunkBits) {
2733 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2734 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2741 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2743 if (dev->blockInfoAlt && dev->blockInfo)
2744 YFREE_ALT(dev->blockInfo);
2745 else if (dev->blockInfo)
2746 YFREE(dev->blockInfo);
2748 dev->blockInfoAlt = 0;
2750 dev->blockInfo = NULL;
2752 if (dev->chunkBitsAlt && dev->chunkBits)
2753 YFREE_ALT(dev->chunkBits);
2754 else if (dev->chunkBits)
2755 YFREE(dev->chunkBits);
2756 dev->chunkBitsAlt = 0;
2757 dev->chunkBits = NULL;
2760 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
2761 yaffs_BlockInfo *bi)
2764 if (!dev->param.isYaffs2)
2765 return 1; /* disqualification only applies to yaffs2. */
2767 if (!bi->hasShrinkHeader)
2768 return 1; /* can gc */
2770 yaffs_FindOldestDirtySequence(dev);
2772 /* Can't do gc of this block if there are any blocks older than this one that have
2775 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2779 * yaffs_FindRefreshBlock()
2780 * periodically finds the oldest full block by sequence number for refreshing.
2783 static __u32 yaffs_FindRefreshBlock(yaffs_Device *dev)
2788 __u32 oldestSequence = 0;
2790 yaffs_BlockInfo *bi;
2793 * If refresh period < 10 then refreshing is disabled.
2795 if(dev->param.refreshPeriod < 10 ||
2796 !dev->param.isYaffs2)
2800 * Fix broken values.
2802 if(dev->refreshSkip > dev->param.refreshPeriod)
2803 dev->refreshSkip = dev->param.refreshPeriod;
2805 if(dev->refreshSkip > 0)
2809 * Refresh skip is now zero.
2810 * We'll do a refresh this time around....
2811 * Update the refresh skip and find the oldest block.
2813 dev->refreshSkip = dev->param.refreshPeriod;
2814 dev->refreshCount++;
2815 bi = dev->blockInfo;
2816 for (b = dev->internalStartBlock; b <=dev->internalEndBlock; b++){
2818 if (bi->blockState == YAFFS_BLOCK_STATE_FULL){
2821 bi->sequenceNumber < oldestSequence){
2823 oldestSequence = bi->sequenceNumber;
2831 (TSTR("GC refresh count %d selected block %d with sequenceNumber %d" TENDSTR),
2832 dev->refreshCount, oldest, oldestSequence));
2839 static void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
2841 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2845 /* If the block is still healthy erase it and mark as clean.
2846 * If the block has had a data failure, then retire it.
2849 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2850 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2851 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2853 yaffs_ClearOldestDirtySequence(dev,bi);
2855 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2857 /* If this is the block being garbage collected then stop gc'ing this block */
2858 if(blockNo == dev->gcBlock)
2861 /* If this block is currently the best candidate for gc then drop as a candidate */
2862 if(blockNo == dev->gcDirtiest){
2863 dev->gcDirtiest = 0;
2864 dev->gcPagesInUse = 0;
2867 if (!bi->needsRetiring) {
2868 yaffs_InvalidateCheckpoint(dev);
2869 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2871 dev->nErasureFailures++;
2872 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2873 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2878 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2880 for (i = 0; i < dev->param.nChunksPerBlock; i++) {
2881 if (!yaffs_CheckChunkErased
2882 (dev, blockNo * dev->param.nChunksPerBlock + i)) {
2883 T(YAFFS_TRACE_ERROR,
2885 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2886 TENDSTR), blockNo, i));
2892 /* Clean it up... */
2893 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2894 bi->sequenceNumber = 0;
2895 dev->nErasedBlocks++;
2897 bi->softDeletions = 0;
2898 bi->hasShrinkHeader = 0;
2899 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2900 bi->gcPrioritise = 0;
2901 yaffs_ClearChunkBits(dev, blockNo);
2903 T(YAFFS_TRACE_ERASE,
2904 (TSTR("Erased block %d" TENDSTR), blockNo));
2906 dev->nFreeChunks -= dev->param.nChunksPerBlock; /* We lost a block of free space */
2908 yaffs_RetireBlock(dev, blockNo);
2909 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2910 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2914 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2918 yaffs_BlockInfo *bi;
2920 if (dev->nErasedBlocks < 1) {
2921 /* Hoosterman we've got a problem.
2922 * Can't get space to gc
2924 T(YAFFS_TRACE_ERROR,
2925 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2930 /* Find an empty block. */
2932 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2933 dev->allocationBlockFinder++;
2934 if (dev->allocationBlockFinder < dev->internalStartBlock
2935 || dev->allocationBlockFinder > dev->internalEndBlock) {
2936 dev->allocationBlockFinder = dev->internalStartBlock;
2939 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2941 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2942 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2943 dev->sequenceNumber++;
2944 bi->sequenceNumber = dev->sequenceNumber;
2945 dev->nErasedBlocks--;
2946 T(YAFFS_TRACE_ALLOCATE,
2947 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2948 dev->allocationBlockFinder, dev->sequenceNumber,
2949 dev->nErasedBlocks));
2950 return dev->allocationBlockFinder;
2954 T(YAFFS_TRACE_ALWAYS,
2956 ("yaffs tragedy: no more erased blocks, but there should have been %d"
2957 TENDSTR), dev->nErasedBlocks));
2964 static int yaffs_CheckpointRequired(yaffs_Device *dev)
2966 int nblocks = dev->internalEndBlock - dev->internalStartBlock + 1 ;
2967 return dev->param.isYaffs2 &&
2968 !dev->param.skipCheckpointWrite &&
2969 (nblocks >= YAFFS_CHECKPOINT_MIN_BLOCKS);
2971 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2973 if (!dev->nCheckpointBlocksRequired &&
2974 yaffs_CheckpointRequired(dev)){
2975 /* Not a valid value so recalculate */
2978 int devBlocks = (dev->param.endBlock - dev->param.startBlock + 1);
2979 int tnodeSize = yaffs_CalcTnodeSize(dev);
2981 nBytes += sizeof(yaffs_CheckpointValidity);
2982 nBytes += sizeof(yaffs_CheckpointDevice);
2983 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2984 nBytes += devBlocks * dev->chunkBitmapStride;
2985 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2986 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2987 nBytes += sizeof(yaffs_CheckpointValidity);
2988 nBytes += sizeof(__u32); /* checksum*/
2990 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2992 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->param.nChunksPerBlock)) + 3;
2994 dev->nCheckpointBlocksRequired = nBlocks;
2997 return dev->nCheckpointBlocksRequired;
3001 * Check if there's space to allocate...
3002 * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
3004 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev, int nChunks)
3007 int reservedBlocks = dev->param.nReservedBlocks;
3008 int checkpointBlocks;
3010 if (dev->param.isYaffs2) {
3011 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
3012 dev->blocksInCheckpoint;
3013 if (checkpointBlocks < 0)
3014 checkpointBlocks = 0;
3016 checkpointBlocks = 0;
3019 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->param.nChunksPerBlock);
3021 return (dev->nFreeChunks > (reservedChunks + nChunks));
3024 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
3025 yaffs_BlockInfo **blockUsedPtr)
3028 yaffs_BlockInfo *bi;
3030 if (dev->allocationBlock < 0) {
3031 /* Get next block to allocate off */
3032 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
3033 dev->allocationPage = 0;
3036 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev, 1)) {
3037 /* Not enough space to allocate unless we're allowed to use the reserve. */
3041 if (dev->nErasedBlocks < dev->param.nReservedBlocks
3042 && dev->allocationPage == 0) {
3043 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
3046 /* Next page please.... */
3047 if (dev->allocationBlock >= 0) {
3048 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3050 retVal = (dev->allocationBlock * dev->param.nChunksPerBlock) +
3051 dev->allocationPage;
3053 yaffs_SetChunkBit(dev, dev->allocationBlock,
3054 dev->allocationPage);
3056 dev->allocationPage++;
3060 /* If the block is full set the state to full */
3061 if (dev->allocationPage >= dev->param.nChunksPerBlock) {
3062 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3063 dev->allocationBlock = -1;
3072 T(YAFFS_TRACE_ERROR,
3073 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
3078 static int yaffs_GetErasedChunks(yaffs_Device *dev)
3082 n = dev->nErasedBlocks * dev->param.nChunksPerBlock;
3084 if (dev->allocationBlock > 0)
3085 n += (dev->param.nChunksPerBlock - dev->allocationPage);
3092 * yaffs_SkipRestOfBlock() skips over the rest of the allocation block
3093 * if we don't want to write to it.
3095 static void yaffs_SkipRestOfBlock(yaffs_Device *dev)
3097 if(dev->allocationBlock > 0){
3098 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3099 if(bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING){
3100 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3101 dev->allocationBlock = -1;
3107 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
3113 int retVal = YAFFS_OK;
3116 int isCheckpointBlock;
3120 int chunksBefore = yaffs_GetErasedChunks(dev);
3123 yaffs_ExtendedTags tags;
3125 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3127 yaffs_Object *object;
3129 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3132 T(YAFFS_TRACE_TRACING,
3133 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3136 bi->hasShrinkHeader,
3139 /*yaffs_VerifyFreeChunks(dev); */
3141 if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
3142 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3144 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
3148 if (isCheckpointBlock ||
3149 !yaffs_StillSomeChunkBits(dev, block)) {
3150 T(YAFFS_TRACE_TRACING,
3152 ("Collecting block %d that has no chunks in use" TENDSTR),
3154 yaffs_BlockBecameDirty(dev, block);
3157 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3159 yaffs_VerifyBlock(dev, bi, block);
3161 maxCopies = (wholeBlock) ? dev->param.nChunksPerBlock : 5;
3162 oldChunk = block * dev->param.nChunksPerBlock + dev->gcChunk;
3164 for (/* init already done */;
3165 retVal == YAFFS_OK &&
3166 dev->gcChunk < dev->param.nChunksPerBlock &&
3167 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
3169 dev->gcChunk++, oldChunk++) {
3170 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3172 /* This page is in use and might need to be copied off */
3178 yaffs_InitialiseTags(&tags);
3180 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3184 yaffs_FindObjectByNumber(dev,
3187 T(YAFFS_TRACE_GC_DETAIL,
3189 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3190 dev->gcChunk, tags.objectId, tags.chunkId,
3193 if (object && !yaffs_SkipVerification(dev)) {
3194 if (tags.chunkId == 0)
3195 matchingChunk = object->hdrChunk;
3196 else if (object->softDeleted)
3197 matchingChunk = oldChunk; /* Defeat the test */
3199 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
3201 if (oldChunk != matchingChunk)
3202 T(YAFFS_TRACE_ERROR,
3203 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3204 oldChunk, matchingChunk, tags.objectId, tags.chunkId));
3209 T(YAFFS_TRACE_ERROR,
3211 ("page %d in gc has no object: %d %d %d "
3213 tags.objectId, tags.chunkId, tags.byteCount));
3218 object->softDeleted &&
3219 tags.chunkId != 0) {
3220 /* Data chunk in a soft deleted file, throw it away
3221 * It's a soft deleted data chunk,
3222 * No need to copy this, just forget about it and
3223 * fix up the object.
3226 /* Free chunks already includes softdeleted chunks.
3227 * How ever this chunk is going to soon be really deleted
3228 * which will increment free chunks.
3229 * We have to decrement free chunks so this works out properly.
3233 object->nDataChunks--;
3235 if (object->nDataChunks <= 0) {
3236 /* remeber to clean up the object */
3237 dev->gcCleanupList[cleanups] =
3243 /* Todo object && object->deleted && object->nDataChunks == 0 */
3244 /* Deleted object header with no data chunks.
3245 * Can be discarded and the file deleted.
3247 object->hdrChunk = 0;
3248 yaffs_FreeTnode(object->myDev,
3251 object->variant.fileVariant.top = NULL;
3252 yaffs_DoGenericObjectDeletion(object);
3254 } else if (object) {
3255 /* It's either a data chunk in a live file or
3256 * an ObjectHeader, so we're interested in it.
3257 * NB Need to keep the ObjectHeaders of deleted files
3258 * until the whole file has been deleted off
3260 tags.serialNumber++;
3264 if (tags.chunkId == 0) {
3265 /* It is an object Id,
3266 * We need to nuke the shrinkheader flags first
3267 * Also need to clean up shadowing.
3268 * We no longer want the shrinkHeader flag since its work is done
3269 * and if it is left in place it will mess up scanning.
3272 yaffs_ObjectHeader *oh;
3273 oh = (yaffs_ObjectHeader *)buffer;
3276 tags.extraIsShrinkHeader = 0;
3278 oh->shadowsObject = 0;
3279 oh->inbandShadowsObject = 0;
3280 tags.extraShadows = 0;
3282 /* Update file size */
3283 if(object->variantType == YAFFS_OBJECT_TYPE_FILE){
3284 oh->fileSize = object->variant.fileVariant.fileSize;
3285 tags.extraFileLength = oh->fileSize;
3288 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
3290 yaffs_WriteNewChunkWithTagsToNAND(dev,(__u8 *) oh, &tags, 1);
3293 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3296 retVal = YAFFS_FAIL;
3299 /* Ok, now fix up the Tnodes etc. */
3301 if (tags.chunkId == 0) {
3303 object->hdrChunk = newChunk;
3304 object->serial = tags.serialNumber;
3306 /* It's a data chunk */
3308 ok = yaffs_PutChunkIntoFile
3316 if (retVal == YAFFS_OK)
3317 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3322 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3325 /* Do any required cleanups */
3326 for (i = 0; i < cleanups; i++) {
3327 /* Time to delete the file too */
3329 yaffs_FindObjectByNumber(dev,
3330 dev->gcCleanupList[i]);
3332 yaffs_FreeTnode(dev,
3333 object->variant.fileVariant.
3335 object->variant.fileVariant.top = NULL;
3338 ("yaffs: About to finally delete object %d"
3339 TENDSTR), object->objectId));
3340 yaffs_DoGenericObjectDeletion(object);
3341 object->myDev->nDeletedFiles--;
3348 yaffs_VerifyCollectedBlock(dev, bi, block);
3352 if (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3354 * The gc did not complete. Set block state back to FULL
3355 * because checkpointing does not restore gc.
3357 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3359 /* The gc completed. */
3360 chunksAfter = yaffs_GetErasedChunks(dev);
3361 if (chunksBefore >= chunksAfter) {
3364 ("gc did not increase free chunks before %d after %d"
3365 TENDSTR), chunksBefore, chunksAfter));
3377 * FindBlockForgarbageCollection is used to select the dirtiest block (or close enough)
3378 * for garbage collection.
3381 static unsigned yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
3387 unsigned selected = 0;
3388 int prioritised = 0;
3389 int prioritisedExists = 0;
3390 yaffs_BlockInfo *bi;
3393 /* First let's see if we need to grab a prioritised block */
3394 if (dev->hasPendingPrioritisedGCs && !aggressive) {
3395 dev->gcDirtiest = 0;
3396 bi = dev->blockInfo;
3397 for (i = dev->internalStartBlock;
3398 i <= dev->internalEndBlock && !selected;
3401 if (bi->gcPrioritise) {
3402 prioritisedExists = 1;
3403 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
3404 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
3413 * If there is a prioritised block and none was selected then
3414 * this happened because there is at least one old dirty block gumming
3415 * up the works. Let's gc the oldest dirty block.
3418 if(prioritisedExists &&
3420 dev->oldestDirtyBlock > 0)
3421 selected = dev->oldestDirtyBlock;
3423 if (!prioritisedExists) /* None found, so we can clear this */
3424 dev->hasPendingPrioritisedGCs = 0;
3427 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
3429 * else (we're doing a leasurely gc), then we only bother to do this if the
3430 * block has only a few pages in use.
3435 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
3437 threshold = dev->param.nChunksPerBlock;
3438 iterations = nBlocks;
3440 int maxThreshold = dev->param.nChunksPerBlock/2;
3441 threshold = background ?
3442 (dev->gcNotDone + 2) * 2 : 0;
3443 if(threshold <YAFFS_GC_PASSIVE_THRESHOLD)
3444 threshold = YAFFS_GC_PASSIVE_THRESHOLD;
3445 if(threshold > maxThreshold)
3446 threshold = maxThreshold;
3448 iterations = nBlocks / 16 + 1;
3449 if (iterations > 100)
3455 (dev->gcDirtiest < 1 ||
3456 dev->gcPagesInUse > YAFFS_GC_GOOD_ENOUGH);
3458 dev->gcBlockFinder++;
3459 if (dev->gcBlockFinder < dev->internalStartBlock ||
3460 dev->gcBlockFinder > dev->internalEndBlock)
3461 dev->gcBlockFinder = dev->internalStartBlock;
3463 bi = yaffs_GetBlockInfo(dev, dev->gcBlockFinder);
3465 pagesUsed = bi->pagesInUse - bi->softDeletions;
3467 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
3468 pagesUsed < dev->param.nChunksPerBlock &&
3469 (dev->gcDirtiest < 1 || pagesUsed < dev->gcPagesInUse) &&
3470 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
3471 dev->gcDirtiest = dev->gcBlockFinder;
3472 dev->gcPagesInUse = pagesUsed;
3476 if(dev->gcDirtiest > 0 && dev->gcPagesInUse <= threshold)
3477 selected = dev->gcDirtiest;
3481 * If nothing has been selected for a while, try selecting the oldest dirty
3482 * because that's gumming up the works.
3485 if(!selected && dev->param.isYaffs2 &&
3486 dev->gcNotDone >= ( background ? 10 : 20)){
3487 yaffs_FindOldestDirtySequence(dev);
3488 if(dev->oldestDirtyBlock > 0) {
3489 selected = dev->oldestDirtyBlock;
3490 dev->gcDirtiest = selected;
3491 dev->oldestDirtyGCs++;
3492 bi = yaffs_GetBlockInfo(dev, selected);
3493 dev->gcPagesInUse = bi->pagesInUse - bi->softDeletions;
3500 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR),
3502 dev->param.nChunksPerBlock - dev->gcPagesInUse,
3506 dev->backgroundGCs++;
3507 dev->gcDirtiest = 0;
3508 dev->gcPagesInUse = 0;
3510 if(dev->refreshSkip > 0)
3515 (TSTR("GC none: finder %d skip %d threshold %d dirtiest %d using %d oldest %d%s" TENDSTR),
3516 dev->gcBlockFinder, dev->gcNotDone,
3518 dev->gcDirtiest, dev->gcPagesInUse,
3519 dev->oldestDirtyBlock,
3520 background ? " bg" : ""));
3526 /* New garbage collector
3527 * If we're very low on erased blocks then we do aggressive garbage collection
3528 * otherwise we do "leasurely" garbage collection.
3529 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3530 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3532 * The idea is to help clear out space in a more spread-out manner.
3533 * Dunno if it really does anything useful.
3535 static int yaffs_CheckGarbageCollection(yaffs_Device *dev, int background)
3538 int gcOk = YAFFS_OK;
3544 int checkpointBlockAdjust;
3546 if(dev->param.gcControl &&
3547 (dev->param.gcControl(dev) & 1) == 0)
3550 if (dev->gcDisable) {
3551 /* Bail out so we don't get recursive gc */
3555 /* This loop should pass the first time.
3556 * We'll only see looping here if the collection does not increase space.
3562 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3563 if (checkpointBlockAdjust < 0)
3564 checkpointBlockAdjust = 0;
3566 minErased = dev->param.nReservedBlocks + checkpointBlockAdjust + 1;
3567 erasedChunks = dev->nErasedBlocks * dev->param.nChunksPerBlock;
3569 /* If we need a block soon then do aggressive gc.*/
3570 if (dev->nErasedBlocks < minErased)
3573 if(dev->gcSkip > 20)
3575 if(erasedChunks < dev->nFreeChunks/2 ||
3587 /* If we don't already have a block being gc'd then see if we should start another */
3589 if (dev->gcBlock < 1 && !aggressive) {
3590 dev->gcBlock = yaffs_FindRefreshBlock(dev);
3593 if (dev->gcBlock < 1) {
3594 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive, background);
3598 if (dev->gcBlock > 0) {
3605 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3606 dev->nErasedBlocks, aggressive));
3608 gcOk = yaffs_GarbageCollectBlock(dev, dev->gcBlock, aggressive);
3611 if (dev->nErasedBlocks < (dev->param.nReservedBlocks) && dev->gcBlock > 0) {
3614 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3615 TENDSTR), dev->nErasedBlocks, maxTries, dev->gcBlock));
3617 } while ((dev->nErasedBlocks < dev->param.nReservedBlocks) &&
3618 (dev->gcBlock > 0) &&
3621 return aggressive ? gcOk : YAFFS_OK;
3625 * yaffs_BackgroundGarbageCollect()
3626 * Garbage collects. Intended to be called from a background thread.
3627 * Returns non-zero if at least half the free chunks are erased.
3629 int yaffs_BackgroundGarbageCollect(yaffs_Device *dev, unsigned urgency)
3631 int erasedChunks = dev->nErasedBlocks * dev->param.nChunksPerBlock;
3633 T(YAFFS_TRACE_BACKGROUND, (TSTR("Background gc %u" TENDSTR),urgency));
3635 yaffs_CheckGarbageCollection(dev, 1);
3636 return erasedChunks > dev->nFreeChunks/2;
3639 /*------------------------- TAGS --------------------------------*/
3641 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
3644 return (tags->chunkId == chunkInObject &&
3645 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3650 /*-------------------- Data file manipulation -----------------*/
3652 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
3653 yaffs_ExtendedTags *tags)
3655 /*Get the Tnode, then get the level 0 offset chunk offset */
3658 yaffs_ExtendedTags localTags;
3661 yaffs_Device *dev = in->myDev;
3664 /* Passed a NULL, so use our own tags space */
3668 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3671 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3674 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3680 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
3681 yaffs_ExtendedTags *tags)
3683 /* Get the Tnode, then get the level 0 offset chunk offset */
3686 yaffs_ExtendedTags localTags;
3688 yaffs_Device *dev = in->myDev;
3692 /* Passed a NULL, so use our own tags space */
3696 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3700 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3703 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3706 /* Delete the entry in the filestructure (if found) */
3708 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, 0);
3714 #ifdef YAFFS_PARANOID
3716 static int yaffs_CheckFileSanity(yaffs_Object *in)
3724 yaffs_Tags localTags;
3725 yaffs_Tags *tags = &localTags;
3729 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3732 objId = in->objectId;
3733 fSize = in->variant.fileVariant.fileSize;
3735 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3737 for (chunk = 1; chunk <= nChunks; chunk++) {
3738 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3743 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunk);
3745 if (yaffs_CheckChunkBits
3746 (dev, theChunk / dev->param.nChunksPerBlock,
3747 theChunk % dev->param.nChunksPerBlock)) {
3749 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3753 (tags, in->objectId, chunk, chunkDeleted)) {
3763 /* T(("No level 0 found for %d\n", chunk)); */
3767 return failed ? YAFFS_FAIL : YAFFS_OK;
3772 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
3773 int chunkInNAND, int inScan)
3775 /* NB inScan is zero unless scanning.
3776 * For forward scanning, inScan is > 0;
3777 * for backward scanning inScan is < 0
3779 * chunkInNAND = 0 is a dummy insert to make sure the tnodes are there.
3783 yaffs_Device *dev = in->myDev;
3785 yaffs_ExtendedTags existingTags;
3786 yaffs_ExtendedTags newTags;
3787 unsigned existingSerial, newSerial;
3789 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3790 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3791 * If it is not during Scanning then something went wrong!
3794 T(YAFFS_TRACE_ERROR,
3796 ("yaffs tragedy:attempt to put data chunk into a non-file"
3801 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3805 tn = yaffs_AddOrFindLevel0Tnode(dev,
3806 &in->variant.fileVariant,
3813 /* Dummy insert, bail now */
3816 existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3819 /* If we're scanning then we need to test for duplicates
3820 * NB This does not need to be efficient since it should only ever
3821 * happen when the power fails during a write, then only one
3822 * chunk should ever be affected.
3824 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3825 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3828 if (existingChunk > 0) {
3829 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3830 * thus we have to do a FindChunkInFile to get the real chunk id.
3832 * We have a duplicate now we need to decide which one to use:
3834 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3835 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3836 * YAFFS1: Get both sets of tags and compare serial numbers.
3840 /* Only do this for forward scanning */
3841 yaffs_ReadChunkWithTagsFromNAND(dev,
3845 /* Do a proper find */
3847 yaffs_FindChunkInFile(in, chunkInInode,
3851 if (existingChunk <= 0) {
3852 /*Hoosterman - how did this happen? */
3854 T(YAFFS_TRACE_ERROR,
3856 ("yaffs tragedy: existing chunk < 0 in scan"
3861 /* NB The deleted flags should be false, otherwise the chunks will
3862 * not be loaded during a scan
3866 newSerial = newTags.serialNumber;
3867 existingSerial = existingTags.serialNumber;
3871 (in->myDev->param.isYaffs2 ||
3872 existingChunk <= 0 ||
3873 ((existingSerial + 1) & 3) == newSerial)) {
3874 /* Forward scanning.
3876 * Delete the old one and drop through to update the tnode
3878 yaffs_DeleteChunk(dev, existingChunk, 1,
3881 /* Backward scanning or we want to use the existing one
3883 * Delete the new one and return early so that the tnode isn't changed
3885 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3893 if (existingChunk == 0)
3896 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
3901 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
3904 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3906 if (chunkInNAND >= 0)
3907 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3910 T(YAFFS_TRACE_NANDACCESS,
3911 (TSTR("Chunk %d not found zero instead" TENDSTR),
3913 /* get sane (zero) data if you read a hole */
3914 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3920 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
3924 yaffs_ExtendedTags tags;
3925 yaffs_BlockInfo *bi;
3931 block = chunkId / dev->param.nChunksPerBlock;
3932 page = chunkId % dev->param.nChunksPerBlock;
3935 if (!yaffs_CheckChunkBit(dev, block, page))
3936 T(YAFFS_TRACE_VERIFY,
3937 (TSTR("Deleting invalid chunk %d"TENDSTR),
3940 bi = yaffs_GetBlockInfo(dev, block);
3942 yaffs_UpdateOldestDirtySequence(dev, block, bi);
3944 T(YAFFS_TRACE_DELETION,
3945 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3948 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->param.isYaffs2) {
3950 yaffs_InitialiseTags(&tags);
3952 tags.chunkDeleted = 1;
3954 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3955 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3957 dev->nUnmarkedDeletions++;
3960 /* Pull out of the management area.
3961 * If the whole block became dirty, this will kick off an erasure.
3963 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3964 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3965 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3966 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3969 yaffs_ClearChunkBit(dev, block, page);
3973 if (bi->pagesInUse == 0 &&
3974 !bi->hasShrinkHeader &&
3975 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3976 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3977 yaffs_BlockBecameDirty(dev, block);
3984 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
3985 const __u8 *buffer, int nBytes,
3988 /* Find old chunk Need to do this to get serial number
3989 * Write new one and patch into tree.
3990 * Invalidate old tags.
3994 yaffs_ExtendedTags prevTags;
3997 yaffs_ExtendedTags newTags;
3999 yaffs_Device *dev = in->myDev;
4001 yaffs_CheckGarbageCollection(dev,0);
4003 /* Get the previous chunk at this location in the file if it exists.
4004 * If it does not exist then put a zero into the tree. This creates
4005 * the tnode now, rather than later when it is harder to clean up.
4007 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
4008 if(prevChunkId < 1 &&
4009 !yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0))
4012 /* Set up new tags */
4013 yaffs_InitialiseTags(&newTags);
4015 newTags.chunkId = chunkInInode;
4016 newTags.objectId = in->objectId;
4017 newTags.serialNumber =
4018 (prevChunkId > 0) ? prevTags.serialNumber + 1 : 1;
4019 newTags.byteCount = nBytes;
4021 if (nBytes < 1 || nBytes > dev->param.totalBytesPerChunk) {
4022 T(YAFFS_TRACE_ERROR,
4023 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
4029 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
4032 if (newChunkId > 0) {
4033 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
4035 if (prevChunkId > 0)
4036 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
4038 yaffs_CheckFileSanity(in);
4044 /* UpdateObjectHeader updates the header on NAND for an object.
4045 * If name is not NULL, then that new name is used.
4047 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
4048 int isShrink, int shadows)
4051 yaffs_BlockInfo *bi;
4053 yaffs_Device *dev = in->myDev;
4060 yaffs_ExtendedTags newTags;
4061 yaffs_ExtendedTags oldTags;
4062 YCHAR *alias = NULL;
4064 __u8 *buffer = NULL;
4065 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
4067 yaffs_ObjectHeader *oh = NULL;
4069 yaffs_strcpy(oldName, _Y("silly old name"));
4073 in == dev->rootDir || /* The rootDir should also be saved */
4076 yaffs_CheckGarbageCollection(dev,0);
4077 yaffs_CheckObjectDetailsLoaded(in);
4079 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
4080 oh = (yaffs_ObjectHeader *) buffer;
4082 prevChunkId = in->hdrChunk;
4084 if (prevChunkId > 0) {
4085 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
4088 yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
4090 memcpy(oldName, oh->name, sizeof(oh->name));
4093 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
4095 oh->type = in->variantType;
4096 oh->yst_mode = in->yst_mode;
4097 oh->shadowsObject = oh->inbandShadowsObject = shadows;
4099 #ifdef CONFIG_YAFFS_WINCE
4100 oh->win_atime[0] = in->win_atime[0];
4101 oh->win_ctime[0] = in->win_ctime[0];
4102 oh->win_mtime[0] = in->win_mtime[0];
4103 oh->win_atime[1] = in->win_atime[1];
4104 oh->win_ctime[1] = in->win_ctime[1];
4105 oh->win_mtime[1] = in->win_mtime[1];
4107 oh->yst_uid = in->yst_uid;
4108 oh->yst_gid = in->yst_gid;
4109 oh->yst_atime = in->yst_atime;
4110 oh->yst_mtime = in->yst_mtime;
4111 oh->yst_ctime = in->yst_ctime;
4112 oh->yst_rdev = in->yst_rdev;
4115 oh->parentObjectId = in->parent->objectId;
4117 oh->parentObjectId = 0;
4119 if (name && *name) {
4120 memset(oh->name, 0, sizeof(oh->name));
4121 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
4122 } else if (prevChunkId > 0)
4123 memcpy(oh->name, oldName, sizeof(oh->name));
4125 memset(oh->name, 0, sizeof(oh->name));
4127 oh->isShrink = isShrink;
4129 switch (in->variantType) {
4130 case YAFFS_OBJECT_TYPE_UNKNOWN:
4131 /* Should not happen */
4133 case YAFFS_OBJECT_TYPE_FILE:
4135 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
4136 || oh->parentObjectId ==
4137 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
4138 fileVariant.fileSize;
4140 case YAFFS_OBJECT_TYPE_HARDLINK:
4141 oh->equivalentObjectId =
4142 in->variant.hardLinkVariant.equivalentObjectId;
4144 case YAFFS_OBJECT_TYPE_SPECIAL:
4147 case YAFFS_OBJECT_TYPE_DIRECTORY:
4150 case YAFFS_OBJECT_TYPE_SYMLINK:
4151 alias = in->variant.symLinkVariant.alias;
4153 alias = _Y("no alias");
4154 yaffs_strncpy(oh->alias,
4156 YAFFS_MAX_ALIAS_LENGTH);
4157 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
4162 yaffs_InitialiseTags(&newTags);
4164 newTags.chunkId = 0;
4165 newTags.objectId = in->objectId;
4166 newTags.serialNumber = in->serial;
4168 /* Add extra info for file header */
4170 newTags.extraHeaderInfoAvailable = 1;
4171 newTags.extraParentObjectId = oh->parentObjectId;
4172 newTags.extraFileLength = oh->fileSize;
4173 newTags.extraIsShrinkHeader = oh->isShrink;
4174 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
4175 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
4176 newTags.extraObjectType = in->variantType;
4178 yaffs_VerifyObjectHeader(in, oh, &newTags, 1);
4180 /* Create new chunk in NAND */
4182 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
4183 (prevChunkId > 0) ? 1 : 0);
4185 if (newChunkId >= 0) {
4187 in->hdrChunk = newChunkId;
4189 if (prevChunkId > 0) {
4190 yaffs_DeleteChunk(dev, prevChunkId, 1,
4194 if (!yaffs_ObjectHasCachedWriteData(in))
4197 /* If this was a shrink, then mark the block that the chunk lives on */
4199 bi = yaffs_GetBlockInfo(in->myDev,
4200 newChunkId / in->myDev->param.nChunksPerBlock);
4201 bi->hasShrinkHeader = 1;
4206 retVal = newChunkId;
4211 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
4216 /*------------------------ Short Operations Cache ----------------------------------------
4217 * In many situations where there is no high level buffering (eg WinCE) a lot of
4218 * reads might be short sequential reads, and a lot of writes may be short
4219 * sequential writes. eg. scanning/writing a jpeg file.
4220 * In these cases, a short read/write cache can provide a huge perfomance benefit
4221 * with dumb-as-a-rock code.
4222 * In Linux, the page cache provides read buffering aand the short op cache provides write
4225 * There are a limited number (~10) of cache chunks per device so that we don't
4226 * need a very intelligent search.
4229 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
4231 yaffs_Device *dev = obj->myDev;
4233 yaffs_ChunkCache *cache;
4234 int nCaches = obj->myDev->param.nShortOpCaches;
4236 for (i = 0; i < nCaches; i++) {
4237 cache = &dev->srCache[i];
4238 if (cache->object == obj &&
4247 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
4249 yaffs_Device *dev = obj->myDev;
4250 int lowest = -99; /* Stop compiler whining. */
4252 yaffs_ChunkCache *cache;
4253 int chunkWritten = 0;
4254 int nCaches = obj->myDev->param.nShortOpCaches;
4260 /* Find the dirty cache for this object with the lowest chunk id. */
4261 for (i = 0; i < nCaches; i++) {
4262 if (dev->srCache[i].object == obj &&
4263 dev->srCache[i].dirty) {
4265 || dev->srCache[i].chunkId <
4267 cache = &dev->srCache[i];
4268 lowest = cache->chunkId;
4273 if (cache && !cache->locked) {
4274 /* Write it out and free it up */
4277 yaffs_WriteChunkDataToObject(cache->object,
4283 cache->object = NULL;
4286 } while (cache && chunkWritten > 0);
4289 /* Hoosterman, disk full while writing cache out. */
4290 T(YAFFS_TRACE_ERROR,
4291 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
4298 /*yaffs_FlushEntireDeviceCache(dev)
4303 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
4306 int nCaches = dev->param.nShortOpCaches;
4309 /* Find a dirty object in the cache and flush it...
4310 * until there are no further dirty objects.
4314 for (i = 0; i < nCaches && !obj; i++) {
4315 if (dev->srCache[i].object &&
4316 dev->srCache[i].dirty)
4317 obj = dev->srCache[i].object;
4321 yaffs_FlushFilesChunkCache(obj);
4328 /* Grab us a cache chunk for use.
4329 * First look for an empty one.
4330 * Then look for the least recently used non-dirty one.
4331 * Then look for the least recently used dirty one...., flush and look again.
4333 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
4337 if (dev->param.nShortOpCaches > 0) {
4338 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4339 if (!dev->srCache[i].object)
4340 return &dev->srCache[i];
4347 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
4349 yaffs_ChunkCache *cache;
4350 yaffs_Object *theObj;
4355 if (dev->param.nShortOpCaches > 0) {
4356 /* Try find a non-dirty one... */
4358 cache = yaffs_GrabChunkCacheWorker(dev);
4361 /* They were all dirty, find the last recently used object and flush
4362 * its cache, then find again.
4363 * NB what's here is not very accurate, we actually flush the object
4364 * the last recently used page.
4367 /* With locking we can't assume we can use entry zero */
4374 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4375 if (dev->srCache[i].object &&
4376 !dev->srCache[i].locked &&
4377 (dev->srCache[i].lastUse < usage || !cache)) {
4378 usage = dev->srCache[i].lastUse;
4379 theObj = dev->srCache[i].object;
4380 cache = &dev->srCache[i];
4385 if (!cache || cache->dirty) {
4386 /* Flush and try again */
4387 yaffs_FlushFilesChunkCache(theObj);
4388 cache = yaffs_GrabChunkCacheWorker(dev);
4398 /* Find a cached chunk */
4399 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj,
4402 yaffs_Device *dev = obj->myDev;
4404 if (dev->param.nShortOpCaches > 0) {
4405 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4406 if (dev->srCache[i].object == obj &&
4407 dev->srCache[i].chunkId == chunkId) {
4410 return &dev->srCache[i];
4417 /* Mark the chunk for the least recently used algorithym */
4418 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache,
4422 if (dev->param.nShortOpCaches > 0) {
4423 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4424 /* Reset the cache usages */
4426 for (i = 1; i < dev->param.nShortOpCaches; i++)
4427 dev->srCache[i].lastUse = 0;
4434 cache->lastUse = dev->srLastUse;
4441 /* Invalidate a single cache page.
4442 * Do this when a whole page gets written,
4443 * ie the short cache for this page is no longer valid.
4445 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
4447 if (object->myDev->param.nShortOpCaches > 0) {
4448 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4451 cache->object = NULL;
4455 /* Invalidate all the cache pages associated with this object
4456 * Do this whenever ther file is deleted or resized.
4458 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
4461 yaffs_Device *dev = in->myDev;
4463 if (dev->param.nShortOpCaches > 0) {
4464 /* Invalidate it. */
4465 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4466 if (dev->srCache[i].object == in)
4467 dev->srCache[i].object = NULL;
4472 /*--------------------- Checkpointing --------------------*/
4475 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev, int head)
4477 yaffs_CheckpointValidity cp;
4479 memset(&cp, 0, sizeof(cp));
4481 cp.structType = sizeof(cp);
4482 cp.magic = YAFFS_MAGIC;
4483 cp.version = YAFFS_CHECKPOINT_VERSION;
4484 cp.head = (head) ? 1 : 0;
4486 return (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp)) ?
4490 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4492 yaffs_CheckpointValidity cp;
4495 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4498 ok = (cp.structType == sizeof(cp)) &&
4499 (cp.magic == YAFFS_MAGIC) &&
4500 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4501 (cp.head == ((head) ? 1 : 0));
4505 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4508 cp->nErasedBlocks = dev->nErasedBlocks;
4509 cp->allocationBlock = dev->allocationBlock;
4510 cp->allocationPage = dev->allocationPage;
4511 cp->nFreeChunks = dev->nFreeChunks;
4513 cp->nDeletedFiles = dev->nDeletedFiles;
4514 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4515 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4516 cp->sequenceNumber = dev->sequenceNumber;
4520 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4521 yaffs_CheckpointDevice *cp)
4523 dev->nErasedBlocks = cp->nErasedBlocks;
4524 dev->allocationBlock = cp->allocationBlock;
4525 dev->allocationPage = cp->allocationPage;
4526 dev->nFreeChunks = cp->nFreeChunks;
4528 dev->nDeletedFiles = cp->nDeletedFiles;
4529 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4530 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4531 dev->sequenceNumber = cp->sequenceNumber;
4535 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4537 yaffs_CheckpointDevice cp;
4539 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4543 /* Write device runtime values*/
4544 yaffs_DeviceToCheckpointDevice(&cp, dev);
4545 cp.structType = sizeof(cp);
4547 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4549 /* Write block info */
4551 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4552 ok = (yaffs_CheckpointWrite(dev, dev->blockInfo, nBytes) == nBytes);
4555 /* Write chunk bits */
4557 nBytes = nBlocks * dev->chunkBitmapStride;
4558 ok = (yaffs_CheckpointWrite(dev, dev->chunkBits, nBytes) == nBytes);
4564 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4566 yaffs_CheckpointDevice cp;
4568 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4572 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4576 if (cp.structType != sizeof(cp))
4580 yaffs_CheckpointDeviceToDevice(dev, &cp);
4582 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4584 ok = (yaffs_CheckpointRead(dev, dev->blockInfo, nBytes) == nBytes);
4588 nBytes = nBlocks * dev->chunkBitmapStride;
4590 ok = (yaffs_CheckpointRead(dev, dev->chunkBits, nBytes) == nBytes);
4595 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4599 cp->objectId = obj->objectId;
4600 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4601 cp->hdrChunk = obj->hdrChunk;
4602 cp->variantType = obj->variantType;
4603 cp->deleted = obj->deleted;
4604 cp->softDeleted = obj->softDeleted;
4605 cp->unlinked = obj->unlinked;
4606 cp->fake = obj->fake;
4607 cp->renameAllowed = obj->renameAllowed;
4608 cp->unlinkAllowed = obj->unlinkAllowed;
4609 cp->serial = obj->serial;
4610 cp->nDataChunks = obj->nDataChunks;
4612 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4613 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4614 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4615 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4618 static int yaffs_CheckpointObjectToObject(yaffs_Object *obj, yaffs_CheckpointObject *cp)
4621 yaffs_Object *parent;
4623 if (obj->variantType != cp->variantType) {
4624 T(YAFFS_TRACE_ERROR, (TSTR("Checkpoint read object %d type %d "
4625 TCONT("chunk %d does not match existing object type %d")
4626 TENDSTR), cp->objectId, cp->variantType, cp->hdrChunk,
4631 obj->objectId = cp->objectId;
4634 parent = yaffs_FindOrCreateObjectByNumber(
4637 YAFFS_OBJECT_TYPE_DIRECTORY);
4642 if (parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4643 T(YAFFS_TRACE_ALWAYS, (TSTR("Checkpoint read object %d parent %d type %d"
4644 TCONT(" chunk %d Parent type, %d, not directory")
4646 cp->objectId, cp->parentId, cp->variantType,
4647 cp->hdrChunk, parent->variantType));
4650 yaffs_AddObjectToDirectory(parent, obj);
4653 obj->hdrChunk = cp->hdrChunk;
4654 obj->variantType = cp->variantType;
4655 obj->deleted = cp->deleted;
4656 obj->softDeleted = cp->softDeleted;
4657 obj->unlinked = cp->unlinked;
4658 obj->fake = cp->fake;
4659 obj->renameAllowed = cp->renameAllowed;
4660 obj->unlinkAllowed = cp->unlinkAllowed;
4661 obj->serial = cp->serial;
4662 obj->nDataChunks = cp->nDataChunks;
4664 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4665 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4666 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4667 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4669 if (obj->hdrChunk > 0)
4670 obj->lazyLoaded = 1;
4676 static int yaffs_CheckpointTnodeWorker(yaffs_Object *in, yaffs_Tnode *tn,
4677 __u32 level, int chunkOffset)
4680 yaffs_Device *dev = in->myDev;
4682 int tnodeSize = yaffs_CalcTnodeSize(dev);
4687 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
4688 if (tn->internal[i]) {
4689 ok = yaffs_CheckpointTnodeWorker(in,
4692 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4695 } else if (level == 0) {
4696 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4697 ok = (yaffs_CheckpointWrite(dev, &baseOffset, sizeof(baseOffset)) == sizeof(baseOffset));
4699 ok = (yaffs_CheckpointWrite(dev, tn, tnodeSize) == tnodeSize);
4707 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4709 __u32 endMarker = ~0;
4712 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4713 ok = yaffs_CheckpointTnodeWorker(obj,
4714 obj->variant.fileVariant.top,
4715 obj->variant.fileVariant.topLevel,
4718 ok = (yaffs_CheckpointWrite(obj->myDev, &endMarker, sizeof(endMarker)) ==
4725 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4729 yaffs_Device *dev = obj->myDev;
4730 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4733 int tnodeSize = yaffs_CalcTnodeSize(dev);
4735 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4737 while (ok && (~baseChunk)) {
4739 /* Read level 0 tnode */
4742 tn = yaffs_GetTnodeRaw(dev);
4744 ok = (yaffs_CheckpointRead(dev, tn, tnodeSize) == tnodeSize);
4749 ok = yaffs_AddOrFindLevel0Tnode(dev,
4755 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4759 T(YAFFS_TRACE_CHECKPOINT, (
4760 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4761 nread, baseChunk, ok));
4767 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4770 yaffs_CheckpointObject cp;
4773 struct ylist_head *lh;
4776 /* Iterate through the objects in each hash entry,
4777 * dumping them to the checkpointing stream.
4780 for (i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++) {
4781 ylist_for_each(lh, &dev->objectBucket[i].list) {
4783 obj = ylist_entry(lh, yaffs_Object, hashLink);
4784 if (!obj->deferedFree) {
4785 yaffs_ObjectToCheckpointObject(&cp, obj);
4786 cp.structType = sizeof(cp);
4788 T(YAFFS_TRACE_CHECKPOINT, (
4789 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %p" TENDSTR),
4790 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk, obj));
4792 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4794 if (ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4795 ok = yaffs_WriteCheckpointTnodes(obj);
4801 /* Dump end of list */
4802 memset(&cp, 0xFF, sizeof(yaffs_CheckpointObject));
4803 cp.structType = sizeof(cp);
4806 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4811 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4814 yaffs_CheckpointObject cp;
4817 yaffs_Object *hardList = NULL;
4819 while (ok && !done) {
4820 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4821 if (cp.structType != sizeof(cp)) {
4822 T(YAFFS_TRACE_CHECKPOINT, (TSTR("struct size %d instead of %d ok %d"TENDSTR),
4823 cp.structType, (int)sizeof(cp), ok));
4827 T(YAFFS_TRACE_CHECKPOINT, (TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4828 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk));
4830 if (ok && cp.objectId == ~0)
4833 obj = yaffs_FindOrCreateObjectByNumber(dev, cp.objectId, cp.variantType);
4835 ok = yaffs_CheckpointObjectToObject(obj, &cp);
4838 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4839 ok = yaffs_ReadCheckpointTnodes(obj);
4840 } else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4841 obj->hardLinks.next =
4842 (struct ylist_head *) hardList;
4851 yaffs_HardlinkFixup(dev, hardList);
4856 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4858 __u32 checkpointSum;
4861 yaffs_GetCheckpointSum(dev, &checkpointSum);
4863 ok = (yaffs_CheckpointWrite(dev, &checkpointSum, sizeof(checkpointSum)) == sizeof(checkpointSum));
4871 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4873 __u32 checkpointSum0;
4874 __u32 checkpointSum1;
4877 yaffs_GetCheckpointSum(dev, &checkpointSum0);
4879 ok = (yaffs_CheckpointRead(dev, &checkpointSum1, sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4884 if (checkpointSum0 != checkpointSum1)
4891 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4895 if (!yaffs_CheckpointRequired(dev)) {
4896 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint write" TENDSTR)));
4901 ok = yaffs_CheckpointOpen(dev, 1);
4904 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4905 ok = yaffs_WriteCheckpointValidityMarker(dev, 1);
4908 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint device" TENDSTR)));
4909 ok = yaffs_WriteCheckpointDevice(dev);
4912 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint objects" TENDSTR)));
4913 ok = yaffs_WriteCheckpointObjects(dev);
4916 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4917 ok = yaffs_WriteCheckpointValidityMarker(dev, 0);
4921 ok = yaffs_WriteCheckpointSum(dev);
4923 if (!yaffs_CheckpointClose(dev))
4927 dev->isCheckpointed = 1;
4929 dev->isCheckpointed = 0;
4931 return dev->isCheckpointed;
4934 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4938 if (dev->param.skipCheckpointRead || !dev->param.isYaffs2) {
4939 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint read" TENDSTR)));
4944 ok = yaffs_CheckpointOpen(dev, 0); /* open for read */
4947 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4948 ok = yaffs_ReadCheckpointValidityMarker(dev, 1);
4951 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint device" TENDSTR)));
4952 ok = yaffs_ReadCheckpointDevice(dev);
4955 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint objects" TENDSTR)));
4956 ok = yaffs_ReadCheckpointObjects(dev);
4959 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4960 ok = yaffs_ReadCheckpointValidityMarker(dev, 0);
4964 ok = yaffs_ReadCheckpointSum(dev);
4965 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint checksum %d" TENDSTR), ok));
4968 if (!yaffs_CheckpointClose(dev))
4972 dev->isCheckpointed = 1;
4974 dev->isCheckpointed = 0;
4980 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4982 if (dev->isCheckpointed ||
4983 dev->blocksInCheckpoint > 0) {
4984 dev->isCheckpointed = 0;
4985 yaffs_CheckpointInvalidateStream(dev);
4987 if (dev->param.markSuperBlockDirty)
4988 dev->param.markSuperBlockDirty(dev);
4992 int yaffs_CheckpointSave(yaffs_Device *dev)
4995 T(YAFFS_TRACE_CHECKPOINT, (TSTR("save entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4997 yaffs_VerifyObjects(dev);
4998 yaffs_VerifyBlocks(dev);
4999 yaffs_VerifyFreeChunks(dev);
5001 if (!dev->isCheckpointed) {
5002 yaffs_InvalidateCheckpoint(dev);
5003 yaffs_WriteCheckpointData(dev);
5006 T(YAFFS_TRACE_ALWAYS, (TSTR("save exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
5008 return dev->isCheckpointed;
5011 int yaffs_CheckpointRestore(yaffs_Device *dev)
5014 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
5016 retval = yaffs_ReadCheckpointData(dev);
5018 if (dev->isCheckpointed) {
5019 yaffs_VerifyObjects(dev);
5020 yaffs_VerifyBlocks(dev);
5021 yaffs_VerifyFreeChunks(dev);
5024 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
5029 /*--------------------- File read/write ------------------------
5030 * Read and write have very similar structures.
5031 * In general the read/write has three parts to it
5032 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
5033 * Some complete chunks
5034 * An incomplete chunk to end off with
5036 * Curve-balls: the first chunk might also be the last chunk.
5039 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 *buffer, loff_t offset,
5048 yaffs_ChunkCache *cache;
5055 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
5056 /* start = offset % dev->nDataBytesPerChunk; */
5057 yaffs_AddrToChunk(dev, offset, &chunk, &start);
5060 /* OK now check for the curveball where the start and end are in
5063 if ((start + n) < dev->nDataBytesPerChunk)
5066 nToCopy = dev->nDataBytesPerChunk - start;
5068 cache = yaffs_FindChunkCache(in, chunk);
5070 /* If the chunk is already in the cache or it is less than a whole chunk
5071 * or we're using inband tags then use the cache (if there is caching)
5072 * else bypass the cache.
5074 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
5075 if (dev->param.nShortOpCaches > 0) {
5077 /* If we can't find the data in the cache, then load it up. */
5080 cache = yaffs_GrabChunkCache(in->myDev);
5082 cache->chunkId = chunk;
5085 yaffs_ReadChunkDataFromObject(in, chunk,
5091 yaffs_UseChunkCache(dev, cache, 0);
5096 memcpy(buffer, &cache->data[start], nToCopy);
5100 /* Read into the local buffer then copy..*/
5103 yaffs_GetTempBuffer(dev, __LINE__);
5104 yaffs_ReadChunkDataFromObject(in, chunk,
5107 memcpy(buffer, &localBuffer[start], nToCopy);
5110 yaffs_ReleaseTempBuffer(dev, localBuffer,
5116 /* A full chunk. Read directly into the supplied buffer. */
5117 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
5131 int yaffs_DoWriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
5132 int nBytes, int writeThrough)
5141 int startOfWrite = offset;
5142 int chunkWritten = 0;
5150 while (n > 0 && chunkWritten >= 0) {
5151 yaffs_AddrToChunk(dev, offset, &chunk, &start);
5153 if (chunk * dev->nDataBytesPerChunk + start != offset ||
5154 start >= dev->nDataBytesPerChunk) {
5155 T(YAFFS_TRACE_ERROR, (
5156 TSTR("AddrToChunk of offset %d gives chunk %d start %d"
5158 (int)offset, chunk, start));
5160 chunk++; /* File pos to chunk in file offset */
5162 /* OK now check for the curveball where the start and end are in
5166 if ((start + n) < dev->nDataBytesPerChunk) {
5169 /* Now folks, to calculate how many bytes to write back....
5170 * If we're overwriting and not writing to then end of file then
5171 * we need to write back as much as was there before.
5174 chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
5176 if (chunkStart > in->variant.fileVariant.fileSize)
5177 nBytesRead = 0; /* Past end of file */
5179 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
5181 if (nBytesRead > dev->nDataBytesPerChunk)
5182 nBytesRead = dev->nDataBytesPerChunk;
5186 (start + n)) ? nBytesRead : (start + n);
5188 if (nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
5192 nToCopy = dev->nDataBytesPerChunk - start;
5193 nToWriteBack = dev->nDataBytesPerChunk;
5196 if (nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
5197 /* An incomplete start or end chunk (or maybe both start and end chunk),
5198 * or we're using inband tags, so we want to use the cache buffers.
5200 if (dev->param.nShortOpCaches > 0) {
5201 yaffs_ChunkCache *cache;
5202 /* If we can't find the data in the cache, then load the cache */
5203 cache = yaffs_FindChunkCache(in, chunk);
5206 && yaffs_CheckSpaceForAllocation(dev, 1)) {
5207 cache = yaffs_GrabChunkCache(dev);
5209 cache->chunkId = chunk;
5212 yaffs_ReadChunkDataFromObject(in, chunk,
5216 !yaffs_CheckSpaceForAllocation(dev, 1)) {
5217 /* Drop the cache if it was a read cache item and
5218 * no space check has been made for it.
5224 yaffs_UseChunkCache(dev, cache, 1);
5228 memcpy(&cache->data[start], buffer,
5233 cache->nBytes = nToWriteBack;
5237 yaffs_WriteChunkDataToObject
5240 cache->data, cache->nBytes,
5246 chunkWritten = -1; /* fail the write */
5249 /* An incomplete start or end chunk (or maybe both start and end chunk)
5250 * Read into the local buffer then copy, then copy over and write back.
5254 yaffs_GetTempBuffer(dev, __LINE__);
5256 yaffs_ReadChunkDataFromObject(in, chunk,
5261 memcpy(&localBuffer[start], buffer, nToCopy);
5264 yaffs_WriteChunkDataToObject(in, chunk,
5269 yaffs_ReleaseTempBuffer(dev, localBuffer,
5275 /* A full chunk. Write directly from the supplied buffer. */
5280 yaffs_WriteChunkDataToObject(in, chunk, buffer,
5281 dev->nDataBytesPerChunk,
5284 /* Since we've overwritten the cached data, we better invalidate it. */
5285 yaffs_InvalidateChunkCache(in, chunk);
5288 if (chunkWritten >= 0) {
5297 /* Update file object */
5299 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
5300 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
5307 int yaffs_WriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
5308 int nBytes, int writeThrough)
5310 yaffs_HandleHole(in,offset);
5311 return yaffs_DoWriteDataToFile(in,buffer,offset,nBytes,writeThrough);
5316 /* ---------------------- File resizing stuff ------------------ */
5318 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
5321 yaffs_Device *dev = in->myDev;
5322 int oldFileSize = in->variant.fileVariant.fileSize;
5324 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
5326 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
5327 dev->nDataBytesPerChunk;
5331 /* Delete backwards so that we don't end up with holes if
5332 * power is lost part-way through the operation.
5334 for (i = lastDel; i >= startDel; i--) {
5335 /* NB this could be optimised somewhat,
5336 * eg. could retrieve the tags and write them without
5337 * using yaffs_DeleteChunk
5340 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5343 (dev->internalStartBlock * dev->param.nChunksPerBlock)
5345 ((dev->internalEndBlock +
5346 1) * dev->param.nChunksPerBlock)) {
5347 T(YAFFS_TRACE_ALWAYS,
5348 (TSTR("Found daft chunkId %d for %d" TENDSTR),
5352 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5360 static void yaffs_ResizeDown( yaffs_Object *obj, loff_t newSize)
5363 __u32 newSizeOfPartialChunk;
5364 yaffs_Device *dev = obj->myDev;
5366 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5368 yaffs_PruneResizedChunks(obj, newSize);
5370 if (newSizeOfPartialChunk != 0) {
5371 int lastChunk = 1 + newFullChunks;
5372 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5374 /* Got to read and rewrite the last chunk with its new size and zero pad */
5375 yaffs_ReadChunkDataFromObject(obj, lastChunk, localBuffer);
5376 memset(localBuffer + newSizeOfPartialChunk, 0,
5377 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5379 yaffs_WriteChunkDataToObject(obj, lastChunk, localBuffer,
5380 newSizeOfPartialChunk, 1);
5382 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5385 obj->variant.fileVariant.fileSize = newSize;
5387 yaffs_PruneFileStructure(dev, &obj->variant.fileVariant);
5391 static int yaffs_HandleHole(yaffs_Object *obj, loff_t newSize)
5393 /* if newsSize > oldFileSize.
5394 * We're going to be writing a hole.
5395 * If the hole is small then write zeros otherwise write a start of hole marker.
5402 int result = YAFFS_OK;
5403 yaffs_Device *dev = NULL;
5405 __u8 *localBuffer = NULL;
5407 int smallIncreaseOk = 0;
5412 if(obj->variantType != YAFFS_OBJECT_TYPE_FILE)
5417 /* Bail out if not yaffs2 mode */
5418 if(!dev->param.isYaffs2)
5421 oldFileSize = obj->variant.fileVariant.fileSize;
5423 if (newSize <= oldFileSize)
5426 increase = newSize - oldFileSize;
5428 if(increase < YAFFS_SMALL_HOLE_THRESHOLD * dev->nDataBytesPerChunk &&
5429 yaffs_CheckSpaceForAllocation(dev, YAFFS_SMALL_HOLE_THRESHOLD + 1))
5435 localBuffer= yaffs_GetTempBuffer(dev, __LINE__);
5438 /* fill hole with zero bytes */
5439 int pos = oldFileSize;
5442 memset(localBuffer,0,dev->nDataBytesPerChunk);
5443 smallIncreaseOk = 1;
5445 while(increase > 0 && smallIncreaseOk){
5446 thisWrite = increase;
5447 if(thisWrite > dev->nDataBytesPerChunk)
5448 thisWrite = dev->nDataBytesPerChunk;
5449 written = yaffs_DoWriteDataToFile(obj,localBuffer,pos,thisWrite,0);
5450 if(written == thisWrite){
5452 increase -= thisWrite;
5454 smallIncreaseOk = 0;
5457 yaffs_ReleaseTempBuffer(dev,localBuffer,__LINE__);
5459 /* If we were out of space then reverse any chunks we've added */
5460 if(!smallIncreaseOk)
5461 yaffs_ResizeDown(obj, oldFileSize);
5464 if (!smallIncreaseOk &&
5466 obj->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5467 obj->parent->objectId != YAFFS_OBJECTID_DELETED){
5468 /* Write a hole start header with the old file size */
5469 yaffs_UpdateObjectHeader(obj, NULL, 0,1,0);
5476 int yaffs_ResizeFile(yaffs_Object *in, loff_t newSize)
5478 yaffs_Device *dev = in->myDev;
5479 int oldFileSize = in->variant.fileVariant.fileSize;
5481 yaffs_FlushFilesChunkCache(in);
5482 yaffs_InvalidateWholeChunkCache(in);
5484 yaffs_CheckGarbageCollection(dev,0);
5486 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
5489 if (newSize == oldFileSize)
5492 if(newSize > oldFileSize){
5493 yaffs_HandleHole(in,newSize);
5494 in->variant.fileVariant.fileSize = newSize;
5496 /* newSize < oldFileSize */
5497 yaffs_ResizeDown(in, newSize);
5500 /* Write a new object header to reflect the resize.
5501 * show we've shrunk the file, if need be
5502 * Do this only if the file is not in the deleted directories
5503 * and is not shadowed.
5507 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5508 in->parent->objectId != YAFFS_OBJECTID_DELETED)
5509 yaffs_UpdateObjectHeader(in, NULL, 0,0,0);
5515 loff_t yaffs_GetFileSize(yaffs_Object *obj)
5517 YCHAR *alias = NULL;
5518 obj = yaffs_GetEquivalentObject(obj);
5520 switch (obj->variantType) {
5521 case YAFFS_OBJECT_TYPE_FILE:
5522 return obj->variant.fileVariant.fileSize;
5523 case YAFFS_OBJECT_TYPE_SYMLINK:
5524 alias = obj->variant.symLinkVariant.alias;
5527 return yaffs_strnlen(alias,YAFFS_MAX_ALIAS_LENGTH);
5535 int yaffs_FlushFile(yaffs_Object *in, int updateTime, int dataSync)
5539 yaffs_FlushFilesChunkCache(in);
5540 if(dataSync) /* Only sync data */
5544 #ifdef CONFIG_YAFFS_WINCE
5545 yfsd_WinFileTimeNow(in->win_mtime);
5548 in->yst_mtime = Y_CURRENT_TIME;
5553 retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5554 0) ? YAFFS_OK : YAFFS_FAIL;
5564 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
5567 /* First off, invalidate the file's data in the cache, without flushing. */
5568 yaffs_InvalidateWholeChunkCache(in);
5570 if (in->myDev->param.isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5571 /* Move to the unlinked directory so we have a record that it was deleted. */
5572 yaffs_ChangeObjectName(in, in->myDev->deletedDir, _Y("deleted"), 0, 0);
5576 yaffs_RemoveObjectFromDirectory(in);
5577 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5580 yaffs_FreeObject(in);
5585 /* yaffs_DeleteFile deletes the whole file data
5586 * and the inode associated with the file.
5587 * It does not delete the links associated with the file.
5589 static int yaffs_UnlinkFileIfNeeded(yaffs_Object *in)
5593 int immediateDeletion = 0;
5594 yaffs_Device *dev = in->myDev;
5597 immediateDeletion = 1;
5599 if (immediateDeletion) {
5601 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5602 _Y("deleted"), 0, 0);
5603 T(YAFFS_TRACE_TRACING,
5604 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5607 in->myDev->nDeletedFiles++;
5608 if (dev->param.disableSoftDelete || dev->param.isYaffs2)
5609 yaffs_ResizeFile(in, 0);
5610 yaffs_SoftDeleteFile(in);
5613 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5614 _Y("unlinked"), 0, 0);
5621 int yaffs_DeleteFile(yaffs_Object *in)
5623 int retVal = YAFFS_OK;
5624 int deleted = in->deleted;
5625 yaffs_Device *dev = in->myDev;
5627 if (dev->param.disableSoftDelete || dev->param.isYaffs2)
5628 yaffs_ResizeFile(in, 0);
5630 if (in->nDataChunks > 0) {
5631 /* Use soft deletion if there is data in the file.
5632 * That won't be the case if it has been resized to zero.
5635 retVal = yaffs_UnlinkFileIfNeeded(in);
5637 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5640 in->myDev->nDeletedFiles++;
5641 yaffs_SoftDeleteFile(in);
5643 return deleted ? YAFFS_OK : YAFFS_FAIL;
5645 /* The file has no data chunks so we toss it immediately */
5646 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5647 in->variant.fileVariant.top = NULL;
5648 yaffs_DoGenericObjectDeletion(in);
5654 static int yaffs_IsNonEmptyDirectory(yaffs_Object *obj)
5656 return (obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) &&
5657 !(ylist_empty(&obj->variant.directoryVariant.children));
5660 static int yaffs_DeleteDirectory(yaffs_Object *obj)
5662 /* First check that the directory is empty. */
5663 if (yaffs_IsNonEmptyDirectory(obj))
5666 return yaffs_DoGenericObjectDeletion(obj);
5669 static int yaffs_DeleteSymLink(yaffs_Object *in)
5671 if(in->variant.symLinkVariant.alias)
5672 YFREE(in->variant.symLinkVariant.alias);
5673 in->variant.symLinkVariant.alias=NULL;
5675 return yaffs_DoGenericObjectDeletion(in);
5678 static int yaffs_DeleteHardLink(yaffs_Object *in)
5680 /* remove this hardlink from the list assocaited with the equivalent
5683 ylist_del_init(&in->hardLinks);
5684 return yaffs_DoGenericObjectDeletion(in);
5687 int yaffs_DeleteObject(yaffs_Object *obj)
5690 switch (obj->variantType) {
5691 case YAFFS_OBJECT_TYPE_FILE:
5692 retVal = yaffs_DeleteFile(obj);
5694 case YAFFS_OBJECT_TYPE_DIRECTORY:
5695 if(!ylist_empty(&obj->variant.directoryVariant.dirty)){
5696 T(YAFFS_TRACE_BACKGROUND, (TSTR("Remove object %d from dirty directories" TENDSTR),obj->objectId));
5697 ylist_del_init(&obj->variant.directoryVariant.dirty);
5699 return yaffs_DeleteDirectory(obj);
5701 case YAFFS_OBJECT_TYPE_SYMLINK:
5702 retVal = yaffs_DeleteSymLink(obj);
5704 case YAFFS_OBJECT_TYPE_HARDLINK:
5705 retVal = yaffs_DeleteHardLink(obj);
5707 case YAFFS_OBJECT_TYPE_SPECIAL:
5708 retVal = yaffs_DoGenericObjectDeletion(obj);
5710 case YAFFS_OBJECT_TYPE_UNKNOWN:
5712 break; /* should not happen. */
5718 static int yaffs_UnlinkWorker(yaffs_Object *obj)
5721 int immediateDeletion = 0;
5724 immediateDeletion = 1;
5727 yaffs_UpdateParent(obj->parent);
5729 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5730 return yaffs_DeleteHardLink(obj);
5731 } else if (!ylist_empty(&obj->hardLinks)) {
5732 /* Curve ball: We're unlinking an object that has a hardlink.
5734 * This problem arises because we are not strictly following
5735 * The Linux link/inode model.
5737 * We can't really delete the object.
5738 * Instead, we do the following:
5739 * - Select a hardlink.
5740 * - Unhook it from the hard links
5741 * - Move it from its parent directory (so that the rename can work)
5742 * - Rename the object to the hardlink's name.
5743 * - Delete the hardlink
5747 yaffs_Object *parent;
5749 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5751 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5753 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5754 parent = hl->parent;
5756 ylist_del_init(&hl->hardLinks);
5758 yaffs_AddObjectToDirectory(obj->myDev->unlinkedDir, hl);
5760 retVal = yaffs_ChangeObjectName(obj,parent, name, 0, 0);
5762 if (retVal == YAFFS_OK)
5763 retVal = yaffs_DoGenericObjectDeletion(hl);
5767 } else if (immediateDeletion) {
5768 switch (obj->variantType) {
5769 case YAFFS_OBJECT_TYPE_FILE:
5770 return yaffs_DeleteFile(obj);
5772 case YAFFS_OBJECT_TYPE_DIRECTORY:
5773 ylist_del_init(&obj->variant.directoryVariant.dirty);
5774 return yaffs_DeleteDirectory(obj);
5776 case YAFFS_OBJECT_TYPE_SYMLINK:
5777 return yaffs_DeleteSymLink(obj);
5779 case YAFFS_OBJECT_TYPE_SPECIAL:
5780 return yaffs_DoGenericObjectDeletion(obj);
5782 case YAFFS_OBJECT_TYPE_HARDLINK:
5783 case YAFFS_OBJECT_TYPE_UNKNOWN:
5787 } else if(yaffs_IsNonEmptyDirectory(obj))
5790 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
5791 _Y("unlinked"), 0, 0);
5795 static int yaffs_UnlinkObject(yaffs_Object *obj)
5798 if (obj && obj->unlinkAllowed)
5799 return yaffs_UnlinkWorker(obj);
5804 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
5808 obj = yaffs_FindObjectByName(dir, name);
5809 return yaffs_UnlinkObject(obj);
5812 /*----------------------- Initialisation Scanning ---------------------- */
5814 static void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
5815 int backwardScanning)
5819 if (!backwardScanning) {
5820 /* Handle YAFFS1 forward scanning case
5821 * For YAFFS1 we always do the deletion
5825 /* Handle YAFFS2 case (backward scanning)
5826 * If the shadowed object exists then ignore.
5828 obj = yaffs_FindObjectByNumber(dev, objId);
5833 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5834 * We put it in unlinked dir to be cleaned up after the scanning
5837 yaffs_FindOrCreateObjectByNumber(dev, objId,
5838 YAFFS_OBJECT_TYPE_FILE);
5841 obj->isShadowed = 1;
5842 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5843 obj->variant.fileVariant.shrinkSize = 0;
5844 obj->valid = 1; /* So that we don't read any other info for this file */
5854 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5861 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5863 in = yaffs_FindObjectByNumber(dev,
5864 hl->variant.hardLinkVariant.
5865 equivalentObjectId);
5868 /* Add the hardlink pointers */
5869 hl->variant.hardLinkVariant.equivalentObject = in;
5870 ylist_add(&hl->hardLinks, &in->hardLinks);
5872 /* Todo Need to report/handle this better.
5873 * Got a problem... hardlink to a non-existant object
5875 hl->variant.hardLinkVariant.equivalentObject = NULL;
5876 YINIT_LIST_HEAD(&hl->hardLinks);
5886 static int ybicmp(const void *a, const void *b)
5888 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5889 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5890 register int ablock = ((yaffs_BlockIndex *)a)->block;
5891 register int bblock = ((yaffs_BlockIndex *)b)->block;
5893 return ablock - bblock;
5899 struct yaffs_ShadowFixerStruct {
5902 struct yaffs_ShadowFixerStruct *next;
5906 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5909 * Sort out state of unlinked and deleted objects after scanning.
5911 struct ylist_head *i;
5912 struct ylist_head *n;
5915 /* Soft delete all the unlinked files */
5916 ylist_for_each_safe(i, n,
5917 &dev->unlinkedDir->variant.directoryVariant.children) {
5919 l = ylist_entry(i, yaffs_Object, siblings);
5920 yaffs_DeleteObject(l);
5924 ylist_for_each_safe(i, n,
5925 &dev->deletedDir->variant.directoryVariant.children) {
5927 l = ylist_entry(i, yaffs_Object, siblings);
5928 yaffs_DeleteObject(l);
5935 * This code iterates through all the objects making sure that they are rooted.
5936 * Any unrooted objects are re-rooted in lost+found.
5937 * An object needs to be in one of:
5938 * - Directly under deleted, unlinked
5939 * - Directly or indirectly under root.
5942 * This code assumes that we don't ever change the current relationships between
5944 * rootDir->parent == unlinkedDir->parent == deletedDir->parent == NULL
5945 * lostNfound->parent == rootDir
5947 * This fixes the problem where directories might have inadvertently been deleted
5948 * leaving the object "hanging" without being rooted in the directory tree.
5951 static int yaffs_HasNULLParent(yaffs_Device *dev, yaffs_Object *obj)
5953 return (obj == dev->deletedDir ||
5954 obj == dev->unlinkedDir||
5955 obj == dev->rootDir);
5958 static void yaffs_FixHangingObjects(yaffs_Device *dev)
5961 yaffs_Object *parent;
5963 struct ylist_head *lh;
5964 struct ylist_head *n;
5969 /* Iterate through the objects in each hash entry,
5970 * looking at each object.
5971 * Make sure it is rooted.
5974 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
5975 ylist_for_each_safe(lh, n, &dev->objectBucket[i].list) {
5977 obj = ylist_entry(lh, yaffs_Object, hashLink);
5978 parent= obj->parent;
5980 if(yaffs_HasNULLParent(dev,obj)){
5981 /* These directories are not hanging */
5984 else if(!parent || parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5986 else if(yaffs_HasNULLParent(dev,parent))
5990 * Need to follow the parent chain to see if it is hanging.
5995 while(parent != dev->rootDir &&
5997 parent->parent->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
5999 parent = parent->parent;
6002 if(parent != dev->rootDir)
6007 (TSTR("Hanging object %d moved to lost and found" TENDSTR),
6009 yaffs_AddObjectToDirectory(dev->lostNFoundDir,obj);
6018 * Delete directory contents for cleaning up lost and found.
6020 static void yaffs_DeleteDirectoryContents(yaffs_Object *dir)
6023 struct ylist_head *lh;
6024 struct ylist_head *n;
6026 if(dir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
6029 ylist_for_each_safe(lh, n, &dir->variant.directoryVariant.children) {
6031 obj = ylist_entry(lh, yaffs_Object, siblings);
6032 if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
6033 yaffs_DeleteDirectoryContents(obj);
6036 (TSTR("Deleting lost_found object %d" TENDSTR),
6039 /* Need to use UnlinkObject since Delete would not handle
6040 * hardlinked objects correctly.
6042 yaffs_UnlinkObject(obj);
6048 static void yaffs_EmptyLostAndFound(yaffs_Device *dev)
6050 yaffs_DeleteDirectoryContents(dev->lostNFoundDir);
6053 static int yaffs_Scan(yaffs_Device *dev)
6055 yaffs_ExtendedTags tags;
6065 yaffs_BlockState state;
6066 yaffs_Object *hardList = NULL;
6067 yaffs_BlockInfo *bi;
6068 __u32 sequenceNumber;
6069 yaffs_ObjectHeader *oh;
6071 yaffs_Object *parent;
6073 int alloc_failed = 0;
6075 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
6083 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
6084 dev->internalStartBlock, dev->internalEndBlock));
6086 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6088 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6090 /* Scan all the blocks to determine their state */
6091 bi = dev->blockInfo;
6092 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6093 yaffs_ClearChunkBits(dev, blk);
6095 bi->softDeletions = 0;
6097 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6099 bi->blockState = state;
6100 bi->sequenceNumber = sequenceNumber;
6102 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6103 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6105 T(YAFFS_TRACE_SCAN_DEBUG,
6106 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6107 state, sequenceNumber));
6109 if (state == YAFFS_BLOCK_STATE_DEAD) {
6110 T(YAFFS_TRACE_BAD_BLOCKS,
6111 (TSTR("block %d is bad" TENDSTR), blk));
6112 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6113 T(YAFFS_TRACE_SCAN_DEBUG,
6114 (TSTR("Block empty " TENDSTR)));
6115 dev->nErasedBlocks++;
6116 dev->nFreeChunks += dev->param.nChunksPerBlock;
6121 startIterator = dev->internalStartBlock;
6122 endIterator = dev->internalEndBlock;
6124 /* For each block.... */
6125 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
6132 blk = blockIterator;
6134 bi = yaffs_GetBlockInfo(dev, blk);
6135 state = bi->blockState;
6139 /* For each chunk in each block that needs scanning....*/
6140 for (c = 0; !alloc_failed && c < dev->param.nChunksPerBlock &&
6141 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
6142 /* Read the tags and decide what to do */
6143 chunk = blk * dev->param.nChunksPerBlock + c;
6145 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6148 /* Let's have a good look at this chunk... */
6150 if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
6156 /*T((" %d %d deleted\n",blk,c)); */
6157 } else if (!tags.chunkUsed) {
6158 /* An unassigned chunk in the block
6159 * This means that either the block is empty or
6160 * this is the one being allocated from
6164 /* We're looking at the first chunk in the block so the block is unused */
6165 state = YAFFS_BLOCK_STATE_EMPTY;
6166 dev->nErasedBlocks++;
6168 /* this is the block being allocated from */
6171 (" Allocating from %d %d" TENDSTR),
6173 state = YAFFS_BLOCK_STATE_ALLOCATING;
6174 dev->allocationBlock = blk;
6175 dev->allocationPage = c;
6176 dev->allocationBlockFinder = blk;
6177 /* Set block finder here to encourage the allocator to go forth from here. */
6181 dev->nFreeChunks += (dev->param.nChunksPerBlock - c);
6182 } else if (tags.chunkId > 0) {
6183 /* chunkId > 0 so it is a data chunk... */
6184 unsigned int endpos;
6186 yaffs_SetChunkBit(dev, blk, c);
6189 in = yaffs_FindOrCreateObjectByNumber(dev,
6192 YAFFS_OBJECT_TYPE_FILE);
6193 /* PutChunkIntoFile checks for a clash (two data chunks with
6194 * the same chunkId).
6201 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, 1))
6206 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
6209 in->variantType == YAFFS_OBJECT_TYPE_FILE
6210 && in->variant.fileVariant.scannedFileSize <
6212 in->variant.fileVariant.
6213 scannedFileSize = endpos;
6214 if (!dev->param.useHeaderFileSize) {
6215 in->variant.fileVariant.
6217 in->variant.fileVariant.
6222 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
6224 /* chunkId == 0, so it is an ObjectHeader.
6225 * Thus, we read in the object header and make the object
6227 yaffs_SetChunkBit(dev, blk, c);
6230 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
6234 oh = (yaffs_ObjectHeader *) chunkData;
6236 in = yaffs_FindObjectByNumber(dev,
6238 if (in && in->variantType != oh->type) {
6239 /* This should not happen, but somehow
6240 * Wev'e ended up with an objectId that has been reused but not yet
6241 * deleted, and worse still it has changed type. Delete the old object.
6244 yaffs_DeleteObject(in);
6249 in = yaffs_FindOrCreateObjectByNumber(dev,
6257 if (in && oh->shadowsObject > 0) {
6259 struct yaffs_ShadowFixerStruct *fixer;
6260 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
6262 fixer->next = shadowFixerList;
6263 shadowFixerList = fixer;
6264 fixer->objectId = tags.objectId;
6265 fixer->shadowedId = oh->shadowsObject;
6270 if (in && in->valid) {
6271 /* We have already filled this one. We have a duplicate and need to resolve it. */
6273 unsigned existingSerial = in->serial;
6274 unsigned newSerial = tags.serialNumber;
6276 if (((existingSerial + 1) & 3) == newSerial) {
6277 /* Use new one - destroy the exisiting one */
6278 yaffs_DeleteChunk(dev,
6283 /* Use existing - destroy this one. */
6284 yaffs_DeleteChunk(dev, chunk, 1,
6289 if (in && !in->valid &&
6290 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6291 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
6292 /* We only load some info, don't fiddle with directory structure */
6294 in->variantType = oh->type;
6296 in->yst_mode = oh->yst_mode;
6297 #ifdef CONFIG_YAFFS_WINCE
6298 in->win_atime[0] = oh->win_atime[0];
6299 in->win_ctime[0] = oh->win_ctime[0];
6300 in->win_mtime[0] = oh->win_mtime[0];
6301 in->win_atime[1] = oh->win_atime[1];
6302 in->win_ctime[1] = oh->win_ctime[1];
6303 in->win_mtime[1] = oh->win_mtime[1];
6305 in->yst_uid = oh->yst_uid;
6306 in->yst_gid = oh->yst_gid;
6307 in->yst_atime = oh->yst_atime;
6308 in->yst_mtime = oh->yst_mtime;
6309 in->yst_ctime = oh->yst_ctime;
6310 in->yst_rdev = oh->yst_rdev;
6312 in->hdrChunk = chunk;
6313 in->serial = tags.serialNumber;
6315 } else if (in && !in->valid) {
6316 /* we need to load this info */
6319 in->variantType = oh->type;
6321 in->yst_mode = oh->yst_mode;
6322 #ifdef CONFIG_YAFFS_WINCE
6323 in->win_atime[0] = oh->win_atime[0];
6324 in->win_ctime[0] = oh->win_ctime[0];
6325 in->win_mtime[0] = oh->win_mtime[0];
6326 in->win_atime[1] = oh->win_atime[1];
6327 in->win_ctime[1] = oh->win_ctime[1];
6328 in->win_mtime[1] = oh->win_mtime[1];
6330 in->yst_uid = oh->yst_uid;
6331 in->yst_gid = oh->yst_gid;
6332 in->yst_atime = oh->yst_atime;
6333 in->yst_mtime = oh->yst_mtime;
6334 in->yst_ctime = oh->yst_ctime;
6335 in->yst_rdev = oh->yst_rdev;
6337 in->hdrChunk = chunk;
6338 in->serial = tags.serialNumber;
6340 yaffs_SetObjectName(in, oh->name);
6343 /* directory stuff...
6348 yaffs_FindOrCreateObjectByNumber
6349 (dev, oh->parentObjectId,
6350 YAFFS_OBJECT_TYPE_DIRECTORY);
6353 if (parent && parent->variantType ==
6354 YAFFS_OBJECT_TYPE_UNKNOWN) {
6355 /* Set up as a directory */
6356 parent->variantType =
6357 YAFFS_OBJECT_TYPE_DIRECTORY;
6358 YINIT_LIST_HEAD(&parent->variant.
6361 } else if (!parent || parent->variantType !=
6362 YAFFS_OBJECT_TYPE_DIRECTORY) {
6363 /* Hoosterman, another problem....
6364 * We're trying to use a non-directory as a directory
6367 T(YAFFS_TRACE_ERROR,
6369 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6371 parent = dev->lostNFoundDir;
6374 yaffs_AddObjectToDirectory(parent, in);
6376 if (0 && (parent == dev->deletedDir ||
6377 parent == dev->unlinkedDir)) {
6378 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
6379 dev->nDeletedFiles++;
6381 /* Note re hardlinks.
6382 * Since we might scan a hardlink before its equivalent object is scanned
6383 * we put them all in a list.
6384 * After scanning is complete, we should have all the objects, so we run through this
6385 * list and fix up all the chains.
6388 switch (in->variantType) {
6389 case YAFFS_OBJECT_TYPE_UNKNOWN:
6390 /* Todo got a problem */
6392 case YAFFS_OBJECT_TYPE_FILE:
6393 if (dev->param.useHeaderFileSize)
6395 in->variant.fileVariant.
6400 case YAFFS_OBJECT_TYPE_HARDLINK:
6401 in->variant.hardLinkVariant.
6402 equivalentObjectId =
6403 oh->equivalentObjectId;
6404 in->hardLinks.next =
6405 (struct ylist_head *)
6409 case YAFFS_OBJECT_TYPE_DIRECTORY:
6412 case YAFFS_OBJECT_TYPE_SPECIAL:
6415 case YAFFS_OBJECT_TYPE_SYMLINK:
6416 in->variant.symLinkVariant.alias =
6417 yaffs_CloneString(oh->alias);
6418 if (!in->variant.symLinkVariant.alias)
6427 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6428 /* If we got this far while scanning, then the block is fully allocated.*/
6429 state = YAFFS_BLOCK_STATE_FULL;
6432 if (state == YAFFS_BLOCK_STATE_ALLOCATING) {
6433 /* If the block was partially allocated then treat it as fully allocated.*/
6434 state = YAFFS_BLOCK_STATE_FULL;
6435 dev->allocationBlock = -1;
6438 bi->blockState = state;
6440 /* Now let's see if it was dirty */
6441 if (bi->pagesInUse == 0 &&
6442 !bi->hasShrinkHeader &&
6443 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6444 yaffs_BlockBecameDirty(dev, blk);
6450 /* Ok, we've done all the scanning.
6451 * Fix up the hard link chains.
6452 * We should now have scanned all the objects, now it's time to add these
6456 yaffs_HardlinkFixup(dev, hardList);
6458 /* Fix up any shadowed objects */
6460 struct yaffs_ShadowFixerStruct *fixer;
6463 while (shadowFixerList) {
6464 fixer = shadowFixerList;
6465 shadowFixerList = fixer->next;
6466 /* Complete the rename transaction by deleting the shadowed object
6467 * then setting the object header to unshadowed.
6469 obj = yaffs_FindObjectByNumber(dev, fixer->shadowedId);
6471 yaffs_DeleteObject(obj);
6473 obj = yaffs_FindObjectByNumber(dev, fixer->objectId);
6476 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6482 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6487 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
6493 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
6496 yaffs_ObjectHeader *oh;
6498 yaffs_ExtendedTags tags;
6500 int alloc_failed = 0;
6508 T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
6510 in->lazyLoaded ? "not yet" : "already"));
6513 if (in->lazyLoaded && in->hdrChunk > 0) {
6515 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6517 result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
6518 oh = (yaffs_ObjectHeader *) chunkData;
6520 in->yst_mode = oh->yst_mode;
6521 #ifdef CONFIG_YAFFS_WINCE
6522 in->win_atime[0] = oh->win_atime[0];
6523 in->win_ctime[0] = oh->win_ctime[0];
6524 in->win_mtime[0] = oh->win_mtime[0];
6525 in->win_atime[1] = oh->win_atime[1];
6526 in->win_ctime[1] = oh->win_ctime[1];
6527 in->win_mtime[1] = oh->win_mtime[1];
6529 in->yst_uid = oh->yst_uid;
6530 in->yst_gid = oh->yst_gid;
6531 in->yst_atime = oh->yst_atime;
6532 in->yst_mtime = oh->yst_mtime;
6533 in->yst_ctime = oh->yst_ctime;
6534 in->yst_rdev = oh->yst_rdev;
6537 yaffs_SetObjectName(in, oh->name);
6539 if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6540 in->variant.symLinkVariant.alias =
6541 yaffs_CloneString(oh->alias);
6542 if (!in->variant.symLinkVariant.alias)
6543 alloc_failed = 1; /* Not returned to caller */
6546 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6550 static int yaffs_ScanBackwards(yaffs_Device *dev)
6552 yaffs_ExtendedTags tags;
6557 int nBlocksToScan = 0;
6563 yaffs_BlockState state;
6564 yaffs_Object *hardList = NULL;
6565 yaffs_BlockInfo *bi;
6566 __u32 sequenceNumber;
6567 yaffs_ObjectHeader *oh;
6569 yaffs_Object *parent;
6570 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6576 int foundChunksInBlock;
6577 int equivalentObjectId;
6578 int alloc_failed = 0;
6581 yaffs_BlockIndex *blockIndex = NULL;
6582 int altBlockIndex = 0;
6584 if (!dev->param.isYaffs2) {
6586 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6592 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
6593 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6596 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6598 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6601 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6607 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6611 dev->blocksInCheckpoint = 0;
6613 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6615 /* Scan all the blocks to determine their state */
6616 bi = dev->blockInfo;
6617 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6618 yaffs_ClearChunkBits(dev, blk);
6620 bi->softDeletions = 0;
6622 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6624 bi->blockState = state;
6625 bi->sequenceNumber = sequenceNumber;
6627 if (bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6628 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6629 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6630 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6632 T(YAFFS_TRACE_SCAN_DEBUG,
6633 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6634 state, sequenceNumber));
6637 if (state == YAFFS_BLOCK_STATE_CHECKPOINT) {
6638 dev->blocksInCheckpoint++;
6640 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6641 T(YAFFS_TRACE_BAD_BLOCKS,
6642 (TSTR("block %d is bad" TENDSTR), blk));
6643 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6644 T(YAFFS_TRACE_SCAN_DEBUG,
6645 (TSTR("Block empty " TENDSTR)));
6646 dev->nErasedBlocks++;
6647 dev->nFreeChunks += dev->param.nChunksPerBlock;
6648 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6650 /* Determine the highest sequence number */
6651 if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6652 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6654 blockIndex[nBlocksToScan].seq = sequenceNumber;
6655 blockIndex[nBlocksToScan].block = blk;
6659 if (sequenceNumber >= dev->sequenceNumber)
6660 dev->sequenceNumber = sequenceNumber;
6662 /* TODO: Nasty sequence number! */
6665 ("Block scanning block %d has bad sequence number %d"
6666 TENDSTR), blk, sequenceNumber));
6674 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6680 /* Sort the blocks */
6681 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6683 /* Use qsort now. */
6684 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6688 /* Dungy old bubble sort... */
6690 yaffs_BlockIndex temp;
6694 for (i = 0; i < nBlocksToScan; i++)
6695 for (j = i + 1; j < nBlocksToScan; j++)
6696 if (blockIndex[i].seq > blockIndex[j].seq) {
6697 temp = blockIndex[j];
6698 blockIndex[j] = blockIndex[i];
6699 blockIndex[i] = temp;
6706 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6708 /* Now scan the blocks looking at the data. */
6710 endIterator = nBlocksToScan - 1;
6711 T(YAFFS_TRACE_SCAN_DEBUG,
6712 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6714 /* For each block.... backwards */
6715 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6717 /* Cooperative multitasking! This loop can run for so
6718 long that watchdog timers expire. */
6721 /* get the block to scan in the correct order */
6722 blk = blockIndex[blockIterator].block;
6724 bi = yaffs_GetBlockInfo(dev, blk);
6727 state = bi->blockState;
6731 /* For each chunk in each block that needs scanning.... */
6732 foundChunksInBlock = 0;
6733 for (c = dev->param.nChunksPerBlock - 1;
6734 !alloc_failed && c >= 0 &&
6735 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6736 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6737 /* Scan backwards...
6738 * Read the tags and decide what to do
6741 chunk = blk * dev->param.nChunksPerBlock + c;
6743 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6746 /* Let's have a good look at this chunk... */
6748 if (!tags.chunkUsed) {
6749 /* An unassigned chunk in the block.
6750 * If there are used chunks after this one, then
6751 * it is a chunk that was skipped due to failing the erased
6752 * check. Just skip it so that it can be deleted.
6753 * But, more typically, We get here when this is an unallocated
6754 * chunk and his means that either the block is empty or
6755 * this is the one being allocated from
6758 if (foundChunksInBlock) {
6759 /* This is a chunk that was skipped due to failing the erased check */
6760 } else if (c == 0) {
6761 /* We're looking at the first chunk in the block so the block is unused */
6762 state = YAFFS_BLOCK_STATE_EMPTY;
6763 dev->nErasedBlocks++;
6765 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6766 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6767 if (dev->sequenceNumber == bi->sequenceNumber) {
6768 /* this is the block being allocated from */
6772 (" Allocating from %d %d"
6775 state = YAFFS_BLOCK_STATE_ALLOCATING;
6776 dev->allocationBlock = blk;
6777 dev->allocationPage = c;
6778 dev->allocationBlockFinder = blk;
6780 /* This is a partially written block that is not
6781 * the current allocation block.
6785 (TSTR("Partially written block %d detected" TENDSTR),
6793 } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED) {
6795 (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
6800 } else if (tags.chunkId > 0) {
6801 /* chunkId > 0 so it is a data chunk... */
6802 unsigned int endpos;
6804 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6806 foundChunksInBlock = 1;
6809 yaffs_SetChunkBit(dev, blk, c);
6812 in = yaffs_FindOrCreateObjectByNumber(dev,
6815 YAFFS_OBJECT_TYPE_FILE);
6822 in->variantType == YAFFS_OBJECT_TYPE_FILE
6823 && chunkBase < in->variant.fileVariant.shrinkSize) {
6824 /* This has not been invalidated by a resize */
6825 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, -1)) {
6829 /* File size is calculated by looking at the data chunks if we have not
6830 * seen an object header yet. Stop this practice once we find an object header.
6832 endpos = chunkBase + tags.byteCount;
6834 if (!in->valid && /* have not got an object header yet */
6835 in->variant.fileVariant.scannedFileSize < endpos) {
6836 in->variant.fileVariant.scannedFileSize = endpos;
6837 in->variant.fileVariant.fileSize = endpos;
6841 /* This chunk has been invalidated by a resize, or a past file deletion
6842 * so delete the chunk*/
6843 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6847 /* chunkId == 0, so it is an ObjectHeader.
6848 * Thus, we read in the object header and make the object
6850 foundChunksInBlock = 1;
6852 yaffs_SetChunkBit(dev, blk, c);
6858 if (tags.extraHeaderInfoAvailable) {
6859 in = yaffs_FindOrCreateObjectByNumber(dev,
6861 tags.extraObjectType);
6867 (!in->valid && dev->param.disableLazyLoad) ||
6868 tags.extraShadows ||
6870 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6871 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))) {
6873 /* If we don't have valid info then we need to read the chunk
6874 * TODO In future we can probably defer reading the chunk and
6875 * living with invalid data until needed.
6878 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6883 oh = (yaffs_ObjectHeader *) chunkData;
6885 if (dev->param.inbandTags) {
6886 /* Fix up the header if they got corrupted by inband tags */
6887 oh->shadowsObject = oh->inbandShadowsObject;
6888 oh->isShrink = oh->inbandIsShrink;
6892 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6900 /* TODO Hoosterman we have a problem! */
6901 T(YAFFS_TRACE_ERROR,
6903 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6904 TENDSTR), tags.objectId, chunk));
6909 /* We have already filled this one.
6910 * We have a duplicate that will be discarded, but
6911 * we first have to suck out resize info if it is a file.
6914 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6916 oh->type == YAFFS_OBJECT_TYPE_FILE) ||
6917 (tags.extraHeaderInfoAvailable &&
6918 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))) {
6920 (oh) ? oh->fileSize : tags.
6922 __u32 parentObjectId =
6924 parentObjectId : tags.
6925 extraParentObjectId;
6929 (oh) ? oh->isShrink : tags.
6930 extraIsShrinkHeader;
6932 /* If it is deleted (unlinked at start also means deleted)
6933 * we treat the file size as being zeroed at this point.
6935 if (parentObjectId ==
6936 YAFFS_OBJECTID_DELETED
6937 || parentObjectId ==
6938 YAFFS_OBJECTID_UNLINKED) {
6943 if (isShrink && in->variant.fileVariant.shrinkSize > thisSize)
6944 in->variant.fileVariant.shrinkSize = thisSize;
6947 bi->hasShrinkHeader = 1;
6950 /* Use existing - destroy this one. */
6951 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6955 if (!in->valid && in->variantType !=
6956 (oh ? oh->type : tags.extraObjectType))
6957 T(YAFFS_TRACE_ERROR, (
6958 TSTR("yaffs tragedy: Bad object type, "
6959 TCONT("%d != %d, for object %d at chunk ")
6960 TCONT("%d during scan")
6962 oh->type : tags.extraObjectType,
6963 in->variantType, tags.objectId,
6967 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6969 YAFFS_OBJECTID_LOSTNFOUND)) {
6970 /* We only load some info, don't fiddle with directory structure */
6974 in->variantType = oh->type;
6976 in->yst_mode = oh->yst_mode;
6977 #ifdef CONFIG_YAFFS_WINCE
6978 in->win_atime[0] = oh->win_atime[0];
6979 in->win_ctime[0] = oh->win_ctime[0];
6980 in->win_mtime[0] = oh->win_mtime[0];
6981 in->win_atime[1] = oh->win_atime[1];
6982 in->win_ctime[1] = oh->win_ctime[1];
6983 in->win_mtime[1] = oh->win_mtime[1];
6985 in->yst_uid = oh->yst_uid;
6986 in->yst_gid = oh->yst_gid;
6987 in->yst_atime = oh->yst_atime;
6988 in->yst_mtime = oh->yst_mtime;
6989 in->yst_ctime = oh->yst_ctime;
6990 in->yst_rdev = oh->yst_rdev;
6994 in->variantType = tags.extraObjectType;
6998 in->hdrChunk = chunk;
7000 } else if (!in->valid) {
7001 /* we need to load this info */
7004 in->hdrChunk = chunk;
7007 in->variantType = oh->type;
7009 in->yst_mode = oh->yst_mode;
7010 #ifdef CONFIG_YAFFS_WINCE
7011 in->win_atime[0] = oh->win_atime[0];
7012 in->win_ctime[0] = oh->win_ctime[0];
7013 in->win_mtime[0] = oh->win_mtime[0];
7014 in->win_atime[1] = oh->win_atime[1];
7015 in->win_ctime[1] = oh->win_ctime[1];
7016 in->win_mtime[1] = oh->win_mtime[1];
7018 in->yst_uid = oh->yst_uid;
7019 in->yst_gid = oh->yst_gid;
7020 in->yst_atime = oh->yst_atime;
7021 in->yst_mtime = oh->yst_mtime;
7022 in->yst_ctime = oh->yst_ctime;
7023 in->yst_rdev = oh->yst_rdev;
7026 if (oh->shadowsObject > 0)
7027 yaffs_HandleShadowedObject(dev,
7034 yaffs_SetObjectName(in, oh->name);
7036 yaffs_FindOrCreateObjectByNumber
7037 (dev, oh->parentObjectId,
7038 YAFFS_OBJECT_TYPE_DIRECTORY);
7040 fileSize = oh->fileSize;
7041 isShrink = oh->isShrink;
7042 equivalentObjectId = oh->equivalentObjectId;
7045 in->variantType = tags.extraObjectType;
7047 yaffs_FindOrCreateObjectByNumber
7048 (dev, tags.extraParentObjectId,
7049 YAFFS_OBJECT_TYPE_DIRECTORY);
7050 fileSize = tags.extraFileLength;
7051 isShrink = tags.extraIsShrinkHeader;
7052 equivalentObjectId = tags.extraEquivalentObjectId;
7061 /* directory stuff...
7065 if (parent && parent->variantType ==
7066 YAFFS_OBJECT_TYPE_UNKNOWN) {
7067 /* Set up as a directory */
7068 parent->variantType =
7069 YAFFS_OBJECT_TYPE_DIRECTORY;
7070 YINIT_LIST_HEAD(&parent->variant.
7073 } else if (!parent || parent->variantType !=
7074 YAFFS_OBJECT_TYPE_DIRECTORY) {
7075 /* Hoosterman, another problem....
7076 * We're trying to use a non-directory as a directory
7079 T(YAFFS_TRACE_ERROR,
7081 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
7083 parent = dev->lostNFoundDir;
7086 yaffs_AddObjectToDirectory(parent, in);
7088 itsUnlinked = (parent == dev->deletedDir) ||
7089 (parent == dev->unlinkedDir);
7092 /* Mark the block as having a shrinkHeader */
7093 bi->hasShrinkHeader = 1;
7096 /* Note re hardlinks.
7097 * Since we might scan a hardlink before its equivalent object is scanned
7098 * we put them all in a list.
7099 * After scanning is complete, we should have all the objects, so we run
7100 * through this list and fix up all the chains.
7103 switch (in->variantType) {
7104 case YAFFS_OBJECT_TYPE_UNKNOWN:
7105 /* Todo got a problem */
7107 case YAFFS_OBJECT_TYPE_FILE:
7109 if (in->variant.fileVariant.
7110 scannedFileSize < fileSize) {
7111 /* This covers the case where the file size is greater
7112 * than where the data is
7113 * This will happen if the file is resized to be larger
7114 * than its current data extents.
7116 in->variant.fileVariant.fileSize = fileSize;
7117 in->variant.fileVariant.scannedFileSize = fileSize;
7120 if (in->variant.fileVariant.shrinkSize > fileSize)
7121 in->variant.fileVariant.shrinkSize = fileSize;
7125 case YAFFS_OBJECT_TYPE_HARDLINK:
7127 in->variant.hardLinkVariant.equivalentObjectId =
7129 in->hardLinks.next =
7130 (struct ylist_head *) hardList;
7134 case YAFFS_OBJECT_TYPE_DIRECTORY:
7137 case YAFFS_OBJECT_TYPE_SPECIAL:
7140 case YAFFS_OBJECT_TYPE_SYMLINK:
7142 in->variant.symLinkVariant.alias =
7143 yaffs_CloneString(oh->alias);
7144 if (!in->variant.symLinkVariant.alias)
7154 } /* End of scanning for each chunk */
7156 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
7157 /* If we got this far while scanning, then the block is fully allocated. */
7158 state = YAFFS_BLOCK_STATE_FULL;
7162 bi->blockState = state;
7164 /* Now let's see if it was dirty */
7165 if (bi->pagesInUse == 0 &&
7166 !bi->hasShrinkHeader &&
7167 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
7168 yaffs_BlockBecameDirty(dev, blk);
7173 yaffs_SkipRestOfBlock(dev);
7176 YFREE_ALT(blockIndex);
7180 /* Ok, we've done all the scanning.
7181 * Fix up the hard link chains.
7182 * We should now have scanned all the objects, now it's time to add these
7185 yaffs_HardlinkFixup(dev, hardList);
7188 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
7193 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
7198 /*------------------------------ Directory Functions ----------------------------- */
7200 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
7202 struct ylist_head *lh;
7203 yaffs_Object *listObj;
7208 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
7213 if (yaffs_SkipVerification(obj->myDev))
7217 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
7222 if (obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7223 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
7227 /* Iterate through the objects in each hash entry */
7229 ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
7231 listObj = ylist_entry(lh, yaffs_Object, siblings);
7232 yaffs_VerifyObject(listObj);
7239 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR), count));
7244 static void yaffs_VerifyDirectory(yaffs_Object *directory)
7246 struct ylist_head *lh;
7247 yaffs_Object *listObj;
7254 if (yaffs_SkipFullVerification(directory->myDev))
7257 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7258 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR), directory->variantType));
7262 /* Iterate through the objects in each hash entry */
7264 ylist_for_each(lh, &directory->variant.directoryVariant.children) {
7266 listObj = ylist_entry(lh, yaffs_Object, siblings);
7267 if (listObj->parent != directory) {
7268 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR), listObj->parent));
7271 yaffs_VerifyObjectInDirectory(listObj);
7277 *yaffs_UpdateParent() handles fixing a directories mtime and ctime when a new
7278 * link (ie. name) is created or deleted in the directory.
7281 * create dir/a : update dir's mtime/ctime
7282 * rm dir/a: update dir's mtime/ctime
7283 * modify dir/a: don't update dir's mtimme/ctime
7285 * This can be handled immediately or defered. Defering helps reduce the number
7286 * of updates when many files in a directory are changed within a brief period.
7288 * If the directory updating is defered then yaffs_UpdateDirtyDirecories must be
7289 * called periodically.
7292 static void yaffs_UpdateParent(yaffs_Object *obj)
7300 obj->yst_mtime = obj->yst_ctime = Y_CURRENT_TIME;
7301 if(dev->param.deferDirectoryUpdate){
7302 struct ylist_head *link = &obj->variant.directoryVariant.dirty;
7304 if(ylist_empty(link)){
7305 ylist_add(link,&dev->dirtyDirectories);
7306 T(YAFFS_TRACE_BACKGROUND, (TSTR("Added object %d to dirty directories" TENDSTR),obj->objectId));
7310 yaffs_UpdateObjectHeader(obj,NULL,0,0,0);
7313 void yaffs_UpdateDirtyDirectories(yaffs_Device *dev)
7315 struct ylist_head *link;
7317 yaffs_DirectoryStructure *dS;
7318 yaffs_ObjectVariant *oV;
7320 T(YAFFS_TRACE_BACKGROUND, (TSTR("Update dirty directories" TENDSTR)));
7322 while(!ylist_empty(&dev->dirtyDirectories)){
7323 link = dev->dirtyDirectories.next;
7324 ylist_del_init(link);
7326 dS=ylist_entry(link,yaffs_DirectoryStructure,dirty);
7327 oV = ylist_entry(dS,yaffs_ObjectVariant,directoryVariant);
7328 obj = ylist_entry(oV,yaffs_Object,variant);
7330 T(YAFFS_TRACE_BACKGROUND, (TSTR("Update directory %d" TENDSTR), obj->objectId));
7333 yaffs_UpdateObjectHeader(obj,NULL,0,0,0);
7337 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
7339 yaffs_Device *dev = obj->myDev;
7340 yaffs_Object *parent;
7342 yaffs_VerifyObjectInDirectory(obj);
7343 parent = obj->parent;
7345 yaffs_VerifyDirectory(parent);
7347 if (dev && dev->param.removeObjectCallback)
7348 dev->param.removeObjectCallback(obj);
7351 ylist_del_init(&obj->siblings);
7354 yaffs_VerifyDirectory(parent);
7357 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
7361 T(YAFFS_TRACE_ALWAYS,
7363 ("tragedy: Trying to add an object to a null pointer directory"
7368 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7369 T(YAFFS_TRACE_ALWAYS,
7371 ("tragedy: Trying to add an object to a non-directory"
7376 if (obj->siblings.prev == NULL) {
7377 /* Not initialised */
7382 yaffs_VerifyDirectory(directory);
7384 yaffs_RemoveObjectFromDirectory(obj);
7388 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
7389 obj->parent = directory;
7391 if (directory == obj->myDev->unlinkedDir
7392 || directory == obj->myDev->deletedDir) {
7394 obj->myDev->nUnlinkedFiles++;
7395 obj->renameAllowed = 0;
7398 yaffs_VerifyDirectory(directory);
7399 yaffs_VerifyObjectInDirectory(obj);
7402 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
7407 struct ylist_head *i;
7408 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
7416 T(YAFFS_TRACE_ALWAYS,
7418 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7423 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7424 T(YAFFS_TRACE_ALWAYS,
7426 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7430 sum = yaffs_CalcNameSum(name);
7432 ylist_for_each(i, &directory->variant.directoryVariant.children) {
7434 l = ylist_entry(i, yaffs_Object, siblings);
7436 if (l->parent != directory)
7439 yaffs_CheckObjectDetailsLoaded(l);
7441 /* Special case for lost-n-found */
7442 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7443 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
7445 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
7446 /* LostnFound chunk called Objxxx
7449 yaffs_GetObjectName(l, buffer,
7450 YAFFS_MAX_NAME_LENGTH + 1);
7451 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
7462 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
7463 int (*fn) (yaffs_Object *))
7465 struct ylist_head *i;
7469 T(YAFFS_TRACE_ALWAYS,
7471 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7476 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7477 T(YAFFS_TRACE_ALWAYS,
7479 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7484 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
7486 l = ylist_entry(i, yaffs_Object, siblings);
7497 /* GetEquivalentObject dereferences any hard links to get to the
7501 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
7503 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
7504 /* We want the object id of the equivalent object, not this one */
7505 obj = obj->variant.hardLinkVariant.equivalentObject;
7506 yaffs_CheckObjectDetailsLoaded(obj);
7511 int yaffs_GetObjectName(yaffs_Object *obj, YCHAR *name, int buffSize)
7513 memset(name, 0, buffSize * sizeof(YCHAR));
7515 yaffs_CheckObjectDetailsLoaded(obj);
7517 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7518 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
7519 } else if (obj->hdrChunk <= 0) {
7521 YCHAR numString[20];
7522 YCHAR *x = &numString[19];
7523 unsigned v = obj->objectId;
7527 *x = '0' + (v % 10);
7530 /* make up a name */
7531 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
7532 yaffs_strcat(locName, x);
7533 yaffs_strncpy(name, locName, buffSize - 1);
7536 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
7537 else if (obj->shortName[0])
7538 yaffs_strncpy(name, obj->shortName,YAFFS_SHORT_NAME_LENGTH+1);
7542 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
7544 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
7546 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
7548 if (obj->hdrChunk > 0) {
7549 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
7550 obj->hdrChunk, buffer,
7553 yaffs_strncpy(name, oh->name, buffSize - 1);
7556 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
7559 return yaffs_strnlen(name,buffSize-1);
7562 int yaffs_GetObjectFileLength(yaffs_Object *obj)
7564 /* Dereference any hard linking */
7565 obj = yaffs_GetEquivalentObject(obj);
7567 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
7568 return obj->variant.fileVariant.fileSize;
7569 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
7570 if(!obj->variant.symLinkVariant.alias)
7572 return yaffs_strnlen(obj->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
7574 /* Only a directory should drop through to here */
7575 return obj->myDev->nDataBytesPerChunk;
7579 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
7582 struct ylist_head *i;
7585 count++; /* the object itself */
7587 ylist_for_each(i, &obj->hardLinks)
7588 count++; /* add the hard links; */
7593 int yaffs_GetObjectInode(yaffs_Object *obj)
7595 obj = yaffs_GetEquivalentObject(obj);
7597 return obj->objectId;
7600 unsigned yaffs_GetObjectType(yaffs_Object *obj)
7602 obj = yaffs_GetEquivalentObject(obj);
7604 switch (obj->variantType) {
7605 case YAFFS_OBJECT_TYPE_FILE:
7608 case YAFFS_OBJECT_TYPE_DIRECTORY:
7611 case YAFFS_OBJECT_TYPE_SYMLINK:
7614 case YAFFS_OBJECT_TYPE_HARDLINK:
7617 case YAFFS_OBJECT_TYPE_SPECIAL:
7618 if (S_ISFIFO(obj->yst_mode))
7620 if (S_ISCHR(obj->yst_mode))
7622 if (S_ISBLK(obj->yst_mode))
7624 if (S_ISSOCK(obj->yst_mode))
7632 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
7634 obj = yaffs_GetEquivalentObject(obj);
7635 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
7636 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7638 return yaffs_CloneString(_Y(""));
7641 #ifndef CONFIG_YAFFS_WINCE
7643 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
7645 unsigned int valid = attr->ia_valid;
7647 if (valid & ATTR_MODE)
7648 obj->yst_mode = attr->ia_mode;
7649 if (valid & ATTR_UID)
7650 obj->yst_uid = attr->ia_uid;
7651 if (valid & ATTR_GID)
7652 obj->yst_gid = attr->ia_gid;
7654 if (valid & ATTR_ATIME)
7655 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7656 if (valid & ATTR_CTIME)
7657 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7658 if (valid & ATTR_MTIME)
7659 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7661 if (valid & ATTR_SIZE)
7662 yaffs_ResizeFile(obj, attr->ia_size);
7664 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7669 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
7671 unsigned int valid = 0;
7673 attr->ia_mode = obj->yst_mode;
7675 attr->ia_uid = obj->yst_uid;
7677 attr->ia_gid = obj->yst_gid;
7680 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7681 valid |= ATTR_ATIME;
7682 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7683 valid |= ATTR_CTIME;
7684 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7685 valid |= ATTR_MTIME;
7687 attr->ia_size = yaffs_GetFileSize(obj);
7690 attr->ia_valid = valid;
7698 int yaffs_DumpObject(yaffs_Object *obj)
7702 yaffs_GetObjectName(obj, name, YAFFS_MAX_NAME_LENGTH + 1);
7704 T(YAFFS_TRACE_ALWAYS,
7706 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7707 " chunk %d type %d size %d\n"
7708 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7709 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7710 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7716 /*---------------------------- Initialisation code -------------------------------------- */
7718 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
7721 /* Common functions, gotta have */
7722 if (!dev->param.eraseBlockInNAND || !dev->param.initialiseNAND)
7725 #ifdef CONFIG_YAFFS_YAFFS2
7727 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7728 if (dev->param.writeChunkWithTagsToNAND &&
7729 dev->param.readChunkWithTagsFromNAND &&
7730 !dev->param.writeChunkToNAND &&
7731 !dev->param.readChunkFromNAND &&
7732 dev->param.markNANDBlockBad &&
7733 dev->param.queryNANDBlock)
7737 /* Can use the "spare" style interface for yaffs1 */
7738 if (!dev->param.isYaffs2 &&
7739 !dev->param.writeChunkWithTagsToNAND &&
7740 !dev->param.readChunkWithTagsFromNAND &&
7741 dev->param.writeChunkToNAND &&
7742 dev->param.readChunkFromNAND &&
7743 !dev->param.markNANDBlockBad &&
7744 !dev->param.queryNANDBlock)
7751 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7753 /* Initialise the unlinked, deleted, root and lost and found directories */
7755 dev->lostNFoundDir = dev->rootDir = NULL;
7756 dev->unlinkedDir = dev->deletedDir = NULL;
7759 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7762 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7765 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7766 YAFFS_ROOT_MODE | S_IFDIR);
7767 dev->lostNFoundDir =
7768 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7769 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7771 if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
7772 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7779 int yaffs_GutsInitialise(yaffs_Device *dev)
7781 int init_failed = 0;
7785 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7787 /* Check stuff that must be set */
7790 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7794 dev->internalStartBlock = dev->param.startBlock;
7795 dev->internalEndBlock = dev->param.endBlock;
7796 dev->blockOffset = 0;
7797 dev->chunkOffset = 0;
7798 dev->nFreeChunks = 0;
7802 if (dev->param.startBlock == 0) {
7803 dev->internalStartBlock = dev->param.startBlock + 1;
7804 dev->internalEndBlock = dev->param.endBlock + 1;
7805 dev->blockOffset = 1;
7806 dev->chunkOffset = dev->param.nChunksPerBlock;
7809 /* Check geometry parameters. */
7811 if ((!dev->param.inbandTags && dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 1024) ||
7812 (!dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 512) ||
7813 (dev->param.inbandTags && !dev->param.isYaffs2) ||
7814 dev->param.nChunksPerBlock < 2 ||
7815 dev->param.nReservedBlocks < 2 ||
7816 dev->internalStartBlock <= 0 ||
7817 dev->internalEndBlock <= 0 ||
7818 dev->internalEndBlock <= (dev->internalStartBlock + dev->param.nReservedBlocks + 2)) { /* otherwise it is too small */
7819 T(YAFFS_TRACE_ALWAYS,
7821 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7822 TENDSTR), dev->param.totalBytesPerChunk, dev->param.isYaffs2 ? "2" : "", dev->param.inbandTags));
7826 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7827 T(YAFFS_TRACE_ALWAYS,
7828 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7832 /* Sort out space for inband tags, if required */
7833 if (dev->param.inbandTags)
7834 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7836 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk;
7838 /* Got the right mix of functions? */
7839 if (!yaffs_CheckDevFunctions(dev)) {
7840 /* Function missing */
7841 T(YAFFS_TRACE_ALWAYS,
7843 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7848 /* This is really a compilation check. */
7849 if (!yaffs_CheckStructures()) {
7850 T(YAFFS_TRACE_ALWAYS,
7851 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7855 if (dev->isMounted) {
7856 T(YAFFS_TRACE_ALWAYS,
7857 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7861 /* Finished with most checks. One or two more checks happen later on too. */
7865 /* OK now calculate a few things for the device */
7868 * Calculate all the chunk size manipulation numbers:
7870 x = dev->nDataBytesPerChunk;
7871 /* We always use dev->chunkShift and dev->chunkDiv */
7872 dev->chunkShift = Shifts(x);
7873 x >>= dev->chunkShift;
7875 /* We only use chunk mask if chunkDiv is 1 */
7876 dev->chunkMask = (1<<dev->chunkShift) - 1;
7879 * Calculate chunkGroupBits.
7880 * We need to find the next power of 2 > than internalEndBlock
7883 x = dev->param.nChunksPerBlock * (dev->internalEndBlock + 1);
7887 /* Set up tnode width if wide tnodes are enabled. */
7888 if (!dev->param.wideTnodesDisabled) {
7889 /* bits must be even so that we end up with 32-bit words */
7893 dev->tnodeWidth = 16;
7895 dev->tnodeWidth = bits;
7897 dev->tnodeWidth = 16;
7899 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7901 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7902 * so if the bitwidth of the
7903 * chunk range we're using is greater than 16 we need
7904 * to figure out chunk shift and chunkGroupSize
7907 if (bits <= dev->tnodeWidth)
7908 dev->chunkGroupBits = 0;
7910 dev->chunkGroupBits = bits - dev->tnodeWidth;
7913 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7915 if (dev->param.nChunksPerBlock < dev->chunkGroupSize) {
7916 /* We have a problem because the soft delete won't work if
7917 * the chunk group size > chunks per block.
7918 * This can be remedied by using larger "virtual blocks".
7920 T(YAFFS_TRACE_ALWAYS,
7921 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7926 /* OK, we've finished verifying the device, lets continue with initialisation */
7928 /* More device initialisation */
7930 dev->passiveGCs = 0;
7931 dev->oldestDirtyGCs = 0;
7932 dev->backgroundGCs = 0;
7933 dev->gcBlockFinder = 0;
7934 dev->bufferedBlock = -1;
7935 dev->doingBufferedBlockRewrite = 0;
7936 dev->nDeletedFiles = 0;
7937 dev->nBackgroundDeletions = 0;
7938 dev->nUnlinkedFiles = 0;
7940 dev->eccUnfixed = 0;
7941 dev->tagsEccFixed = 0;
7942 dev->tagsEccUnfixed = 0;
7943 dev->nErasureFailures = 0;
7944 dev->nErasedBlocks = 0;
7946 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7947 YINIT_LIST_HEAD(&dev->dirtyDirectories);
7948 dev->oldestDirtySequence = 0;
7949 dev->oldestDirtyBlock = 0;
7951 /* Initialise temporary buffers and caches. */
7952 if (!yaffs_InitialiseTempBuffers(dev))
7955 dev->srCache = NULL;
7956 dev->gcCleanupList = NULL;
7960 dev->param.nShortOpCaches > 0) {
7963 int srCacheBytes = dev->param.nShortOpCaches * sizeof(yaffs_ChunkCache);
7965 if (dev->param.nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
7966 dev->param.nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7968 dev->srCache = YMALLOC(srCacheBytes);
7970 buf = (__u8 *) dev->srCache;
7973 memset(dev->srCache, 0, srCacheBytes);
7975 for (i = 0; i < dev->param.nShortOpCaches && buf; i++) {
7976 dev->srCache[i].object = NULL;
7977 dev->srCache[i].lastUse = 0;
7978 dev->srCache[i].dirty = 0;
7979 dev->srCache[i].data = buf = YMALLOC_DMA(dev->param.totalBytesPerChunk);
7990 dev->gcCleanupList = YMALLOC(dev->param.nChunksPerBlock * sizeof(__u32));
7991 if (!dev->gcCleanupList)
7995 if (dev->param.isYaffs2)
7996 dev->param.useHeaderFileSize = 1;
7998 if (!init_failed && !yaffs_InitialiseBlocks(dev))
8001 yaffs_InitialiseTnodes(dev);
8002 yaffs_InitialiseObjects(dev);
8004 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
8009 /* Now scan the flash. */
8010 if (dev->param.isYaffs2) {
8011 if (yaffs_CheckpointRestore(dev)) {
8012 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
8013 T(YAFFS_TRACE_ALWAYS,
8014 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
8017 /* Clean up the mess caused by an aborted checkpoint load
8018 * and scan backwards.
8020 yaffs_DeinitialiseBlocks(dev);
8021 yaffs_DeinitialiseTnodes(dev);
8022 yaffs_DeinitialiseObjects(dev);
8025 dev->nErasedBlocks = 0;
8026 dev->nFreeChunks = 0;
8027 dev->allocationBlock = -1;
8028 dev->allocationPage = -1;
8029 dev->nDeletedFiles = 0;
8030 dev->nUnlinkedFiles = 0;
8031 dev->nBackgroundDeletions = 0;
8033 if (!init_failed && !yaffs_InitialiseBlocks(dev))
8036 yaffs_InitialiseTnodes(dev);
8037 yaffs_InitialiseObjects(dev);
8039 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
8042 if (!init_failed && !yaffs_ScanBackwards(dev))
8045 } else if (!yaffs_Scan(dev))
8048 yaffs_StripDeletedObjects(dev);
8049 yaffs_FixHangingObjects(dev);
8050 if(dev->param.emptyLostAndFound)
8051 yaffs_EmptyLostAndFound(dev);
8055 /* Clean up the mess */
8056 T(YAFFS_TRACE_TRACING,
8057 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
8059 yaffs_Deinitialise(dev);
8063 /* Zero out stats */
8064 dev->nPageReads = 0;
8065 dev->nPageWrites = 0;
8066 dev->nBlockErasures = 0;
8068 dev->nRetriedWrites = 0;
8070 dev->nRetiredBlocks = 0;
8072 yaffs_VerifyFreeChunks(dev);
8073 yaffs_VerifyBlocks(dev);
8075 /* Clean up any aborted checkpoint data */
8076 if(!dev->isCheckpointed && dev->blocksInCheckpoint > 0)
8077 yaffs_InvalidateCheckpoint(dev);
8079 T(YAFFS_TRACE_TRACING,
8080 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
8085 void yaffs_Deinitialise(yaffs_Device *dev)
8087 if (dev->isMounted) {
8090 yaffs_DeinitialiseBlocks(dev);
8091 yaffs_DeinitialiseTnodes(dev);
8092 yaffs_DeinitialiseObjects(dev);
8093 if (dev->param.nShortOpCaches > 0 &&
8096 for (i = 0; i < dev->param.nShortOpCaches; i++) {
8097 if (dev->srCache[i].data)
8098 YFREE(dev->srCache[i].data);
8099 dev->srCache[i].data = NULL;
8102 YFREE(dev->srCache);
8103 dev->srCache = NULL;
8106 YFREE(dev->gcCleanupList);
8108 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
8109 YFREE(dev->tempBuffer[i].buffer);
8113 if (dev->param.deinitialiseNAND)
8114 dev->param.deinitialiseNAND(dev);
8118 static int yaffs_CountFreeChunks(yaffs_Device *dev)
8123 yaffs_BlockInfo *blk;
8125 blk = dev->blockInfo;
8126 for (b = dev->internalStartBlock; b <= dev->internalEndBlock; b++) {
8127 switch (blk->blockState) {
8128 case YAFFS_BLOCK_STATE_EMPTY:
8129 case YAFFS_BLOCK_STATE_ALLOCATING:
8130 case YAFFS_BLOCK_STATE_COLLECTING:
8131 case YAFFS_BLOCK_STATE_FULL:
8133 (dev->param.nChunksPerBlock - blk->pagesInUse +
8134 blk->softDeletions);
8145 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
8147 /* This is what we report to the outside world */
8150 int nDirtyCacheChunks;
8151 int blocksForCheckpoint;
8155 nFree = dev->nFreeChunks;
8157 nFree = yaffs_CountFreeChunks(dev);
8160 nFree += dev->nDeletedFiles;
8162 /* Now count the number of dirty chunks in the cache and subtract those */
8164 for (nDirtyCacheChunks = 0, i = 0; i < dev->param.nShortOpCaches; i++) {
8165 if (dev->srCache[i].dirty)
8166 nDirtyCacheChunks++;
8169 nFree -= nDirtyCacheChunks;
8171 nFree -= ((dev->param.nReservedBlocks + 1) * dev->param.nChunksPerBlock);
8173 /* Now we figure out how much to reserve for the checkpoint and report that... */
8174 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
8175 if (blocksForCheckpoint < 0)
8176 blocksForCheckpoint = 0;
8178 nFree -= (blocksForCheckpoint * dev->param.nChunksPerBlock);
8187 static int yaffs_freeVerificationFailures;
8189 static void yaffs_VerifyFreeChunks(yaffs_Device *dev)
8194 if (yaffs_SkipVerification(dev))
8197 counted = yaffs_CountFreeChunks(dev);
8199 difference = dev->nFreeChunks - counted;
8202 T(YAFFS_TRACE_ALWAYS,
8203 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
8204 dev->nFreeChunks, counted, difference));
8205 yaffs_freeVerificationFailures++;
8209 /*---------------------------------------- YAFFS test code ----------------------*/
8211 #define yaffs_CheckStruct(structure, syze, name) \
8213 if (sizeof(structure) != syze) { \
8214 T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
8215 name, syze, (int) sizeof(structure))); \
8216 return YAFFS_FAIL; \
8220 static int yaffs_CheckStructures(void)
8222 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
8223 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
8224 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
8225 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
8226 /* yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode"); */
8228 #ifndef CONFIG_YAFFS_WINCE
8229 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");