2 * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
4 * Copyright (C) 2002-2007 Aleph One Ltd.
5 * for Toby Churchill Ltd and Brightstar Engineering
7 * Created by Charles Manning <charles@aleph1.co.uk>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2 as
11 * published by the Free Software Foundation.
14 const char *yaffs_guts_c_version =
15 "$Id: yaffs_guts.c,v 1.108 2010-02-18 01:18:04 charles Exp $";
18 #include "yaffs_trace.h"
20 #include "yaffsinterface.h"
21 #include "yaffs_guts.h"
22 #include "yaffs_tagsvalidity.h"
23 #include "yaffs_getblockinfo.h"
25 #include "yaffs_tagscompat.h"
26 #ifndef CONFIG_YAFFS_USE_OWN_SORT
27 #include "yaffs_qsort.h"
29 #include "yaffs_nand.h"
31 #include "yaffs_checkptrw.h"
33 #include "yaffs_nand.h"
34 #include "yaffs_packedtags2.h"
37 #define YAFFS_PASSIVE_GC_CHUNKS 2
39 #include "yaffs_ecc.h"
42 /* Robustification (if it ever comes about...) */
43 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND);
44 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
46 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
48 const yaffs_ExtendedTags *tags);
49 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
50 const yaffs_ExtendedTags *tags);
52 /* Other local prototypes */
53 static void yaffs_UpdateParent(yaffs_Object *obj);
54 static int yaffs_UnlinkObject(yaffs_Object *obj);
55 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
57 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
59 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev,
61 yaffs_ExtendedTags *tags,
63 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
64 int chunkInNAND, int inScan);
66 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
67 yaffs_ObjectType type);
68 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
70 static int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name,
71 int force, int isShrink, int shadows);
72 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
73 static int yaffs_CheckStructures(void);
74 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
75 int chunkOffset, int *limit);
76 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
78 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev, int blockNo);
81 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
84 static int yaffs_UnlinkWorker(yaffs_Object *obj);
86 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
89 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
90 yaffs_BlockInfo **blockUsedPtr);
92 static void yaffs_VerifyFreeChunks(yaffs_Device *dev);
94 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
96 static void yaffs_VerifyDirectory(yaffs_Object *directory);
98 static int yaffs_CheckFileSanity(yaffs_Object *in);
100 #define yaffs_CheckFileSanity(in)
103 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
104 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
106 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
108 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
109 yaffs_ExtendedTags *tags);
111 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
113 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
114 yaffs_FileStructure *fStruct,
117 static void yaffs_SkipRestOfBlock(yaffs_Device *dev);
118 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
121 yaffs_ExtendedTags *tags);
123 /* Function to calculate chunk and offset */
125 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut,
131 chunk = (__u32)(addr >> dev->chunkShift);
133 if (dev->chunkDiv == 1) {
134 /* easy power of 2 case */
135 offset = (__u32)(addr & dev->chunkMask);
137 /* Non power-of-2 case */
141 chunk /= dev->chunkDiv;
143 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
144 offset = (__u32)(addr - chunkBase);
151 /* Function to return the number of shifts for a power of 2 greater than or
152 * equal to the given number
153 * Note we don't try to cater for all possible numbers and this does not have to
154 * be hellishly efficient.
157 static __u32 ShiftsGE(__u32 x)
162 nShifts = extraBits = 0;
177 /* Function to return the number of shifts to get a 1 in bit 0
180 static __u32 Shifts(__u32 x)
200 * Temporary buffer manipulations.
203 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
206 __u8 *buf = (__u8 *)1;
208 memset(dev->tempBuffer, 0, sizeof(dev->tempBuffer));
210 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
211 dev->tempBuffer[i].line = 0; /* not in use */
212 dev->tempBuffer[i].buffer = buf =
213 YMALLOC_DMA(dev->param.totalBytesPerChunk);
216 return buf ? YAFFS_OK : YAFFS_FAIL;
219 __u8 *yaffs_GetTempBuffer(yaffs_Device *dev, int lineNo)
224 if (dev->tempInUse > dev->maxTemp)
225 dev->maxTemp = dev->tempInUse;
227 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
228 if (dev->tempBuffer[i].line == 0) {
229 dev->tempBuffer[i].line = lineNo;
230 if ((i + 1) > dev->maxTemp) {
231 dev->maxTemp = i + 1;
232 for (j = 0; j <= i; j++)
233 dev->tempBuffer[j].maxLine =
234 dev->tempBuffer[j].line;
237 return dev->tempBuffer[i].buffer;
241 T(YAFFS_TRACE_BUFFERS,
242 (TSTR("Out of temp buffers at line %d, other held by lines:"),
244 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
245 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
247 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
250 * If we got here then we have to allocate an unmanaged one
254 dev->unmanagedTempAllocations++;
255 return YMALLOC(dev->nDataBytesPerChunk);
259 void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer,
266 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
267 if (dev->tempBuffer[i].buffer == buffer) {
268 dev->tempBuffer[i].line = 0;
274 /* assume it is an unmanaged one. */
275 T(YAFFS_TRACE_BUFFERS,
276 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
279 dev->unmanagedTempDeallocations++;
285 * Determine if we have a managed buffer.
287 int yaffs_IsManagedTempBuffer(yaffs_Device *dev, const __u8 *buffer)
291 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
292 if (dev->tempBuffer[i].buffer == buffer)
296 for (i = 0; i < dev->param.nShortOpCaches; i++) {
297 if (dev->srCache[i].data == buffer)
301 if (buffer == dev->checkpointBuffer)
304 T(YAFFS_TRACE_ALWAYS,
305 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
312 * Chunk bitmap manipulations
315 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
317 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
319 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
323 return dev->chunkBits +
324 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
327 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
329 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
330 chunk < 0 || chunk >= dev->param.nChunksPerBlock) {
332 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),
338 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device *dev, int blk)
340 __u8 *blkBits = yaffs_BlockBits(dev, blk);
342 memset(blkBits, 0, dev->chunkBitmapStride);
345 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device *dev, int blk, int chunk)
347 __u8 *blkBits = yaffs_BlockBits(dev, blk);
349 yaffs_VerifyChunkBitId(dev, blk, chunk);
351 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
354 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device *dev, int blk, int chunk)
356 __u8 *blkBits = yaffs_BlockBits(dev, blk);
358 yaffs_VerifyChunkBitId(dev, blk, chunk);
360 blkBits[chunk / 8] |= (1 << (chunk & 7));
363 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device *dev, int blk, int chunk)
365 __u8 *blkBits = yaffs_BlockBits(dev, blk);
366 yaffs_VerifyChunkBitId(dev, blk, chunk);
368 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
371 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device *dev, int blk)
373 __u8 *blkBits = yaffs_BlockBits(dev, blk);
375 for (i = 0; i < dev->chunkBitmapStride; i++) {
383 static int yaffs_CountChunkBits(yaffs_Device *dev, int blk)
385 __u8 *blkBits = yaffs_BlockBits(dev, blk);
388 for (i = 0; i < dev->chunkBitmapStride; i++) {
405 static int yaffs_SkipVerification(yaffs_Device *dev)
407 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
410 static int yaffs_SkipFullVerification(yaffs_Device *dev)
412 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
415 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
417 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
420 static const char *blockStateName[] = {
433 static void yaffs_VerifyBlock(yaffs_Device *dev, yaffs_BlockInfo *bi, int n)
438 if (yaffs_SkipVerification(dev))
441 /* Report illegal runtime states */
442 if (bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
443 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has undefined state %d"TENDSTR), n, bi->blockState));
445 switch (bi->blockState) {
446 case YAFFS_BLOCK_STATE_UNKNOWN:
447 case YAFFS_BLOCK_STATE_SCANNING:
448 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
449 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has bad run-state %s"TENDSTR),
450 n, blockStateName[bi->blockState]));
453 /* Check pages in use and soft deletions are legal */
455 actuallyUsed = bi->pagesInUse - bi->softDeletions;
457 if (bi->pagesInUse < 0 || bi->pagesInUse > dev->param.nChunksPerBlock ||
458 bi->softDeletions < 0 || bi->softDeletions > dev->param.nChunksPerBlock ||
459 actuallyUsed < 0 || actuallyUsed > dev->param.nChunksPerBlock)
460 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
461 n, bi->pagesInUse, bi->softDeletions));
464 /* Check chunk bitmap legal */
465 inUse = yaffs_CountChunkBits(dev, n);
466 if (inUse != bi->pagesInUse)
467 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
468 n, bi->pagesInUse, inUse));
470 /* Check that the sequence number is valid.
471 * Ten million is legal, but is very unlikely
473 if (dev->param.isYaffs2 &&
474 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
475 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000))
476 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has suspect sequence number of %d"TENDSTR),
477 n, bi->sequenceNumber));
480 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev, yaffs_BlockInfo *bi,
483 yaffs_VerifyBlock(dev, bi, n);
485 /* After collection the block should be in the erased state */
486 /* This will need to change if we do partial gc */
488 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
489 bi->blockState != YAFFS_BLOCK_STATE_EMPTY) {
490 T(YAFFS_TRACE_ERROR, (TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
495 static void yaffs_VerifyBlocks(yaffs_Device *dev)
498 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
499 int nIllegalBlockStates = 0;
501 if (yaffs_SkipVerification(dev))
504 memset(nBlocksPerState, 0, sizeof(nBlocksPerState));
506 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
507 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, i);
508 yaffs_VerifyBlock(dev, bi, i);
510 if (bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
511 nBlocksPerState[bi->blockState]++;
513 nIllegalBlockStates++;
516 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
517 T(YAFFS_TRACE_VERIFY, (TSTR("Block summary"TENDSTR)));
519 T(YAFFS_TRACE_VERIFY, (TSTR("%d blocks have illegal states"TENDSTR), nIllegalBlockStates));
520 if (nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
521 T(YAFFS_TRACE_VERIFY, (TSTR("Too many allocating blocks"TENDSTR)));
523 for (i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
524 T(YAFFS_TRACE_VERIFY,
525 (TSTR("%s %d blocks"TENDSTR),
526 blockStateName[i], nBlocksPerState[i]));
528 if (dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
529 T(YAFFS_TRACE_VERIFY,
530 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
531 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
533 if (dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
534 T(YAFFS_TRACE_VERIFY,
535 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
536 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
538 if (nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
539 T(YAFFS_TRACE_VERIFY,
540 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
541 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
543 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
548 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
549 * case those tests will not be performed.
551 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
553 if (obj && yaffs_SkipVerification(obj->myDev))
556 if (!(tags && obj && oh)) {
557 T(YAFFS_TRACE_VERIFY,
558 (TSTR("Verifying object header tags %p obj %p oh %p"TENDSTR),
563 if (oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
564 oh->type > YAFFS_OBJECT_TYPE_MAX)
565 T(YAFFS_TRACE_VERIFY,
566 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
567 tags->objectId, oh->type));
569 if (tags->objectId != obj->objectId)
570 T(YAFFS_TRACE_VERIFY,
571 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
572 tags->objectId, obj->objectId));
576 * Check that the object's parent ids match if parentCheck requested.
578 * Tests do not apply to the root object.
581 if (parentCheck && tags->objectId > 1 && !obj->parent)
582 T(YAFFS_TRACE_VERIFY,
583 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
584 tags->objectId, oh->parentObjectId));
586 if (parentCheck && obj->parent &&
587 oh->parentObjectId != obj->parent->objectId &&
588 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
589 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
590 T(YAFFS_TRACE_VERIFY,
591 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
592 tags->objectId, oh->parentObjectId, obj->parent->objectId));
594 if (tags->objectId > 1 && oh->name[0] == 0) /* Null name */
595 T(YAFFS_TRACE_VERIFY,
596 (TSTR("Obj %d header name is NULL"TENDSTR),
599 if (tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
600 T(YAFFS_TRACE_VERIFY,
601 (TSTR("Obj %d header name is 0xFF"TENDSTR),
607 static int yaffs_VerifyTnodeWorker(yaffs_Object *obj, yaffs_Tnode *tn,
608 __u32 level, int chunkOffset)
611 yaffs_Device *dev = obj->myDev;
617 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
618 if (tn->internal[i]) {
619 ok = yaffs_VerifyTnodeWorker(obj,
622 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
625 } else if (level == 0) {
626 yaffs_ExtendedTags tags;
627 __u32 objectId = obj->objectId;
629 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
631 for (i = 0; i < YAFFS_NTNODES_LEVEL0; i++) {
632 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
635 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
636 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
637 if (tags.objectId != objectId || tags.chunkId != chunkOffset) {
638 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
639 objectId, chunkOffset, theChunk,
640 tags.objectId, tags.chunkId));
653 static void yaffs_VerifyFile(yaffs_Object *obj)
655 int requiredTallness;
661 yaffs_ExtendedTags tags;
668 if (yaffs_SkipVerification(obj->myDev))
672 objectId = obj->objectId;
674 /* Check file size is consistent with tnode depth */
675 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
676 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
677 requiredTallness = 0;
679 x >>= YAFFS_TNODES_INTERNAL_BITS;
683 actualTallness = obj->variant.fileVariant.topLevel;
685 if (requiredTallness > actualTallness)
686 T(YAFFS_TRACE_VERIFY,
687 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
688 obj->objectId, actualTallness, requiredTallness));
691 /* Check that the chunks in the tnode tree are all correct.
692 * We do this by scanning through the tnode tree and
693 * checking the tags for every chunk match.
696 if (yaffs_SkipNANDVerification(dev))
699 for (i = 1; i <= lastChunk; i++) {
700 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant, i);
703 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
705 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
706 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
707 if (tags.objectId != objectId || tags.chunkId != i) {
708 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
709 objectId, i, theChunk,
710 tags.objectId, tags.chunkId));
718 static void yaffs_VerifyHardLink(yaffs_Object *obj)
720 if (obj && yaffs_SkipVerification(obj->myDev))
723 /* Verify sane equivalent object */
726 static void yaffs_VerifySymlink(yaffs_Object *obj)
728 if (obj && yaffs_SkipVerification(obj->myDev))
731 /* Verify symlink string */
734 static void yaffs_VerifySpecial(yaffs_Object *obj)
736 if (obj && yaffs_SkipVerification(obj->myDev))
740 static void yaffs_VerifyObject(yaffs_Object *obj)
749 __u32 chunkShouldNotBeDeleted;
755 if (obj->beingCreated)
760 if (yaffs_SkipVerification(dev))
763 /* Check sane object header chunk */
765 chunkMin = dev->internalStartBlock * dev->param.nChunksPerBlock;
766 chunkMax = (dev->internalEndBlock+1) * dev->param.nChunksPerBlock - 1;
768 chunkInRange = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
769 chunkIdOk = chunkInRange || (obj->hdrChunk == 0);
770 chunkValid = chunkInRange &&
771 yaffs_CheckChunkBit(dev,
772 obj->hdrChunk / dev->param.nChunksPerBlock,
773 obj->hdrChunk % dev->param.nChunksPerBlock);
774 chunkShouldNotBeDeleted = chunkInRange && !chunkValid;
777 (!chunkIdOk || chunkShouldNotBeDeleted)) {
778 T(YAFFS_TRACE_VERIFY,
779 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
780 obj->objectId, obj->hdrChunk,
781 chunkIdOk ? "" : ",out of range",
782 chunkShouldNotBeDeleted ? ",marked as deleted" : ""));
785 if (chunkValid && !yaffs_SkipNANDVerification(dev)) {
786 yaffs_ExtendedTags tags;
787 yaffs_ObjectHeader *oh;
788 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
790 oh = (yaffs_ObjectHeader *)buffer;
792 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk, buffer,
795 yaffs_VerifyObjectHeader(obj, oh, &tags, 1);
797 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
800 /* Verify it has a parent */
801 if (obj && !obj->fake &&
802 (!obj->parent || obj->parent->myDev != dev)) {
803 T(YAFFS_TRACE_VERIFY,
804 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
805 obj->objectId, obj->parent));
808 /* Verify parent is a directory */
809 if (obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
810 T(YAFFS_TRACE_VERIFY,
811 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
812 obj->objectId, obj->parent->variantType));
815 switch (obj->variantType) {
816 case YAFFS_OBJECT_TYPE_FILE:
817 yaffs_VerifyFile(obj);
819 case YAFFS_OBJECT_TYPE_SYMLINK:
820 yaffs_VerifySymlink(obj);
822 case YAFFS_OBJECT_TYPE_DIRECTORY:
823 yaffs_VerifyDirectory(obj);
825 case YAFFS_OBJECT_TYPE_HARDLINK:
826 yaffs_VerifyHardLink(obj);
828 case YAFFS_OBJECT_TYPE_SPECIAL:
829 yaffs_VerifySpecial(obj);
831 case YAFFS_OBJECT_TYPE_UNKNOWN:
833 T(YAFFS_TRACE_VERIFY,
834 (TSTR("Obj %d has illegaltype %d"TENDSTR),
835 obj->objectId, obj->variantType));
840 static void yaffs_VerifyObjects(yaffs_Device *dev)
844 struct ylist_head *lh;
846 if (yaffs_SkipVerification(dev))
849 /* Iterate through the objects in each hash entry */
851 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
852 ylist_for_each(lh, &dev->objectBucket[i].list) {
854 obj = ylist_entry(lh, yaffs_Object, hashLink);
855 yaffs_VerifyObject(obj);
863 * Simple hash function. Needs to have a reasonable spread
866 static Y_INLINE int yaffs_HashFunction(int n)
869 return n % YAFFS_NOBJECT_BUCKETS;
873 * Access functions to useful fake objects.
874 * Note that root might have a presence in NAND if permissions are set.
877 yaffs_Object *yaffs_Root(yaffs_Device *dev)
882 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
884 return dev->lostNFoundDir;
889 * Erased NAND checking functions
892 int yaffs_CheckFF(__u8 *buffer, int nBytes)
894 /* Horrible, slow implementation */
903 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
906 int retval = YAFFS_OK;
907 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
908 yaffs_ExtendedTags tags;
911 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
913 if (tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
916 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
917 T(YAFFS_TRACE_NANDACCESS,
918 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
922 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
929 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
932 yaffs_ExtendedTags *tags)
934 int retval = YAFFS_OK;
935 yaffs_ExtendedTags tempTags;
936 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
939 result = yaffs_ReadChunkWithTagsFromNAND(dev,chunkInNAND,buffer,&tempTags);
940 if(memcmp(buffer,data,dev->nDataBytesPerChunk) ||
941 tempTags.objectId != tags->objectId ||
942 tempTags.chunkId != tags->chunkId ||
943 tempTags.byteCount != tags->byteCount)
946 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
951 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
953 yaffs_ExtendedTags *tags,
960 yaffs_InvalidateCheckpoint(dev);
963 yaffs_BlockInfo *bi = 0;
966 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
972 /* First check this chunk is erased, if it needs
973 * checking. The checking policy (unless forced
974 * always on) is as follows:
976 * Check the first page we try to write in a block.
977 * If the check passes then we don't need to check any
978 * more. If the check fails, we check again...
979 * If the block has been erased, we don't need to check.
981 * However, if the block has been prioritised for gc,
982 * then we think there might be something odd about
983 * this block and stop using it.
985 * Rationale: We should only ever see chunks that have
986 * not been erased if there was a partially written
987 * chunk due to power loss. This checking policy should
988 * catch that case with very few checks and thus save a
989 * lot of checks that are most likely not needed.
992 * If an erase check fails or the write fails we skip the
996 /* let's give it a try */
999 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
1000 bi->skipErasedCheck = 0;
1002 if (!bi->skipErasedCheck) {
1003 erasedOk = yaffs_CheckChunkErased(dev, chunk);
1004 if (erasedOk != YAFFS_OK) {
1005 T(YAFFS_TRACE_ERROR,
1006 (TSTR("**>> yaffs chunk %d was not erased"
1009 /* If not erased, delete this one,
1010 * skip rest of block and
1011 * try another chunk */
1012 yaffs_DeleteChunk(dev,chunk,1,__LINE__);
1013 yaffs_SkipRestOfBlock(dev);
1018 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
1021 if(!bi->skipErasedCheck)
1022 writeOk = yaffs_VerifyChunkWritten(dev, chunk, data, tags);
1024 if (writeOk != YAFFS_OK) {
1025 /* Clean up aborted write, skip to next block and
1026 * try another chunk */
1027 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
1031 bi->skipErasedCheck = 1;
1033 /* Copy the data into the robustification buffer */
1034 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1036 } while (writeOk != YAFFS_OK &&
1037 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1043 T(YAFFS_TRACE_ERROR,
1044 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1047 dev->nRetriedWrites += (attempts - 1);
1054 * Block retiring for handling a broken block.
1057 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND)
1059 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1061 yaffs_InvalidateCheckpoint(dev);
1063 if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
1064 if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
1065 T(YAFFS_TRACE_ALWAYS, (TSTR(
1066 "yaffs: Failed to mark bad and erase block %d"
1067 TENDSTR), blockInNAND));
1069 yaffs_ExtendedTags tags;
1070 int chunkId = blockInNAND * dev->param.nChunksPerBlock;
1072 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
1074 memset(buffer, 0xff, dev->nDataBytesPerChunk);
1075 yaffs_InitialiseTags(&tags);
1076 tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
1077 if (dev->param.writeChunkWithTagsToNAND(dev, chunkId -
1078 dev->chunkOffset, buffer, &tags) != YAFFS_OK)
1079 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
1080 TCONT("write bad block marker to block %d")
1081 TENDSTR), blockInNAND));
1083 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
1087 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1088 bi->gcPrioritise = 0;
1089 bi->needsRetiring = 0;
1091 dev->nRetiredBlocks++;
1095 * Functions for robustisizing TODO
1099 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
1101 const yaffs_ExtendedTags *tags)
1105 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
1106 const yaffs_ExtendedTags *tags)
1110 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1112 if (!bi->gcPrioritise) {
1113 bi->gcPrioritise = 1;
1114 dev->hasPendingPrioritisedGCs = 1;
1115 bi->chunkErrorStrikes++;
1117 if (bi->chunkErrorStrikes > 3) {
1118 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1119 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1125 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
1128 int blockInNAND = chunkInNAND / dev->param.nChunksPerBlock;
1129 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1131 yaffs_HandleChunkError(dev, bi);
1134 /* Was an actual write failure, so mark the block for retirement */
1135 bi->needsRetiring = 1;
1136 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1137 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1140 /* Delete the chunk */
1141 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1142 yaffs_SkipRestOfBlock(dev);
1146 /*---------------- Name handling functions ------------*/
1148 static __u16 yaffs_CalcNameSum(const YCHAR *name)
1153 const YUCHAR *bname = (const YUCHAR *) name;
1155 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1157 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1158 sum += yaffs_toupper(*bname) * i;
1160 sum += (*bname) * i;
1169 static void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
1171 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1172 memset(obj->shortName, 0, sizeof(YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1173 if (name && yaffs_strnlen(name,YAFFS_SHORT_NAME_LENGTH+1) <= YAFFS_SHORT_NAME_LENGTH)
1174 yaffs_strcpy(obj->shortName, name);
1176 obj->shortName[0] = _Y('\0');
1178 obj->sum = yaffs_CalcNameSum(name);
1181 /*-------------------- TNODES -------------------
1183 * List of spare tnodes
1184 * The list is hooked together using the first pointer
1188 /* yaffs_CreateTnodes creates a bunch more tnodes and
1189 * adds them to the tnode free list.
1190 * Don't use this function directly
1192 static Y_INLINE int yaffs_CalcTnodeSize(yaffs_Device *dev)
1195 /* Calculate the tnode size in bytes for variable width tnode support.
1196 * Must be a multiple of 32-bits */
1197 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1199 if (tnodeSize < sizeof(yaffs_Tnode))
1200 tnodeSize = sizeof(yaffs_Tnode);
1204 static int yaffs_CreateTnodes(yaffs_Device *dev, int nTnodes)
1207 int tnodeSize = yaffs_CalcTnodeSize(dev);
1208 yaffs_Tnode *newTnodes;
1212 yaffs_TnodeList *tnl;
1218 /* make these things */
1220 newTnodes = YMALLOC(nTnodes * tnodeSize);
1221 mem = (__u8 *)newTnodes;
1224 T(YAFFS_TRACE_ERROR,
1225 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1229 /* Hook them into the free list */
1231 for (i = 0; i < nTnodes - 1; i++) {
1232 newTnodes[i].internal[0] = &newTnodes[i + 1];
1233 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1234 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1238 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1239 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1240 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1242 dev->freeTnodes = newTnodes;
1244 /* New hookup for wide tnodes */
1245 for (i = 0; i < nTnodes - 1; i++) {
1246 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1247 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1248 curr->internal[0] = next;
1251 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1252 curr->internal[0] = dev->freeTnodes;
1253 dev->freeTnodes = (yaffs_Tnode *)mem;
1258 dev->nFreeTnodes += nTnodes;
1259 dev->nTnodesCreated += nTnodes;
1261 /* Now add this bunch of tnodes to a list for freeing up.
1262 * NB If we can't add this to the management list it isn't fatal
1263 * but it just means we can't free this bunch of tnodes later.
1266 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1268 T(YAFFS_TRACE_ERROR,
1270 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1273 tnl->tnodes = newTnodes;
1274 tnl->next = dev->allocatedTnodeList;
1275 dev->allocatedTnodeList = tnl;
1278 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1283 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1285 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device *dev)
1287 yaffs_Tnode *tn = NULL;
1289 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1290 tn = YMALLOC(yaffs_CalcTnodeSize(dev));
1292 dev->nTnodesCreated++;
1294 /* If there are none left make more */
1295 if (!dev->freeTnodes)
1296 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1298 if (dev->freeTnodes) {
1299 tn = dev->freeTnodes;
1300 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1301 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1302 /* Hoosterman, this thing looks like it isn't in the list */
1303 T(YAFFS_TRACE_ALWAYS,
1304 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1307 dev->freeTnodes = dev->freeTnodes->internal[0];
1311 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1316 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
1318 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1319 int tnodeSize = yaffs_CalcTnodeSize(dev);
1322 memset(tn, 0, tnodeSize);
1327 /* FreeTnode frees up a tnode and puts it back on the free list */
1328 static void yaffs_FreeTnode(yaffs_Device *dev, yaffs_Tnode *tn)
1331 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1333 dev->nTnodesCreated--;
1335 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1336 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1337 /* Hoosterman, this thing looks like it is already in the list */
1338 T(YAFFS_TRACE_ALWAYS,
1339 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1341 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1343 tn->internal[0] = dev->freeTnodes;
1344 dev->freeTnodes = tn;
1348 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1351 static void yaffs_DeinitialiseTnodes(yaffs_Device *dev)
1353 /* Free the list of allocated tnodes */
1354 yaffs_TnodeList *tmp;
1356 while (dev->allocatedTnodeList) {
1357 tmp = dev->allocatedTnodeList->next;
1359 YFREE(dev->allocatedTnodeList->tnodes);
1360 YFREE(dev->allocatedTnodeList);
1361 dev->allocatedTnodeList = tmp;
1365 dev->freeTnodes = NULL;
1366 dev->nFreeTnodes = 0;
1367 dev->nTnodesCreated = 0;
1370 static void yaffs_InitialiseTnodes(yaffs_Device *dev)
1372 dev->allocatedTnodeList = NULL;
1373 dev->freeTnodes = NULL;
1374 dev->nFreeTnodes = 0;
1375 dev->nTnodesCreated = 0;
1379 void yaffs_LoadLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
1382 __u32 *map = (__u32 *)tn;
1388 pos &= YAFFS_TNODES_LEVEL0_MASK;
1389 val >>= dev->chunkGroupBits;
1391 bitInMap = pos * dev->tnodeWidth;
1392 wordInMap = bitInMap / 32;
1393 bitInWord = bitInMap & (32 - 1);
1395 mask = dev->tnodeMask << bitInWord;
1397 map[wordInMap] &= ~mask;
1398 map[wordInMap] |= (mask & (val << bitInWord));
1400 if (dev->tnodeWidth > (32 - bitInWord)) {
1401 bitInWord = (32 - bitInWord);
1403 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1404 map[wordInMap] &= ~mask;
1405 map[wordInMap] |= (mask & (val >> bitInWord));
1409 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
1412 __u32 *map = (__u32 *)tn;
1418 pos &= YAFFS_TNODES_LEVEL0_MASK;
1420 bitInMap = pos * dev->tnodeWidth;
1421 wordInMap = bitInMap / 32;
1422 bitInWord = bitInMap & (32 - 1);
1424 val = map[wordInMap] >> bitInWord;
1426 if (dev->tnodeWidth > (32 - bitInWord)) {
1427 bitInWord = (32 - bitInWord);
1429 val |= (map[wordInMap] << bitInWord);
1432 val &= dev->tnodeMask;
1433 val <<= dev->chunkGroupBits;
1438 /* ------------------- End of individual tnode manipulation -----------------*/
1440 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1441 * The look up tree is represented by the top tnode and the number of topLevel
1442 * in the tree. 0 means only the level 0 tnode is in the tree.
1445 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1446 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
1447 yaffs_FileStructure *fStruct,
1450 yaffs_Tnode *tn = fStruct->top;
1452 int requiredTallness;
1453 int level = fStruct->topLevel;
1455 /* Check sane level and chunk Id */
1456 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
1459 if (chunkId > YAFFS_MAX_CHUNK_ID)
1462 /* First check we're tall enough (ie enough topLevel) */
1464 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1465 requiredTallness = 0;
1467 i >>= YAFFS_TNODES_INTERNAL_BITS;
1471 if (requiredTallness > fStruct->topLevel)
1472 return NULL; /* Not tall enough, so we can't find it */
1474 /* Traverse down to level 0 */
1475 while (level > 0 && tn) {
1476 tn = tn->internal[(chunkId >>
1477 (YAFFS_TNODES_LEVEL0_BITS +
1479 YAFFS_TNODES_INTERNAL_BITS)) &
1480 YAFFS_TNODES_INTERNAL_MASK];
1487 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1488 * This happens in two steps:
1489 * 1. If the tree isn't tall enough, then make it taller.
1490 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1492 * Used when modifying the tree.
1494 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1495 * be plugged into the ttree.
1498 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
1499 yaffs_FileStructure *fStruct,
1501 yaffs_Tnode *passedTn)
1503 int requiredTallness;
1511 /* Check sane level and page Id */
1512 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
1515 if (chunkId > YAFFS_MAX_CHUNK_ID)
1518 /* First check we're tall enough (ie enough topLevel) */
1520 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1521 requiredTallness = 0;
1523 x >>= YAFFS_TNODES_INTERNAL_BITS;
1528 if (requiredTallness > fStruct->topLevel) {
1529 /* Not tall enough, gotta make the tree taller */
1530 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1532 tn = yaffs_GetTnode(dev);
1535 tn->internal[0] = fStruct->top;
1537 fStruct->topLevel++;
1539 T(YAFFS_TRACE_ERROR,
1540 (TSTR("yaffs: no more tnodes" TENDSTR)));
1546 /* Traverse down to level 0, adding anything we need */
1548 l = fStruct->topLevel;
1552 while (l > 0 && tn) {
1554 (YAFFS_TNODES_LEVEL0_BITS +
1555 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1556 YAFFS_TNODES_INTERNAL_MASK;
1559 if ((l > 1) && !tn->internal[x]) {
1560 /* Add missing non-level-zero tnode */
1561 tn->internal[x] = yaffs_GetTnode(dev);
1562 if(!tn->internal[x])
1564 } else if (l == 1) {
1565 /* Looking from level 1 at level 0 */
1567 /* If we already have one, then release it.*/
1568 if (tn->internal[x])
1569 yaffs_FreeTnode(dev, tn->internal[x]);
1570 tn->internal[x] = passedTn;
1572 } else if (!tn->internal[x]) {
1573 /* Don't have one, none passed in */
1574 tn->internal[x] = yaffs_GetTnode(dev);
1575 if(!tn->internal[x])
1580 tn = tn->internal[x];
1584 /* top is level 0 */
1586 memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1587 yaffs_FreeTnode(dev, passedTn);
1594 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
1595 yaffs_ExtendedTags *tags, int objectId,
1600 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1601 if (yaffs_CheckChunkBit(dev, theChunk / dev->param.nChunksPerBlock,
1602 theChunk % dev->param.nChunksPerBlock)) {
1604 if(dev->chunkGroupSize == 1)
1607 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1609 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1621 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1622 * chunks and tnodes in the file
1623 * Returns 1 if the tree was deleted.
1624 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1627 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
1628 int chunkOffset, int *limit)
1633 yaffs_ExtendedTags tags;
1635 yaffs_Device *dev = in->myDev;
1641 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1643 if (tn->internal[i]) {
1644 if (limit && (*limit) < 0) {
1648 yaffs_DeleteWorker(in,
1656 YAFFS_TNODES_INTERNAL_BITS)
1661 yaffs_FreeTnode(dev,
1664 tn->internal[i] = NULL;
1668 return (allDone) ? 1 : 0;
1669 } else if (level == 0) {
1672 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1674 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1677 chunkInInode = (chunkOffset <<
1678 YAFFS_TNODES_LEVEL0_BITS) + i;
1681 yaffs_FindChunkInGroup(dev,
1687 if (foundChunk > 0) {
1688 yaffs_DeleteChunk(dev,
1693 *limit = *limit - 1;
1700 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1704 return (i < 0) ? 1 : 0;
1714 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1716 yaffs_BlockInfo *theBlock;
1718 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1720 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->param.nChunksPerBlock);
1722 theBlock->softDeletions++;
1727 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1728 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1730 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1733 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1734 __u32 level, int chunkOffset)
1739 yaffs_Device *dev = in->myDev;
1744 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1746 if (tn->internal[i]) {
1748 yaffs_SoftDeleteWorker(in,
1754 YAFFS_TNODES_INTERNAL_BITS)
1757 yaffs_FreeTnode(dev,
1760 tn->internal[i] = NULL;
1762 /* Hoosterman... how could this happen? */
1766 return (allDone) ? 1 : 0;
1767 } else if (level == 0) {
1769 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1770 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1772 /* Note this does not find the real chunk, only the chunk group.
1773 * We make an assumption that a chunk group is not larger than
1776 yaffs_SoftDeleteChunk(dev, theChunk);
1777 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1791 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1794 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1795 if (obj->nDataChunks <= 0) {
1796 /* Empty file with no duplicate object headers, just delete it immediately */
1797 yaffs_FreeTnode(obj->myDev,
1798 obj->variant.fileVariant.top);
1799 obj->variant.fileVariant.top = NULL;
1800 T(YAFFS_TRACE_TRACING,
1801 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1803 yaffs_DoGenericObjectDeletion(obj);
1805 yaffs_SoftDeleteWorker(obj,
1806 obj->variant.fileVariant.top,
1807 obj->variant.fileVariant.
1809 obj->softDeleted = 1;
1814 /* Pruning removes any part of the file structure tree that is beyond the
1815 * bounds of the file (ie that does not point to chunks).
1817 * A file should only get pruned when its size is reduced.
1819 * Before pruning, the chunks must be pulled from the tree and the
1820 * level 0 tnode entries must be zeroed out.
1821 * Could also use this for file deletion, but that's probably better handled
1822 * by a special case.
1824 * This function is recursive. For levels > 0 the function is called again on
1825 * any sub-tree. For level == 0 we just check if the sub-tree has data.
1826 * If there is no data in a subtree then it is pruned.
1829 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1830 __u32 level, int del0)
1839 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1840 if (tn->internal[i]) {
1842 yaffs_PruneWorker(dev, tn->internal[i],
1844 (i == 0) ? del0 : 1);
1847 if (tn->internal[i])
1851 int tnodeSize_u32 = yaffs_CalcTnodeSize(dev)/sizeof(__u32);
1852 __u32 *map = (__u32 *)tn;
1854 for(i = 0; !hasData && i < tnodeSize_u32; i++){
1860 if (hasData == 0 && del0) {
1861 /* Free and return NULL */
1863 yaffs_FreeTnode(dev, tn);
1873 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1874 yaffs_FileStructure *fStruct)
1881 if (fStruct->topLevel > 0) {
1883 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1885 /* Now we have a tree with all the non-zero branches NULL but the height
1886 * is the same as it was.
1887 * Let's see if we can trim internal tnodes to shorten the tree.
1888 * We can do this if only the 0th element in the tnode is in use
1889 * (ie all the non-zero are NULL)
1892 while (fStruct->topLevel && !done) {
1896 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1897 if (tn->internal[i])
1902 fStruct->top = tn->internal[0];
1903 fStruct->topLevel--;
1904 yaffs_FreeTnode(dev, tn);
1914 /*-------------------- End of File Structure functions.-------------------*/
1916 /* yaffs_CreateFreeObjects creates a bunch more objects and
1917 * adds them to the object free list.
1919 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1922 yaffs_Object *newObjects;
1923 yaffs_ObjectList *list;
1928 /* make these things */
1929 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1930 list = YMALLOC(sizeof(yaffs_ObjectList));
1932 if (!newObjects || !list) {
1941 T(YAFFS_TRACE_ALLOCATE,
1942 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1946 /* Hook them into the free list */
1947 for (i = 0; i < nObjects - 1; i++) {
1948 newObjects[i].siblings.next =
1949 (struct ylist_head *)(&newObjects[i + 1]);
1952 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1953 dev->freeObjects = newObjects;
1954 dev->nFreeObjects += nObjects;
1955 dev->nObjectsCreated += nObjects;
1957 /* Now add this bunch of Objects to a list for freeing up. */
1959 list->objects = newObjects;
1960 list->next = dev->allocatedObjectList;
1961 dev->allocatedObjectList = list;
1967 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1968 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1970 yaffs_Object *tn = NULL;
1972 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1973 tn = YMALLOC(sizeof(yaffs_Object));
1975 dev->nObjectsCreated++;
1977 /* If there are none left make more */
1978 if (!dev->freeObjects)
1979 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1981 if (dev->freeObjects) {
1982 tn = dev->freeObjects;
1984 (yaffs_Object *) (dev->freeObjects->siblings.next);
1985 dev->nFreeObjects--;
1989 /* Now sweeten it up... */
1991 memset(tn, 0, sizeof(yaffs_Object));
1992 tn->beingCreated = 1;
1996 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1997 YINIT_LIST_HEAD(&(tn->hardLinks));
1998 YINIT_LIST_HEAD(&(tn->hashLink));
1999 YINIT_LIST_HEAD(&tn->siblings);
2002 /* Now make the directory sane */
2004 tn->parent = dev->rootDir;
2005 ylist_add(&(tn->siblings), &dev->rootDir->variant.directoryVariant.children);
2008 /* Add it to the lost and found directory.
2009 * NB Can't put root or lostNFound in lostNFound so
2010 * check if lostNFound exists first
2012 if (dev->lostNFoundDir)
2013 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
2015 tn->beingCreated = 0;
2018 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2023 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
2028 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
2030 obj->fake = 1; /* it is fake so it might have no NAND presence... */
2031 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
2032 obj->unlinkAllowed = 0; /* ... or unlink it */
2035 obj->yst_mode = mode;
2037 obj->hdrChunk = 0; /* Not a valid chunk. */
2044 static void yaffs_UnhashObject(yaffs_Object *tn)
2047 yaffs_Device *dev = tn->myDev;
2049 /* If it is still linked into the bucket list, free from the list */
2050 if (!ylist_empty(&tn->hashLink)) {
2051 ylist_del_init(&tn->hashLink);
2052 bucket = yaffs_HashFunction(tn->objectId);
2053 dev->objectBucket[bucket].count--;
2057 /* FreeObject frees up a Object and puts it back on the free list */
2058 static void yaffs_FreeObject(yaffs_Object *tn)
2060 yaffs_Device *dev = tn->myDev;
2062 T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), tn, tn->myInode));
2068 if (!ylist_empty(&tn->siblings))
2073 /* We're still hooked up to a cached inode.
2074 * Don't delete now, but mark for later deletion
2076 tn->deferedFree = 1;
2080 yaffs_UnhashObject(tn);
2082 #ifdef CONFIG_YAFFS_VALGRIND_TEST
2084 dev->nObjectsCreated--;
2087 /* Link into the free list. */
2088 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2089 dev->freeObjects = tn;
2090 dev->nFreeObjects++;
2092 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2096 void yaffs_HandleDeferedFree(yaffs_Object *obj)
2098 if (obj->deferedFree)
2099 yaffs_FreeObject(obj);
2103 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
2105 /* Free the list of allocated Objects */
2107 yaffs_ObjectList *tmp;
2109 while (dev->allocatedObjectList) {
2110 tmp = dev->allocatedObjectList->next;
2111 YFREE(dev->allocatedObjectList->objects);
2112 YFREE(dev->allocatedObjectList);
2114 dev->allocatedObjectList = tmp;
2117 dev->freeObjects = NULL;
2118 dev->nFreeObjects = 0;
2119 dev->nObjectsCreated = 0;
2122 static void yaffs_InitialiseObjects(yaffs_Device *dev)
2126 dev->allocatedObjectList = NULL;
2127 dev->freeObjects = NULL;
2128 dev->nFreeObjects = 0;
2130 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2131 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2132 dev->objectBucket[i].count = 0;
2136 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
2141 int lowest = 999999;
2143 /* First let's see if we can find one that's empty. */
2145 for (i = 0; i < 10 && lowest > 0; i++) {
2147 x %= YAFFS_NOBJECT_BUCKETS;
2148 if (dev->objectBucket[x].count < lowest) {
2149 lowest = dev->objectBucket[x].count;
2155 /* If we didn't find an empty list, then try
2156 * looking a bit further for a short one
2159 for (i = 0; i < 10 && lowest > 3; i++) {
2161 x %= YAFFS_NOBJECT_BUCKETS;
2162 if (dev->objectBucket[x].count < lowest) {
2163 lowest = dev->objectBucket[x].count;
2172 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
2174 int bucket = yaffs_FindNiceObjectBucket(dev);
2176 /* Now find an object value that has not already been taken
2177 * by scanning the list.
2181 struct ylist_head *i;
2183 __u32 n = (__u32) bucket;
2185 /* yaffs_CheckObjectHashSanity(); */
2189 n += YAFFS_NOBJECT_BUCKETS;
2190 if (1 || dev->objectBucket[bucket].count > 0) {
2191 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2192 /* If there is already one in the list */
2193 if (i && ylist_entry(i, yaffs_Object,
2194 hashLink)->objectId == n) {
2204 static void yaffs_HashObject(yaffs_Object *in)
2206 int bucket = yaffs_HashFunction(in->objectId);
2207 yaffs_Device *dev = in->myDev;
2209 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2210 dev->objectBucket[bucket].count++;
2213 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
2215 int bucket = yaffs_HashFunction(number);
2216 struct ylist_head *i;
2219 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2220 /* Look if it is in the list */
2222 in = ylist_entry(i, yaffs_Object, hashLink);
2223 if (in->objectId == number) {
2225 /* Don't tell the VFS about this one if it is defered free */
2226 if (in->deferedFree)
2237 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
2238 yaffs_ObjectType type)
2240 yaffs_Object *theObject=NULL;
2241 yaffs_Tnode *tn = NULL;
2244 number = yaffs_CreateNewObjectNumber(dev);
2246 if (type == YAFFS_OBJECT_TYPE_FILE) {
2247 tn = yaffs_GetTnode(dev);
2252 theObject = yaffs_AllocateEmptyObject(dev);
2255 yaffs_FreeTnode(dev,tn);
2261 theObject->fake = 0;
2262 theObject->renameAllowed = 1;
2263 theObject->unlinkAllowed = 1;
2264 theObject->objectId = number;
2265 yaffs_HashObject(theObject);
2266 theObject->variantType = type;
2267 #ifdef CONFIG_YAFFS_WINCE
2268 yfsd_WinFileTimeNow(theObject->win_atime);
2269 theObject->win_ctime[0] = theObject->win_mtime[0] =
2270 theObject->win_atime[0];
2271 theObject->win_ctime[1] = theObject->win_mtime[1] =
2272 theObject->win_atime[1];
2276 theObject->yst_atime = theObject->yst_mtime =
2277 theObject->yst_ctime = Y_CURRENT_TIME;
2280 case YAFFS_OBJECT_TYPE_FILE:
2281 theObject->variant.fileVariant.fileSize = 0;
2282 theObject->variant.fileVariant.scannedFileSize = 0;
2283 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2284 theObject->variant.fileVariant.topLevel = 0;
2285 theObject->variant.fileVariant.top = tn;
2287 case YAFFS_OBJECT_TYPE_DIRECTORY:
2288 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2291 case YAFFS_OBJECT_TYPE_SYMLINK:
2292 case YAFFS_OBJECT_TYPE_HARDLINK:
2293 case YAFFS_OBJECT_TYPE_SPECIAL:
2294 /* No action required */
2296 case YAFFS_OBJECT_TYPE_UNKNOWN:
2297 /* todo this should not happen */
2305 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
2307 yaffs_ObjectType type)
2309 yaffs_Object *theObject = NULL;
2312 theObject = yaffs_FindObjectByNumber(dev, number);
2315 theObject = yaffs_CreateNewObject(dev, number, type);
2322 static YCHAR *yaffs_CloneString(const YCHAR *str)
2324 YCHAR *newStr = NULL;
2330 len = yaffs_strnlen(str,YAFFS_MAX_ALIAS_LENGTH);
2331 newStr = YMALLOC((len + 1) * sizeof(YCHAR));
2333 yaffs_strncpy(newStr, str,len);
2341 * Mknod (create) a new object.
2342 * equivalentObject only has meaning for a hard link;
2343 * aliasString only has meaning for a symlink.
2344 * rdev only has meaning for devices (a subset of special objects)
2347 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2348 yaffs_Object *parent,
2353 yaffs_Object *equivalentObject,
2354 const YCHAR *aliasString, __u32 rdev)
2359 yaffs_Device *dev = parent->myDev;
2361 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2362 if (yaffs_FindObjectByName(parent, name))
2365 if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2366 str = yaffs_CloneString(aliasString);
2371 in = yaffs_CreateNewObject(dev, -1, type);
2386 in->variantType = type;
2388 in->yst_mode = mode;
2390 #ifdef CONFIG_YAFFS_WINCE
2391 yfsd_WinFileTimeNow(in->win_atime);
2392 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2393 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2396 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2398 in->yst_rdev = rdev;
2402 in->nDataChunks = 0;
2404 yaffs_SetObjectName(in, name);
2407 yaffs_AddObjectToDirectory(parent, in);
2409 in->myDev = parent->myDev;
2412 case YAFFS_OBJECT_TYPE_SYMLINK:
2413 in->variant.symLinkVariant.alias = str;
2415 case YAFFS_OBJECT_TYPE_HARDLINK:
2416 in->variant.hardLinkVariant.equivalentObject =
2418 in->variant.hardLinkVariant.equivalentObjectId =
2419 equivalentObject->objectId;
2420 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2422 case YAFFS_OBJECT_TYPE_FILE:
2423 case YAFFS_OBJECT_TYPE_DIRECTORY:
2424 case YAFFS_OBJECT_TYPE_SPECIAL:
2425 case YAFFS_OBJECT_TYPE_UNKNOWN:
2430 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2431 /* Could not create the object header, fail the creation */
2432 yaffs_DeleteObject(in);
2436 yaffs_UpdateParent(parent);
2442 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
2443 __u32 mode, __u32 uid, __u32 gid)
2445 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2446 uid, gid, NULL, NULL, 0);
2449 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
2450 __u32 mode, __u32 uid, __u32 gid)
2452 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2453 mode, uid, gid, NULL, NULL, 0);
2456 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
2457 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2459 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2460 uid, gid, NULL, NULL, rdev);
2463 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
2464 __u32 mode, __u32 uid, __u32 gid,
2467 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2468 uid, gid, NULL, alias, 0);
2471 /* yaffs_Link returns the object id of the equivalent object.*/
2472 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
2473 yaffs_Object *equivalentObject)
2475 /* Get the real object in case we were fed a hard link as an equivalent object */
2476 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2478 if (yaffs_MknodObject
2479 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2480 equivalentObject, NULL, 0)) {
2481 return equivalentObject;
2488 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
2489 const YCHAR *newName, int force, int shadows)
2494 yaffs_Object *existingTarget;
2497 newDir = obj->parent; /* use the old directory */
2499 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2500 T(YAFFS_TRACE_ALWAYS,
2502 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2507 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2508 if (obj->myDev->param.isYaffs2)
2509 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2511 unlinkOp = (newDir == obj->myDev->unlinkedDir
2512 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2514 deleteOp = (newDir == obj->myDev->deletedDir);
2516 existingTarget = yaffs_FindObjectByName(newDir, newName);
2518 /* If the object is a file going into the unlinked directory,
2519 * then it is OK to just stuff it in since duplicate names are allowed.
2520 * else only proceed if the new name does not exist and if we're putting
2521 * it into a directory.
2528 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2529 yaffs_SetObjectName(obj, newName);
2532 yaffs_AddObjectToDirectory(newDir, obj);
2537 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2538 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows) >= 0)
2545 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
2546 yaffs_Object *newDir, const YCHAR *newName)
2548 yaffs_Object *obj = NULL;
2549 yaffs_Object *existingTarget = NULL;
2555 if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2557 if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2560 dev = oldDir->myDev;
2562 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2563 /* Special case for case insemsitive systems (eg. WinCE).
2564 * While look-up is case insensitive, the name isn't.
2565 * Therefore we might want to change x.txt to X.txt
2567 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
2571 if(yaffs_strnlen(newName,YAFFS_MAX_NAME_LENGTH+1) > YAFFS_MAX_NAME_LENGTH)
2575 obj = yaffs_FindObjectByName(oldDir, oldName);
2577 if (obj && obj->renameAllowed) {
2579 /* Now do the handling for an existing target, if there is one */
2581 existingTarget = yaffs_FindObjectByName(newDir, newName);
2582 if (existingTarget &&
2583 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2584 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2585 /* There is a target that is a non-empty directory, so we fail */
2586 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2587 } else if (existingTarget && existingTarget != obj) {
2588 /* Nuke the target first, using shadowing,
2589 * but only if it isn't the same object.
2591 * Note we must disable gc otherwise it can mess up the shadowing.
2595 yaffs_ChangeObjectName(obj, newDir, newName, force,
2596 existingTarget->objectId);
2597 existingTarget->isShadowed = 1;
2598 yaffs_UnlinkObject(existingTarget);
2602 result = yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2604 yaffs_UpdateParent(oldDir);
2605 if(newDir != oldDir)
2606 yaffs_UpdateParent(newDir);
2613 /*------------------------- Block Management and Page Allocation ----------------*/
2615 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
2617 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2619 dev->blockInfo = NULL;
2620 dev->chunkBits = NULL;
2622 dev->allocationBlock = -1; /* force it to get a new one */
2624 /* If the first allocation strategy fails, thry the alternate one */
2625 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2626 if (!dev->blockInfo) {
2627 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2628 dev->blockInfoAlt = 1;
2630 dev->blockInfoAlt = 0;
2632 if (dev->blockInfo) {
2633 /* Set up dynamic blockinfo stuff. */
2634 dev->chunkBitmapStride = (dev->param.nChunksPerBlock + 7) / 8; /* round up bytes */
2635 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2636 if (!dev->chunkBits) {
2637 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2638 dev->chunkBitsAlt = 1;
2640 dev->chunkBitsAlt = 0;
2643 if (dev->blockInfo && dev->chunkBits) {
2644 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2645 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2652 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2654 if (dev->blockInfoAlt && dev->blockInfo)
2655 YFREE_ALT(dev->blockInfo);
2656 else if (dev->blockInfo)
2657 YFREE(dev->blockInfo);
2659 dev->blockInfoAlt = 0;
2661 dev->blockInfo = NULL;
2663 if (dev->chunkBitsAlt && dev->chunkBits)
2664 YFREE_ALT(dev->chunkBits);
2665 else if (dev->chunkBits)
2666 YFREE(dev->chunkBits);
2667 dev->chunkBitsAlt = 0;
2668 dev->chunkBits = NULL;
2671 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
2672 yaffs_BlockInfo *bi)
2678 if (!dev->param.isYaffs2)
2679 return 1; /* disqualification only applies to yaffs2. */
2681 if (!bi->hasShrinkHeader)
2682 return 1; /* can gc */
2684 /* Find the oldest dirty sequence number if we don't know it and save it
2685 * so we don't have to keep recomputing it.
2687 if (!dev->oldestDirtySequence) {
2688 seq = dev->sequenceNumber;
2690 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2692 b = yaffs_GetBlockInfo(dev, i);
2693 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2694 (b->pagesInUse - b->softDeletions) <
2695 dev->param.nChunksPerBlock && b->sequenceNumber < seq) {
2696 seq = b->sequenceNumber;
2699 dev->oldestDirtySequence = seq;
2702 /* Can't do gc of this block if there are any blocks older than this one that have
2705 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2708 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2709 * for garbage collection.
2712 static int yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
2715 int b = dev->currentDirtyChecker;
2721 int prioritised = 0;
2722 yaffs_BlockInfo *bi;
2723 int pendingPrioritisedExist = 0;
2725 /* First let's see if we need to grab a prioritised block */
2726 if (dev->hasPendingPrioritisedGCs) {
2727 for (i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++) {
2729 bi = yaffs_GetBlockInfo(dev, i);
2730 /* yaffs_VerifyBlock(dev,bi,i); */
2732 if (bi->gcPrioritise) {
2733 pendingPrioritisedExist = 1;
2734 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2735 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2736 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2739 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2744 if (!pendingPrioritisedExist) /* None found, so we can clear this */
2745 dev->hasPendingPrioritisedGCs = 0;
2748 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2750 * else (we're doing a leasurely gc), then we only bother to do this if the
2751 * block has only a few pages in use.
2754 dev->nonAggressiveSkip--;
2756 if (!aggressive && (dev->nonAggressiveSkip > 0))
2761 (aggressive) ? dev->param.nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2765 dev->internalEndBlock - dev->internalStartBlock + 1;
2768 dev->internalEndBlock - dev->internalStartBlock + 1;
2769 iterations = iterations / 16;
2770 if (iterations > 200)
2774 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2776 if (b < dev->internalStartBlock || b > dev->internalEndBlock)
2777 b = dev->internalStartBlock;
2779 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2780 T(YAFFS_TRACE_ERROR,
2781 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2785 bi = yaffs_GetBlockInfo(dev, b);
2787 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2788 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2789 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2791 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2795 dev->currentDirtyChecker = b;
2799 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2800 dev->param.nChunksPerBlock - pagesInUse, prioritised));
2803 dev->oldestDirtySequence = 0;
2806 dev->nonAggressiveSkip = 4;
2811 static void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
2813 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2817 /* If the block is still healthy erase it and mark as clean.
2818 * If the block has had a data failure, then retire it.
2821 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2822 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2823 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2825 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2827 if (!bi->needsRetiring) {
2828 yaffs_InvalidateCheckpoint(dev);
2829 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2831 dev->nErasureFailures++;
2832 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2833 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2838 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2840 for (i = 0; i < dev->param.nChunksPerBlock; i++) {
2841 if (!yaffs_CheckChunkErased
2842 (dev, blockNo * dev->param.nChunksPerBlock + i)) {
2843 T(YAFFS_TRACE_ERROR,
2845 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2846 TENDSTR), blockNo, i));
2852 /* Clean it up... */
2853 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2854 dev->nErasedBlocks++;
2856 bi->softDeletions = 0;
2857 bi->hasShrinkHeader = 0;
2858 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2859 bi->gcPrioritise = 0;
2860 yaffs_ClearChunkBits(dev, blockNo);
2862 T(YAFFS_TRACE_ERASE,
2863 (TSTR("Erased block %d" TENDSTR), blockNo));
2865 dev->nFreeChunks -= dev->param.nChunksPerBlock; /* We lost a block of free space */
2867 yaffs_RetireBlock(dev, blockNo);
2868 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2869 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2873 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2877 yaffs_BlockInfo *bi;
2879 if (dev->nErasedBlocks < 1) {
2880 /* Hoosterman we've got a problem.
2881 * Can't get space to gc
2883 T(YAFFS_TRACE_ERROR,
2884 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2889 /* Find an empty block. */
2891 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2892 dev->allocationBlockFinder++;
2893 if (dev->allocationBlockFinder < dev->internalStartBlock
2894 || dev->allocationBlockFinder > dev->internalEndBlock) {
2895 dev->allocationBlockFinder = dev->internalStartBlock;
2898 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2900 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2901 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2902 dev->sequenceNumber++;
2903 bi->sequenceNumber = dev->sequenceNumber;
2904 dev->nErasedBlocks--;
2905 T(YAFFS_TRACE_ALLOCATE,
2906 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2907 dev->allocationBlockFinder, dev->sequenceNumber,
2908 dev->nErasedBlocks));
2909 return dev->allocationBlockFinder;
2913 T(YAFFS_TRACE_ALWAYS,
2915 ("yaffs tragedy: no more erased blocks, but there should have been %d"
2916 TENDSTR), dev->nErasedBlocks));
2923 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2925 if (!dev->nCheckpointBlocksRequired &&
2926 dev->param.isYaffs2) {
2927 /* Not a valid value so recalculate */
2930 int devBlocks = (dev->param.endBlock - dev->param.startBlock + 1);
2931 int tnodeSize = yaffs_CalcTnodeSize(dev);
2933 nBytes += sizeof(yaffs_CheckpointValidity);
2934 nBytes += sizeof(yaffs_CheckpointDevice);
2935 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2936 nBytes += devBlocks * dev->chunkBitmapStride;
2937 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2938 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2939 nBytes += sizeof(yaffs_CheckpointValidity);
2940 nBytes += sizeof(__u32); /* checksum*/
2942 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2944 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->param.nChunksPerBlock)) + 3;
2946 dev->nCheckpointBlocksRequired = nBlocks;
2949 return dev->nCheckpointBlocksRequired;
2953 * Check if there's space to allocate...
2954 * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2956 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev)
2959 int reservedBlocks = dev->param.nReservedBlocks;
2960 int checkpointBlocks;
2962 if (dev->param.isYaffs2) {
2963 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
2964 dev->blocksInCheckpoint;
2965 if (checkpointBlocks < 0)
2966 checkpointBlocks = 0;
2968 checkpointBlocks = 0;
2971 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->param.nChunksPerBlock);
2973 return (dev->nFreeChunks > reservedChunks);
2976 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
2977 yaffs_BlockInfo **blockUsedPtr)
2980 yaffs_BlockInfo *bi;
2982 if (dev->allocationBlock < 0) {
2983 /* Get next block to allocate off */
2984 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2985 dev->allocationPage = 0;
2988 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2989 /* Not enough space to allocate unless we're allowed to use the reserve. */
2993 if (dev->nErasedBlocks < dev->param.nReservedBlocks
2994 && dev->allocationPage == 0) {
2995 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2998 /* Next page please.... */
2999 if (dev->allocationBlock >= 0) {
3000 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3002 retVal = (dev->allocationBlock * dev->param.nChunksPerBlock) +
3003 dev->allocationPage;
3005 yaffs_SetChunkBit(dev, dev->allocationBlock,
3006 dev->allocationPage);
3008 dev->allocationPage++;
3012 /* If the block is full set the state to full */
3013 if (dev->allocationPage >= dev->param.nChunksPerBlock) {
3014 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3015 dev->allocationBlock = -1;
3024 T(YAFFS_TRACE_ERROR,
3025 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
3030 static int yaffs_GetErasedChunks(yaffs_Device *dev)
3034 n = dev->nErasedBlocks * dev->param.nChunksPerBlock;
3036 if (dev->allocationBlock > 0)
3037 n += (dev->param.nChunksPerBlock - dev->allocationPage);
3044 * yaffs_SkipRestOfBlock() skips over the rest of the allocation block
3045 * if we don't want to write to it.
3047 static void yaffs_SkipRestOfBlock(yaffs_Device *dev)
3049 if(dev->allocationBlock > 0){
3050 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3051 if(bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING){
3052 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3053 dev->allocationBlock = -1;
3059 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
3065 int retVal = YAFFS_OK;
3068 int isCheckpointBlock;
3072 int chunksBefore = yaffs_GetErasedChunks(dev);
3075 yaffs_ExtendedTags tags;
3077 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3079 yaffs_Object *object;
3081 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3084 T(YAFFS_TRACE_TRACING,
3085 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3088 bi->hasShrinkHeader,
3091 /*yaffs_VerifyFreeChunks(dev); */
3093 if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
3094 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3096 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
3098 /* Take off the number of soft deleted entries because
3099 * they're going to get really deleted during GC.
3101 if(dev->gcChunk == 0) /* first time through for this block */
3102 dev->nFreeChunks -= bi->softDeletions;
3106 if (isCheckpointBlock ||
3107 !yaffs_StillSomeChunkBits(dev, block)) {
3108 T(YAFFS_TRACE_TRACING,
3110 ("Collecting block %d that has no chunks in use" TENDSTR),
3112 yaffs_BlockBecameDirty(dev, block);
3115 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3117 yaffs_VerifyBlock(dev, bi, block);
3119 maxCopies = (wholeBlock) ? dev->param.nChunksPerBlock : 10;
3120 oldChunk = block * dev->param.nChunksPerBlock + dev->gcChunk;
3122 for (/* init already done */;
3123 retVal == YAFFS_OK &&
3124 dev->gcChunk < dev->param.nChunksPerBlock &&
3125 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
3127 dev->gcChunk++, oldChunk++) {
3128 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3130 /* This page is in use and might need to be copied off */
3136 yaffs_InitialiseTags(&tags);
3138 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3142 yaffs_FindObjectByNumber(dev,
3145 T(YAFFS_TRACE_GC_DETAIL,
3147 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3148 dev->gcChunk, tags.objectId, tags.chunkId,
3151 if (object && !yaffs_SkipVerification(dev)) {
3152 if (tags.chunkId == 0)
3153 matchingChunk = object->hdrChunk;
3154 else if (object->softDeleted)
3155 matchingChunk = oldChunk; /* Defeat the test */
3157 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
3159 if (oldChunk != matchingChunk)
3160 T(YAFFS_TRACE_ERROR,
3161 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3162 oldChunk, matchingChunk, tags.objectId, tags.chunkId));
3167 T(YAFFS_TRACE_ERROR,
3169 ("page %d in gc has no object: %d %d %d "
3171 tags.objectId, tags.chunkId, tags.byteCount));
3176 object->softDeleted &&
3177 tags.chunkId != 0) {
3178 /* Data chunk in a soft deleted file, throw it away
3179 * It's a soft deleted data chunk,
3180 * No need to copy this, just forget about it and
3181 * fix up the object.
3184 object->nDataChunks--;
3186 if (object->nDataChunks <= 0) {
3187 /* remeber to clean up the object */
3188 dev->gcCleanupList[cleanups] =
3194 /* Todo object && object->deleted && object->nDataChunks == 0 */
3195 /* Deleted object header with no data chunks.
3196 * Can be discarded and the file deleted.
3198 object->hdrChunk = 0;
3199 yaffs_FreeTnode(object->myDev,
3202 object->variant.fileVariant.top = NULL;
3203 yaffs_DoGenericObjectDeletion(object);
3205 } else if (object) {
3206 /* It's either a data chunk in a live file or
3207 * an ObjectHeader, so we're interested in it.
3208 * NB Need to keep the ObjectHeaders of deleted files
3209 * until the whole file has been deleted off
3211 tags.serialNumber++;
3215 if (tags.chunkId == 0) {
3216 /* It is an object Id,
3217 * We need to nuke the shrinkheader flags first
3218 * Also need to clean up shadowing.
3219 * We no longer want the shrinkHeader flag since its work is done
3220 * and if it is left in place it will mess up scanning.
3223 yaffs_ObjectHeader *oh;
3224 oh = (yaffs_ObjectHeader *)buffer;
3226 tags.extraIsShrinkHeader = 0;
3227 oh->shadowsObject = 0;
3228 oh->inbandShadowsObject = 0;
3229 tags.extraShadows = 0;
3231 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
3235 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3238 retVal = YAFFS_FAIL;
3241 /* Ok, now fix up the Tnodes etc. */
3243 if (tags.chunkId == 0) {
3245 object->hdrChunk = newChunk;
3246 object->serial = tags.serialNumber;
3248 /* It's a data chunk */
3250 ok = yaffs_PutChunkIntoFile
3258 if (retVal == YAFFS_OK)
3259 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3264 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3267 /* Do any required cleanups */
3268 for (i = 0; i < cleanups; i++) {
3269 /* Time to delete the file too */
3271 yaffs_FindObjectByNumber(dev,
3272 dev->gcCleanupList[i]);
3274 yaffs_FreeTnode(dev,
3275 object->variant.fileVariant.
3277 object->variant.fileVariant.top = NULL;
3280 ("yaffs: About to finally delete object %d"
3281 TENDSTR), object->objectId));
3282 yaffs_DoGenericObjectDeletion(object);
3283 object->myDev->nDeletedFiles--;
3290 yaffs_VerifyCollectedBlock(dev, bi, block);
3292 chunksAfter = yaffs_GetErasedChunks(dev);
3293 if (chunksBefore >= chunksAfter) {
3296 ("gc did not increase free chunks before %d after %d"
3297 TENDSTR), chunksBefore, chunksAfter));
3300 /* If the gc completed then clear the current gcBlock so that we find another. */
3301 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING) {
3311 /* New garbage collector
3312 * If we're very low on erased blocks then we do aggressive garbage collection
3313 * otherwise we do "leasurely" garbage collection.
3314 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3315 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3317 * The idea is to help clear out space in a more spread-out manner.
3318 * Dunno if it really does anything useful.
3320 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
3324 int gcOk = YAFFS_OK;
3327 int checkpointBlockAdjust;
3329 if (dev->isDoingGC) {
3330 /* Bail out so we don't get recursive gc */
3334 /* This loop should pass the first time.
3335 * We'll only see looping here if the erase of the collected block fails.
3341 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3342 if (checkpointBlockAdjust < 0)
3343 checkpointBlockAdjust = 0;
3345 if (dev->nErasedBlocks < (dev->param.nReservedBlocks + checkpointBlockAdjust + 2)) {
3346 /* We need a block soon...*/
3349 /* We're in no hurry */
3353 if (dev->gcBlock <= 0) {
3354 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3358 block = dev->gcBlock;
3361 dev->garbageCollections++;
3363 dev->passiveGarbageCollections++;
3367 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3368 dev->nErasedBlocks, aggressive));
3370 gcOk = yaffs_GarbageCollectBlock(dev, block, aggressive);
3373 if (dev->nErasedBlocks < (dev->param.nReservedBlocks) && block > 0) {
3376 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3377 TENDSTR), dev->nErasedBlocks, maxTries, block));
3379 } while ((dev->nErasedBlocks < dev->param.nReservedBlocks) &&
3383 return aggressive ? gcOk : YAFFS_OK;
3386 /*------------------------- TAGS --------------------------------*/
3388 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
3391 return (tags->chunkId == chunkInObject &&
3392 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3397 /*-------------------- Data file manipulation -----------------*/
3399 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
3400 yaffs_ExtendedTags *tags)
3402 /*Get the Tnode, then get the level 0 offset chunk offset */
3405 yaffs_ExtendedTags localTags;
3408 yaffs_Device *dev = in->myDev;
3411 /* Passed a NULL, so use our own tags space */
3415 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3418 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3421 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3427 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
3428 yaffs_ExtendedTags *tags)
3430 /* Get the Tnode, then get the level 0 offset chunk offset */
3433 yaffs_ExtendedTags localTags;
3435 yaffs_Device *dev = in->myDev;
3439 /* Passed a NULL, so use our own tags space */
3443 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3447 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3450 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3453 /* Delete the entry in the filestructure (if found) */
3455 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, 0);
3461 #ifdef YAFFS_PARANOID
3463 static int yaffs_CheckFileSanity(yaffs_Object *in)
3471 yaffs_Tags localTags;
3472 yaffs_Tags *tags = &localTags;
3476 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3479 objId = in->objectId;
3480 fSize = in->variant.fileVariant.fileSize;
3482 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3484 for (chunk = 1; chunk <= nChunks; chunk++) {
3485 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3490 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunk);
3492 if (yaffs_CheckChunkBits
3493 (dev, theChunk / dev->param.nChunksPerBlock,
3494 theChunk % dev->param.nChunksPerBlock)) {
3496 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3500 (tags, in->objectId, chunk, chunkDeleted)) {
3510 /* T(("No level 0 found for %d\n", chunk)); */
3514 return failed ? YAFFS_FAIL : YAFFS_OK;
3519 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
3520 int chunkInNAND, int inScan)
3522 /* NB inScan is zero unless scanning.
3523 * For forward scanning, inScan is > 0;
3524 * for backward scanning inScan is < 0
3526 * chunkInNAND = 0 is a dummy insert to make sure the tnodes are there.
3530 yaffs_Device *dev = in->myDev;
3532 yaffs_ExtendedTags existingTags;
3533 yaffs_ExtendedTags newTags;
3534 unsigned existingSerial, newSerial;
3536 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3537 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3538 * If it is not during Scanning then something went wrong!
3541 T(YAFFS_TRACE_ERROR,
3543 ("yaffs tragedy:attempt to put data chunk into a non-file"
3548 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3552 tn = yaffs_AddOrFindLevel0Tnode(dev,
3553 &in->variant.fileVariant,
3560 /* Dummy insert, bail now */
3563 existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3566 /* If we're scanning then we need to test for duplicates
3567 * NB This does not need to be efficient since it should only ever
3568 * happen when the power fails during a write, then only one
3569 * chunk should ever be affected.
3571 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3572 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3575 if (existingChunk > 0) {
3576 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3577 * thus we have to do a FindChunkInFile to get the real chunk id.
3579 * We have a duplicate now we need to decide which one to use:
3581 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3582 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3583 * YAFFS1: Get both sets of tags and compare serial numbers.
3587 /* Only do this for forward scanning */
3588 yaffs_ReadChunkWithTagsFromNAND(dev,
3592 /* Do a proper find */
3594 yaffs_FindChunkInFile(in, chunkInInode,
3598 if (existingChunk <= 0) {
3599 /*Hoosterman - how did this happen? */
3601 T(YAFFS_TRACE_ERROR,
3603 ("yaffs tragedy: existing chunk < 0 in scan"
3608 /* NB The deleted flags should be false, otherwise the chunks will
3609 * not be loaded during a scan
3613 newSerial = newTags.serialNumber;
3614 existingSerial = existingTags.serialNumber;
3618 (in->myDev->param.isYaffs2 ||
3619 existingChunk <= 0 ||
3620 ((existingSerial + 1) & 3) == newSerial)) {
3621 /* Forward scanning.
3623 * Delete the old one and drop through to update the tnode
3625 yaffs_DeleteChunk(dev, existingChunk, 1,
3628 /* Backward scanning or we want to use the existing one
3630 * Delete the new one and return early so that the tnode isn't changed
3632 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3640 if (existingChunk == 0)
3643 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
3648 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
3651 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3653 if (chunkInNAND >= 0)
3654 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3657 T(YAFFS_TRACE_NANDACCESS,
3658 (TSTR("Chunk %d not found zero instead" TENDSTR),
3660 /* get sane (zero) data if you read a hole */
3661 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3667 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
3671 yaffs_ExtendedTags tags;
3672 yaffs_BlockInfo *bi;
3678 block = chunkId / dev->param.nChunksPerBlock;
3679 page = chunkId % dev->param.nChunksPerBlock;
3682 if (!yaffs_CheckChunkBit(dev, block, page))
3683 T(YAFFS_TRACE_VERIFY,
3684 (TSTR("Deleting invalid chunk %d"TENDSTR),
3687 bi = yaffs_GetBlockInfo(dev, block);
3689 T(YAFFS_TRACE_DELETION,
3690 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3693 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->param.isYaffs2) {
3695 yaffs_InitialiseTags(&tags);
3697 tags.chunkDeleted = 1;
3699 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3700 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3702 dev->nUnmarkedDeletions++;
3705 /* Pull out of the management area.
3706 * If the whole block became dirty, this will kick off an erasure.
3708 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3709 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3710 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3711 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3714 yaffs_ClearChunkBit(dev, block, page);
3718 if (bi->pagesInUse == 0 &&
3719 !bi->hasShrinkHeader &&
3720 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3721 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3722 yaffs_BlockBecameDirty(dev, block);
3729 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
3730 const __u8 *buffer, int nBytes,
3733 /* Find old chunk Need to do this to get serial number
3734 * Write new one and patch into tree.
3735 * Invalidate old tags.
3739 yaffs_ExtendedTags prevTags;
3742 yaffs_ExtendedTags newTags;
3744 yaffs_Device *dev = in->myDev;
3746 yaffs_CheckGarbageCollection(dev);
3748 /* Get the previous chunk at this location in the file if it exists.
3749 * If it does not exist then put a zero into the tree. This creates
3750 * the tnode now, rather than later when it is harder to clean up.
3752 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3753 if(prevChunkId <= 0 &&
3754 !yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0)){
3757 /* Set up new tags */
3758 yaffs_InitialiseTags(&newTags);
3760 newTags.chunkId = chunkInInode;
3761 newTags.objectId = in->objectId;
3762 newTags.serialNumber =
3763 (prevChunkId > 0) ? prevTags.serialNumber + 1 : 1;
3764 newTags.byteCount = nBytes;
3766 if (nBytes < 1 || nBytes > dev->param.totalBytesPerChunk) {
3767 T(YAFFS_TRACE_ERROR,
3768 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3773 * If there isn't already a chunk there then do a dummy
3774 * insert to make sue we have the desired tnode structure.
3776 if(prevChunkId < 1 &&
3777 yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0) != YAFFS_OK)
3781 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3784 if (newChunkId > 0) {
3785 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3787 if (prevChunkId > 0)
3788 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3790 yaffs_CheckFileSanity(in);
3796 /* UpdateObjectHeader updates the header on NAND for an object.
3797 * If name is not NULL, then that new name is used.
3799 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
3800 int isShrink, int shadows)
3803 yaffs_BlockInfo *bi;
3805 yaffs_Device *dev = in->myDev;
3812 yaffs_ExtendedTags newTags;
3813 yaffs_ExtendedTags oldTags;
3814 YCHAR *alias = NULL;
3816 __u8 *buffer = NULL;
3817 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3819 yaffs_ObjectHeader *oh = NULL;
3821 yaffs_strcpy(oldName, _Y("silly old name"));
3825 in == dev->rootDir || /* The rootDir should also be saved */
3828 yaffs_CheckGarbageCollection(dev);
3829 yaffs_CheckObjectDetailsLoaded(in);
3831 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3832 oh = (yaffs_ObjectHeader *) buffer;
3834 prevChunkId = in->hdrChunk;
3836 if (prevChunkId > 0) {
3837 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3840 yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
3842 memcpy(oldName, oh->name, sizeof(oh->name));
3845 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3847 oh->type = in->variantType;
3848 oh->yst_mode = in->yst_mode;
3849 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3851 #ifdef CONFIG_YAFFS_WINCE
3852 oh->win_atime[0] = in->win_atime[0];
3853 oh->win_ctime[0] = in->win_ctime[0];
3854 oh->win_mtime[0] = in->win_mtime[0];
3855 oh->win_atime[1] = in->win_atime[1];
3856 oh->win_ctime[1] = in->win_ctime[1];
3857 oh->win_mtime[1] = in->win_mtime[1];
3859 oh->yst_uid = in->yst_uid;
3860 oh->yst_gid = in->yst_gid;
3861 oh->yst_atime = in->yst_atime;
3862 oh->yst_mtime = in->yst_mtime;
3863 oh->yst_ctime = in->yst_ctime;
3864 oh->yst_rdev = in->yst_rdev;
3867 oh->parentObjectId = in->parent->objectId;
3869 oh->parentObjectId = 0;
3871 if (name && *name) {
3872 memset(oh->name, 0, sizeof(oh->name));
3873 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3874 } else if (prevChunkId > 0)
3875 memcpy(oh->name, oldName, sizeof(oh->name));
3877 memset(oh->name, 0, sizeof(oh->name));
3879 oh->isShrink = isShrink;
3881 switch (in->variantType) {
3882 case YAFFS_OBJECT_TYPE_UNKNOWN:
3883 /* Should not happen */
3885 case YAFFS_OBJECT_TYPE_FILE:
3887 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3888 || oh->parentObjectId ==
3889 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3890 fileVariant.fileSize;
3892 case YAFFS_OBJECT_TYPE_HARDLINK:
3893 oh->equivalentObjectId =
3894 in->variant.hardLinkVariant.equivalentObjectId;
3896 case YAFFS_OBJECT_TYPE_SPECIAL:
3899 case YAFFS_OBJECT_TYPE_DIRECTORY:
3902 case YAFFS_OBJECT_TYPE_SYMLINK:
3903 alias = in->variant.symLinkVariant.alias;
3905 alias = _Y("no alias");
3906 yaffs_strncpy(oh->alias,
3908 YAFFS_MAX_ALIAS_LENGTH);
3909 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3914 yaffs_InitialiseTags(&newTags);
3916 newTags.chunkId = 0;
3917 newTags.objectId = in->objectId;
3918 newTags.serialNumber = in->serial;
3920 /* Add extra info for file header */
3922 newTags.extraHeaderInfoAvailable = 1;
3923 newTags.extraParentObjectId = oh->parentObjectId;
3924 newTags.extraFileLength = oh->fileSize;
3925 newTags.extraIsShrinkHeader = oh->isShrink;
3926 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3927 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3928 newTags.extraObjectType = in->variantType;
3930 yaffs_VerifyObjectHeader(in, oh, &newTags, 1);
3932 /* Create new chunk in NAND */
3934 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3935 (prevChunkId > 0) ? 1 : 0);
3937 if (newChunkId >= 0) {
3939 in->hdrChunk = newChunkId;
3941 if (prevChunkId > 0) {
3942 yaffs_DeleteChunk(dev, prevChunkId, 1,
3946 if (!yaffs_ObjectHasCachedWriteData(in))
3949 /* If this was a shrink, then mark the block that the chunk lives on */
3951 bi = yaffs_GetBlockInfo(in->myDev,
3952 newChunkId / in->myDev->param.nChunksPerBlock);
3953 bi->hasShrinkHeader = 1;
3958 retVal = newChunkId;
3963 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3968 /*------------------------ Short Operations Cache ----------------------------------------
3969 * In many situations where there is no high level buffering (eg WinCE) a lot of
3970 * reads might be short sequential reads, and a lot of writes may be short
3971 * sequential writes. eg. scanning/writing a jpeg file.
3972 * In these cases, a short read/write cache can provide a huge perfomance benefit
3973 * with dumb-as-a-rock code.
3974 * In Linux, the page cache provides read buffering aand the short op cache provides write
3977 * There are a limited number (~10) of cache chunks per device so that we don't
3978 * need a very intelligent search.
3981 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3983 yaffs_Device *dev = obj->myDev;
3985 yaffs_ChunkCache *cache;
3986 int nCaches = obj->myDev->param.nShortOpCaches;
3988 for (i = 0; i < nCaches; i++) {
3989 cache = &dev->srCache[i];
3990 if (cache->object == obj &&
3999 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
4001 yaffs_Device *dev = obj->myDev;
4002 int lowest = -99; /* Stop compiler whining. */
4004 yaffs_ChunkCache *cache;
4005 int chunkWritten = 0;
4006 int nCaches = obj->myDev->param.nShortOpCaches;
4012 /* Find the dirty cache for this object with the lowest chunk id. */
4013 for (i = 0; i < nCaches; i++) {
4014 if (dev->srCache[i].object == obj &&
4015 dev->srCache[i].dirty) {
4017 || dev->srCache[i].chunkId <
4019 cache = &dev->srCache[i];
4020 lowest = cache->chunkId;
4025 if (cache && !cache->locked) {
4026 /* Write it out and free it up */
4029 yaffs_WriteChunkDataToObject(cache->object,
4035 cache->object = NULL;
4038 } while (cache && chunkWritten > 0);
4041 /* Hoosterman, disk full while writing cache out. */
4042 T(YAFFS_TRACE_ERROR,
4043 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
4050 /*yaffs_FlushEntireDeviceCache(dev)
4055 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
4058 int nCaches = dev->param.nShortOpCaches;
4061 /* Find a dirty object in the cache and flush it...
4062 * until there are no further dirty objects.
4066 for (i = 0; i < nCaches && !obj; i++) {
4067 if (dev->srCache[i].object &&
4068 dev->srCache[i].dirty)
4069 obj = dev->srCache[i].object;
4073 yaffs_FlushFilesChunkCache(obj);
4080 /* Grab us a cache chunk for use.
4081 * First look for an empty one.
4082 * Then look for the least recently used non-dirty one.
4083 * Then look for the least recently used dirty one...., flush and look again.
4085 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
4089 if (dev->param.nShortOpCaches > 0) {
4090 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4091 if (!dev->srCache[i].object)
4092 return &dev->srCache[i];
4099 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
4101 yaffs_ChunkCache *cache;
4102 yaffs_Object *theObj;
4107 if (dev->param.nShortOpCaches > 0) {
4108 /* Try find a non-dirty one... */
4110 cache = yaffs_GrabChunkCacheWorker(dev);
4113 /* They were all dirty, find the last recently used object and flush
4114 * its cache, then find again.
4115 * NB what's here is not very accurate, we actually flush the object
4116 * the last recently used page.
4119 /* With locking we can't assume we can use entry zero */
4126 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4127 if (dev->srCache[i].object &&
4128 !dev->srCache[i].locked &&
4129 (dev->srCache[i].lastUse < usage || !cache)) {
4130 usage = dev->srCache[i].lastUse;
4131 theObj = dev->srCache[i].object;
4132 cache = &dev->srCache[i];
4137 if (!cache || cache->dirty) {
4138 /* Flush and try again */
4139 yaffs_FlushFilesChunkCache(theObj);
4140 cache = yaffs_GrabChunkCacheWorker(dev);
4150 /* Find a cached chunk */
4151 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj,
4154 yaffs_Device *dev = obj->myDev;
4156 if (dev->param.nShortOpCaches > 0) {
4157 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4158 if (dev->srCache[i].object == obj &&
4159 dev->srCache[i].chunkId == chunkId) {
4162 return &dev->srCache[i];
4169 /* Mark the chunk for the least recently used algorithym */
4170 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache,
4174 if (dev->param.nShortOpCaches > 0) {
4175 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4176 /* Reset the cache usages */
4178 for (i = 1; i < dev->param.nShortOpCaches; i++)
4179 dev->srCache[i].lastUse = 0;
4186 cache->lastUse = dev->srLastUse;
4193 /* Invalidate a single cache page.
4194 * Do this when a whole page gets written,
4195 * ie the short cache for this page is no longer valid.
4197 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
4199 if (object->myDev->param.nShortOpCaches > 0) {
4200 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4203 cache->object = NULL;
4207 /* Invalidate all the cache pages associated with this object
4208 * Do this whenever ther file is deleted or resized.
4210 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
4213 yaffs_Device *dev = in->myDev;
4215 if (dev->param.nShortOpCaches > 0) {
4216 /* Invalidate it. */
4217 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4218 if (dev->srCache[i].object == in)
4219 dev->srCache[i].object = NULL;
4224 /*--------------------- Checkpointing --------------------*/
4227 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev, int head)
4229 yaffs_CheckpointValidity cp;
4231 memset(&cp, 0, sizeof(cp));
4233 cp.structType = sizeof(cp);
4234 cp.magic = YAFFS_MAGIC;
4235 cp.version = YAFFS_CHECKPOINT_VERSION;
4236 cp.head = (head) ? 1 : 0;
4238 return (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp)) ?
4242 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4244 yaffs_CheckpointValidity cp;
4247 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4250 ok = (cp.structType == sizeof(cp)) &&
4251 (cp.magic == YAFFS_MAGIC) &&
4252 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4253 (cp.head == ((head) ? 1 : 0));
4257 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4260 cp->nErasedBlocks = dev->nErasedBlocks;
4261 cp->allocationBlock = dev->allocationBlock;
4262 cp->allocationPage = dev->allocationPage;
4263 cp->nFreeChunks = dev->nFreeChunks;
4265 cp->nDeletedFiles = dev->nDeletedFiles;
4266 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4267 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4268 cp->sequenceNumber = dev->sequenceNumber;
4269 cp->oldestDirtySequence = dev->oldestDirtySequence;
4273 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4274 yaffs_CheckpointDevice *cp)
4276 dev->nErasedBlocks = cp->nErasedBlocks;
4277 dev->allocationBlock = cp->allocationBlock;
4278 dev->allocationPage = cp->allocationPage;
4279 dev->nFreeChunks = cp->nFreeChunks;
4281 dev->nDeletedFiles = cp->nDeletedFiles;
4282 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4283 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4284 dev->sequenceNumber = cp->sequenceNumber;
4285 dev->oldestDirtySequence = cp->oldestDirtySequence;
4289 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4291 yaffs_CheckpointDevice cp;
4293 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4297 /* Write device runtime values*/
4298 yaffs_DeviceToCheckpointDevice(&cp, dev);
4299 cp.structType = sizeof(cp);
4301 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4303 /* Write block info */
4305 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4306 ok = (yaffs_CheckpointWrite(dev, dev->blockInfo, nBytes) == nBytes);
4309 /* Write chunk bits */
4311 nBytes = nBlocks * dev->chunkBitmapStride;
4312 ok = (yaffs_CheckpointWrite(dev, dev->chunkBits, nBytes) == nBytes);
4318 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4320 yaffs_CheckpointDevice cp;
4322 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4326 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4330 if (cp.structType != sizeof(cp))
4334 yaffs_CheckpointDeviceToDevice(dev, &cp);
4336 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4338 ok = (yaffs_CheckpointRead(dev, dev->blockInfo, nBytes) == nBytes);
4342 nBytes = nBlocks * dev->chunkBitmapStride;
4344 ok = (yaffs_CheckpointRead(dev, dev->chunkBits, nBytes) == nBytes);
4349 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4353 cp->objectId = obj->objectId;
4354 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4355 cp->hdrChunk = obj->hdrChunk;
4356 cp->variantType = obj->variantType;
4357 cp->deleted = obj->deleted;
4358 cp->softDeleted = obj->softDeleted;
4359 cp->unlinked = obj->unlinked;
4360 cp->fake = obj->fake;
4361 cp->renameAllowed = obj->renameAllowed;
4362 cp->unlinkAllowed = obj->unlinkAllowed;
4363 cp->serial = obj->serial;
4364 cp->nDataChunks = obj->nDataChunks;
4366 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4367 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4368 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4369 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4372 static int yaffs_CheckpointObjectToObject(yaffs_Object *obj, yaffs_CheckpointObject *cp)
4375 yaffs_Object *parent;
4377 if (obj->variantType != cp->variantType) {
4378 T(YAFFS_TRACE_ERROR, (TSTR("Checkpoint read object %d type %d "
4379 TCONT("chunk %d does not match existing object type %d")
4380 TENDSTR), cp->objectId, cp->variantType, cp->hdrChunk,
4385 obj->objectId = cp->objectId;
4388 parent = yaffs_FindOrCreateObjectByNumber(
4391 YAFFS_OBJECT_TYPE_DIRECTORY);
4396 if (parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4397 T(YAFFS_TRACE_ALWAYS, (TSTR("Checkpoint read object %d parent %d type %d"
4398 TCONT(" chunk %d Parent type, %d, not directory")
4400 cp->objectId, cp->parentId, cp->variantType,
4401 cp->hdrChunk, parent->variantType));
4404 yaffs_AddObjectToDirectory(parent, obj);
4407 obj->hdrChunk = cp->hdrChunk;
4408 obj->variantType = cp->variantType;
4409 obj->deleted = cp->deleted;
4410 obj->softDeleted = cp->softDeleted;
4411 obj->unlinked = cp->unlinked;
4412 obj->fake = cp->fake;
4413 obj->renameAllowed = cp->renameAllowed;
4414 obj->unlinkAllowed = cp->unlinkAllowed;
4415 obj->serial = cp->serial;
4416 obj->nDataChunks = cp->nDataChunks;
4418 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4419 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4420 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4421 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4423 if (obj->hdrChunk > 0)
4424 obj->lazyLoaded = 1;
4430 static int yaffs_CheckpointTnodeWorker(yaffs_Object *in, yaffs_Tnode *tn,
4431 __u32 level, int chunkOffset)
4434 yaffs_Device *dev = in->myDev;
4436 int tnodeSize = yaffs_CalcTnodeSize(dev);
4441 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
4442 if (tn->internal[i]) {
4443 ok = yaffs_CheckpointTnodeWorker(in,
4446 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4449 } else if (level == 0) {
4450 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4451 ok = (yaffs_CheckpointWrite(dev, &baseOffset, sizeof(baseOffset)) == sizeof(baseOffset));
4453 ok = (yaffs_CheckpointWrite(dev, tn, tnodeSize) == tnodeSize);
4461 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4463 __u32 endMarker = ~0;
4466 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4467 ok = yaffs_CheckpointTnodeWorker(obj,
4468 obj->variant.fileVariant.top,
4469 obj->variant.fileVariant.topLevel,
4472 ok = (yaffs_CheckpointWrite(obj->myDev, &endMarker, sizeof(endMarker)) ==
4479 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4483 yaffs_Device *dev = obj->myDev;
4484 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4487 int tnodeSize = yaffs_CalcTnodeSize(dev);
4489 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4491 while (ok && (~baseChunk)) {
4493 /* Read level 0 tnode */
4496 tn = yaffs_GetTnodeRaw(dev);
4498 ok = (yaffs_CheckpointRead(dev, tn, tnodeSize) == tnodeSize);
4503 ok = yaffs_AddOrFindLevel0Tnode(dev,
4509 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4513 T(YAFFS_TRACE_CHECKPOINT, (
4514 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4515 nread, baseChunk, ok));
4521 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4524 yaffs_CheckpointObject cp;
4527 struct ylist_head *lh;
4530 /* Iterate through the objects in each hash entry,
4531 * dumping them to the checkpointing stream.
4534 for (i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++) {
4535 ylist_for_each(lh, &dev->objectBucket[i].list) {
4537 obj = ylist_entry(lh, yaffs_Object, hashLink);
4538 if (!obj->deferedFree) {
4539 yaffs_ObjectToCheckpointObject(&cp, obj);
4540 cp.structType = sizeof(cp);
4542 T(YAFFS_TRACE_CHECKPOINT, (
4543 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %p" TENDSTR),
4544 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk, obj));
4546 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4548 if (ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4549 ok = yaffs_WriteCheckpointTnodes(obj);
4555 /* Dump end of list */
4556 memset(&cp, 0xFF, sizeof(yaffs_CheckpointObject));
4557 cp.structType = sizeof(cp);
4560 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4565 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4568 yaffs_CheckpointObject cp;
4571 yaffs_Object *hardList = NULL;
4573 while (ok && !done) {
4574 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4575 if (cp.structType != sizeof(cp)) {
4576 T(YAFFS_TRACE_CHECKPOINT, (TSTR("struct size %d instead of %d ok %d"TENDSTR),
4577 cp.structType, (int)sizeof(cp), ok));
4581 T(YAFFS_TRACE_CHECKPOINT, (TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4582 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk));
4584 if (ok && cp.objectId == ~0)
4587 obj = yaffs_FindOrCreateObjectByNumber(dev, cp.objectId, cp.variantType);
4589 ok = yaffs_CheckpointObjectToObject(obj, &cp);
4592 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4593 ok = yaffs_ReadCheckpointTnodes(obj);
4594 } else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4595 obj->hardLinks.next =
4596 (struct ylist_head *) hardList;
4605 yaffs_HardlinkFixup(dev, hardList);
4610 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4612 __u32 checkpointSum;
4615 yaffs_GetCheckpointSum(dev, &checkpointSum);
4617 ok = (yaffs_CheckpointWrite(dev, &checkpointSum, sizeof(checkpointSum)) == sizeof(checkpointSum));
4625 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4627 __u32 checkpointSum0;
4628 __u32 checkpointSum1;
4631 yaffs_GetCheckpointSum(dev, &checkpointSum0);
4633 ok = (yaffs_CheckpointRead(dev, &checkpointSum1, sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4638 if (checkpointSum0 != checkpointSum1)
4645 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4649 if (dev->param.skipCheckpointWrite || !dev->param.isYaffs2) {
4650 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint write" TENDSTR)));
4655 ok = yaffs_CheckpointOpen(dev, 1);
4658 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4659 ok = yaffs_WriteCheckpointValidityMarker(dev, 1);
4662 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint device" TENDSTR)));
4663 ok = yaffs_WriteCheckpointDevice(dev);
4666 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint objects" TENDSTR)));
4667 ok = yaffs_WriteCheckpointObjects(dev);
4670 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4671 ok = yaffs_WriteCheckpointValidityMarker(dev, 0);
4675 ok = yaffs_WriteCheckpointSum(dev);
4677 if (!yaffs_CheckpointClose(dev))
4681 dev->isCheckpointed = 1;
4683 dev->isCheckpointed = 0;
4685 return dev->isCheckpointed;
4688 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4692 if (dev->param.skipCheckpointRead || !dev->param.isYaffs2) {
4693 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint read" TENDSTR)));
4698 ok = yaffs_CheckpointOpen(dev, 0); /* open for read */
4701 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4702 ok = yaffs_ReadCheckpointValidityMarker(dev, 1);
4705 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint device" TENDSTR)));
4706 ok = yaffs_ReadCheckpointDevice(dev);
4709 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint objects" TENDSTR)));
4710 ok = yaffs_ReadCheckpointObjects(dev);
4713 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4714 ok = yaffs_ReadCheckpointValidityMarker(dev, 0);
4718 ok = yaffs_ReadCheckpointSum(dev);
4719 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint checksum %d" TENDSTR), ok));
4722 if (!yaffs_CheckpointClose(dev))
4726 dev->isCheckpointed = 1;
4728 dev->isCheckpointed = 0;
4734 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4736 if (dev->isCheckpointed ||
4737 dev->blocksInCheckpoint > 0) {
4738 dev->isCheckpointed = 0;
4739 yaffs_CheckpointInvalidateStream(dev);
4740 if (dev->param.markSuperBlockDirty)
4741 dev->param.markSuperBlockDirty(dev->context);
4746 int yaffs_CheckpointSave(yaffs_Device *dev)
4749 T(YAFFS_TRACE_CHECKPOINT, (TSTR("save entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4751 yaffs_VerifyObjects(dev);
4752 yaffs_VerifyBlocks(dev);
4753 yaffs_VerifyFreeChunks(dev);
4755 if (!dev->isCheckpointed) {
4756 yaffs_InvalidateCheckpoint(dev);
4757 yaffs_WriteCheckpointData(dev);
4760 T(YAFFS_TRACE_ALWAYS, (TSTR("save exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4762 return dev->isCheckpointed;
4765 int yaffs_CheckpointRestore(yaffs_Device *dev)
4768 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4770 retval = yaffs_ReadCheckpointData(dev);
4772 if (dev->isCheckpointed) {
4773 yaffs_VerifyObjects(dev);
4774 yaffs_VerifyBlocks(dev);
4775 yaffs_VerifyFreeChunks(dev);
4778 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4783 /*--------------------- File read/write ------------------------
4784 * Read and write have very similar structures.
4785 * In general the read/write has three parts to it
4786 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4787 * Some complete chunks
4788 * An incomplete chunk to end off with
4790 * Curve-balls: the first chunk might also be the last chunk.
4793 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 *buffer, loff_t offset,
4802 yaffs_ChunkCache *cache;
4809 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4810 /* start = offset % dev->nDataBytesPerChunk; */
4811 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4814 /* OK now check for the curveball where the start and end are in
4817 if ((start + n) < dev->nDataBytesPerChunk)
4820 nToCopy = dev->nDataBytesPerChunk - start;
4822 cache = yaffs_FindChunkCache(in, chunk);
4824 /* If the chunk is already in the cache or it is less than a whole chunk
4825 * or we're using inband tags then use the cache (if there is caching)
4826 * else bypass the cache.
4828 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
4829 if (dev->param.nShortOpCaches > 0) {
4831 /* If we can't find the data in the cache, then load it up. */
4834 cache = yaffs_GrabChunkCache(in->myDev);
4836 cache->chunkId = chunk;
4839 yaffs_ReadChunkDataFromObject(in, chunk,
4845 yaffs_UseChunkCache(dev, cache, 0);
4850 memcpy(buffer, &cache->data[start], nToCopy);
4854 /* Read into the local buffer then copy..*/
4857 yaffs_GetTempBuffer(dev, __LINE__);
4858 yaffs_ReadChunkDataFromObject(in, chunk,
4861 memcpy(buffer, &localBuffer[start], nToCopy);
4864 yaffs_ReleaseTempBuffer(dev, localBuffer,
4870 /* A full chunk. Read directly into the supplied buffer. */
4871 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4885 int yaffs_WriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
4886 int nBytes, int writeThrough)
4895 int startOfWrite = offset;
4896 int chunkWritten = 0;
4904 while (n > 0 && chunkWritten >= 0) {
4905 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4906 /* start = offset % dev->nDataBytesPerChunk; */
4907 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4909 if (chunk * dev->nDataBytesPerChunk + start != offset ||
4910 start >= dev->nDataBytesPerChunk) {
4911 T(YAFFS_TRACE_ERROR, (
4912 TSTR("AddrToChunk of offset %d gives chunk %d start %d"
4914 (int)offset, chunk, start));
4918 /* OK now check for the curveball where the start and end are in
4922 if ((start + n) < dev->nDataBytesPerChunk) {
4925 /* Now folks, to calculate how many bytes to write back....
4926 * If we're overwriting and not writing to then end of file then
4927 * we need to write back as much as was there before.
4930 chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
4932 if (chunkStart > in->variant.fileVariant.fileSize)
4933 nBytesRead = 0; /* Past end of file */
4935 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
4937 if (nBytesRead > dev->nDataBytesPerChunk)
4938 nBytesRead = dev->nDataBytesPerChunk;
4942 (start + n)) ? nBytesRead : (start + n);
4944 if (nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
4948 nToCopy = dev->nDataBytesPerChunk - start;
4949 nToWriteBack = dev->nDataBytesPerChunk;
4952 if (nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
4953 /* An incomplete start or end chunk (or maybe both start and end chunk),
4954 * or we're using inband tags, so we want to use the cache buffers.
4956 if (dev->param.nShortOpCaches > 0) {
4957 yaffs_ChunkCache *cache;
4958 /* If we can't find the data in the cache, then load the cache */
4959 cache = yaffs_FindChunkCache(in, chunk);
4962 && yaffs_CheckSpaceForAllocation(in->
4964 cache = yaffs_GrabChunkCache(in->myDev);
4966 cache->chunkId = chunk;
4969 yaffs_ReadChunkDataFromObject(in, chunk,
4974 !yaffs_CheckSpaceForAllocation(in->myDev)) {
4975 /* Drop the cache if it was a read cache item and
4976 * no space check has been made for it.
4982 yaffs_UseChunkCache(dev, cache, 1);
4986 memcpy(&cache->data[start], buffer,
4991 cache->nBytes = nToWriteBack;
4995 yaffs_WriteChunkDataToObject
4998 cache->data, cache->nBytes,
5004 chunkWritten = -1; /* fail the write */
5007 /* An incomplete start or end chunk (or maybe both start and end chunk)
5008 * Read into the local buffer then copy, then copy over and write back.
5012 yaffs_GetTempBuffer(dev, __LINE__);
5014 yaffs_ReadChunkDataFromObject(in, chunk,
5019 memcpy(&localBuffer[start], buffer, nToCopy);
5022 yaffs_WriteChunkDataToObject(in, chunk,
5027 yaffs_ReleaseTempBuffer(dev, localBuffer,
5033 /* A full chunk. Write directly from the supplied buffer. */
5038 yaffs_WriteChunkDataToObject(in, chunk, buffer,
5039 dev->nDataBytesPerChunk,
5042 /* Since we've overwritten the cached data, we better invalidate it. */
5043 yaffs_InvalidateChunkCache(in, chunk);
5046 if (chunkWritten >= 0) {
5055 /* Update file object */
5057 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
5058 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
5066 /* ---------------------- File resizing stuff ------------------ */
5068 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
5071 yaffs_Device *dev = in->myDev;
5072 int oldFileSize = in->variant.fileVariant.fileSize;
5074 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
5076 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
5077 dev->nDataBytesPerChunk;
5081 /* Delete backwards so that we don't end up with holes if
5082 * power is lost part-way through the operation.
5084 for (i = lastDel; i >= startDel; i--) {
5085 /* NB this could be optimised somewhat,
5086 * eg. could retrieve the tags and write them without
5087 * using yaffs_DeleteChunk
5090 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5093 (dev->internalStartBlock * dev->param.nChunksPerBlock)
5095 ((dev->internalEndBlock +
5096 1) * dev->param.nChunksPerBlock)) {
5097 T(YAFFS_TRACE_ALWAYS,
5098 (TSTR("Found daft chunkId %d for %d" TENDSTR),
5102 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5109 int yaffs_ResizeFile(yaffs_Object *in, loff_t newSize)
5112 int oldFileSize = in->variant.fileVariant.fileSize;
5113 __u32 newSizeOfPartialChunk;
5116 yaffs_Device *dev = in->myDev;
5118 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5120 yaffs_FlushFilesChunkCache(in);
5121 yaffs_InvalidateWholeChunkCache(in);
5123 yaffs_CheckGarbageCollection(dev);
5125 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
5128 if (newSize == oldFileSize)
5131 if (newSize < oldFileSize) {
5133 yaffs_PruneResizedChunks(in, newSize);
5135 if (newSizeOfPartialChunk != 0) {
5136 int lastChunk = 1 + newFullChunks;
5138 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5140 /* Got to read and rewrite the last chunk with its new size and zero pad */
5141 yaffs_ReadChunkDataFromObject(in, lastChunk,
5144 memset(localBuffer + newSizeOfPartialChunk, 0,
5145 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5147 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5148 newSizeOfPartialChunk, 1);
5150 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5153 in->variant.fileVariant.fileSize = newSize;
5155 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5157 /* newsSize > oldFileSize */
5158 in->variant.fileVariant.fileSize = newSize;
5162 /* Write a new object header to reflect the resize.
5163 * show we've shrunk the file, if need be
5164 * Do this only if the file is not in the deleted directories
5165 * and is not shadowed.
5169 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5170 in->parent->objectId != YAFFS_OBJECTID_DELETED)
5171 yaffs_UpdateObjectHeader(in, NULL, 0,
5172 (newSize < oldFileSize) ? 1 : 0, 0);
5177 loff_t yaffs_GetFileSize(yaffs_Object *obj)
5179 YCHAR *alias = NULL;
5180 obj = yaffs_GetEquivalentObject(obj);
5182 switch (obj->variantType) {
5183 case YAFFS_OBJECT_TYPE_FILE:
5184 return obj->variant.fileVariant.fileSize;
5185 case YAFFS_OBJECT_TYPE_SYMLINK:
5186 alias = obj->variant.symLinkVariant.alias;
5189 return yaffs_strnlen(alias,YAFFS_MAX_ALIAS_LENGTH);
5197 int yaffs_FlushFile(yaffs_Object *in, int updateTime, int dataSync)
5201 yaffs_FlushFilesChunkCache(in);
5202 if(dataSync) /* Only sync data */
5206 #ifdef CONFIG_YAFFS_WINCE
5207 yfsd_WinFileTimeNow(in->win_mtime);
5210 in->yst_mtime = Y_CURRENT_TIME;
5215 retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5216 0) ? YAFFS_OK : YAFFS_FAIL;
5226 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
5229 /* First off, invalidate the file's data in the cache, without flushing. */
5230 yaffs_InvalidateWholeChunkCache(in);
5232 if (in->myDev->param.isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5233 /* Move to the unlinked directory so we have a record that it was deleted. */
5234 yaffs_ChangeObjectName(in, in->myDev->deletedDir, _Y("deleted"), 0, 0);
5238 yaffs_RemoveObjectFromDirectory(in);
5239 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5242 yaffs_FreeObject(in);
5247 /* yaffs_DeleteFile deletes the whole file data
5248 * and the inode associated with the file.
5249 * It does not delete the links associated with the file.
5251 static int yaffs_UnlinkFileIfNeeded(yaffs_Object *in)
5255 int immediateDeletion = 0;
5258 immediateDeletion = 1;
5260 if (immediateDeletion) {
5262 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5263 _Y("deleted"), 0, 0);
5264 T(YAFFS_TRACE_TRACING,
5265 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5268 in->myDev->nDeletedFiles++;
5269 if (1 || in->myDev->param.isYaffs2)
5270 yaffs_ResizeFile(in, 0);
5271 yaffs_SoftDeleteFile(in);
5274 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5275 _Y("unlinked"), 0, 0);
5282 int yaffs_DeleteFile(yaffs_Object *in)
5284 int retVal = YAFFS_OK;
5285 int deleted = in->deleted;
5287 yaffs_ResizeFile(in, 0);
5289 if (in->nDataChunks > 0) {
5290 /* Use soft deletion if there is data in the file.
5291 * That won't be the case if it has been resized to zero.
5294 retVal = yaffs_UnlinkFileIfNeeded(in);
5296 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5299 in->myDev->nDeletedFiles++;
5300 yaffs_SoftDeleteFile(in);
5302 return deleted ? YAFFS_OK : YAFFS_FAIL;
5304 /* The file has no data chunks so we toss it immediately */
5305 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5306 in->variant.fileVariant.top = NULL;
5307 yaffs_DoGenericObjectDeletion(in);
5313 static int yaffs_IsNonEmptyDirectory(yaffs_Object *obj)
5315 return (obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) &&
5316 !(ylist_empty(&obj->variant.directoryVariant.children));
5319 static int yaffs_DeleteDirectory(yaffs_Object *obj)
5321 /* First check that the directory is empty. */
5322 if (yaffs_IsNonEmptyDirectory(obj))
5325 return yaffs_DoGenericObjectDeletion(obj);
5328 static int yaffs_DeleteSymLink(yaffs_Object *in)
5330 if(in->variant.symLinkVariant.alias)
5331 YFREE(in->variant.symLinkVariant.alias);
5332 in->variant.symLinkVariant.alias=NULL;
5334 return yaffs_DoGenericObjectDeletion(in);
5337 static int yaffs_DeleteHardLink(yaffs_Object *in)
5339 /* remove this hardlink from the list assocaited with the equivalent
5342 ylist_del_init(&in->hardLinks);
5343 return yaffs_DoGenericObjectDeletion(in);
5346 int yaffs_DeleteObject(yaffs_Object *obj)
5349 switch (obj->variantType) {
5350 case YAFFS_OBJECT_TYPE_FILE:
5351 retVal = yaffs_DeleteFile(obj);
5353 case YAFFS_OBJECT_TYPE_DIRECTORY:
5354 return yaffs_DeleteDirectory(obj);
5356 case YAFFS_OBJECT_TYPE_SYMLINK:
5357 retVal = yaffs_DeleteSymLink(obj);
5359 case YAFFS_OBJECT_TYPE_HARDLINK:
5360 retVal = yaffs_DeleteHardLink(obj);
5362 case YAFFS_OBJECT_TYPE_SPECIAL:
5363 retVal = yaffs_DoGenericObjectDeletion(obj);
5365 case YAFFS_OBJECT_TYPE_UNKNOWN:
5367 break; /* should not happen. */
5373 static int yaffs_UnlinkWorker(yaffs_Object *obj)
5376 int immediateDeletion = 0;
5379 immediateDeletion = 1;
5382 yaffs_UpdateParent(obj->parent);
5384 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5385 return yaffs_DeleteHardLink(obj);
5386 } else if (!ylist_empty(&obj->hardLinks)) {
5387 /* Curve ball: We're unlinking an object that has a hardlink.
5389 * This problem arises because we are not strictly following
5390 * The Linux link/inode model.
5392 * We can't really delete the object.
5393 * Instead, we do the following:
5394 * - Select a hardlink.
5395 * - Unhook it from the hard links
5396 * - Move it from its parent directory (so that the rename can work)
5397 * - Rename the object to the hardlink's name.
5398 * - Delete the hardlink
5402 yaffs_Object *parent;
5404 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5406 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5408 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5409 parent = hl->parent;
5411 ylist_del_init(&hl->hardLinks);
5413 yaffs_AddObjectToDirectory(obj->myDev->unlinkedDir, hl);
5415 retVal = yaffs_ChangeObjectName(obj,parent, name, 0, 0);
5417 if (retVal == YAFFS_OK)
5418 retVal = yaffs_DoGenericObjectDeletion(hl);
5422 } else if (immediateDeletion) {
5423 switch (obj->variantType) {
5424 case YAFFS_OBJECT_TYPE_FILE:
5425 return yaffs_DeleteFile(obj);
5427 case YAFFS_OBJECT_TYPE_DIRECTORY:
5428 return yaffs_DeleteDirectory(obj);
5430 case YAFFS_OBJECT_TYPE_SYMLINK:
5431 return yaffs_DeleteSymLink(obj);
5433 case YAFFS_OBJECT_TYPE_SPECIAL:
5434 return yaffs_DoGenericObjectDeletion(obj);
5436 case YAFFS_OBJECT_TYPE_HARDLINK:
5437 case YAFFS_OBJECT_TYPE_UNKNOWN:
5441 } else if(yaffs_IsNonEmptyDirectory(obj))
5444 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
5445 _Y("unlinked"), 0, 0);
5449 static int yaffs_UnlinkObject(yaffs_Object *obj)
5452 if (obj && obj->unlinkAllowed)
5453 return yaffs_UnlinkWorker(obj);
5458 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
5462 obj = yaffs_FindObjectByName(dir, name);
5463 return yaffs_UnlinkObject(obj);
5466 /*----------------------- Initialisation Scanning ---------------------- */
5468 static void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
5469 int backwardScanning)
5473 if (!backwardScanning) {
5474 /* Handle YAFFS1 forward scanning case
5475 * For YAFFS1 we always do the deletion
5479 /* Handle YAFFS2 case (backward scanning)
5480 * If the shadowed object exists then ignore.
5482 obj = yaffs_FindObjectByNumber(dev, objId);
5487 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5488 * We put it in unlinked dir to be cleaned up after the scanning
5491 yaffs_FindOrCreateObjectByNumber(dev, objId,
5492 YAFFS_OBJECT_TYPE_FILE);
5495 obj->isShadowed = 1;
5496 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5497 obj->variant.fileVariant.shrinkSize = 0;
5498 obj->valid = 1; /* So that we don't read any other info for this file */
5508 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5515 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5517 in = yaffs_FindObjectByNumber(dev,
5518 hl->variant.hardLinkVariant.
5519 equivalentObjectId);
5522 /* Add the hardlink pointers */
5523 hl->variant.hardLinkVariant.equivalentObject = in;
5524 ylist_add(&hl->hardLinks, &in->hardLinks);
5526 /* Todo Need to report/handle this better.
5527 * Got a problem... hardlink to a non-existant object
5529 hl->variant.hardLinkVariant.equivalentObject = NULL;
5530 YINIT_LIST_HEAD(&hl->hardLinks);
5540 static int ybicmp(const void *a, const void *b)
5542 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5543 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5544 register int ablock = ((yaffs_BlockIndex *)a)->block;
5545 register int bblock = ((yaffs_BlockIndex *)b)->block;
5547 return ablock - bblock;
5553 struct yaffs_ShadowFixerStruct {
5556 struct yaffs_ShadowFixerStruct *next;
5560 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5563 * Sort out state of unlinked and deleted objects after scanning.
5565 struct ylist_head *i;
5566 struct ylist_head *n;
5569 /* Soft delete all the unlinked files */
5570 ylist_for_each_safe(i, n,
5571 &dev->unlinkedDir->variant.directoryVariant.children) {
5573 l = ylist_entry(i, yaffs_Object, siblings);
5574 yaffs_DeleteObject(l);
5578 ylist_for_each_safe(i, n,
5579 &dev->deletedDir->variant.directoryVariant.children) {
5581 l = ylist_entry(i, yaffs_Object, siblings);
5582 yaffs_DeleteObject(l);
5589 * This code iterates through all the objects making sure that they are rooted.
5590 * Any unrooted objects are re-rooted in lost+found.
5591 * An object needs to be in one of:
5592 * - Directly under deleted, unlinked
5593 * - Directly or indirectly under root.
5596 * This code assumes that we don't ever change the current relationships between
5598 * rootDir->parent == unlinkedDir->parent == deletedDir->parent == NULL
5599 * lostNfound->parent == rootDir
5601 * This fixes the problem where directories might have inadvertently been deleted
5602 * leaving the object "hanging" without being rooted in the directory tree.
5605 static int yaffs_HasNULLParent(yaffs_Device *dev, yaffs_Object *obj)
5607 return (obj == dev->deletedDir ||
5608 obj == dev->unlinkedDir||
5609 obj == dev->rootDir);
5612 static void yaffs_FixHangingObjects(yaffs_Device *dev)
5615 yaffs_Object *parent;
5617 struct ylist_head *lh;
5618 struct ylist_head *n;
5623 /* Iterate through the objects in each hash entry,
5624 * looking at each object.
5625 * Make sure it is rooted.
5628 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
5629 ylist_for_each_safe(lh, n, &dev->objectBucket[i].list) {
5631 obj = ylist_entry(lh, yaffs_Object, hashLink);
5632 parent= obj->parent;
5634 if(yaffs_HasNULLParent(dev,obj)){
5635 /* These directories are not hanging */
5638 else if(!parent || parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5640 else if(yaffs_HasNULLParent(dev,parent))
5644 * Need to follow the parent chain to see if it is hanging.
5649 while(parent != dev->rootDir &&
5651 parent->parent->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
5653 parent = parent->parent;
5656 if(parent != dev->rootDir)
5661 (TSTR("Hanging object %d moved to lost and found" TENDSTR),
5663 yaffs_AddObjectToDirectory(dev->lostNFoundDir,obj);
5672 * Delete directory contents for cleaning up lost and found.
5674 static void yaffs_DeleteDirectoryContents(yaffs_Object *dir)
5677 struct ylist_head *lh;
5678 struct ylist_head *n;
5680 if(dir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5683 ylist_for_each_safe(lh, n, &dir->variant.directoryVariant.children) {
5685 obj = ylist_entry(lh, yaffs_Object, siblings);
5686 if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
5687 yaffs_DeleteDirectoryContents(obj);
5690 (TSTR("Deleting lost_found object %d" TENDSTR),
5693 /* Need to use UnlinkObject since Delete would not handle
5694 * hardlinked objects correctly.
5696 yaffs_UnlinkObject(obj);
5702 static void yaffs_EmptyLostAndFound(yaffs_Device *dev)
5704 yaffs_DeleteDirectoryContents(dev->lostNFoundDir);
5707 static int yaffs_Scan(yaffs_Device *dev)
5709 yaffs_ExtendedTags tags;
5719 yaffs_BlockState state;
5720 yaffs_Object *hardList = NULL;
5721 yaffs_BlockInfo *bi;
5722 __u32 sequenceNumber;
5723 yaffs_ObjectHeader *oh;
5725 yaffs_Object *parent;
5727 int alloc_failed = 0;
5729 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5737 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5738 dev->internalStartBlock, dev->internalEndBlock));
5740 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5742 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5744 /* Scan all the blocks to determine their state */
5745 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5746 bi = yaffs_GetBlockInfo(dev, blk);
5747 yaffs_ClearChunkBits(dev, blk);
5749 bi->softDeletions = 0;
5751 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5753 bi->blockState = state;
5754 bi->sequenceNumber = sequenceNumber;
5756 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
5757 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
5759 T(YAFFS_TRACE_SCAN_DEBUG,
5760 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5761 state, sequenceNumber));
5763 if (state == YAFFS_BLOCK_STATE_DEAD) {
5764 T(YAFFS_TRACE_BAD_BLOCKS,
5765 (TSTR("block %d is bad" TENDSTR), blk));
5766 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5767 T(YAFFS_TRACE_SCAN_DEBUG,
5768 (TSTR("Block empty " TENDSTR)));
5769 dev->nErasedBlocks++;
5770 dev->nFreeChunks += dev->param.nChunksPerBlock;
5774 startIterator = dev->internalStartBlock;
5775 endIterator = dev->internalEndBlock;
5777 /* For each block.... */
5778 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5785 blk = blockIterator;
5787 bi = yaffs_GetBlockInfo(dev, blk);
5788 state = bi->blockState;
5792 /* For each chunk in each block that needs scanning....*/
5793 for (c = 0; !alloc_failed && c < dev->param.nChunksPerBlock &&
5794 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5795 /* Read the tags and decide what to do */
5796 chunk = blk * dev->param.nChunksPerBlock + c;
5798 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5801 /* Let's have a good look at this chunk... */
5803 if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
5809 /*T((" %d %d deleted\n",blk,c)); */
5810 } else if (!tags.chunkUsed) {
5811 /* An unassigned chunk in the block
5812 * This means that either the block is empty or
5813 * this is the one being allocated from
5817 /* We're looking at the first chunk in the block so the block is unused */
5818 state = YAFFS_BLOCK_STATE_EMPTY;
5819 dev->nErasedBlocks++;
5821 /* this is the block being allocated from */
5824 (" Allocating from %d %d" TENDSTR),
5826 state = YAFFS_BLOCK_STATE_ALLOCATING;
5827 dev->allocationBlock = blk;
5828 dev->allocationPage = c;
5829 dev->allocationBlockFinder = blk;
5830 /* Set block finder here to encourage the allocator to go forth from here. */
5834 dev->nFreeChunks += (dev->param.nChunksPerBlock - c);
5835 } else if (tags.chunkId > 0) {
5836 /* chunkId > 0 so it is a data chunk... */
5837 unsigned int endpos;
5839 yaffs_SetChunkBit(dev, blk, c);
5842 in = yaffs_FindOrCreateObjectByNumber(dev,
5845 YAFFS_OBJECT_TYPE_FILE);
5846 /* PutChunkIntoFile checks for a clash (two data chunks with
5847 * the same chunkId).
5854 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, 1))
5859 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5862 in->variantType == YAFFS_OBJECT_TYPE_FILE
5863 && in->variant.fileVariant.scannedFileSize <
5865 in->variant.fileVariant.
5866 scannedFileSize = endpos;
5867 if (!dev->param.useHeaderFileSize) {
5868 in->variant.fileVariant.
5870 in->variant.fileVariant.
5875 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
5877 /* chunkId == 0, so it is an ObjectHeader.
5878 * Thus, we read in the object header and make the object
5880 yaffs_SetChunkBit(dev, blk, c);
5883 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5887 oh = (yaffs_ObjectHeader *) chunkData;
5889 in = yaffs_FindObjectByNumber(dev,
5891 if (in && in->variantType != oh->type) {
5892 /* This should not happen, but somehow
5893 * Wev'e ended up with an objectId that has been reused but not yet
5894 * deleted, and worse still it has changed type. Delete the old object.
5897 yaffs_DeleteObject(in);
5902 in = yaffs_FindOrCreateObjectByNumber(dev,
5910 if (in && oh->shadowsObject > 0) {
5912 struct yaffs_ShadowFixerStruct *fixer;
5913 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
5915 fixer->next = shadowFixerList;
5916 shadowFixerList = fixer;
5917 fixer->objectId = tags.objectId;
5918 fixer->shadowedId = oh->shadowsObject;
5923 if (in && in->valid) {
5924 /* We have already filled this one. We have a duplicate and need to resolve it. */
5926 unsigned existingSerial = in->serial;
5927 unsigned newSerial = tags.serialNumber;
5929 if (((existingSerial + 1) & 3) == newSerial) {
5930 /* Use new one - destroy the exisiting one */
5931 yaffs_DeleteChunk(dev,
5936 /* Use existing - destroy this one. */
5937 yaffs_DeleteChunk(dev, chunk, 1,
5942 if (in && !in->valid &&
5943 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5944 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5945 /* We only load some info, don't fiddle with directory structure */
5947 in->variantType = oh->type;
5949 in->yst_mode = oh->yst_mode;
5950 #ifdef CONFIG_YAFFS_WINCE
5951 in->win_atime[0] = oh->win_atime[0];
5952 in->win_ctime[0] = oh->win_ctime[0];
5953 in->win_mtime[0] = oh->win_mtime[0];
5954 in->win_atime[1] = oh->win_atime[1];
5955 in->win_ctime[1] = oh->win_ctime[1];
5956 in->win_mtime[1] = oh->win_mtime[1];
5958 in->yst_uid = oh->yst_uid;
5959 in->yst_gid = oh->yst_gid;
5960 in->yst_atime = oh->yst_atime;
5961 in->yst_mtime = oh->yst_mtime;
5962 in->yst_ctime = oh->yst_ctime;
5963 in->yst_rdev = oh->yst_rdev;
5965 in->hdrChunk = chunk;
5966 in->serial = tags.serialNumber;
5968 } else if (in && !in->valid) {
5969 /* we need to load this info */
5972 in->variantType = oh->type;
5974 in->yst_mode = oh->yst_mode;
5975 #ifdef CONFIG_YAFFS_WINCE
5976 in->win_atime[0] = oh->win_atime[0];
5977 in->win_ctime[0] = oh->win_ctime[0];
5978 in->win_mtime[0] = oh->win_mtime[0];
5979 in->win_atime[1] = oh->win_atime[1];
5980 in->win_ctime[1] = oh->win_ctime[1];
5981 in->win_mtime[1] = oh->win_mtime[1];
5983 in->yst_uid = oh->yst_uid;
5984 in->yst_gid = oh->yst_gid;
5985 in->yst_atime = oh->yst_atime;
5986 in->yst_mtime = oh->yst_mtime;
5987 in->yst_ctime = oh->yst_ctime;
5988 in->yst_rdev = oh->yst_rdev;
5990 in->hdrChunk = chunk;
5991 in->serial = tags.serialNumber;
5993 yaffs_SetObjectName(in, oh->name);
5996 /* directory stuff...
6001 yaffs_FindOrCreateObjectByNumber
6002 (dev, oh->parentObjectId,
6003 YAFFS_OBJECT_TYPE_DIRECTORY);
6006 if (parent && parent->variantType ==
6007 YAFFS_OBJECT_TYPE_UNKNOWN) {
6008 /* Set up as a directory */
6009 parent->variantType =
6010 YAFFS_OBJECT_TYPE_DIRECTORY;
6011 YINIT_LIST_HEAD(&parent->variant.
6014 } else if (!parent || parent->variantType !=
6015 YAFFS_OBJECT_TYPE_DIRECTORY) {
6016 /* Hoosterman, another problem....
6017 * We're trying to use a non-directory as a directory
6020 T(YAFFS_TRACE_ERROR,
6022 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6024 parent = dev->lostNFoundDir;
6027 yaffs_AddObjectToDirectory(parent, in);
6029 if (0 && (parent == dev->deletedDir ||
6030 parent == dev->unlinkedDir)) {
6031 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
6032 dev->nDeletedFiles++;
6034 /* Note re hardlinks.
6035 * Since we might scan a hardlink before its equivalent object is scanned
6036 * we put them all in a list.
6037 * After scanning is complete, we should have all the objects, so we run through this
6038 * list and fix up all the chains.
6041 switch (in->variantType) {
6042 case YAFFS_OBJECT_TYPE_UNKNOWN:
6043 /* Todo got a problem */
6045 case YAFFS_OBJECT_TYPE_FILE:
6046 if (dev->param.useHeaderFileSize)
6048 in->variant.fileVariant.
6053 case YAFFS_OBJECT_TYPE_HARDLINK:
6054 in->variant.hardLinkVariant.
6055 equivalentObjectId =
6056 oh->equivalentObjectId;
6057 in->hardLinks.next =
6058 (struct ylist_head *)
6062 case YAFFS_OBJECT_TYPE_DIRECTORY:
6065 case YAFFS_OBJECT_TYPE_SPECIAL:
6068 case YAFFS_OBJECT_TYPE_SYMLINK:
6069 in->variant.symLinkVariant.alias =
6070 yaffs_CloneString(oh->alias);
6071 if (!in->variant.symLinkVariant.alias)
6080 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6081 /* If we got this far while scanning, then the block is fully allocated.*/
6082 state = YAFFS_BLOCK_STATE_FULL;
6085 if (state == YAFFS_BLOCK_STATE_ALLOCATING) {
6086 /* If the block was partially allocated then treat it as fully allocated.*/
6087 state = YAFFS_BLOCK_STATE_FULL;
6088 dev->allocationBlock = -1;
6091 bi->blockState = state;
6093 /* Now let's see if it was dirty */
6094 if (bi->pagesInUse == 0 &&
6095 !bi->hasShrinkHeader &&
6096 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6097 yaffs_BlockBecameDirty(dev, blk);
6103 /* Ok, we've done all the scanning.
6104 * Fix up the hard link chains.
6105 * We should now have scanned all the objects, now it's time to add these
6109 yaffs_HardlinkFixup(dev, hardList);
6111 /* Fix up any shadowed objects */
6113 struct yaffs_ShadowFixerStruct *fixer;
6116 while (shadowFixerList) {
6117 fixer = shadowFixerList;
6118 shadowFixerList = fixer->next;
6119 /* Complete the rename transaction by deleting the shadowed object
6120 * then setting the object header to unshadowed.
6122 obj = yaffs_FindObjectByNumber(dev, fixer->shadowedId);
6124 yaffs_DeleteObject(obj);
6126 obj = yaffs_FindObjectByNumber(dev, fixer->objectId);
6129 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6135 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6140 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
6146 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
6149 yaffs_ObjectHeader *oh;
6151 yaffs_ExtendedTags tags;
6153 int alloc_failed = 0;
6161 T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
6163 in->lazyLoaded ? "not yet" : "already"));
6166 if (in->lazyLoaded && in->hdrChunk > 0) {
6168 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6170 result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
6171 oh = (yaffs_ObjectHeader *) chunkData;
6173 in->yst_mode = oh->yst_mode;
6174 #ifdef CONFIG_YAFFS_WINCE
6175 in->win_atime[0] = oh->win_atime[0];
6176 in->win_ctime[0] = oh->win_ctime[0];
6177 in->win_mtime[0] = oh->win_mtime[0];
6178 in->win_atime[1] = oh->win_atime[1];
6179 in->win_ctime[1] = oh->win_ctime[1];
6180 in->win_mtime[1] = oh->win_mtime[1];
6182 in->yst_uid = oh->yst_uid;
6183 in->yst_gid = oh->yst_gid;
6184 in->yst_atime = oh->yst_atime;
6185 in->yst_mtime = oh->yst_mtime;
6186 in->yst_ctime = oh->yst_ctime;
6187 in->yst_rdev = oh->yst_rdev;
6190 yaffs_SetObjectName(in, oh->name);
6192 if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6193 in->variant.symLinkVariant.alias =
6194 yaffs_CloneString(oh->alias);
6195 if (!in->variant.symLinkVariant.alias)
6196 alloc_failed = 1; /* Not returned to caller */
6199 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6203 static int yaffs_ScanBackwards(yaffs_Device *dev)
6205 yaffs_ExtendedTags tags;
6210 int nBlocksToScan = 0;
6216 yaffs_BlockState state;
6217 yaffs_Object *hardList = NULL;
6218 yaffs_BlockInfo *bi;
6219 __u32 sequenceNumber;
6220 yaffs_ObjectHeader *oh;
6222 yaffs_Object *parent;
6223 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6229 int foundChunksInBlock;
6230 int equivalentObjectId;
6231 int alloc_failed = 0;
6234 yaffs_BlockIndex *blockIndex = NULL;
6235 int altBlockIndex = 0;
6237 if (!dev->param.isYaffs2) {
6239 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6245 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
6246 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6249 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6251 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6254 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6260 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6264 dev->blocksInCheckpoint = 0;
6266 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6268 /* Scan all the blocks to determine their state */
6269 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6270 bi = yaffs_GetBlockInfo(dev, blk);
6271 yaffs_ClearChunkBits(dev, blk);
6273 bi->softDeletions = 0;
6275 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6277 bi->blockState = state;
6278 bi->sequenceNumber = sequenceNumber;
6280 if (bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6281 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6282 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6283 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6285 T(YAFFS_TRACE_SCAN_DEBUG,
6286 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6287 state, sequenceNumber));
6290 if (state == YAFFS_BLOCK_STATE_CHECKPOINT) {
6291 dev->blocksInCheckpoint++;
6293 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6294 T(YAFFS_TRACE_BAD_BLOCKS,
6295 (TSTR("block %d is bad" TENDSTR), blk));
6296 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6297 T(YAFFS_TRACE_SCAN_DEBUG,
6298 (TSTR("Block empty " TENDSTR)));
6299 dev->nErasedBlocks++;
6300 dev->nFreeChunks += dev->param.nChunksPerBlock;
6301 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6303 /* Determine the highest sequence number */
6304 if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6305 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6307 blockIndex[nBlocksToScan].seq = sequenceNumber;
6308 blockIndex[nBlocksToScan].block = blk;
6312 if (sequenceNumber >= dev->sequenceNumber)
6313 dev->sequenceNumber = sequenceNumber;
6315 /* TODO: Nasty sequence number! */
6318 ("Block scanning block %d has bad sequence number %d"
6319 TENDSTR), blk, sequenceNumber));
6326 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6332 /* Sort the blocks */
6333 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6335 /* Use qsort now. */
6336 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6340 /* Dungy old bubble sort... */
6342 yaffs_BlockIndex temp;
6346 for (i = 0; i < nBlocksToScan; i++)
6347 for (j = i + 1; j < nBlocksToScan; j++)
6348 if (blockIndex[i].seq > blockIndex[j].seq) {
6349 temp = blockIndex[j];
6350 blockIndex[j] = blockIndex[i];
6351 blockIndex[i] = temp;
6358 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6360 /* Now scan the blocks looking at the data. */
6362 endIterator = nBlocksToScan - 1;
6363 T(YAFFS_TRACE_SCAN_DEBUG,
6364 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6366 /* For each block.... backwards */
6367 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6369 /* Cooperative multitasking! This loop can run for so
6370 long that watchdog timers expire. */
6373 /* get the block to scan in the correct order */
6374 blk = blockIndex[blockIterator].block;
6376 bi = yaffs_GetBlockInfo(dev, blk);
6379 state = bi->blockState;
6383 /* For each chunk in each block that needs scanning.... */
6384 foundChunksInBlock = 0;
6385 for (c = dev->param.nChunksPerBlock - 1;
6386 !alloc_failed && c >= 0 &&
6387 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6388 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6389 /* Scan backwards...
6390 * Read the tags and decide what to do
6393 chunk = blk * dev->param.nChunksPerBlock + c;
6395 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6398 /* Let's have a good look at this chunk... */
6400 if (!tags.chunkUsed) {
6401 /* An unassigned chunk in the block.
6402 * If there are used chunks after this one, then
6403 * it is a chunk that was skipped due to failing the erased
6404 * check. Just skip it so that it can be deleted.
6405 * But, more typically, We get here when this is an unallocated
6406 * chunk and his means that either the block is empty or
6407 * this is the one being allocated from
6410 if (foundChunksInBlock) {
6411 /* This is a chunk that was skipped due to failing the erased check */
6412 } else if (c == 0) {
6413 /* We're looking at the first chunk in the block so the block is unused */
6414 state = YAFFS_BLOCK_STATE_EMPTY;
6415 dev->nErasedBlocks++;
6417 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6418 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6419 if (dev->sequenceNumber == bi->sequenceNumber) {
6420 /* this is the block being allocated from */
6424 (" Allocating from %d %d"
6427 state = YAFFS_BLOCK_STATE_ALLOCATING;
6428 dev->allocationBlock = blk;
6429 dev->allocationPage = c;
6430 dev->allocationBlockFinder = blk;
6432 /* This is a partially written block that is not
6433 * the current allocation block.
6436 T(YAFFS_TRACE_ALWAYS,
6437 (TSTR("Partially written block %d detected" TENDSTR),
6445 } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED) {
6447 (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
6452 } else if (tags.chunkId > 0) {
6453 /* chunkId > 0 so it is a data chunk... */
6454 unsigned int endpos;
6456 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6458 foundChunksInBlock = 1;
6461 yaffs_SetChunkBit(dev, blk, c);
6464 in = yaffs_FindOrCreateObjectByNumber(dev,
6467 YAFFS_OBJECT_TYPE_FILE);
6474 in->variantType == YAFFS_OBJECT_TYPE_FILE
6476 in->variant.fileVariant.shrinkSize) {
6477 /* This has not been invalidated by a resize */
6478 if (!yaffs_PutChunkIntoFile(in, tags.chunkId,
6483 /* File size is calculated by looking at the data chunks if we have not
6484 * seen an object header yet. Stop this practice once we find an object header.
6488 1) * dev->nDataBytesPerChunk +
6491 if (!in->valid && /* have not got an object header yet */
6492 in->variant.fileVariant.
6493 scannedFileSize < endpos) {
6494 in->variant.fileVariant.
6495 scannedFileSize = endpos;
6496 in->variant.fileVariant.
6498 in->variant.fileVariant.
6503 /* This chunk has been invalidated by a resize, so delete */
6504 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6508 /* chunkId == 0, so it is an ObjectHeader.
6509 * Thus, we read in the object header and make the object
6511 foundChunksInBlock = 1;
6513 yaffs_SetChunkBit(dev, blk, c);
6519 if (tags.extraHeaderInfoAvailable) {
6520 in = yaffs_FindOrCreateObjectByNumber
6521 (dev, tags.objectId,
6522 tags.extraObjectType);
6528 (!in->valid && dev->param.disableLazyLoad) ||
6529 tags.extraShadows ||
6531 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6532 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))) {
6534 /* If we don't have valid info then we need to read the chunk
6535 * TODO In future we can probably defer reading the chunk and
6536 * living with invalid data until needed.
6539 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6544 oh = (yaffs_ObjectHeader *) chunkData;
6546 if (dev->param.inbandTags) {
6547 /* Fix up the header if they got corrupted by inband tags */
6548 oh->shadowsObject = oh->inbandShadowsObject;
6549 oh->isShrink = oh->inbandIsShrink;
6553 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6561 /* TODO Hoosterman we have a problem! */
6562 T(YAFFS_TRACE_ERROR,
6564 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6565 TENDSTR), tags.objectId, chunk));
6570 /* We have already filled this one.
6571 * We have a duplicate that will be discarded, but
6572 * we first have to suck out resize info if it is a file.
6575 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6577 oh->type == YAFFS_OBJECT_TYPE_FILE) ||
6578 (tags.extraHeaderInfoAvailable &&
6579 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))) {
6581 (oh) ? oh->fileSize : tags.
6583 __u32 parentObjectId =
6585 parentObjectId : tags.
6586 extraParentObjectId;
6590 (oh) ? oh->isShrink : tags.
6591 extraIsShrinkHeader;
6593 /* If it is deleted (unlinked at start also means deleted)
6594 * we treat the file size as being zeroed at this point.
6596 if (parentObjectId ==
6597 YAFFS_OBJECTID_DELETED
6598 || parentObjectId ==
6599 YAFFS_OBJECTID_UNLINKED) {
6605 in->variant.fileVariant.
6606 shrinkSize > thisSize) {
6607 in->variant.fileVariant.
6613 bi->hasShrinkHeader = 1;
6616 /* Use existing - destroy this one. */
6617 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6621 if (!in->valid && in->variantType !=
6622 (oh ? oh->type : tags.extraObjectType))
6623 T(YAFFS_TRACE_ERROR, (
6624 TSTR("yaffs tragedy: Bad object type, "
6625 TCONT("%d != %d, for object %d at chunk ")
6626 TCONT("%d during scan")
6628 oh->type : tags.extraObjectType,
6629 in->variantType, tags.objectId,
6633 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6635 YAFFS_OBJECTID_LOSTNFOUND)) {
6636 /* We only load some info, don't fiddle with directory structure */
6640 in->variantType = oh->type;
6642 in->yst_mode = oh->yst_mode;
6643 #ifdef CONFIG_YAFFS_WINCE
6644 in->win_atime[0] = oh->win_atime[0];
6645 in->win_ctime[0] = oh->win_ctime[0];
6646 in->win_mtime[0] = oh->win_mtime[0];
6647 in->win_atime[1] = oh->win_atime[1];
6648 in->win_ctime[1] = oh->win_ctime[1];
6649 in->win_mtime[1] = oh->win_mtime[1];
6651 in->yst_uid = oh->yst_uid;
6652 in->yst_gid = oh->yst_gid;
6653 in->yst_atime = oh->yst_atime;
6654 in->yst_mtime = oh->yst_mtime;
6655 in->yst_ctime = oh->yst_ctime;
6656 in->yst_rdev = oh->yst_rdev;
6660 in->variantType = tags.extraObjectType;
6664 in->hdrChunk = chunk;
6666 } else if (!in->valid) {
6667 /* we need to load this info */
6670 in->hdrChunk = chunk;
6673 in->variantType = oh->type;
6675 in->yst_mode = oh->yst_mode;
6676 #ifdef CONFIG_YAFFS_WINCE
6677 in->win_atime[0] = oh->win_atime[0];
6678 in->win_ctime[0] = oh->win_ctime[0];
6679 in->win_mtime[0] = oh->win_mtime[0];
6680 in->win_atime[1] = oh->win_atime[1];
6681 in->win_ctime[1] = oh->win_ctime[1];
6682 in->win_mtime[1] = oh->win_mtime[1];
6684 in->yst_uid = oh->yst_uid;
6685 in->yst_gid = oh->yst_gid;
6686 in->yst_atime = oh->yst_atime;
6687 in->yst_mtime = oh->yst_mtime;
6688 in->yst_ctime = oh->yst_ctime;
6689 in->yst_rdev = oh->yst_rdev;
6692 if (oh->shadowsObject > 0)
6693 yaffs_HandleShadowedObject(dev,
6700 yaffs_SetObjectName(in, oh->name);
6702 yaffs_FindOrCreateObjectByNumber
6703 (dev, oh->parentObjectId,
6704 YAFFS_OBJECT_TYPE_DIRECTORY);
6706 fileSize = oh->fileSize;
6707 isShrink = oh->isShrink;
6708 equivalentObjectId = oh->equivalentObjectId;
6711 in->variantType = tags.extraObjectType;
6713 yaffs_FindOrCreateObjectByNumber
6714 (dev, tags.extraParentObjectId,
6715 YAFFS_OBJECT_TYPE_DIRECTORY);
6716 fileSize = tags.extraFileLength;
6717 isShrink = tags.extraIsShrinkHeader;
6718 equivalentObjectId = tags.extraEquivalentObjectId;
6727 /* directory stuff...
6731 if (parent && parent->variantType ==
6732 YAFFS_OBJECT_TYPE_UNKNOWN) {
6733 /* Set up as a directory */
6734 parent->variantType =
6735 YAFFS_OBJECT_TYPE_DIRECTORY;
6736 YINIT_LIST_HEAD(&parent->variant.
6739 } else if (!parent || parent->variantType !=
6740 YAFFS_OBJECT_TYPE_DIRECTORY) {
6741 /* Hoosterman, another problem....
6742 * We're trying to use a non-directory as a directory
6745 T(YAFFS_TRACE_ERROR,
6747 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6749 parent = dev->lostNFoundDir;
6752 yaffs_AddObjectToDirectory(parent, in);
6754 itsUnlinked = (parent == dev->deletedDir) ||
6755 (parent == dev->unlinkedDir);
6758 /* Mark the block as having a shrinkHeader */
6759 bi->hasShrinkHeader = 1;
6762 /* Note re hardlinks.
6763 * Since we might scan a hardlink before its equivalent object is scanned
6764 * we put them all in a list.
6765 * After scanning is complete, we should have all the objects, so we run
6766 * through this list and fix up all the chains.
6769 switch (in->variantType) {
6770 case YAFFS_OBJECT_TYPE_UNKNOWN:
6771 /* Todo got a problem */
6773 case YAFFS_OBJECT_TYPE_FILE:
6775 if (in->variant.fileVariant.
6776 scannedFileSize < fileSize) {
6777 /* This covers the case where the file size is greater
6778 * than where the data is
6779 * This will happen if the file is resized to be larger
6780 * than its current data extents.
6782 in->variant.fileVariant.fileSize = fileSize;
6783 in->variant.fileVariant.scannedFileSize =
6784 in->variant.fileVariant.fileSize;
6788 in->variant.fileVariant.shrinkSize > fileSize) {
6789 in->variant.fileVariant.shrinkSize = fileSize;
6793 case YAFFS_OBJECT_TYPE_HARDLINK:
6795 in->variant.hardLinkVariant.equivalentObjectId =
6797 in->hardLinks.next =
6798 (struct ylist_head *) hardList;
6802 case YAFFS_OBJECT_TYPE_DIRECTORY:
6805 case YAFFS_OBJECT_TYPE_SPECIAL:
6808 case YAFFS_OBJECT_TYPE_SYMLINK:
6810 in->variant.symLinkVariant.alias =
6811 yaffs_CloneString(oh->alias);
6812 if (!in->variant.symLinkVariant.alias)
6822 } /* End of scanning for each chunk */
6824 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6825 /* If we got this far while scanning, then the block is fully allocated. */
6826 state = YAFFS_BLOCK_STATE_FULL;
6830 bi->blockState = state;
6832 /* Now let's see if it was dirty */
6833 if (bi->pagesInUse == 0 &&
6834 !bi->hasShrinkHeader &&
6835 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6836 yaffs_BlockBecameDirty(dev, blk);
6841 yaffs_SkipRestOfBlock(dev);
6844 YFREE_ALT(blockIndex);
6848 /* Ok, we've done all the scanning.
6849 * Fix up the hard link chains.
6850 * We should now have scanned all the objects, now it's time to add these
6853 yaffs_HardlinkFixup(dev, hardList);
6856 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6861 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6866 /*------------------------------ Directory Functions ----------------------------- */
6868 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
6870 struct ylist_head *lh;
6871 yaffs_Object *listObj;
6876 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
6881 if (yaffs_SkipVerification(obj->myDev))
6885 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
6890 if (obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6891 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
6895 /* Iterate through the objects in each hash entry */
6897 ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
6899 listObj = ylist_entry(lh, yaffs_Object, siblings);
6900 yaffs_VerifyObject(listObj);
6907 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR), count));
6912 static void yaffs_VerifyDirectory(yaffs_Object *directory)
6914 struct ylist_head *lh;
6915 yaffs_Object *listObj;
6922 if (yaffs_SkipFullVerification(directory->myDev))
6925 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6926 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR), directory->variantType));
6930 /* Iterate through the objects in each hash entry */
6932 ylist_for_each(lh, &directory->variant.directoryVariant.children) {
6934 listObj = ylist_entry(lh, yaffs_Object, siblings);
6935 if (listObj->parent != directory) {
6936 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR), listObj->parent));
6939 yaffs_VerifyObjectInDirectory(listObj);
6945 *yaffs_UpdateParent() handles fixing a directories mtime and ctime when a new
6946 * link (ie. name) is created or deleted in the directory.
6949 * create dir/a : update dir's mtime/ctime
6950 * rm dir/a: update dir's mtime/ctime
6951 * modify dir/a: don't update dir's mtimme/ctime
6954 static void yaffs_UpdateParent(yaffs_Object *obj)
6960 obj->yst_mtime = obj->yst_ctime = Y_CURRENT_TIME;
6962 yaffs_UpdateObjectHeader(obj,NULL,0,0,0);
6965 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
6967 yaffs_Device *dev = obj->myDev;
6968 yaffs_Object *parent;
6970 yaffs_VerifyObjectInDirectory(obj);
6971 parent = obj->parent;
6973 yaffs_VerifyDirectory(parent);
6975 if (dev && dev->param.removeObjectCallback)
6976 dev->param.removeObjectCallback(obj);
6979 ylist_del_init(&obj->siblings);
6982 yaffs_VerifyDirectory(parent);
6985 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
6989 T(YAFFS_TRACE_ALWAYS,
6991 ("tragedy: Trying to add an object to a null pointer directory"
6996 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6997 T(YAFFS_TRACE_ALWAYS,
6999 ("tragedy: Trying to add an object to a non-directory"
7004 if (obj->siblings.prev == NULL) {
7005 /* Not initialised */
7010 yaffs_VerifyDirectory(directory);
7012 yaffs_RemoveObjectFromDirectory(obj);
7016 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
7017 obj->parent = directory;
7019 if (directory == obj->myDev->unlinkedDir
7020 || directory == obj->myDev->deletedDir) {
7022 obj->myDev->nUnlinkedFiles++;
7023 obj->renameAllowed = 0;
7026 yaffs_VerifyDirectory(directory);
7027 yaffs_VerifyObjectInDirectory(obj);
7030 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
7035 struct ylist_head *i;
7036 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
7044 T(YAFFS_TRACE_ALWAYS,
7046 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7051 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7052 T(YAFFS_TRACE_ALWAYS,
7054 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7058 sum = yaffs_CalcNameSum(name);
7060 ylist_for_each(i, &directory->variant.directoryVariant.children) {
7062 l = ylist_entry(i, yaffs_Object, siblings);
7064 if (l->parent != directory)
7067 yaffs_CheckObjectDetailsLoaded(l);
7069 /* Special case for lost-n-found */
7070 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7071 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
7073 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
7074 /* LostnFound chunk called Objxxx
7077 yaffs_GetObjectName(l, buffer,
7078 YAFFS_MAX_NAME_LENGTH + 1);
7079 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
7090 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
7091 int (*fn) (yaffs_Object *))
7093 struct ylist_head *i;
7097 T(YAFFS_TRACE_ALWAYS,
7099 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7104 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7105 T(YAFFS_TRACE_ALWAYS,
7107 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7112 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
7114 l = ylist_entry(i, yaffs_Object, siblings);
7125 /* GetEquivalentObject dereferences any hard links to get to the
7129 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
7131 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
7132 /* We want the object id of the equivalent object, not this one */
7133 obj = obj->variant.hardLinkVariant.equivalentObject;
7134 yaffs_CheckObjectDetailsLoaded(obj);
7139 int yaffs_GetObjectName(yaffs_Object *obj, YCHAR *name, int buffSize)
7141 memset(name, 0, buffSize * sizeof(YCHAR));
7143 yaffs_CheckObjectDetailsLoaded(obj);
7145 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7146 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
7147 } else if (obj->hdrChunk <= 0) {
7149 YCHAR numString[20];
7150 YCHAR *x = &numString[19];
7151 unsigned v = obj->objectId;
7155 *x = '0' + (v % 10);
7158 /* make up a name */
7159 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
7160 yaffs_strcat(locName, x);
7161 yaffs_strncpy(name, locName, buffSize - 1);
7164 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
7165 else if (obj->shortName[0])
7166 yaffs_strncpy(name, obj->shortName,YAFFS_SHORT_NAME_LENGTH+1);
7170 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
7172 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
7174 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
7176 if (obj->hdrChunk > 0) {
7177 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
7178 obj->hdrChunk, buffer,
7181 yaffs_strncpy(name, oh->name, buffSize - 1);
7184 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
7187 return yaffs_strnlen(name,buffSize-1);
7190 int yaffs_GetObjectFileLength(yaffs_Object *obj)
7192 /* Dereference any hard linking */
7193 obj = yaffs_GetEquivalentObject(obj);
7195 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
7196 return obj->variant.fileVariant.fileSize;
7197 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
7198 if(!obj->variant.symLinkVariant.alias)
7200 return yaffs_strnlen(obj->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
7202 /* Only a directory should drop through to here */
7203 return obj->myDev->nDataBytesPerChunk;
7207 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
7210 struct ylist_head *i;
7213 count++; /* the object itself */
7215 ylist_for_each(i, &obj->hardLinks)
7216 count++; /* add the hard links; */
7221 int yaffs_GetObjectInode(yaffs_Object *obj)
7223 obj = yaffs_GetEquivalentObject(obj);
7225 return obj->objectId;
7228 unsigned yaffs_GetObjectType(yaffs_Object *obj)
7230 obj = yaffs_GetEquivalentObject(obj);
7232 switch (obj->variantType) {
7233 case YAFFS_OBJECT_TYPE_FILE:
7236 case YAFFS_OBJECT_TYPE_DIRECTORY:
7239 case YAFFS_OBJECT_TYPE_SYMLINK:
7242 case YAFFS_OBJECT_TYPE_HARDLINK:
7245 case YAFFS_OBJECT_TYPE_SPECIAL:
7246 if (S_ISFIFO(obj->yst_mode))
7248 if (S_ISCHR(obj->yst_mode))
7250 if (S_ISBLK(obj->yst_mode))
7252 if (S_ISSOCK(obj->yst_mode))
7260 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
7262 obj = yaffs_GetEquivalentObject(obj);
7263 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
7264 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7266 return yaffs_CloneString(_Y(""));
7269 #ifndef CONFIG_YAFFS_WINCE
7271 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
7273 unsigned int valid = attr->ia_valid;
7275 if (valid & ATTR_MODE)
7276 obj->yst_mode = attr->ia_mode;
7277 if (valid & ATTR_UID)
7278 obj->yst_uid = attr->ia_uid;
7279 if (valid & ATTR_GID)
7280 obj->yst_gid = attr->ia_gid;
7282 if (valid & ATTR_ATIME)
7283 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7284 if (valid & ATTR_CTIME)
7285 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7286 if (valid & ATTR_MTIME)
7287 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7289 if (valid & ATTR_SIZE)
7290 yaffs_ResizeFile(obj, attr->ia_size);
7292 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7297 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
7299 unsigned int valid = 0;
7301 attr->ia_mode = obj->yst_mode;
7303 attr->ia_uid = obj->yst_uid;
7305 attr->ia_gid = obj->yst_gid;
7308 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7309 valid |= ATTR_ATIME;
7310 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7311 valid |= ATTR_CTIME;
7312 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7313 valid |= ATTR_MTIME;
7315 attr->ia_size = yaffs_GetFileSize(obj);
7318 attr->ia_valid = valid;
7326 int yaffs_DumpObject(yaffs_Object *obj)
7330 yaffs_GetObjectName(obj, name, YAFFS_MAX_NAME_LENGTH + 1);
7332 T(YAFFS_TRACE_ALWAYS,
7334 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7335 " chunk %d type %d size %d\n"
7336 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7337 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7338 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7344 /*---------------------------- Initialisation code -------------------------------------- */
7346 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
7349 /* Common functions, gotta have */
7350 if (!dev->param.eraseBlockInNAND || !dev->param.initialiseNAND)
7353 #ifdef CONFIG_YAFFS_YAFFS2
7355 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7356 if (dev->param.writeChunkWithTagsToNAND &&
7357 dev->param.readChunkWithTagsFromNAND &&
7358 !dev->param.writeChunkToNAND &&
7359 !dev->param.readChunkFromNAND &&
7360 dev->param.markNANDBlockBad &&
7361 dev->param.queryNANDBlock)
7365 /* Can use the "spare" style interface for yaffs1 */
7366 if (!dev->param.isYaffs2 &&
7367 !dev->param.writeChunkWithTagsToNAND &&
7368 !dev->param.readChunkWithTagsFromNAND &&
7369 dev->param.writeChunkToNAND &&
7370 dev->param.readChunkFromNAND &&
7371 !dev->param.markNANDBlockBad &&
7372 !dev->param.queryNANDBlock)
7379 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7381 /* Initialise the unlinked, deleted, root and lost and found directories */
7383 dev->lostNFoundDir = dev->rootDir = NULL;
7384 dev->unlinkedDir = dev->deletedDir = NULL;
7387 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7390 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7393 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7394 YAFFS_ROOT_MODE | S_IFDIR);
7395 dev->lostNFoundDir =
7396 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7397 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7399 if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
7400 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7407 int yaffs_GutsInitialise(yaffs_Device *dev)
7409 int init_failed = 0;
7413 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7415 /* Check stuff that must be set */
7418 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7422 dev->internalStartBlock = dev->param.startBlock;
7423 dev->internalEndBlock = dev->param.endBlock;
7424 dev->blockOffset = 0;
7425 dev->chunkOffset = 0;
7426 dev->nFreeChunks = 0;
7430 if (dev->param.startBlock == 0) {
7431 dev->internalStartBlock = dev->param.startBlock + 1;
7432 dev->internalEndBlock = dev->param.endBlock + 1;
7433 dev->blockOffset = 1;
7434 dev->chunkOffset = dev->param.nChunksPerBlock;
7437 /* Check geometry parameters. */
7439 if ((!dev->param.inbandTags && dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 1024) ||
7440 (!dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 512) ||
7441 (dev->param.inbandTags && !dev->param.isYaffs2) ||
7442 dev->param.nChunksPerBlock < 2 ||
7443 dev->param.nReservedBlocks < 2 ||
7444 dev->internalStartBlock <= 0 ||
7445 dev->internalEndBlock <= 0 ||
7446 dev->internalEndBlock <= (dev->internalStartBlock + dev->param.nReservedBlocks + 2)) { /* otherwise it is too small */
7447 T(YAFFS_TRACE_ALWAYS,
7449 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7450 TENDSTR), dev->param.totalBytesPerChunk, dev->param.isYaffs2 ? "2" : "", dev->param.inbandTags));
7454 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7455 T(YAFFS_TRACE_ALWAYS,
7456 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7460 /* Sort out space for inband tags, if required */
7461 if (dev->param.inbandTags)
7462 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7464 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk;
7466 /* Got the right mix of functions? */
7467 if (!yaffs_CheckDevFunctions(dev)) {
7468 /* Function missing */
7469 T(YAFFS_TRACE_ALWAYS,
7471 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7476 /* This is really a compilation check. */
7477 if (!yaffs_CheckStructures()) {
7478 T(YAFFS_TRACE_ALWAYS,
7479 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7483 if (dev->isMounted) {
7484 T(YAFFS_TRACE_ALWAYS,
7485 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7489 /* Finished with most checks. One or two more checks happen later on too. */
7493 /* OK now calculate a few things for the device */
7496 * Calculate all the chunk size manipulation numbers:
7498 x = dev->nDataBytesPerChunk;
7499 /* We always use dev->chunkShift and dev->chunkDiv */
7500 dev->chunkShift = Shifts(x);
7501 x >>= dev->chunkShift;
7503 /* We only use chunk mask if chunkDiv is 1 */
7504 dev->chunkMask = (1<<dev->chunkShift) - 1;
7507 * Calculate chunkGroupBits.
7508 * We need to find the next power of 2 > than internalEndBlock
7511 x = dev->param.nChunksPerBlock * (dev->internalEndBlock + 1);
7515 /* Set up tnode width if wide tnodes are enabled. */
7516 if (!dev->param.wideTnodesDisabled) {
7517 /* bits must be even so that we end up with 32-bit words */
7521 dev->tnodeWidth = 16;
7523 dev->tnodeWidth = bits;
7525 dev->tnodeWidth = 16;
7527 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7529 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7530 * so if the bitwidth of the
7531 * chunk range we're using is greater than 16 we need
7532 * to figure out chunk shift and chunkGroupSize
7535 if (bits <= dev->tnodeWidth)
7536 dev->chunkGroupBits = 0;
7538 dev->chunkGroupBits = bits - dev->tnodeWidth;
7541 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7543 if (dev->param.nChunksPerBlock < dev->chunkGroupSize) {
7544 /* We have a problem because the soft delete won't work if
7545 * the chunk group size > chunks per block.
7546 * This can be remedied by using larger "virtual blocks".
7548 T(YAFFS_TRACE_ALWAYS,
7549 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7554 /* OK, we've finished verifying the device, lets continue with initialisation */
7556 /* More device initialisation */
7557 dev->garbageCollections = 0;
7558 dev->passiveGarbageCollections = 0;
7559 dev->currentDirtyChecker = 0;
7560 dev->bufferedBlock = -1;
7561 dev->doingBufferedBlockRewrite = 0;
7562 dev->nDeletedFiles = 0;
7563 dev->nBackgroundDeletions = 0;
7564 dev->nUnlinkedFiles = 0;
7566 dev->eccUnfixed = 0;
7567 dev->tagsEccFixed = 0;
7568 dev->tagsEccUnfixed = 0;
7569 dev->nErasureFailures = 0;
7570 dev->nErasedBlocks = 0;
7572 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7574 /* Initialise temporary buffers and caches. */
7575 if (!yaffs_InitialiseTempBuffers(dev))
7578 dev->srCache = NULL;
7579 dev->gcCleanupList = NULL;
7583 dev->param.nShortOpCaches > 0) {
7586 int srCacheBytes = dev->param.nShortOpCaches * sizeof(yaffs_ChunkCache);
7588 if (dev->param.nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
7589 dev->param.nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7591 dev->srCache = YMALLOC(srCacheBytes);
7593 buf = (__u8 *) dev->srCache;
7596 memset(dev->srCache, 0, srCacheBytes);
7598 for (i = 0; i < dev->param.nShortOpCaches && buf; i++) {
7599 dev->srCache[i].object = NULL;
7600 dev->srCache[i].lastUse = 0;
7601 dev->srCache[i].dirty = 0;
7602 dev->srCache[i].data = buf = YMALLOC_DMA(dev->param.totalBytesPerChunk);
7613 dev->gcCleanupList = YMALLOC(dev->param.nChunksPerBlock * sizeof(__u32));
7614 if (!dev->gcCleanupList)
7618 if (dev->param.isYaffs2)
7619 dev->param.useHeaderFileSize = 1;
7621 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7624 yaffs_InitialiseTnodes(dev);
7625 yaffs_InitialiseObjects(dev);
7627 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7632 /* Now scan the flash. */
7633 if (dev->param.isYaffs2) {
7634 if (yaffs_CheckpointRestore(dev)) {
7635 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7636 T(YAFFS_TRACE_ALWAYS,
7637 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7640 /* Clean up the mess caused by an aborted checkpoint load
7641 * and scan backwards.
7643 yaffs_DeinitialiseBlocks(dev);
7644 yaffs_DeinitialiseTnodes(dev);
7645 yaffs_DeinitialiseObjects(dev);
7648 dev->nErasedBlocks = 0;
7649 dev->nFreeChunks = 0;
7650 dev->allocationBlock = -1;
7651 dev->allocationPage = -1;
7652 dev->nDeletedFiles = 0;
7653 dev->nUnlinkedFiles = 0;
7654 dev->nBackgroundDeletions = 0;
7655 dev->oldestDirtySequence = 0;
7657 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7660 yaffs_InitialiseTnodes(dev);
7661 yaffs_InitialiseObjects(dev);
7663 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7666 if (!init_failed && !yaffs_ScanBackwards(dev))
7669 } else if (!yaffs_Scan(dev))
7672 yaffs_StripDeletedObjects(dev);
7673 yaffs_FixHangingObjects(dev);
7674 if(dev->param.emptyLostAndFound)
7675 yaffs_EmptyLostAndFound(dev);
7679 /* Clean up the mess */
7680 T(YAFFS_TRACE_TRACING,
7681 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7683 yaffs_Deinitialise(dev);
7687 /* Zero out stats */
7688 dev->nPageReads = 0;
7689 dev->nPageWrites = 0;
7690 dev->nBlockErasures = 0;
7692 dev->nRetriedWrites = 0;
7694 dev->nRetiredBlocks = 0;
7696 yaffs_VerifyFreeChunks(dev);
7697 yaffs_VerifyBlocks(dev);
7699 /* Clean up any aborted checkpoint data */
7700 if(!dev->isCheckpointed && dev->blocksInCheckpoint > 0)
7701 yaffs_InvalidateCheckpoint(dev);
7703 T(YAFFS_TRACE_TRACING,
7704 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7709 void yaffs_Deinitialise(yaffs_Device *dev)
7711 if (dev->isMounted) {
7714 yaffs_DeinitialiseBlocks(dev);
7715 yaffs_DeinitialiseTnodes(dev);
7716 yaffs_DeinitialiseObjects(dev);
7717 if (dev->param.nShortOpCaches > 0 &&
7720 for (i = 0; i < dev->param.nShortOpCaches; i++) {
7721 if (dev->srCache[i].data)
7722 YFREE(dev->srCache[i].data);
7723 dev->srCache[i].data = NULL;
7726 YFREE(dev->srCache);
7727 dev->srCache = NULL;
7730 YFREE(dev->gcCleanupList);
7732 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
7733 YFREE(dev->tempBuffer[i].buffer);
7737 if (dev->param.deinitialiseNAND)
7738 dev->param.deinitialiseNAND(dev);
7742 static int yaffs_CountFreeChunks(yaffs_Device *dev)
7747 yaffs_BlockInfo *blk;
7749 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7751 blk = yaffs_GetBlockInfo(dev, b);
7753 switch (blk->blockState) {
7754 case YAFFS_BLOCK_STATE_EMPTY:
7755 case YAFFS_BLOCK_STATE_ALLOCATING:
7756 case YAFFS_BLOCK_STATE_COLLECTING:
7757 case YAFFS_BLOCK_STATE_FULL:
7759 (dev->param.nChunksPerBlock - blk->pagesInUse +
7760 blk->softDeletions);
7770 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
7772 /* This is what we report to the outside world */
7775 int nDirtyCacheChunks;
7776 int blocksForCheckpoint;
7780 nFree = dev->nFreeChunks;
7782 nFree = yaffs_CountFreeChunks(dev);
7785 nFree += dev->nDeletedFiles;
7787 /* Now count the number of dirty chunks in the cache and subtract those */
7789 for (nDirtyCacheChunks = 0, i = 0; i < dev->param.nShortOpCaches; i++) {
7790 if (dev->srCache[i].dirty)
7791 nDirtyCacheChunks++;
7794 nFree -= nDirtyCacheChunks;
7796 nFree -= ((dev->param.nReservedBlocks + 1) * dev->param.nChunksPerBlock);
7798 /* Now we figure out how much to reserve for the checkpoint and report that... */
7799 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7800 if (blocksForCheckpoint < 0)
7801 blocksForCheckpoint = 0;
7803 nFree -= (blocksForCheckpoint * dev->param.nChunksPerBlock);
7812 static int yaffs_freeVerificationFailures;
7814 static void yaffs_VerifyFreeChunks(yaffs_Device *dev)
7819 if (yaffs_SkipVerification(dev))
7822 counted = yaffs_CountFreeChunks(dev);
7824 difference = dev->nFreeChunks - counted;
7827 T(YAFFS_TRACE_ALWAYS,
7828 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7829 dev->nFreeChunks, counted, difference));
7830 yaffs_freeVerificationFailures++;
7834 /*---------------------------------------- YAFFS test code ----------------------*/
7836 #define yaffs_CheckStruct(structure, syze, name) \
7838 if (sizeof(structure) != syze) { \
7839 T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
7840 name, syze, (int) sizeof(structure))); \
7841 return YAFFS_FAIL; \
7845 static int yaffs_CheckStructures(void)
7847 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
7848 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
7849 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
7850 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7851 /* yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode"); */
7853 #ifndef CONFIG_YAFFS_WINCE
7854 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");