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.106 2010-01-11 04:06:46 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->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->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->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->nChunksPerBlock ||
458 bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
459 actuallyUsed < 0 || actuallyUsed > dev->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
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->nChunksPerBlock;
766 chunkMax = (dev->internalEndBlock+1) * dev->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->nChunksPerBlock,
773 obj->hdrChunk % dev->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->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->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->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
1193 static int yaffs_CreateTnodes(yaffs_Device *dev, int nTnodes)
1197 yaffs_Tnode *newTnodes;
1201 yaffs_TnodeList *tnl;
1206 /* Calculate the tnode size in bytes for variable width tnode support.
1207 * Must be a multiple of 32-bits */
1208 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1210 if (tnodeSize < sizeof(yaffs_Tnode))
1211 tnodeSize = sizeof(yaffs_Tnode);
1213 /* make these things */
1215 newTnodes = YMALLOC(nTnodes * tnodeSize);
1216 mem = (__u8 *)newTnodes;
1219 T(YAFFS_TRACE_ERROR,
1220 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1224 /* Hook them into the free list */
1226 for (i = 0; i < nTnodes - 1; i++) {
1227 newTnodes[i].internal[0] = &newTnodes[i + 1];
1228 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1229 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1233 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1234 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1235 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1237 dev->freeTnodes = newTnodes;
1239 /* New hookup for wide tnodes */
1240 for (i = 0; i < nTnodes - 1; i++) {
1241 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1242 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1243 curr->internal[0] = next;
1246 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1247 curr->internal[0] = dev->freeTnodes;
1248 dev->freeTnodes = (yaffs_Tnode *)mem;
1253 dev->nFreeTnodes += nTnodes;
1254 dev->nTnodesCreated += nTnodes;
1256 /* Now add this bunch of tnodes to a list for freeing up.
1257 * NB If we can't add this to the management list it isn't fatal
1258 * but it just means we can't free this bunch of tnodes later.
1261 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1263 T(YAFFS_TRACE_ERROR,
1265 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1268 tnl->tnodes = newTnodes;
1269 tnl->next = dev->allocatedTnodeList;
1270 dev->allocatedTnodeList = tnl;
1273 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1278 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1280 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device *dev)
1282 yaffs_Tnode *tn = NULL;
1284 /* If there are none left make more */
1285 if (!dev->freeTnodes)
1286 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1288 if (dev->freeTnodes) {
1289 tn = dev->freeTnodes;
1290 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1291 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1292 /* Hoosterman, this thing looks like it isn't in the list */
1293 T(YAFFS_TRACE_ALWAYS,
1294 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1297 dev->freeTnodes = dev->freeTnodes->internal[0];
1301 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1306 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
1308 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1309 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1311 if (tnodeSize < sizeof(yaffs_Tnode))
1312 tnodeSize = sizeof(yaffs_Tnode);
1315 memset(tn, 0, tnodeSize);
1320 /* FreeTnode frees up a tnode and puts it back on the free list */
1321 static void yaffs_FreeTnode(yaffs_Device *dev, yaffs_Tnode *tn)
1324 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1325 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1326 /* Hoosterman, this thing looks like it is already in the list */
1327 T(YAFFS_TRACE_ALWAYS,
1328 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1330 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1332 tn->internal[0] = dev->freeTnodes;
1333 dev->freeTnodes = tn;
1336 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1339 static void yaffs_DeinitialiseTnodes(yaffs_Device *dev)
1341 /* Free the list of allocated tnodes */
1342 yaffs_TnodeList *tmp;
1344 while (dev->allocatedTnodeList) {
1345 tmp = dev->allocatedTnodeList->next;
1347 YFREE(dev->allocatedTnodeList->tnodes);
1348 YFREE(dev->allocatedTnodeList);
1349 dev->allocatedTnodeList = tmp;
1353 dev->freeTnodes = NULL;
1354 dev->nFreeTnodes = 0;
1355 dev->nTnodesCreated = 0;
1358 static void yaffs_InitialiseTnodes(yaffs_Device *dev)
1360 dev->allocatedTnodeList = NULL;
1361 dev->freeTnodes = NULL;
1362 dev->nFreeTnodes = 0;
1363 dev->nTnodesCreated = 0;
1367 void yaffs_LoadLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
1370 __u32 *map = (__u32 *)tn;
1376 pos &= YAFFS_TNODES_LEVEL0_MASK;
1377 val >>= dev->chunkGroupBits;
1379 bitInMap = pos * dev->tnodeWidth;
1380 wordInMap = bitInMap / 32;
1381 bitInWord = bitInMap & (32 - 1);
1383 mask = dev->tnodeMask << bitInWord;
1385 map[wordInMap] &= ~mask;
1386 map[wordInMap] |= (mask & (val << bitInWord));
1388 if (dev->tnodeWidth > (32 - bitInWord)) {
1389 bitInWord = (32 - bitInWord);
1391 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1392 map[wordInMap] &= ~mask;
1393 map[wordInMap] |= (mask & (val >> bitInWord));
1397 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
1400 __u32 *map = (__u32 *)tn;
1406 pos &= YAFFS_TNODES_LEVEL0_MASK;
1408 bitInMap = pos * dev->tnodeWidth;
1409 wordInMap = bitInMap / 32;
1410 bitInWord = bitInMap & (32 - 1);
1412 val = map[wordInMap] >> bitInWord;
1414 if (dev->tnodeWidth > (32 - bitInWord)) {
1415 bitInWord = (32 - bitInWord);
1417 val |= (map[wordInMap] << bitInWord);
1420 val &= dev->tnodeMask;
1421 val <<= dev->chunkGroupBits;
1426 /* ------------------- End of individual tnode manipulation -----------------*/
1428 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1429 * The look up tree is represented by the top tnode and the number of topLevel
1430 * in the tree. 0 means only the level 0 tnode is in the tree.
1433 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1434 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
1435 yaffs_FileStructure *fStruct,
1438 yaffs_Tnode *tn = fStruct->top;
1440 int requiredTallness;
1441 int level = fStruct->topLevel;
1443 /* Check sane level and chunk Id */
1444 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
1447 if (chunkId > YAFFS_MAX_CHUNK_ID)
1450 /* First check we're tall enough (ie enough topLevel) */
1452 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1453 requiredTallness = 0;
1455 i >>= YAFFS_TNODES_INTERNAL_BITS;
1459 if (requiredTallness > fStruct->topLevel)
1460 return NULL; /* Not tall enough, so we can't find it */
1462 /* Traverse down to level 0 */
1463 while (level > 0 && tn) {
1464 tn = tn->internal[(chunkId >>
1465 (YAFFS_TNODES_LEVEL0_BITS +
1467 YAFFS_TNODES_INTERNAL_BITS)) &
1468 YAFFS_TNODES_INTERNAL_MASK];
1475 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1476 * This happens in two steps:
1477 * 1. If the tree isn't tall enough, then make it taller.
1478 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1480 * Used when modifying the tree.
1482 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1483 * be plugged into the ttree.
1486 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
1487 yaffs_FileStructure *fStruct,
1489 yaffs_Tnode *passedTn)
1491 int requiredTallness;
1499 /* Check sane level and page Id */
1500 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
1503 if (chunkId > YAFFS_MAX_CHUNK_ID)
1506 /* First check we're tall enough (ie enough topLevel) */
1508 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1509 requiredTallness = 0;
1511 x >>= YAFFS_TNODES_INTERNAL_BITS;
1516 if (requiredTallness > fStruct->topLevel) {
1517 /* Not tall enough, gotta make the tree taller */
1518 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1520 tn = yaffs_GetTnode(dev);
1523 tn->internal[0] = fStruct->top;
1525 fStruct->topLevel++;
1527 T(YAFFS_TRACE_ERROR,
1528 (TSTR("yaffs: no more tnodes" TENDSTR)));
1534 /* Traverse down to level 0, adding anything we need */
1536 l = fStruct->topLevel;
1540 while (l > 0 && tn) {
1542 (YAFFS_TNODES_LEVEL0_BITS +
1543 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1544 YAFFS_TNODES_INTERNAL_MASK;
1547 if ((l > 1) && !tn->internal[x]) {
1548 /* Add missing non-level-zero tnode */
1549 tn->internal[x] = yaffs_GetTnode(dev);
1550 if(!tn->internal[x])
1553 } else if (l == 1) {
1554 /* Looking from level 1 at level 0 */
1556 /* If we already have one, then release it.*/
1557 if (tn->internal[x])
1558 yaffs_FreeTnode(dev, tn->internal[x]);
1559 tn->internal[x] = passedTn;
1561 } else if (!tn->internal[x]) {
1562 /* Don't have one, none passed in */
1563 tn->internal[x] = yaffs_GetTnode(dev);
1564 if(!tn->internal[x])
1569 tn = tn->internal[x];
1573 /* top is level 0 */
1575 memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1576 yaffs_FreeTnode(dev, passedTn);
1583 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
1584 yaffs_ExtendedTags *tags, int objectId,
1589 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1590 if (yaffs_CheckChunkBit(dev, theChunk / dev->nChunksPerBlock,
1591 theChunk % dev->nChunksPerBlock)) {
1593 if(dev->chunkGroupSize == 1)
1596 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1598 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1610 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1611 * chunks and tnodes in the file
1612 * Returns 1 if the tree was deleted.
1613 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1616 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
1617 int chunkOffset, int *limit)
1622 yaffs_ExtendedTags tags;
1624 yaffs_Device *dev = in->myDev;
1630 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1632 if (tn->internal[i]) {
1633 if (limit && (*limit) < 0) {
1637 yaffs_DeleteWorker(in,
1645 YAFFS_TNODES_INTERNAL_BITS)
1650 yaffs_FreeTnode(dev,
1653 tn->internal[i] = NULL;
1657 return (allDone) ? 1 : 0;
1658 } else if (level == 0) {
1661 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1663 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1666 chunkInInode = (chunkOffset <<
1667 YAFFS_TNODES_LEVEL0_BITS) + i;
1670 yaffs_FindChunkInGroup(dev,
1676 if (foundChunk > 0) {
1677 yaffs_DeleteChunk(dev,
1682 *limit = *limit - 1;
1689 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1693 return (i < 0) ? 1 : 0;
1703 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1705 yaffs_BlockInfo *theBlock;
1707 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1709 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1711 theBlock->softDeletions++;
1716 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1717 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1719 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1722 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1723 __u32 level, int chunkOffset)
1728 yaffs_Device *dev = in->myDev;
1733 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1735 if (tn->internal[i]) {
1737 yaffs_SoftDeleteWorker(in,
1743 YAFFS_TNODES_INTERNAL_BITS)
1746 yaffs_FreeTnode(dev,
1749 tn->internal[i] = NULL;
1751 /* Hoosterman... how could this happen? */
1755 return (allDone) ? 1 : 0;
1756 } else if (level == 0) {
1758 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1759 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1761 /* Note this does not find the real chunk, only the chunk group.
1762 * We make an assumption that a chunk group is not larger than
1765 yaffs_SoftDeleteChunk(dev, theChunk);
1766 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1780 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1783 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1784 if (obj->nDataChunks <= 0) {
1785 /* Empty file with no duplicate object headers, just delete it immediately */
1786 yaffs_FreeTnode(obj->myDev,
1787 obj->variant.fileVariant.top);
1788 obj->variant.fileVariant.top = NULL;
1789 T(YAFFS_TRACE_TRACING,
1790 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1792 yaffs_DoGenericObjectDeletion(obj);
1794 yaffs_SoftDeleteWorker(obj,
1795 obj->variant.fileVariant.top,
1796 obj->variant.fileVariant.
1798 obj->softDeleted = 1;
1803 /* Pruning removes any part of the file structure tree that is beyond the
1804 * bounds of the file (ie that does not point to chunks).
1806 * A file should only get pruned when its size is reduced.
1808 * Before pruning, the chunks must be pulled from the tree and the
1809 * level 0 tnode entries must be zeroed out.
1810 * Could also use this for file deletion, but that's probably better handled
1811 * by a special case.
1813 * This function is recursive. For levels > 0 the function is called again on
1814 * any sub-tree. For level == 0 we just check if the sub-tree has data.
1815 * If there is no data in a subtree then it is pruned.
1818 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1819 __u32 level, int del0)
1828 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1829 if (tn->internal[i]) {
1831 yaffs_PruneWorker(dev, tn->internal[i],
1833 (i == 0) ? del0 : 1);
1836 if (tn->internal[i])
1841 __u32 *map = (__u32 *)tn;
1842 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1844 if (tnodeSize < sizeof(yaffs_Tnode))
1845 tnodeSize = sizeof(yaffs_Tnode);
1846 tnodeSize /= sizeof(__u32);
1848 for(i = 0; !hasData && i < tnodeSize; i++){
1854 if (hasData == 0 && del0) {
1855 /* Free and return NULL */
1857 yaffs_FreeTnode(dev, tn);
1867 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1868 yaffs_FileStructure *fStruct)
1875 if (fStruct->topLevel > 0) {
1877 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1879 /* Now we have a tree with all the non-zero branches NULL but the height
1880 * is the same as it was.
1881 * Let's see if we can trim internal tnodes to shorten the tree.
1882 * We can do this if only the 0th element in the tnode is in use
1883 * (ie all the non-zero are NULL)
1886 while (fStruct->topLevel && !done) {
1890 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1891 if (tn->internal[i])
1896 fStruct->top = tn->internal[0];
1897 fStruct->topLevel--;
1898 yaffs_FreeTnode(dev, tn);
1908 /*-------------------- End of File Structure functions.-------------------*/
1910 /* yaffs_CreateFreeObjects creates a bunch more objects and
1911 * adds them to the object free list.
1913 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1916 yaffs_Object *newObjects;
1917 yaffs_ObjectList *list;
1922 /* make these things */
1923 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1924 list = YMALLOC(sizeof(yaffs_ObjectList));
1926 if (!newObjects || !list) {
1935 T(YAFFS_TRACE_ALLOCATE,
1936 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1940 /* Hook them into the free list */
1941 for (i = 0; i < nObjects - 1; i++) {
1942 newObjects[i].siblings.next =
1943 (struct ylist_head *)(&newObjects[i + 1]);
1946 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1947 dev->freeObjects = newObjects;
1948 dev->nFreeObjects += nObjects;
1949 dev->nObjectsCreated += nObjects;
1951 /* Now add this bunch of Objects to a list for freeing up. */
1953 list->objects = newObjects;
1954 list->next = dev->allocatedObjectList;
1955 dev->allocatedObjectList = list;
1961 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1962 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1964 yaffs_Object *tn = NULL;
1966 #ifdef VALGRIND_TEST
1967 tn = YMALLOC(sizeof(yaffs_Object));
1969 /* If there are none left make more */
1970 if (!dev->freeObjects)
1971 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1973 if (dev->freeObjects) {
1974 tn = dev->freeObjects;
1976 (yaffs_Object *) (dev->freeObjects->siblings.next);
1977 dev->nFreeObjects--;
1981 /* Now sweeten it up... */
1983 memset(tn, 0, sizeof(yaffs_Object));
1984 tn->beingCreated = 1;
1988 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1989 YINIT_LIST_HEAD(&(tn->hardLinks));
1990 YINIT_LIST_HEAD(&(tn->hashLink));
1991 YINIT_LIST_HEAD(&tn->siblings);
1994 /* Now make the directory sane */
1996 tn->parent = dev->rootDir;
1997 ylist_add(&(tn->siblings), &dev->rootDir->variant.directoryVariant.children);
2000 /* Add it to the lost and found directory.
2001 * NB Can't put root or lostNFound in lostNFound so
2002 * check if lostNFound exists first
2004 if (dev->lostNFoundDir)
2005 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
2007 tn->beingCreated = 0;
2010 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2015 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
2020 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
2022 obj->fake = 1; /* it is fake so it might have no NAND presence... */
2023 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
2024 obj->unlinkAllowed = 0; /* ... or unlink it */
2027 obj->yst_mode = mode;
2029 obj->hdrChunk = 0; /* Not a valid chunk. */
2036 static void yaffs_UnhashObject(yaffs_Object *tn)
2039 yaffs_Device *dev = tn->myDev;
2041 /* If it is still linked into the bucket list, free from the list */
2042 if (!ylist_empty(&tn->hashLink)) {
2043 ylist_del_init(&tn->hashLink);
2044 bucket = yaffs_HashFunction(tn->objectId);
2045 dev->objectBucket[bucket].count--;
2049 /* FreeObject frees up a Object and puts it back on the free list */
2050 static void yaffs_FreeObject(yaffs_Object *tn)
2052 yaffs_Device *dev = tn->myDev;
2054 T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), tn, tn->myInode));
2058 if (!ylist_empty(&tn->siblings))
2063 /* We're still hooked up to a cached inode.
2064 * Don't delete now, but mark for later deletion
2066 tn->deferedFree = 1;
2070 yaffs_UnhashObject(tn);
2072 #ifdef VALGRIND_TEST
2076 /* Link into the free list. */
2077 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2078 dev->freeObjects = tn;
2079 dev->nFreeObjects++;
2081 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2086 void yaffs_HandleDeferedFree(yaffs_Object *obj)
2088 if (obj->deferedFree)
2089 yaffs_FreeObject(obj);
2094 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
2096 /* Free the list of allocated Objects */
2098 yaffs_ObjectList *tmp;
2100 while (dev->allocatedObjectList) {
2101 tmp = dev->allocatedObjectList->next;
2102 YFREE(dev->allocatedObjectList->objects);
2103 YFREE(dev->allocatedObjectList);
2105 dev->allocatedObjectList = tmp;
2108 dev->freeObjects = NULL;
2109 dev->nFreeObjects = 0;
2110 dev->nObjectsCreated = 0;
2113 static void yaffs_InitialiseObjects(yaffs_Device *dev)
2117 dev->allocatedObjectList = NULL;
2118 dev->freeObjects = NULL;
2119 dev->nFreeObjects = 0;
2121 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2122 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2123 dev->objectBucket[i].count = 0;
2127 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
2132 int lowest = 999999;
2134 /* First let's see if we can find one that's empty. */
2136 for (i = 0; i < 10 && lowest > 0; i++) {
2138 x %= YAFFS_NOBJECT_BUCKETS;
2139 if (dev->objectBucket[x].count < lowest) {
2140 lowest = dev->objectBucket[x].count;
2146 /* If we didn't find an empty list, then try
2147 * looking a bit further for a short one
2150 for (i = 0; i < 10 && lowest > 3; i++) {
2152 x %= YAFFS_NOBJECT_BUCKETS;
2153 if (dev->objectBucket[x].count < lowest) {
2154 lowest = dev->objectBucket[x].count;
2163 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
2165 int bucket = yaffs_FindNiceObjectBucket(dev);
2167 /* Now find an object value that has not already been taken
2168 * by scanning the list.
2172 struct ylist_head *i;
2174 __u32 n = (__u32) bucket;
2176 /* yaffs_CheckObjectHashSanity(); */
2180 n += YAFFS_NOBJECT_BUCKETS;
2181 if (1 || dev->objectBucket[bucket].count > 0) {
2182 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2183 /* If there is already one in the list */
2184 if (i && ylist_entry(i, yaffs_Object,
2185 hashLink)->objectId == n) {
2195 static void yaffs_HashObject(yaffs_Object *in)
2197 int bucket = yaffs_HashFunction(in->objectId);
2198 yaffs_Device *dev = in->myDev;
2200 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2201 dev->objectBucket[bucket].count++;
2204 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
2206 int bucket = yaffs_HashFunction(number);
2207 struct ylist_head *i;
2210 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2211 /* Look if it is in the list */
2213 in = ylist_entry(i, yaffs_Object, hashLink);
2214 if (in->objectId == number) {
2216 /* Don't tell the VFS about this one if it is defered free */
2217 if (in->deferedFree)
2229 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
2230 yaffs_ObjectType type)
2232 yaffs_Object *theObject;
2233 yaffs_Tnode *tn = NULL;
2236 number = yaffs_CreateNewObjectNumber(dev);
2238 if (type == YAFFS_OBJECT_TYPE_FILE) {
2239 tn = yaffs_GetTnode(dev);
2244 theObject = yaffs_AllocateEmptyObject(dev);
2247 yaffs_FreeTnode(dev,tn);
2253 theObject->fake = 0;
2254 theObject->renameAllowed = 1;
2255 theObject->unlinkAllowed = 1;
2256 theObject->objectId = number;
2257 yaffs_HashObject(theObject);
2258 theObject->variantType = type;
2259 #ifdef CONFIG_YAFFS_WINCE
2260 yfsd_WinFileTimeNow(theObject->win_atime);
2261 theObject->win_ctime[0] = theObject->win_mtime[0] =
2262 theObject->win_atime[0];
2263 theObject->win_ctime[1] = theObject->win_mtime[1] =
2264 theObject->win_atime[1];
2268 theObject->yst_atime = theObject->yst_mtime =
2269 theObject->yst_ctime = Y_CURRENT_TIME;
2272 case YAFFS_OBJECT_TYPE_FILE:
2273 theObject->variant.fileVariant.fileSize = 0;
2274 theObject->variant.fileVariant.scannedFileSize = 0;
2275 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2276 theObject->variant.fileVariant.topLevel = 0;
2277 theObject->variant.fileVariant.top = tn;
2279 case YAFFS_OBJECT_TYPE_DIRECTORY:
2280 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2283 case YAFFS_OBJECT_TYPE_SYMLINK:
2284 case YAFFS_OBJECT_TYPE_HARDLINK:
2285 case YAFFS_OBJECT_TYPE_SPECIAL:
2286 /* No action required */
2288 case YAFFS_OBJECT_TYPE_UNKNOWN:
2289 /* todo this should not happen */
2297 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
2299 yaffs_ObjectType type)
2301 yaffs_Object *theObject = NULL;
2304 theObject = yaffs_FindObjectByNumber(dev, number);
2307 theObject = yaffs_CreateNewObject(dev, number, type);
2314 static YCHAR *yaffs_CloneString(const YCHAR *str)
2316 YCHAR *newStr = NULL;
2322 len = yaffs_strnlen(str,YAFFS_MAX_ALIAS_LENGTH);
2323 newStr = YMALLOC((len + 1) * sizeof(YCHAR));
2325 yaffs_strncpy(newStr, str,len);
2333 * Mknod (create) a new object.
2334 * equivalentObject only has meaning for a hard link;
2335 * aliasString only has meaning for a symlink.
2336 * rdev only has meaning for devices (a subset of special objects)
2339 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2340 yaffs_Object *parent,
2345 yaffs_Object *equivalentObject,
2346 const YCHAR *aliasString, __u32 rdev)
2351 yaffs_Device *dev = parent->myDev;
2353 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2354 if (yaffs_FindObjectByName(parent, name))
2357 if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2358 str = yaffs_CloneString(aliasString);
2363 in = yaffs_CreateNewObject(dev, -1, type);
2377 in->variantType = type;
2379 in->yst_mode = mode;
2381 #ifdef CONFIG_YAFFS_WINCE
2382 yfsd_WinFileTimeNow(in->win_atime);
2383 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2384 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2387 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2389 in->yst_rdev = rdev;
2393 in->nDataChunks = 0;
2395 yaffs_SetObjectName(in, name);
2398 yaffs_AddObjectToDirectory(parent, in);
2400 in->myDev = parent->myDev;
2403 case YAFFS_OBJECT_TYPE_SYMLINK:
2404 in->variant.symLinkVariant.alias = str;
2406 case YAFFS_OBJECT_TYPE_HARDLINK:
2407 in->variant.hardLinkVariant.equivalentObject =
2409 in->variant.hardLinkVariant.equivalentObjectId =
2410 equivalentObject->objectId;
2411 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2413 case YAFFS_OBJECT_TYPE_FILE:
2414 case YAFFS_OBJECT_TYPE_DIRECTORY:
2415 case YAFFS_OBJECT_TYPE_SPECIAL:
2416 case YAFFS_OBJECT_TYPE_UNKNOWN:
2421 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2422 /* Could not create the object header, fail the creation */
2423 yaffs_DeleteObject(in);
2427 yaffs_UpdateParent(parent);
2433 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
2434 __u32 mode, __u32 uid, __u32 gid)
2436 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2437 uid, gid, NULL, NULL, 0);
2440 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
2441 __u32 mode, __u32 uid, __u32 gid)
2443 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2444 mode, uid, gid, NULL, NULL, 0);
2447 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
2448 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2450 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2451 uid, gid, NULL, NULL, rdev);
2454 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
2455 __u32 mode, __u32 uid, __u32 gid,
2458 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2459 uid, gid, NULL, alias, 0);
2462 /* yaffs_Link returns the object id of the equivalent object.*/
2463 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
2464 yaffs_Object *equivalentObject)
2466 /* Get the real object in case we were fed a hard link as an equivalent object */
2467 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2469 if (yaffs_MknodObject
2470 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2471 equivalentObject, NULL, 0)) {
2472 return equivalentObject;
2479 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
2480 const YCHAR *newName, int force, int shadows)
2485 yaffs_Object *existingTarget;
2488 newDir = obj->parent; /* use the old directory */
2490 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2491 T(YAFFS_TRACE_ALWAYS,
2493 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2498 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2499 if (obj->myDev->isYaffs2)
2500 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2502 unlinkOp = (newDir == obj->myDev->unlinkedDir
2503 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2505 deleteOp = (newDir == obj->myDev->deletedDir);
2507 existingTarget = yaffs_FindObjectByName(newDir, newName);
2509 /* If the object is a file going into the unlinked directory,
2510 * then it is OK to just stuff it in since duplicate names are allowed.
2511 * else only proceed if the new name does not exist and if we're putting
2512 * it into a directory.
2519 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2520 yaffs_SetObjectName(obj, newName);
2523 yaffs_AddObjectToDirectory(newDir, obj);
2528 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2529 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows) >= 0)
2536 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
2537 yaffs_Object *newDir, const YCHAR *newName)
2539 yaffs_Object *obj = NULL;
2540 yaffs_Object *existingTarget = NULL;
2546 if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2548 if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2551 dev = oldDir->myDev;
2553 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2554 /* Special case for case insemsitive systems (eg. WinCE).
2555 * While look-up is case insensitive, the name isn't.
2556 * Therefore we might want to change x.txt to X.txt
2558 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
2562 if(yaffs_strnlen(newName,YAFFS_MAX_NAME_LENGTH+1) > YAFFS_MAX_NAME_LENGTH)
2566 obj = yaffs_FindObjectByName(oldDir, oldName);
2568 if (obj && obj->renameAllowed) {
2570 /* Now do the handling for an existing target, if there is one */
2572 existingTarget = yaffs_FindObjectByName(newDir, newName);
2573 if (existingTarget &&
2574 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2575 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2576 /* There is a target that is a non-empty directory, so we fail */
2577 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2578 } else if (existingTarget && existingTarget != obj) {
2579 /* Nuke the target first, using shadowing,
2580 * but only if it isn't the same object.
2582 * Note we must disable gc otherwise it can mess up the shadowing.
2586 yaffs_ChangeObjectName(obj, newDir, newName, force,
2587 existingTarget->objectId);
2588 existingTarget->isShadowed = 1;
2589 yaffs_UnlinkObject(existingTarget);
2593 result = yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2595 yaffs_UpdateParent(oldDir);
2596 if(newDir != oldDir)
2597 yaffs_UpdateParent(newDir);
2604 /*------------------------- Block Management and Page Allocation ----------------*/
2606 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
2608 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2610 dev->blockInfo = NULL;
2611 dev->chunkBits = NULL;
2613 dev->allocationBlock = -1; /* force it to get a new one */
2615 /* If the first allocation strategy fails, thry the alternate one */
2616 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2617 if (!dev->blockInfo) {
2618 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2619 dev->blockInfoAlt = 1;
2621 dev->blockInfoAlt = 0;
2623 if (dev->blockInfo) {
2624 /* Set up dynamic blockinfo stuff. */
2625 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2626 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2627 if (!dev->chunkBits) {
2628 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2629 dev->chunkBitsAlt = 1;
2631 dev->chunkBitsAlt = 0;
2634 if (dev->blockInfo && dev->chunkBits) {
2635 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2636 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2643 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2645 if (dev->blockInfoAlt && dev->blockInfo)
2646 YFREE_ALT(dev->blockInfo);
2647 else if (dev->blockInfo)
2648 YFREE(dev->blockInfo);
2650 dev->blockInfoAlt = 0;
2652 dev->blockInfo = NULL;
2654 if (dev->chunkBitsAlt && dev->chunkBits)
2655 YFREE_ALT(dev->chunkBits);
2656 else if (dev->chunkBits)
2657 YFREE(dev->chunkBits);
2658 dev->chunkBitsAlt = 0;
2659 dev->chunkBits = NULL;
2662 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
2663 yaffs_BlockInfo *bi)
2670 return 1; /* disqualification only applies to yaffs2. */
2672 if (!bi->hasShrinkHeader)
2673 return 1; /* can gc */
2675 /* Find the oldest dirty sequence number if we don't know it and save it
2676 * so we don't have to keep recomputing it.
2678 if (!dev->oldestDirtySequence) {
2679 seq = dev->sequenceNumber;
2681 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2683 b = yaffs_GetBlockInfo(dev, i);
2684 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2685 (b->pagesInUse - b->softDeletions) <
2686 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2687 seq = b->sequenceNumber;
2690 dev->oldestDirtySequence = seq;
2693 /* Can't do gc of this block if there are any blocks older than this one that have
2696 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2699 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2700 * for garbage collection.
2703 static int yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
2706 int b = dev->currentDirtyChecker;
2712 int prioritised = 0;
2713 yaffs_BlockInfo *bi;
2714 int pendingPrioritisedExist = 0;
2716 /* First let's see if we need to grab a prioritised block */
2717 if (dev->hasPendingPrioritisedGCs) {
2718 for (i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++) {
2720 bi = yaffs_GetBlockInfo(dev, i);
2721 /* yaffs_VerifyBlock(dev,bi,i); */
2723 if (bi->gcPrioritise) {
2724 pendingPrioritisedExist = 1;
2725 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2726 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2727 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2730 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2735 if (!pendingPrioritisedExist) /* None found, so we can clear this */
2736 dev->hasPendingPrioritisedGCs = 0;
2739 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2741 * else (we're doing a leasurely gc), then we only bother to do this if the
2742 * block has only a few pages in use.
2745 dev->nonAggressiveSkip--;
2747 if (!aggressive && (dev->nonAggressiveSkip > 0))
2752 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2756 dev->internalEndBlock - dev->internalStartBlock + 1;
2759 dev->internalEndBlock - dev->internalStartBlock + 1;
2760 iterations = iterations / 16;
2761 if (iterations > 200)
2765 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2767 if (b < dev->internalStartBlock || b > dev->internalEndBlock)
2768 b = dev->internalStartBlock;
2770 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2771 T(YAFFS_TRACE_ERROR,
2772 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2776 bi = yaffs_GetBlockInfo(dev, b);
2778 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2779 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2780 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2782 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2786 dev->currentDirtyChecker = b;
2790 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2791 dev->nChunksPerBlock - pagesInUse, prioritised));
2794 dev->oldestDirtySequence = 0;
2797 dev->nonAggressiveSkip = 4;
2802 static void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
2804 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2808 /* If the block is still healthy erase it and mark as clean.
2809 * If the block has had a data failure, then retire it.
2812 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2813 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2814 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2816 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2818 if (!bi->needsRetiring) {
2819 yaffs_InvalidateCheckpoint(dev);
2820 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2822 dev->nErasureFailures++;
2823 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2824 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2829 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2831 for (i = 0; i < dev->nChunksPerBlock; i++) {
2832 if (!yaffs_CheckChunkErased
2833 (dev, blockNo * dev->nChunksPerBlock + i)) {
2834 T(YAFFS_TRACE_ERROR,
2836 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2837 TENDSTR), blockNo, i));
2843 /* Clean it up... */
2844 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2845 dev->nErasedBlocks++;
2847 bi->softDeletions = 0;
2848 bi->hasShrinkHeader = 0;
2849 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2850 bi->gcPrioritise = 0;
2851 yaffs_ClearChunkBits(dev, blockNo);
2853 T(YAFFS_TRACE_ERASE,
2854 (TSTR("Erased block %d" TENDSTR), blockNo));
2856 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2858 yaffs_RetireBlock(dev, blockNo);
2859 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2860 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2864 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2868 yaffs_BlockInfo *bi;
2870 if (dev->nErasedBlocks < 1) {
2871 /* Hoosterman we've got a problem.
2872 * Can't get space to gc
2874 T(YAFFS_TRACE_ERROR,
2875 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2880 /* Find an empty block. */
2882 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2883 dev->allocationBlockFinder++;
2884 if (dev->allocationBlockFinder < dev->internalStartBlock
2885 || dev->allocationBlockFinder > dev->internalEndBlock) {
2886 dev->allocationBlockFinder = dev->internalStartBlock;
2889 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2891 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2892 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2893 dev->sequenceNumber++;
2894 bi->sequenceNumber = dev->sequenceNumber;
2895 dev->nErasedBlocks--;
2896 T(YAFFS_TRACE_ALLOCATE,
2897 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2898 dev->allocationBlockFinder, dev->sequenceNumber,
2899 dev->nErasedBlocks));
2900 return dev->allocationBlockFinder;
2904 T(YAFFS_TRACE_ALWAYS,
2906 ("yaffs tragedy: no more erased blocks, but there should have been %d"
2907 TENDSTR), dev->nErasedBlocks));
2914 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2916 if (!dev->nCheckpointBlocksRequired &&
2918 /* Not a valid value so recalculate */
2921 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2924 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2926 if (tnodeSize < sizeof(yaffs_Tnode))
2927 tnodeSize = sizeof(yaffs_Tnode);
2929 nBytes += sizeof(yaffs_CheckpointValidity);
2930 nBytes += sizeof(yaffs_CheckpointDevice);
2931 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2932 nBytes += devBlocks * dev->chunkBitmapStride;
2933 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2934 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2935 nBytes += sizeof(yaffs_CheckpointValidity);
2936 nBytes += sizeof(__u32); /* checksum*/
2938 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2940 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2942 dev->nCheckpointBlocksRequired = nBlocks;
2945 return dev->nCheckpointBlocksRequired;
2949 * Check if there's space to allocate...
2950 * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2952 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev)
2955 int reservedBlocks = dev->nReservedBlocks;
2956 int checkpointBlocks;
2958 if (dev->isYaffs2) {
2959 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
2960 dev->blocksInCheckpoint;
2961 if (checkpointBlocks < 0)
2962 checkpointBlocks = 0;
2964 checkpointBlocks = 0;
2967 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2969 return (dev->nFreeChunks > reservedChunks);
2972 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
2973 yaffs_BlockInfo **blockUsedPtr)
2976 yaffs_BlockInfo *bi;
2978 if (dev->allocationBlock < 0) {
2979 /* Get next block to allocate off */
2980 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2981 dev->allocationPage = 0;
2984 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2985 /* Not enough space to allocate unless we're allowed to use the reserve. */
2989 if (dev->nErasedBlocks < dev->nReservedBlocks
2990 && dev->allocationPage == 0) {
2991 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2994 /* Next page please.... */
2995 if (dev->allocationBlock >= 0) {
2996 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2998 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2999 dev->allocationPage;
3001 yaffs_SetChunkBit(dev, dev->allocationBlock,
3002 dev->allocationPage);
3004 dev->allocationPage++;
3008 /* If the block is full set the state to full */
3009 if (dev->allocationPage >= dev->nChunksPerBlock) {
3010 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3011 dev->allocationBlock = -1;
3020 T(YAFFS_TRACE_ERROR,
3021 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
3026 static int yaffs_GetErasedChunks(yaffs_Device *dev)
3030 n = dev->nErasedBlocks * dev->nChunksPerBlock;
3032 if (dev->allocationBlock > 0)
3033 n += (dev->nChunksPerBlock - dev->allocationPage);
3040 * yaffs_SkipRestOfBlock() skips over the rest of the allocation block
3041 * if we don't want to write to it.
3043 static void yaffs_SkipRestOfBlock(yaffs_Device *dev)
3045 if(dev->allocationBlock > 0){
3046 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3047 if(bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING){
3048 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3049 dev->allocationBlock = -1;
3055 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
3061 int retVal = YAFFS_OK;
3064 int isCheckpointBlock;
3068 int chunksBefore = yaffs_GetErasedChunks(dev);
3071 yaffs_ExtendedTags tags;
3073 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3075 yaffs_Object *object;
3077 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3080 T(YAFFS_TRACE_TRACING,
3081 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3084 bi->hasShrinkHeader,
3087 /*yaffs_VerifyFreeChunks(dev); */
3089 if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
3090 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3092 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
3094 /* Take off the number of soft deleted entries because
3095 * they're going to get really deleted during GC.
3097 if(dev->gcChunk == 0) /* first time through for this block */
3098 dev->nFreeChunks -= bi->softDeletions;
3102 if (isCheckpointBlock ||
3103 !yaffs_StillSomeChunkBits(dev, block)) {
3104 T(YAFFS_TRACE_TRACING,
3106 ("Collecting block %d that has no chunks in use" TENDSTR),
3108 yaffs_BlockBecameDirty(dev, block);
3111 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3113 yaffs_VerifyBlock(dev, bi, block);
3115 maxCopies = (wholeBlock) ? dev->nChunksPerBlock : 10;
3116 oldChunk = block * dev->nChunksPerBlock + dev->gcChunk;
3118 for (/* init already done */;
3119 retVal == YAFFS_OK &&
3120 dev->gcChunk < dev->nChunksPerBlock &&
3121 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
3123 dev->gcChunk++, oldChunk++) {
3124 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3126 /* This page is in use and might need to be copied off */
3132 yaffs_InitialiseTags(&tags);
3134 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3138 yaffs_FindObjectByNumber(dev,
3141 T(YAFFS_TRACE_GC_DETAIL,
3143 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3144 dev->gcChunk, tags.objectId, tags.chunkId,
3147 if (object && !yaffs_SkipVerification(dev)) {
3148 if (tags.chunkId == 0)
3149 matchingChunk = object->hdrChunk;
3150 else if (object->softDeleted)
3151 matchingChunk = oldChunk; /* Defeat the test */
3153 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
3155 if (oldChunk != matchingChunk)
3156 T(YAFFS_TRACE_ERROR,
3157 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3158 oldChunk, matchingChunk, tags.objectId, tags.chunkId));
3163 T(YAFFS_TRACE_ERROR,
3165 ("page %d in gc has no object: %d %d %d "
3167 tags.objectId, tags.chunkId, tags.byteCount));
3172 object->softDeleted &&
3173 tags.chunkId != 0) {
3174 /* Data chunk in a soft deleted file, throw it away
3175 * It's a soft deleted data chunk,
3176 * No need to copy this, just forget about it and
3177 * fix up the object.
3180 object->nDataChunks--;
3182 if (object->nDataChunks <= 0) {
3183 /* remeber to clean up the object */
3184 dev->gcCleanupList[cleanups] =
3190 /* Todo object && object->deleted && object->nDataChunks == 0 */
3191 /* Deleted object header with no data chunks.
3192 * Can be discarded and the file deleted.
3194 object->hdrChunk = 0;
3195 yaffs_FreeTnode(object->myDev,
3198 object->variant.fileVariant.top = NULL;
3199 yaffs_DoGenericObjectDeletion(object);
3201 } else if (object) {
3202 /* It's either a data chunk in a live file or
3203 * an ObjectHeader, so we're interested in it.
3204 * NB Need to keep the ObjectHeaders of deleted files
3205 * until the whole file has been deleted off
3207 tags.serialNumber++;
3211 if (tags.chunkId == 0) {
3212 /* It is an object Id,
3213 * We need to nuke the shrinkheader flags first
3214 * Also need to clean up shadowing.
3215 * We no longer want the shrinkHeader flag since its work is done
3216 * and if it is left in place it will mess up scanning.
3219 yaffs_ObjectHeader *oh;
3220 oh = (yaffs_ObjectHeader *)buffer;
3222 tags.extraIsShrinkHeader = 0;
3223 oh->shadowsObject = 0;
3224 oh->inbandShadowsObject = 0;
3225 tags.extraShadows = 0;
3227 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
3231 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3234 retVal = YAFFS_FAIL;
3237 /* Ok, now fix up the Tnodes etc. */
3239 if (tags.chunkId == 0) {
3241 object->hdrChunk = newChunk;
3242 object->serial = tags.serialNumber;
3244 /* It's a data chunk */
3245 yaffs_PutChunkIntoFile
3253 if (retVal == YAFFS_OK)
3254 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3259 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3262 /* Do any required cleanups */
3263 for (i = 0; i < cleanups; i++) {
3264 /* Time to delete the file too */
3266 yaffs_FindObjectByNumber(dev,
3267 dev->gcCleanupList[i]);
3269 yaffs_FreeTnode(dev,
3270 object->variant.fileVariant.
3272 object->variant.fileVariant.top = NULL;
3275 ("yaffs: About to finally delete object %d"
3276 TENDSTR), object->objectId));
3277 yaffs_DoGenericObjectDeletion(object);
3278 object->myDev->nDeletedFiles--;
3285 yaffs_VerifyCollectedBlock(dev, bi, block);
3287 chunksAfter = yaffs_GetErasedChunks(dev);
3288 if (chunksBefore >= chunksAfter) {
3291 ("gc did not increase free chunks before %d after %d"
3292 TENDSTR), chunksBefore, chunksAfter));
3295 /* If the gc completed then clear the current gcBlock so that we find another. */
3296 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING) {
3306 /* New garbage collector
3307 * If we're very low on erased blocks then we do aggressive garbage collection
3308 * otherwise we do "leasurely" garbage collection.
3309 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3310 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3312 * The idea is to help clear out space in a more spread-out manner.
3313 * Dunno if it really does anything useful.
3315 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
3319 int gcOk = YAFFS_OK;
3322 int checkpointBlockAdjust;
3324 if (dev->isDoingGC) {
3325 /* Bail out so we don't get recursive gc */
3329 /* This loop should pass the first time.
3330 * We'll only see looping here if the erase of the collected block fails.
3336 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3337 if (checkpointBlockAdjust < 0)
3338 checkpointBlockAdjust = 0;
3340 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3341 /* We need a block soon...*/
3344 /* We're in no hurry */
3348 if (dev->gcBlock <= 0) {
3349 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3353 block = dev->gcBlock;
3356 dev->garbageCollections++;
3358 dev->passiveGarbageCollections++;
3362 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3363 dev->nErasedBlocks, aggressive));
3365 gcOk = yaffs_GarbageCollectBlock(dev, block, aggressive);
3368 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3371 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3372 TENDSTR), dev->nErasedBlocks, maxTries, block));
3374 } while ((dev->nErasedBlocks < dev->nReservedBlocks) &&
3378 return aggressive ? gcOk : YAFFS_OK;
3381 /*------------------------- TAGS --------------------------------*/
3383 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
3386 return (tags->chunkId == chunkInObject &&
3387 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3392 /*-------------------- Data file manipulation -----------------*/
3394 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
3395 yaffs_ExtendedTags *tags)
3397 /*Get the Tnode, then get the level 0 offset chunk offset */
3400 yaffs_ExtendedTags localTags;
3403 yaffs_Device *dev = in->myDev;
3406 /* Passed a NULL, so use our own tags space */
3410 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3413 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3416 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3422 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
3423 yaffs_ExtendedTags *tags)
3425 /* Get the Tnode, then get the level 0 offset chunk offset */
3428 yaffs_ExtendedTags localTags;
3430 yaffs_Device *dev = in->myDev;
3434 /* Passed a NULL, so use our own tags space */
3438 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3442 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3445 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3448 /* Delete the entry in the filestructure (if found) */
3450 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, 0);
3456 #ifdef YAFFS_PARANOID
3458 static int yaffs_CheckFileSanity(yaffs_Object *in)
3466 yaffs_Tags localTags;
3467 yaffs_Tags *tags = &localTags;
3471 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3474 objId = in->objectId;
3475 fSize = in->variant.fileVariant.fileSize;
3477 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3479 for (chunk = 1; chunk <= nChunks; chunk++) {
3480 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3485 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunk);
3487 if (yaffs_CheckChunkBits
3488 (dev, theChunk / dev->nChunksPerBlock,
3489 theChunk % dev->nChunksPerBlock)) {
3491 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3495 (tags, in->objectId, chunk, chunkDeleted)) {
3505 /* T(("No level 0 found for %d\n", chunk)); */
3509 return failed ? YAFFS_FAIL : YAFFS_OK;
3514 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
3515 int chunkInNAND, int inScan)
3517 /* NB inScan is zero unless scanning.
3518 * For forward scanning, inScan is > 0;
3519 * for backward scanning inScan is < 0
3521 * chunkInNAND = 0 is a dummy insert to make sure the tnodes are there.
3525 yaffs_Device *dev = in->myDev;
3527 yaffs_ExtendedTags existingTags;
3528 yaffs_ExtendedTags newTags;
3529 unsigned existingSerial, newSerial;
3531 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3532 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3533 * If it is not during Scanning then something went wrong!
3536 T(YAFFS_TRACE_ERROR,
3538 ("yaffs tragedy:attempt to put data chunk into a non-file"
3543 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3547 tn = yaffs_AddOrFindLevel0Tnode(dev,
3548 &in->variant.fileVariant,
3555 /* Dummy insert, bail now */
3559 existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3562 /* If we're scanning then we need to test for duplicates
3563 * NB This does not need to be efficient since it should only ever
3564 * happen when the power fails during a write, then only one
3565 * chunk should ever be affected.
3567 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3568 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3571 if (existingChunk > 0) {
3572 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3573 * thus we have to do a FindChunkInFile to get the real chunk id.
3575 * We have a duplicate now we need to decide which one to use:
3577 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3578 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3579 * YAFFS1: Get both sets of tags and compare serial numbers.
3583 /* Only do this for forward scanning */
3584 yaffs_ReadChunkWithTagsFromNAND(dev,
3588 /* Do a proper find */
3590 yaffs_FindChunkInFile(in, chunkInInode,
3594 if (existingChunk <= 0) {
3595 /*Hoosterman - how did this happen? */
3597 T(YAFFS_TRACE_ERROR,
3599 ("yaffs tragedy: existing chunk < 0 in scan"
3604 /* NB The deleted flags should be false, otherwise the chunks will
3605 * not be loaded during a scan
3609 newSerial = newTags.serialNumber;
3610 existingSerial = existingTags.serialNumber;
3614 (in->myDev->isYaffs2 ||
3615 existingChunk <= 0 ||
3616 ((existingSerial + 1) & 3) == newSerial)) {
3617 /* Forward scanning.
3619 * Delete the old one and drop through to update the tnode
3621 yaffs_DeleteChunk(dev, existingChunk, 1,
3624 /* Backward scanning or we want to use the existing one
3626 * Delete the new one and return early so that the tnode isn't changed
3628 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3636 if (existingChunk == 0)
3639 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
3644 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
3647 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3649 if (chunkInNAND >= 0)
3650 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3653 T(YAFFS_TRACE_NANDACCESS,
3654 (TSTR("Chunk %d not found zero instead" TENDSTR),
3656 /* get sane (zero) data if you read a hole */
3657 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3663 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
3667 yaffs_ExtendedTags tags;
3668 yaffs_BlockInfo *bi;
3674 block = chunkId / dev->nChunksPerBlock;
3675 page = chunkId % dev->nChunksPerBlock;
3678 if (!yaffs_CheckChunkBit(dev, block, page))
3679 T(YAFFS_TRACE_VERIFY,
3680 (TSTR("Deleting invalid chunk %d"TENDSTR),
3683 bi = yaffs_GetBlockInfo(dev, block);
3685 T(YAFFS_TRACE_DELETION,
3686 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3689 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3691 yaffs_InitialiseTags(&tags);
3693 tags.chunkDeleted = 1;
3695 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3696 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3698 dev->nUnmarkedDeletions++;
3701 /* Pull out of the management area.
3702 * If the whole block became dirty, this will kick off an erasure.
3704 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3705 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3706 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3707 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3710 yaffs_ClearChunkBit(dev, block, page);
3714 if (bi->pagesInUse == 0 &&
3715 !bi->hasShrinkHeader &&
3716 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3717 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3718 yaffs_BlockBecameDirty(dev, block);
3725 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
3726 const __u8 *buffer, int nBytes,
3729 /* Find old chunk Need to do this to get serial number
3730 * Write new one and patch into tree.
3731 * Invalidate old tags.
3735 yaffs_ExtendedTags prevTags;
3738 yaffs_ExtendedTags newTags;
3740 yaffs_Device *dev = in->myDev;
3742 yaffs_CheckGarbageCollection(dev);
3744 /* Get the previous chunk at this location in the file if it exists */
3745 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3747 /* Set up new tags */
3748 yaffs_InitialiseTags(&newTags);
3750 newTags.chunkId = chunkInInode;
3751 newTags.objectId = in->objectId;
3752 newTags.serialNumber =
3753 (prevChunkId > 0) ? prevTags.serialNumber + 1 : 1;
3754 newTags.byteCount = nBytes;
3756 if (nBytes < 1 || nBytes > dev->totalBytesPerChunk) {
3757 T(YAFFS_TRACE_ERROR,
3758 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3763 * If there isn't already a chunk there then do a dummy
3764 * insert to make sue we have the desired tnode structure.
3766 if(prevChunkId < 1 &&
3767 yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0) != YAFFS_OK)
3771 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3774 if (newChunkId > 0) {
3775 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3777 if (prevChunkId > 0)
3778 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3780 yaffs_CheckFileSanity(in);
3786 /* UpdateObjectHeader updates the header on NAND for an object.
3787 * If name is not NULL, then that new name is used.
3789 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
3790 int isShrink, int shadows)
3793 yaffs_BlockInfo *bi;
3795 yaffs_Device *dev = in->myDev;
3802 yaffs_ExtendedTags newTags;
3803 yaffs_ExtendedTags oldTags;
3804 YCHAR *alias = NULL;
3806 __u8 *buffer = NULL;
3807 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3809 yaffs_ObjectHeader *oh = NULL;
3811 yaffs_strcpy(oldName, _Y("silly old name"));
3815 in == dev->rootDir || /* The rootDir should also be saved */
3818 yaffs_CheckGarbageCollection(dev);
3819 yaffs_CheckObjectDetailsLoaded(in);
3821 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3822 oh = (yaffs_ObjectHeader *) buffer;
3824 prevChunkId = in->hdrChunk;
3826 if (prevChunkId > 0) {
3827 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3830 yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
3832 memcpy(oldName, oh->name, sizeof(oh->name));
3835 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3837 oh->type = in->variantType;
3838 oh->yst_mode = in->yst_mode;
3839 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3841 #ifdef CONFIG_YAFFS_WINCE
3842 oh->win_atime[0] = in->win_atime[0];
3843 oh->win_ctime[0] = in->win_ctime[0];
3844 oh->win_mtime[0] = in->win_mtime[0];
3845 oh->win_atime[1] = in->win_atime[1];
3846 oh->win_ctime[1] = in->win_ctime[1];
3847 oh->win_mtime[1] = in->win_mtime[1];
3849 oh->yst_uid = in->yst_uid;
3850 oh->yst_gid = in->yst_gid;
3851 oh->yst_atime = in->yst_atime;
3852 oh->yst_mtime = in->yst_mtime;
3853 oh->yst_ctime = in->yst_ctime;
3854 oh->yst_rdev = in->yst_rdev;
3857 oh->parentObjectId = in->parent->objectId;
3859 oh->parentObjectId = 0;
3861 if (name && *name) {
3862 memset(oh->name, 0, sizeof(oh->name));
3863 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3864 } else if (prevChunkId > 0)
3865 memcpy(oh->name, oldName, sizeof(oh->name));
3867 memset(oh->name, 0, sizeof(oh->name));
3869 oh->isShrink = isShrink;
3871 switch (in->variantType) {
3872 case YAFFS_OBJECT_TYPE_UNKNOWN:
3873 /* Should not happen */
3875 case YAFFS_OBJECT_TYPE_FILE:
3877 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3878 || oh->parentObjectId ==
3879 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3880 fileVariant.fileSize;
3882 case YAFFS_OBJECT_TYPE_HARDLINK:
3883 oh->equivalentObjectId =
3884 in->variant.hardLinkVariant.equivalentObjectId;
3886 case YAFFS_OBJECT_TYPE_SPECIAL:
3889 case YAFFS_OBJECT_TYPE_DIRECTORY:
3892 case YAFFS_OBJECT_TYPE_SYMLINK:
3893 alias = in->variant.symLinkVariant.alias;
3895 alias = _Y("no alias");
3896 yaffs_strncpy(oh->alias,
3898 YAFFS_MAX_ALIAS_LENGTH);
3899 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3904 yaffs_InitialiseTags(&newTags);
3906 newTags.chunkId = 0;
3907 newTags.objectId = in->objectId;
3908 newTags.serialNumber = in->serial;
3910 /* Add extra info for file header */
3912 newTags.extraHeaderInfoAvailable = 1;
3913 newTags.extraParentObjectId = oh->parentObjectId;
3914 newTags.extraFileLength = oh->fileSize;
3915 newTags.extraIsShrinkHeader = oh->isShrink;
3916 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3917 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3918 newTags.extraObjectType = in->variantType;
3920 yaffs_VerifyObjectHeader(in, oh, &newTags, 1);
3922 /* Create new chunk in NAND */
3924 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3925 (prevChunkId > 0) ? 1 : 0);
3927 if (newChunkId >= 0) {
3929 in->hdrChunk = newChunkId;
3931 if (prevChunkId > 0) {
3932 yaffs_DeleteChunk(dev, prevChunkId, 1,
3936 if (!yaffs_ObjectHasCachedWriteData(in))
3939 /* If this was a shrink, then mark the block that the chunk lives on */
3941 bi = yaffs_GetBlockInfo(in->myDev,
3942 newChunkId / in->myDev->nChunksPerBlock);
3943 bi->hasShrinkHeader = 1;
3948 retVal = newChunkId;
3953 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3958 /*------------------------ Short Operations Cache ----------------------------------------
3959 * In many situations where there is no high level buffering (eg WinCE) a lot of
3960 * reads might be short sequential reads, and a lot of writes may be short
3961 * sequential writes. eg. scanning/writing a jpeg file.
3962 * In these cases, a short read/write cache can provide a huge perfomance benefit
3963 * with dumb-as-a-rock code.
3964 * In Linux, the page cache provides read buffering aand the short op cache provides write
3967 * There are a limited number (~10) of cache chunks per device so that we don't
3968 * need a very intelligent search.
3971 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3973 yaffs_Device *dev = obj->myDev;
3975 yaffs_ChunkCache *cache;
3976 int nCaches = obj->myDev->nShortOpCaches;
3978 for (i = 0; i < nCaches; i++) {
3979 cache = &dev->srCache[i];
3980 if (cache->object == obj &&
3989 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
3991 yaffs_Device *dev = obj->myDev;
3992 int lowest = -99; /* Stop compiler whining. */
3994 yaffs_ChunkCache *cache;
3995 int chunkWritten = 0;
3996 int nCaches = obj->myDev->nShortOpCaches;
4002 /* Find the dirty cache for this object with the lowest chunk id. */
4003 for (i = 0; i < nCaches; i++) {
4004 if (dev->srCache[i].object == obj &&
4005 dev->srCache[i].dirty) {
4007 || dev->srCache[i].chunkId <
4009 cache = &dev->srCache[i];
4010 lowest = cache->chunkId;
4015 if (cache && !cache->locked) {
4016 /* Write it out and free it up */
4019 yaffs_WriteChunkDataToObject(cache->object,
4025 cache->object = NULL;
4028 } while (cache && chunkWritten > 0);
4031 /* Hoosterman, disk full while writing cache out. */
4032 T(YAFFS_TRACE_ERROR,
4033 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
4040 /*yaffs_FlushEntireDeviceCache(dev)
4045 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
4048 int nCaches = dev->nShortOpCaches;
4051 /* Find a dirty object in the cache and flush it...
4052 * until there are no further dirty objects.
4056 for (i = 0; i < nCaches && !obj; i++) {
4057 if (dev->srCache[i].object &&
4058 dev->srCache[i].dirty)
4059 obj = dev->srCache[i].object;
4063 yaffs_FlushFilesChunkCache(obj);
4070 /* Grab us a cache chunk for use.
4071 * First look for an empty one.
4072 * Then look for the least recently used non-dirty one.
4073 * Then look for the least recently used dirty one...., flush and look again.
4075 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
4079 if (dev->nShortOpCaches > 0) {
4080 for (i = 0; i < dev->nShortOpCaches; i++) {
4081 if (!dev->srCache[i].object)
4082 return &dev->srCache[i];
4089 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
4091 yaffs_ChunkCache *cache;
4092 yaffs_Object *theObj;
4097 if (dev->nShortOpCaches > 0) {
4098 /* Try find a non-dirty one... */
4100 cache = yaffs_GrabChunkCacheWorker(dev);
4103 /* They were all dirty, find the last recently used object and flush
4104 * its cache, then find again.
4105 * NB what's here is not very accurate, we actually flush the object
4106 * the last recently used page.
4109 /* With locking we can't assume we can use entry zero */
4116 for (i = 0; i < dev->nShortOpCaches; i++) {
4117 if (dev->srCache[i].object &&
4118 !dev->srCache[i].locked &&
4119 (dev->srCache[i].lastUse < usage || !cache)) {
4120 usage = dev->srCache[i].lastUse;
4121 theObj = dev->srCache[i].object;
4122 cache = &dev->srCache[i];
4127 if (!cache || cache->dirty) {
4128 /* Flush and try again */
4129 yaffs_FlushFilesChunkCache(theObj);
4130 cache = yaffs_GrabChunkCacheWorker(dev);
4140 /* Find a cached chunk */
4141 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj,
4144 yaffs_Device *dev = obj->myDev;
4146 if (dev->nShortOpCaches > 0) {
4147 for (i = 0; i < dev->nShortOpCaches; i++) {
4148 if (dev->srCache[i].object == obj &&
4149 dev->srCache[i].chunkId == chunkId) {
4152 return &dev->srCache[i];
4159 /* Mark the chunk for the least recently used algorithym */
4160 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache,
4164 if (dev->nShortOpCaches > 0) {
4165 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4166 /* Reset the cache usages */
4168 for (i = 1; i < dev->nShortOpCaches; i++)
4169 dev->srCache[i].lastUse = 0;
4176 cache->lastUse = dev->srLastUse;
4183 /* Invalidate a single cache page.
4184 * Do this when a whole page gets written,
4185 * ie the short cache for this page is no longer valid.
4187 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
4189 if (object->myDev->nShortOpCaches > 0) {
4190 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4193 cache->object = NULL;
4197 /* Invalidate all the cache pages associated with this object
4198 * Do this whenever ther file is deleted or resized.
4200 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
4203 yaffs_Device *dev = in->myDev;
4205 if (dev->nShortOpCaches > 0) {
4206 /* Invalidate it. */
4207 for (i = 0; i < dev->nShortOpCaches; i++) {
4208 if (dev->srCache[i].object == in)
4209 dev->srCache[i].object = NULL;
4214 /*--------------------- Checkpointing --------------------*/
4217 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev, int head)
4219 yaffs_CheckpointValidity cp;
4221 memset(&cp, 0, sizeof(cp));
4223 cp.structType = sizeof(cp);
4224 cp.magic = YAFFS_MAGIC;
4225 cp.version = YAFFS_CHECKPOINT_VERSION;
4226 cp.head = (head) ? 1 : 0;
4228 return (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp)) ?
4232 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4234 yaffs_CheckpointValidity cp;
4237 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4240 ok = (cp.structType == sizeof(cp)) &&
4241 (cp.magic == YAFFS_MAGIC) &&
4242 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4243 (cp.head == ((head) ? 1 : 0));
4247 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4250 cp->nErasedBlocks = dev->nErasedBlocks;
4251 cp->allocationBlock = dev->allocationBlock;
4252 cp->allocationPage = dev->allocationPage;
4253 cp->nFreeChunks = dev->nFreeChunks;
4255 cp->nDeletedFiles = dev->nDeletedFiles;
4256 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4257 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4258 cp->sequenceNumber = dev->sequenceNumber;
4259 cp->oldestDirtySequence = dev->oldestDirtySequence;
4263 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4264 yaffs_CheckpointDevice *cp)
4266 dev->nErasedBlocks = cp->nErasedBlocks;
4267 dev->allocationBlock = cp->allocationBlock;
4268 dev->allocationPage = cp->allocationPage;
4269 dev->nFreeChunks = cp->nFreeChunks;
4271 dev->nDeletedFiles = cp->nDeletedFiles;
4272 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4273 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4274 dev->sequenceNumber = cp->sequenceNumber;
4275 dev->oldestDirtySequence = cp->oldestDirtySequence;
4279 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4281 yaffs_CheckpointDevice cp;
4283 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4287 /* Write device runtime values*/
4288 yaffs_DeviceToCheckpointDevice(&cp, dev);
4289 cp.structType = sizeof(cp);
4291 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4293 /* Write block info */
4295 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4296 ok = (yaffs_CheckpointWrite(dev, dev->blockInfo, nBytes) == nBytes);
4299 /* Write chunk bits */
4301 nBytes = nBlocks * dev->chunkBitmapStride;
4302 ok = (yaffs_CheckpointWrite(dev, dev->chunkBits, nBytes) == nBytes);
4308 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4310 yaffs_CheckpointDevice cp;
4312 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4316 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4320 if (cp.structType != sizeof(cp))
4324 yaffs_CheckpointDeviceToDevice(dev, &cp);
4326 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4328 ok = (yaffs_CheckpointRead(dev, dev->blockInfo, nBytes) == nBytes);
4332 nBytes = nBlocks * dev->chunkBitmapStride;
4334 ok = (yaffs_CheckpointRead(dev, dev->chunkBits, nBytes) == nBytes);
4339 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4343 cp->objectId = obj->objectId;
4344 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4345 cp->hdrChunk = obj->hdrChunk;
4346 cp->variantType = obj->variantType;
4347 cp->deleted = obj->deleted;
4348 cp->softDeleted = obj->softDeleted;
4349 cp->unlinked = obj->unlinked;
4350 cp->fake = obj->fake;
4351 cp->renameAllowed = obj->renameAllowed;
4352 cp->unlinkAllowed = obj->unlinkAllowed;
4353 cp->serial = obj->serial;
4354 cp->nDataChunks = obj->nDataChunks;
4356 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4357 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4358 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4359 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4362 static int yaffs_CheckpointObjectToObject(yaffs_Object *obj, yaffs_CheckpointObject *cp)
4365 yaffs_Object *parent;
4367 if (obj->variantType != cp->variantType) {
4368 T(YAFFS_TRACE_ERROR, (TSTR("Checkpoint read object %d type %d "
4369 TCONT("chunk %d does not match existing object type %d")
4370 TENDSTR), cp->objectId, cp->variantType, cp->hdrChunk,
4375 obj->objectId = cp->objectId;
4378 parent = yaffs_FindOrCreateObjectByNumber(
4381 YAFFS_OBJECT_TYPE_DIRECTORY);
4386 if (parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4387 T(YAFFS_TRACE_ALWAYS, (TSTR("Checkpoint read object %d parent %d type %d"
4388 TCONT(" chunk %d Parent type, %d, not directory")
4390 cp->objectId, cp->parentId, cp->variantType,
4391 cp->hdrChunk, parent->variantType));
4394 yaffs_AddObjectToDirectory(parent, obj);
4397 obj->hdrChunk = cp->hdrChunk;
4398 obj->variantType = cp->variantType;
4399 obj->deleted = cp->deleted;
4400 obj->softDeleted = cp->softDeleted;
4401 obj->unlinked = cp->unlinked;
4402 obj->fake = cp->fake;
4403 obj->renameAllowed = cp->renameAllowed;
4404 obj->unlinkAllowed = cp->unlinkAllowed;
4405 obj->serial = cp->serial;
4406 obj->nDataChunks = cp->nDataChunks;
4408 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4409 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4410 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4411 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4413 if (obj->hdrChunk > 0)
4414 obj->lazyLoaded = 1;
4420 static int yaffs_CheckpointTnodeWorker(yaffs_Object *in, yaffs_Tnode *tn,
4421 __u32 level, int chunkOffset)
4424 yaffs_Device *dev = in->myDev;
4426 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4428 if (tnodeSize < sizeof(yaffs_Tnode))
4429 tnodeSize = sizeof(yaffs_Tnode);
4435 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
4436 if (tn->internal[i]) {
4437 ok = yaffs_CheckpointTnodeWorker(in,
4440 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4443 } else if (level == 0) {
4444 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4445 ok = (yaffs_CheckpointWrite(dev, &baseOffset, sizeof(baseOffset)) == sizeof(baseOffset));
4447 ok = (yaffs_CheckpointWrite(dev, tn, tnodeSize) == tnodeSize);
4455 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4457 __u32 endMarker = ~0;
4460 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4461 ok = yaffs_CheckpointTnodeWorker(obj,
4462 obj->variant.fileVariant.top,
4463 obj->variant.fileVariant.topLevel,
4466 ok = (yaffs_CheckpointWrite(obj->myDev, &endMarker, sizeof(endMarker)) ==
4473 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4477 yaffs_Device *dev = obj->myDev;
4478 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4481 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4483 if (tnodeSize < sizeof(yaffs_Tnode))
4484 tnodeSize = sizeof(yaffs_Tnode);
4486 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4488 while (ok && (~baseChunk)) {
4490 /* Read level 0 tnode */
4493 tn = yaffs_GetTnodeRaw(dev);
4495 ok = (yaffs_CheckpointRead(dev, tn, tnodeSize) == tnodeSize);
4500 ok = yaffs_AddOrFindLevel0Tnode(dev,
4506 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4510 T(YAFFS_TRACE_CHECKPOINT, (
4511 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4512 nread, baseChunk, ok));
4518 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4521 yaffs_CheckpointObject cp;
4524 struct ylist_head *lh;
4527 /* Iterate through the objects in each hash entry,
4528 * dumping them to the checkpointing stream.
4531 for (i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++) {
4532 ylist_for_each(lh, &dev->objectBucket[i].list) {
4534 obj = ylist_entry(lh, yaffs_Object, hashLink);
4535 if (!obj->deferedFree) {
4536 yaffs_ObjectToCheckpointObject(&cp, obj);
4537 cp.structType = sizeof(cp);
4539 T(YAFFS_TRACE_CHECKPOINT, (
4540 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %p" TENDSTR),
4541 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk, obj));
4543 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4545 if (ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4546 ok = yaffs_WriteCheckpointTnodes(obj);
4552 /* Dump end of list */
4553 memset(&cp, 0xFF, sizeof(yaffs_CheckpointObject));
4554 cp.structType = sizeof(cp);
4557 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4562 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4565 yaffs_CheckpointObject cp;
4568 yaffs_Object *hardList = NULL;
4570 while (ok && !done) {
4571 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4572 if (cp.structType != sizeof(cp)) {
4573 T(YAFFS_TRACE_CHECKPOINT, (TSTR("struct size %d instead of %d ok %d"TENDSTR),
4574 cp.structType, (int)sizeof(cp), ok));
4578 T(YAFFS_TRACE_CHECKPOINT, (TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4579 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk));
4581 if (ok && cp.objectId == ~0)
4584 obj = yaffs_FindOrCreateObjectByNumber(dev, cp.objectId, cp.variantType);
4586 ok = yaffs_CheckpointObjectToObject(obj, &cp);
4589 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4590 ok = yaffs_ReadCheckpointTnodes(obj);
4591 } else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4592 obj->hardLinks.next =
4593 (struct ylist_head *) hardList;
4602 yaffs_HardlinkFixup(dev, hardList);
4607 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4609 __u32 checkpointSum;
4612 yaffs_GetCheckpointSum(dev, &checkpointSum);
4614 ok = (yaffs_CheckpointWrite(dev, &checkpointSum, sizeof(checkpointSum)) == sizeof(checkpointSum));
4622 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4624 __u32 checkpointSum0;
4625 __u32 checkpointSum1;
4628 yaffs_GetCheckpointSum(dev, &checkpointSum0);
4630 ok = (yaffs_CheckpointRead(dev, &checkpointSum1, sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4635 if (checkpointSum0 != checkpointSum1)
4642 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4646 if (dev->skipCheckpointWrite || !dev->isYaffs2) {
4647 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint write" TENDSTR)));
4652 ok = yaffs_CheckpointOpen(dev, 1);
4655 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4656 ok = yaffs_WriteCheckpointValidityMarker(dev, 1);
4659 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint device" TENDSTR)));
4660 ok = yaffs_WriteCheckpointDevice(dev);
4663 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint objects" TENDSTR)));
4664 ok = yaffs_WriteCheckpointObjects(dev);
4667 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4668 ok = yaffs_WriteCheckpointValidityMarker(dev, 0);
4672 ok = yaffs_WriteCheckpointSum(dev);
4674 if (!yaffs_CheckpointClose(dev))
4678 dev->isCheckpointed = 1;
4680 dev->isCheckpointed = 0;
4682 return dev->isCheckpointed;
4685 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4689 if (dev->skipCheckpointRead || !dev->isYaffs2) {
4690 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint read" TENDSTR)));
4695 ok = yaffs_CheckpointOpen(dev, 0); /* open for read */
4698 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4699 ok = yaffs_ReadCheckpointValidityMarker(dev, 1);
4702 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint device" TENDSTR)));
4703 ok = yaffs_ReadCheckpointDevice(dev);
4706 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint objects" TENDSTR)));
4707 ok = yaffs_ReadCheckpointObjects(dev);
4710 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4711 ok = yaffs_ReadCheckpointValidityMarker(dev, 0);
4715 ok = yaffs_ReadCheckpointSum(dev);
4716 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint checksum %d" TENDSTR), ok));
4719 if (!yaffs_CheckpointClose(dev))
4723 dev->isCheckpointed = 1;
4725 dev->isCheckpointed = 0;
4731 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4733 if (dev->isCheckpointed ||
4734 dev->blocksInCheckpoint > 0) {
4735 dev->isCheckpointed = 0;
4736 yaffs_CheckpointInvalidateStream(dev);
4737 if (dev->superBlock && dev->markSuperBlockDirty)
4738 dev->markSuperBlockDirty(dev->superBlock);
4743 int yaffs_CheckpointSave(yaffs_Device *dev)
4746 T(YAFFS_TRACE_CHECKPOINT, (TSTR("save entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4748 yaffs_VerifyObjects(dev);
4749 yaffs_VerifyBlocks(dev);
4750 yaffs_VerifyFreeChunks(dev);
4752 if (!dev->isCheckpointed) {
4753 yaffs_InvalidateCheckpoint(dev);
4754 yaffs_WriteCheckpointData(dev);
4757 T(YAFFS_TRACE_ALWAYS, (TSTR("save exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4759 return dev->isCheckpointed;
4762 int yaffs_CheckpointRestore(yaffs_Device *dev)
4765 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4767 retval = yaffs_ReadCheckpointData(dev);
4769 if (dev->isCheckpointed) {
4770 yaffs_VerifyObjects(dev);
4771 yaffs_VerifyBlocks(dev);
4772 yaffs_VerifyFreeChunks(dev);
4775 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4780 /*--------------------- File read/write ------------------------
4781 * Read and write have very similar structures.
4782 * In general the read/write has three parts to it
4783 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4784 * Some complete chunks
4785 * An incomplete chunk to end off with
4787 * Curve-balls: the first chunk might also be the last chunk.
4790 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 *buffer, loff_t offset,
4799 yaffs_ChunkCache *cache;
4806 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4807 /* start = offset % dev->nDataBytesPerChunk; */
4808 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4811 /* OK now check for the curveball where the start and end are in
4814 if ((start + n) < dev->nDataBytesPerChunk)
4817 nToCopy = dev->nDataBytesPerChunk - start;
4819 cache = yaffs_FindChunkCache(in, chunk);
4821 /* If the chunk is already in the cache or it is less than a whole chunk
4822 * or we're using inband tags then use the cache (if there is caching)
4823 * else bypass the cache.
4825 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4826 if (dev->nShortOpCaches > 0) {
4828 /* If we can't find the data in the cache, then load it up. */
4831 cache = yaffs_GrabChunkCache(in->myDev);
4833 cache->chunkId = chunk;
4836 yaffs_ReadChunkDataFromObject(in, chunk,
4842 yaffs_UseChunkCache(dev, cache, 0);
4847 memcpy(buffer, &cache->data[start], nToCopy);
4851 /* Read into the local buffer then copy..*/
4854 yaffs_GetTempBuffer(dev, __LINE__);
4855 yaffs_ReadChunkDataFromObject(in, chunk,
4858 memcpy(buffer, &localBuffer[start], nToCopy);
4861 yaffs_ReleaseTempBuffer(dev, localBuffer,
4867 /* A full chunk. Read directly into the supplied buffer. */
4868 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4882 int yaffs_WriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
4883 int nBytes, int writeThrough)
4892 int startOfWrite = offset;
4893 int chunkWritten = 0;
4901 while (n > 0 && chunkWritten >= 0) {
4902 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4903 /* start = offset % dev->nDataBytesPerChunk; */
4904 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4906 if (chunk * dev->nDataBytesPerChunk + start != offset ||
4907 start >= dev->nDataBytesPerChunk) {
4908 T(YAFFS_TRACE_ERROR, (
4909 TSTR("AddrToChunk of offset %d gives chunk %d start %d"
4911 (int)offset, chunk, start));
4915 /* OK now check for the curveball where the start and end are in
4919 if ((start + n) < dev->nDataBytesPerChunk) {
4922 /* Now folks, to calculate how many bytes to write back....
4923 * If we're overwriting and not writing to then end of file then
4924 * we need to write back as much as was there before.
4927 chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
4929 if (chunkStart > in->variant.fileVariant.fileSize)
4930 nBytesRead = 0; /* Past end of file */
4932 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
4934 if (nBytesRead > dev->nDataBytesPerChunk)
4935 nBytesRead = dev->nDataBytesPerChunk;
4939 (start + n)) ? nBytesRead : (start + n);
4941 if (nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
4945 nToCopy = dev->nDataBytesPerChunk - start;
4946 nToWriteBack = dev->nDataBytesPerChunk;
4949 if (nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4950 /* An incomplete start or end chunk (or maybe both start and end chunk),
4951 * or we're using inband tags, so we want to use the cache buffers.
4953 if (dev->nShortOpCaches > 0) {
4954 yaffs_ChunkCache *cache;
4955 /* If we can't find the data in the cache, then load the cache */
4956 cache = yaffs_FindChunkCache(in, chunk);
4959 && yaffs_CheckSpaceForAllocation(in->
4961 cache = yaffs_GrabChunkCache(in->myDev);
4963 cache->chunkId = chunk;
4966 yaffs_ReadChunkDataFromObject(in, chunk,
4971 !yaffs_CheckSpaceForAllocation(in->myDev)) {
4972 /* Drop the cache if it was a read cache item and
4973 * no space check has been made for it.
4979 yaffs_UseChunkCache(dev, cache, 1);
4983 memcpy(&cache->data[start], buffer,
4988 cache->nBytes = nToWriteBack;
4992 yaffs_WriteChunkDataToObject
4995 cache->data, cache->nBytes,
5001 chunkWritten = -1; /* fail the write */
5004 /* An incomplete start or end chunk (or maybe both start and end chunk)
5005 * Read into the local buffer then copy, then copy over and write back.
5009 yaffs_GetTempBuffer(dev, __LINE__);
5011 yaffs_ReadChunkDataFromObject(in, chunk,
5016 memcpy(&localBuffer[start], buffer, nToCopy);
5019 yaffs_WriteChunkDataToObject(in, chunk,
5024 yaffs_ReleaseTempBuffer(dev, localBuffer,
5030 /* A full chunk. Write directly from the supplied buffer. */
5035 yaffs_WriteChunkDataToObject(in, chunk, buffer,
5036 dev->nDataBytesPerChunk,
5039 /* Since we've overwritten the cached data, we better invalidate it. */
5040 yaffs_InvalidateChunkCache(in, chunk);
5043 if (chunkWritten >= 0) {
5052 /* Update file object */
5054 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
5055 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
5063 /* ---------------------- File resizing stuff ------------------ */
5065 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
5068 yaffs_Device *dev = in->myDev;
5069 int oldFileSize = in->variant.fileVariant.fileSize;
5071 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
5073 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
5074 dev->nDataBytesPerChunk;
5078 /* Delete backwards so that we don't end up with holes if
5079 * power is lost part-way through the operation.
5081 for (i = lastDel; i >= startDel; i--) {
5082 /* NB this could be optimised somewhat,
5083 * eg. could retrieve the tags and write them without
5084 * using yaffs_DeleteChunk
5087 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5090 (dev->internalStartBlock * dev->nChunksPerBlock)
5092 ((dev->internalEndBlock +
5093 1) * dev->nChunksPerBlock)) {
5094 T(YAFFS_TRACE_ALWAYS,
5095 (TSTR("Found daft chunkId %d for %d" TENDSTR),
5099 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5106 int yaffs_ResizeFile(yaffs_Object *in, loff_t newSize)
5109 int oldFileSize = in->variant.fileVariant.fileSize;
5110 __u32 newSizeOfPartialChunk;
5113 yaffs_Device *dev = in->myDev;
5115 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5117 yaffs_FlushFilesChunkCache(in);
5118 yaffs_InvalidateWholeChunkCache(in);
5120 yaffs_CheckGarbageCollection(dev);
5122 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
5125 if (newSize == oldFileSize)
5128 if (newSize < oldFileSize) {
5130 yaffs_PruneResizedChunks(in, newSize);
5132 if (newSizeOfPartialChunk != 0) {
5133 int lastChunk = 1 + newFullChunks;
5135 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5137 /* Got to read and rewrite the last chunk with its new size and zero pad */
5138 yaffs_ReadChunkDataFromObject(in, lastChunk,
5141 memset(localBuffer + newSizeOfPartialChunk, 0,
5142 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5144 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5145 newSizeOfPartialChunk, 1);
5147 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5150 in->variant.fileVariant.fileSize = newSize;
5152 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5154 /* newsSize > oldFileSize */
5155 in->variant.fileVariant.fileSize = newSize;
5159 /* Write a new object header to reflect the resize.
5160 * show we've shrunk the file, if need be
5161 * Do this only if the file is not in the deleted directories
5162 * and is not shadowed.
5166 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5167 in->parent->objectId != YAFFS_OBJECTID_DELETED)
5168 yaffs_UpdateObjectHeader(in, NULL, 0,
5169 (newSize < oldFileSize) ? 1 : 0, 0);
5174 loff_t yaffs_GetFileSize(yaffs_Object *obj)
5176 YCHAR *alias = NULL;
5177 obj = yaffs_GetEquivalentObject(obj);
5179 switch (obj->variantType) {
5180 case YAFFS_OBJECT_TYPE_FILE:
5181 return obj->variant.fileVariant.fileSize;
5182 case YAFFS_OBJECT_TYPE_SYMLINK:
5183 alias = obj->variant.symLinkVariant.alias;
5186 return yaffs_strnlen(alias,YAFFS_MAX_ALIAS_LENGTH);
5194 int yaffs_FlushFile(yaffs_Object *in, int updateTime, int dataSync)
5198 yaffs_FlushFilesChunkCache(in);
5199 if(dataSync) /* Only sync data */
5203 #ifdef CONFIG_YAFFS_WINCE
5204 yfsd_WinFileTimeNow(in->win_mtime);
5207 in->yst_mtime = Y_CURRENT_TIME;
5212 retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5213 0) ? YAFFS_OK : YAFFS_FAIL;
5223 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
5226 /* First off, invalidate the file's data in the cache, without flushing. */
5227 yaffs_InvalidateWholeChunkCache(in);
5229 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5230 /* Move to the unlinked directory so we have a record that it was deleted. */
5231 yaffs_ChangeObjectName(in, in->myDev->deletedDir, _Y("deleted"), 0, 0);
5235 yaffs_RemoveObjectFromDirectory(in);
5236 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5239 yaffs_FreeObject(in);
5244 /* yaffs_DeleteFile deletes the whole file data
5245 * and the inode associated with the file.
5246 * It does not delete the links associated with the file.
5248 static int yaffs_UnlinkFileIfNeeded(yaffs_Object *in)
5252 int immediateDeletion = 0;
5255 immediateDeletion = 1;
5257 if (immediateDeletion) {
5259 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5260 _Y("deleted"), 0, 0);
5261 T(YAFFS_TRACE_TRACING,
5262 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5265 in->myDev->nDeletedFiles++;
5266 if (1 || in->myDev->isYaffs2)
5267 yaffs_ResizeFile(in, 0);
5268 yaffs_SoftDeleteFile(in);
5271 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5272 _Y("unlinked"), 0, 0);
5279 int yaffs_DeleteFile(yaffs_Object *in)
5281 int retVal = YAFFS_OK;
5282 int deleted = in->deleted;
5284 yaffs_ResizeFile(in, 0);
5286 if (in->nDataChunks > 0) {
5287 /* Use soft deletion if there is data in the file.
5288 * That won't be the case if it has been resized to zero.
5291 retVal = yaffs_UnlinkFileIfNeeded(in);
5293 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5296 in->myDev->nDeletedFiles++;
5297 yaffs_SoftDeleteFile(in);
5299 return deleted ? YAFFS_OK : YAFFS_FAIL;
5301 /* The file has no data chunks so we toss it immediately */
5302 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5303 in->variant.fileVariant.top = NULL;
5304 yaffs_DoGenericObjectDeletion(in);
5310 static int yaffs_IsNonEmptyDirectory(yaffs_Object *obj)
5312 return (obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) &&
5313 !(ylist_empty(&obj->variant.directoryVariant.children));
5316 static int yaffs_DeleteDirectory(yaffs_Object *obj)
5318 /* First check that the directory is empty. */
5319 if (yaffs_IsNonEmptyDirectory(obj))
5322 return yaffs_DoGenericObjectDeletion(obj);
5325 static int yaffs_DeleteSymLink(yaffs_Object *in)
5327 if(in->variant.symLinkVariant.alias)
5328 YFREE(in->variant.symLinkVariant.alias);
5329 in->variant.symLinkVariant.alias=NULL;
5331 return yaffs_DoGenericObjectDeletion(in);
5334 static int yaffs_DeleteHardLink(yaffs_Object *in)
5336 /* remove this hardlink from the list assocaited with the equivalent
5339 ylist_del_init(&in->hardLinks);
5340 return yaffs_DoGenericObjectDeletion(in);
5343 int yaffs_DeleteObject(yaffs_Object *obj)
5346 switch (obj->variantType) {
5347 case YAFFS_OBJECT_TYPE_FILE:
5348 retVal = yaffs_DeleteFile(obj);
5350 case YAFFS_OBJECT_TYPE_DIRECTORY:
5351 return yaffs_DeleteDirectory(obj);
5353 case YAFFS_OBJECT_TYPE_SYMLINK:
5354 retVal = yaffs_DeleteSymLink(obj);
5356 case YAFFS_OBJECT_TYPE_HARDLINK:
5357 retVal = yaffs_DeleteHardLink(obj);
5359 case YAFFS_OBJECT_TYPE_SPECIAL:
5360 retVal = yaffs_DoGenericObjectDeletion(obj);
5362 case YAFFS_OBJECT_TYPE_UNKNOWN:
5364 break; /* should not happen. */
5370 static int yaffs_UnlinkWorker(yaffs_Object *obj)
5373 int immediateDeletion = 0;
5376 immediateDeletion = 1;
5379 yaffs_UpdateParent(obj->parent);
5381 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5382 return yaffs_DeleteHardLink(obj);
5383 } else if (!ylist_empty(&obj->hardLinks)) {
5384 /* Curve ball: We're unlinking an object that has a hardlink.
5386 * This problem arises because we are not strictly following
5387 * The Linux link/inode model.
5389 * We can't really delete the object.
5390 * Instead, we do the following:
5391 * - Select a hardlink.
5392 * - Unhook it from the hard links
5393 * - Move it from its parent directory (so that the rename can work)
5394 * - Rename the object to the hardlink's name.
5395 * - Delete the hardlink
5399 yaffs_Object *parent;
5401 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5403 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5405 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5406 parent = hl->parent;
5408 ylist_del_init(&hl->hardLinks);
5410 yaffs_AddObjectToDirectory(obj->myDev->unlinkedDir, hl);
5412 retVal = yaffs_ChangeObjectName(obj,parent, name, 0, 0);
5414 if (retVal == YAFFS_OK)
5415 retVal = yaffs_DoGenericObjectDeletion(hl);
5419 } else if (immediateDeletion) {
5420 switch (obj->variantType) {
5421 case YAFFS_OBJECT_TYPE_FILE:
5422 return yaffs_DeleteFile(obj);
5424 case YAFFS_OBJECT_TYPE_DIRECTORY:
5425 return yaffs_DeleteDirectory(obj);
5427 case YAFFS_OBJECT_TYPE_SYMLINK:
5428 return yaffs_DeleteSymLink(obj);
5430 case YAFFS_OBJECT_TYPE_SPECIAL:
5431 return yaffs_DoGenericObjectDeletion(obj);
5433 case YAFFS_OBJECT_TYPE_HARDLINK:
5434 case YAFFS_OBJECT_TYPE_UNKNOWN:
5438 } else if(yaffs_IsNonEmptyDirectory(obj))
5441 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
5442 _Y("unlinked"), 0, 0);
5446 static int yaffs_UnlinkObject(yaffs_Object *obj)
5449 if (obj && obj->unlinkAllowed)
5450 return yaffs_UnlinkWorker(obj);
5455 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
5459 obj = yaffs_FindObjectByName(dir, name);
5460 return yaffs_UnlinkObject(obj);
5463 /*----------------------- Initialisation Scanning ---------------------- */
5465 static void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
5466 int backwardScanning)
5470 if (!backwardScanning) {
5471 /* Handle YAFFS1 forward scanning case
5472 * For YAFFS1 we always do the deletion
5476 /* Handle YAFFS2 case (backward scanning)
5477 * If the shadowed object exists then ignore.
5479 obj = yaffs_FindObjectByNumber(dev, objId);
5484 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5485 * We put it in unlinked dir to be cleaned up after the scanning
5488 yaffs_FindOrCreateObjectByNumber(dev, objId,
5489 YAFFS_OBJECT_TYPE_FILE);
5492 obj->isShadowed = 1;
5493 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5494 obj->variant.fileVariant.shrinkSize = 0;
5495 obj->valid = 1; /* So that we don't read any other info for this file */
5505 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5512 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5514 in = yaffs_FindObjectByNumber(dev,
5515 hl->variant.hardLinkVariant.
5516 equivalentObjectId);
5519 /* Add the hardlink pointers */
5520 hl->variant.hardLinkVariant.equivalentObject = in;
5521 ylist_add(&hl->hardLinks, &in->hardLinks);
5523 /* Todo Need to report/handle this better.
5524 * Got a problem... hardlink to a non-existant object
5526 hl->variant.hardLinkVariant.equivalentObject = NULL;
5527 YINIT_LIST_HEAD(&hl->hardLinks);
5537 static int ybicmp(const void *a, const void *b)
5539 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5540 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5541 register int ablock = ((yaffs_BlockIndex *)a)->block;
5542 register int bblock = ((yaffs_BlockIndex *)b)->block;
5544 return ablock - bblock;
5550 struct yaffs_ShadowFixerStruct {
5553 struct yaffs_ShadowFixerStruct *next;
5557 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5560 * Sort out state of unlinked and deleted objects after scanning.
5562 struct ylist_head *i;
5563 struct ylist_head *n;
5566 /* Soft delete all the unlinked files */
5567 ylist_for_each_safe(i, n,
5568 &dev->unlinkedDir->variant.directoryVariant.children) {
5570 l = ylist_entry(i, yaffs_Object, siblings);
5571 yaffs_DeleteObject(l);
5575 ylist_for_each_safe(i, n,
5576 &dev->deletedDir->variant.directoryVariant.children) {
5578 l = ylist_entry(i, yaffs_Object, siblings);
5579 yaffs_DeleteObject(l);
5586 * This code iterates through all the objects making sure that they are rooted.
5587 * Any unrooted objects are re-rooted in lost+found.
5588 * An object needs to be in one of:
5589 * - Directly under deleted, unlinked
5590 * - Directly or indirectly under root.
5593 * This code assumes that we don't ever change the current relationships between
5595 * rootDir->parent == unlinkedDir->parent == deletedDir->parent == NULL
5596 * lostNfound->parent == rootDir
5598 * This fixes the problem where directories might have inadvertently been deleted
5599 * leaving the object "hanging" without being rooted in the directory tree.
5602 static int yaffs_HasNULLParent(yaffs_Device *dev, yaffs_Object *obj)
5604 return (obj == dev->deletedDir ||
5605 obj == dev->unlinkedDir||
5606 obj == dev->rootDir);
5609 static void yaffs_FixHangingObjects(yaffs_Device *dev)
5612 yaffs_Object *parent;
5614 struct ylist_head *lh;
5615 struct ylist_head *n;
5620 /* Iterate through the objects in each hash entry,
5621 * looking at each object.
5622 * Make sure it is rooted.
5625 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
5626 ylist_for_each_safe(lh, n, &dev->objectBucket[i].list) {
5628 obj = ylist_entry(lh, yaffs_Object, hashLink);
5629 parent= obj->parent;
5631 if(yaffs_HasNULLParent(dev,obj)){
5632 /* These directories are not hanging */
5635 else if(!parent || parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5637 else if(yaffs_HasNULLParent(dev,parent))
5641 * Need to follow the parent chain to see if it is hanging.
5646 while(parent != dev->rootDir &&
5648 parent->parent->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
5650 parent = parent->parent;
5653 if(parent != dev->rootDir)
5658 (TSTR("Hanging object %d moved to lost and found" TENDSTR),
5660 yaffs_AddObjectToDirectory(dev->lostNFoundDir,obj);
5669 * Delete directory contents for cleaning up lost and found.
5671 static void yaffs_DeleteDirectoryContents(yaffs_Object *dir)
5674 struct ylist_head *lh;
5675 struct ylist_head *n;
5677 if(dir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5680 ylist_for_each_safe(lh, n, &dir->variant.directoryVariant.children) {
5682 obj = ylist_entry(lh, yaffs_Object, siblings);
5683 if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
5684 yaffs_DeleteDirectoryContents(obj);
5687 (TSTR("Deleting lost_found object %d" TENDSTR),
5690 /* Need to use UnlinkObject since Delete would not handle
5691 * hardlinked objects correctly.
5693 yaffs_UnlinkObject(obj);
5699 static void yaffs_EmptyLostAndFound(yaffs_Device *dev)
5701 yaffs_DeleteDirectoryContents(dev->lostNFoundDir);
5704 static int yaffs_Scan(yaffs_Device *dev)
5706 yaffs_ExtendedTags tags;
5716 yaffs_BlockState state;
5717 yaffs_Object *hardList = NULL;
5718 yaffs_BlockInfo *bi;
5719 __u32 sequenceNumber;
5720 yaffs_ObjectHeader *oh;
5722 yaffs_Object *parent;
5724 int alloc_failed = 0;
5726 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5734 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5735 dev->internalStartBlock, dev->internalEndBlock));
5737 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5739 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5741 /* Scan all the blocks to determine their state */
5742 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5743 bi = yaffs_GetBlockInfo(dev, blk);
5744 yaffs_ClearChunkBits(dev, blk);
5746 bi->softDeletions = 0;
5748 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5750 bi->blockState = state;
5751 bi->sequenceNumber = sequenceNumber;
5753 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
5754 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
5756 T(YAFFS_TRACE_SCAN_DEBUG,
5757 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5758 state, sequenceNumber));
5760 if (state == YAFFS_BLOCK_STATE_DEAD) {
5761 T(YAFFS_TRACE_BAD_BLOCKS,
5762 (TSTR("block %d is bad" TENDSTR), blk));
5763 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5764 T(YAFFS_TRACE_SCAN_DEBUG,
5765 (TSTR("Block empty " TENDSTR)));
5766 dev->nErasedBlocks++;
5767 dev->nFreeChunks += dev->nChunksPerBlock;
5771 startIterator = dev->internalStartBlock;
5772 endIterator = dev->internalEndBlock;
5774 /* For each block.... */
5775 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5782 blk = blockIterator;
5784 bi = yaffs_GetBlockInfo(dev, blk);
5785 state = bi->blockState;
5789 /* For each chunk in each block that needs scanning....*/
5790 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5791 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5792 /* Read the tags and decide what to do */
5793 chunk = blk * dev->nChunksPerBlock + c;
5795 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5798 /* Let's have a good look at this chunk... */
5800 if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
5806 /*T((" %d %d deleted\n",blk,c)); */
5807 } else if (!tags.chunkUsed) {
5808 /* An unassigned chunk in the block
5809 * This means that either the block is empty or
5810 * this is the one being allocated from
5814 /* We're looking at the first chunk in the block so the block is unused */
5815 state = YAFFS_BLOCK_STATE_EMPTY;
5816 dev->nErasedBlocks++;
5818 /* this is the block being allocated from */
5821 (" Allocating from %d %d" TENDSTR),
5823 state = YAFFS_BLOCK_STATE_ALLOCATING;
5824 dev->allocationBlock = blk;
5825 dev->allocationPage = c;
5826 dev->allocationBlockFinder = blk;
5827 /* Set block finder here to encourage the allocator to go forth from here. */
5831 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5832 } else if (tags.chunkId > 0) {
5833 /* chunkId > 0 so it is a data chunk... */
5834 unsigned int endpos;
5836 yaffs_SetChunkBit(dev, blk, c);
5839 in = yaffs_FindOrCreateObjectByNumber(dev,
5842 YAFFS_OBJECT_TYPE_FILE);
5843 /* PutChunkIntoFile checks for a clash (two data chunks with
5844 * the same chunkId).
5851 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, 1))
5856 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5859 in->variantType == YAFFS_OBJECT_TYPE_FILE
5860 && in->variant.fileVariant.scannedFileSize <
5862 in->variant.fileVariant.
5863 scannedFileSize = endpos;
5864 if (!dev->useHeaderFileSize) {
5865 in->variant.fileVariant.
5867 in->variant.fileVariant.
5872 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
5874 /* chunkId == 0, so it is an ObjectHeader.
5875 * Thus, we read in the object header and make the object
5877 yaffs_SetChunkBit(dev, blk, c);
5880 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5884 oh = (yaffs_ObjectHeader *) chunkData;
5886 in = yaffs_FindObjectByNumber(dev,
5888 if (in && in->variantType != oh->type) {
5889 /* This should not happen, but somehow
5890 * Wev'e ended up with an objectId that has been reused but not yet
5891 * deleted, and worse still it has changed type. Delete the old object.
5894 yaffs_DeleteObject(in);
5899 in = yaffs_FindOrCreateObjectByNumber(dev,
5907 if (in && oh->shadowsObject > 0) {
5909 struct yaffs_ShadowFixerStruct *fixer;
5910 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
5912 fixer->next = shadowFixerList;
5913 shadowFixerList = fixer;
5914 fixer->objectId = tags.objectId;
5915 fixer->shadowedId = oh->shadowsObject;
5920 if (in && in->valid) {
5921 /* We have already filled this one. We have a duplicate and need to resolve it. */
5923 unsigned existingSerial = in->serial;
5924 unsigned newSerial = tags.serialNumber;
5926 if (((existingSerial + 1) & 3) == newSerial) {
5927 /* Use new one - destroy the exisiting one */
5928 yaffs_DeleteChunk(dev,
5933 /* Use existing - destroy this one. */
5934 yaffs_DeleteChunk(dev, chunk, 1,
5939 if (in && !in->valid &&
5940 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5941 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5942 /* We only load some info, don't fiddle with directory structure */
5944 in->variantType = oh->type;
5946 in->yst_mode = oh->yst_mode;
5947 #ifdef CONFIG_YAFFS_WINCE
5948 in->win_atime[0] = oh->win_atime[0];
5949 in->win_ctime[0] = oh->win_ctime[0];
5950 in->win_mtime[0] = oh->win_mtime[0];
5951 in->win_atime[1] = oh->win_atime[1];
5952 in->win_ctime[1] = oh->win_ctime[1];
5953 in->win_mtime[1] = oh->win_mtime[1];
5955 in->yst_uid = oh->yst_uid;
5956 in->yst_gid = oh->yst_gid;
5957 in->yst_atime = oh->yst_atime;
5958 in->yst_mtime = oh->yst_mtime;
5959 in->yst_ctime = oh->yst_ctime;
5960 in->yst_rdev = oh->yst_rdev;
5962 in->hdrChunk = chunk;
5963 in->serial = tags.serialNumber;
5965 } else if (in && !in->valid) {
5966 /* we need to load this info */
5969 in->variantType = oh->type;
5971 in->yst_mode = oh->yst_mode;
5972 #ifdef CONFIG_YAFFS_WINCE
5973 in->win_atime[0] = oh->win_atime[0];
5974 in->win_ctime[0] = oh->win_ctime[0];
5975 in->win_mtime[0] = oh->win_mtime[0];
5976 in->win_atime[1] = oh->win_atime[1];
5977 in->win_ctime[1] = oh->win_ctime[1];
5978 in->win_mtime[1] = oh->win_mtime[1];
5980 in->yst_uid = oh->yst_uid;
5981 in->yst_gid = oh->yst_gid;
5982 in->yst_atime = oh->yst_atime;
5983 in->yst_mtime = oh->yst_mtime;
5984 in->yst_ctime = oh->yst_ctime;
5985 in->yst_rdev = oh->yst_rdev;
5987 in->hdrChunk = chunk;
5988 in->serial = tags.serialNumber;
5990 yaffs_SetObjectName(in, oh->name);
5993 /* directory stuff...
5998 yaffs_FindOrCreateObjectByNumber
5999 (dev, oh->parentObjectId,
6000 YAFFS_OBJECT_TYPE_DIRECTORY);
6003 if (parent && parent->variantType ==
6004 YAFFS_OBJECT_TYPE_UNKNOWN) {
6005 /* Set up as a directory */
6006 parent->variantType =
6007 YAFFS_OBJECT_TYPE_DIRECTORY;
6008 YINIT_LIST_HEAD(&parent->variant.
6011 } else if (!parent || parent->variantType !=
6012 YAFFS_OBJECT_TYPE_DIRECTORY) {
6013 /* Hoosterman, another problem....
6014 * We're trying to use a non-directory as a directory
6017 T(YAFFS_TRACE_ERROR,
6019 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6021 parent = dev->lostNFoundDir;
6024 yaffs_AddObjectToDirectory(parent, in);
6026 if (0 && (parent == dev->deletedDir ||
6027 parent == dev->unlinkedDir)) {
6028 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
6029 dev->nDeletedFiles++;
6031 /* Note re hardlinks.
6032 * Since we might scan a hardlink before its equivalent object is scanned
6033 * we put them all in a list.
6034 * After scanning is complete, we should have all the objects, so we run through this
6035 * list and fix up all the chains.
6038 switch (in->variantType) {
6039 case YAFFS_OBJECT_TYPE_UNKNOWN:
6040 /* Todo got a problem */
6042 case YAFFS_OBJECT_TYPE_FILE:
6043 if (dev->useHeaderFileSize)
6045 in->variant.fileVariant.
6050 case YAFFS_OBJECT_TYPE_HARDLINK:
6051 in->variant.hardLinkVariant.
6052 equivalentObjectId =
6053 oh->equivalentObjectId;
6054 in->hardLinks.next =
6055 (struct ylist_head *)
6059 case YAFFS_OBJECT_TYPE_DIRECTORY:
6062 case YAFFS_OBJECT_TYPE_SPECIAL:
6065 case YAFFS_OBJECT_TYPE_SYMLINK:
6066 in->variant.symLinkVariant.alias =
6067 yaffs_CloneString(oh->alias);
6068 if (!in->variant.symLinkVariant.alias)
6077 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6078 /* If we got this far while scanning, then the block is fully allocated.*/
6079 state = YAFFS_BLOCK_STATE_FULL;
6082 if (state == YAFFS_BLOCK_STATE_ALLOCATING) {
6083 /* If the block was partially allocated then treat it as fully allocated.*/
6084 state = YAFFS_BLOCK_STATE_FULL;
6085 dev->allocationBlock = -1;
6088 bi->blockState = state;
6090 /* Now let's see if it was dirty */
6091 if (bi->pagesInUse == 0 &&
6092 !bi->hasShrinkHeader &&
6093 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6094 yaffs_BlockBecameDirty(dev, blk);
6100 /* Ok, we've done all the scanning.
6101 * Fix up the hard link chains.
6102 * We should now have scanned all the objects, now it's time to add these
6106 yaffs_HardlinkFixup(dev, hardList);
6108 /* Fix up any shadowed objects */
6110 struct yaffs_ShadowFixerStruct *fixer;
6113 while (shadowFixerList) {
6114 fixer = shadowFixerList;
6115 shadowFixerList = fixer->next;
6116 /* Complete the rename transaction by deleting the shadowed object
6117 * then setting the object header to unshadowed.
6119 obj = yaffs_FindObjectByNumber(dev, fixer->shadowedId);
6121 yaffs_DeleteObject(obj);
6123 obj = yaffs_FindObjectByNumber(dev, fixer->objectId);
6126 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6132 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6137 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
6143 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
6146 yaffs_ObjectHeader *oh;
6148 yaffs_ExtendedTags tags;
6150 int alloc_failed = 0;
6158 T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
6160 in->lazyLoaded ? "not yet" : "already"));
6163 if (in->lazyLoaded && in->hdrChunk > 0) {
6165 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6167 result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
6168 oh = (yaffs_ObjectHeader *) chunkData;
6170 in->yst_mode = oh->yst_mode;
6171 #ifdef CONFIG_YAFFS_WINCE
6172 in->win_atime[0] = oh->win_atime[0];
6173 in->win_ctime[0] = oh->win_ctime[0];
6174 in->win_mtime[0] = oh->win_mtime[0];
6175 in->win_atime[1] = oh->win_atime[1];
6176 in->win_ctime[1] = oh->win_ctime[1];
6177 in->win_mtime[1] = oh->win_mtime[1];
6179 in->yst_uid = oh->yst_uid;
6180 in->yst_gid = oh->yst_gid;
6181 in->yst_atime = oh->yst_atime;
6182 in->yst_mtime = oh->yst_mtime;
6183 in->yst_ctime = oh->yst_ctime;
6184 in->yst_rdev = oh->yst_rdev;
6187 yaffs_SetObjectName(in, oh->name);
6189 if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6190 in->variant.symLinkVariant.alias =
6191 yaffs_CloneString(oh->alias);
6192 if (!in->variant.symLinkVariant.alias)
6193 alloc_failed = 1; /* Not returned to caller */
6196 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6200 static int yaffs_ScanBackwards(yaffs_Device *dev)
6202 yaffs_ExtendedTags tags;
6207 int nBlocksToScan = 0;
6213 yaffs_BlockState state;
6214 yaffs_Object *hardList = NULL;
6215 yaffs_BlockInfo *bi;
6216 __u32 sequenceNumber;
6217 yaffs_ObjectHeader *oh;
6219 yaffs_Object *parent;
6220 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6226 int foundChunksInBlock;
6227 int equivalentObjectId;
6228 int alloc_failed = 0;
6231 yaffs_BlockIndex *blockIndex = NULL;
6232 int altBlockIndex = 0;
6234 if (!dev->isYaffs2) {
6236 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6242 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
6243 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6246 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6248 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6251 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6257 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6261 dev->blocksInCheckpoint = 0;
6263 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6265 /* Scan all the blocks to determine their state */
6266 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6267 bi = yaffs_GetBlockInfo(dev, blk);
6268 yaffs_ClearChunkBits(dev, blk);
6270 bi->softDeletions = 0;
6272 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6274 bi->blockState = state;
6275 bi->sequenceNumber = sequenceNumber;
6277 if (bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6278 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6279 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6280 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6282 T(YAFFS_TRACE_SCAN_DEBUG,
6283 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6284 state, sequenceNumber));
6287 if (state == YAFFS_BLOCK_STATE_CHECKPOINT) {
6288 dev->blocksInCheckpoint++;
6290 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6291 T(YAFFS_TRACE_BAD_BLOCKS,
6292 (TSTR("block %d is bad" TENDSTR), blk));
6293 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6294 T(YAFFS_TRACE_SCAN_DEBUG,
6295 (TSTR("Block empty " TENDSTR)));
6296 dev->nErasedBlocks++;
6297 dev->nFreeChunks += dev->nChunksPerBlock;
6298 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6300 /* Determine the highest sequence number */
6301 if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6302 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6304 blockIndex[nBlocksToScan].seq = sequenceNumber;
6305 blockIndex[nBlocksToScan].block = blk;
6309 if (sequenceNumber >= dev->sequenceNumber)
6310 dev->sequenceNumber = sequenceNumber;
6312 /* TODO: Nasty sequence number! */
6315 ("Block scanning block %d has bad sequence number %d"
6316 TENDSTR), blk, sequenceNumber));
6323 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6329 /* Sort the blocks */
6330 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6332 /* Use qsort now. */
6333 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6337 /* Dungy old bubble sort... */
6339 yaffs_BlockIndex temp;
6343 for (i = 0; i < nBlocksToScan; i++)
6344 for (j = i + 1; j < nBlocksToScan; j++)
6345 if (blockIndex[i].seq > blockIndex[j].seq) {
6346 temp = blockIndex[j];
6347 blockIndex[j] = blockIndex[i];
6348 blockIndex[i] = temp;
6355 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6357 /* Now scan the blocks looking at the data. */
6359 endIterator = nBlocksToScan - 1;
6360 T(YAFFS_TRACE_SCAN_DEBUG,
6361 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6363 /* For each block.... backwards */
6364 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6366 /* Cooperative multitasking! This loop can run for so
6367 long that watchdog timers expire. */
6370 /* get the block to scan in the correct order */
6371 blk = blockIndex[blockIterator].block;
6373 bi = yaffs_GetBlockInfo(dev, blk);
6376 state = bi->blockState;
6380 /* For each chunk in each block that needs scanning.... */
6381 foundChunksInBlock = 0;
6382 for (c = dev->nChunksPerBlock - 1;
6383 !alloc_failed && c >= 0 &&
6384 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6385 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6386 /* Scan backwards...
6387 * Read the tags and decide what to do
6390 chunk = blk * dev->nChunksPerBlock + c;
6392 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6395 /* Let's have a good look at this chunk... */
6397 if (!tags.chunkUsed) {
6398 /* An unassigned chunk in the block.
6399 * If there are used chunks after this one, then
6400 * it is a chunk that was skipped due to failing the erased
6401 * check. Just skip it so that it can be deleted.
6402 * But, more typically, We get here when this is an unallocated
6403 * chunk and his means that either the block is empty or
6404 * this is the one being allocated from
6407 if (foundChunksInBlock) {
6408 /* This is a chunk that was skipped due to failing the erased check */
6409 } else if (c == 0) {
6410 /* We're looking at the first chunk in the block so the block is unused */
6411 state = YAFFS_BLOCK_STATE_EMPTY;
6412 dev->nErasedBlocks++;
6414 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6415 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6416 if (dev->sequenceNumber == bi->sequenceNumber) {
6417 /* this is the block being allocated from */
6421 (" Allocating from %d %d"
6424 state = YAFFS_BLOCK_STATE_ALLOCATING;
6425 dev->allocationBlock = blk;
6426 dev->allocationPage = c;
6427 dev->allocationBlockFinder = blk;
6429 /* This is a partially written block that is not
6430 * the current allocation block.
6433 T(YAFFS_TRACE_ALWAYS,
6434 (TSTR("Partially written block %d detected" TENDSTR),
6442 } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED) {
6444 (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
6449 } else if (tags.chunkId > 0) {
6450 /* chunkId > 0 so it is a data chunk... */
6451 unsigned int endpos;
6453 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6455 foundChunksInBlock = 1;
6458 yaffs_SetChunkBit(dev, blk, c);
6461 in = yaffs_FindOrCreateObjectByNumber(dev,
6464 YAFFS_OBJECT_TYPE_FILE);
6471 in->variantType == YAFFS_OBJECT_TYPE_FILE
6473 in->variant.fileVariant.shrinkSize) {
6474 /* This has not been invalidated by a resize */
6475 if (!yaffs_PutChunkIntoFile(in, tags.chunkId,
6480 /* File size is calculated by looking at the data chunks if we have not
6481 * seen an object header yet. Stop this practice once we find an object header.
6485 1) * dev->nDataBytesPerChunk +
6488 if (!in->valid && /* have not got an object header yet */
6489 in->variant.fileVariant.
6490 scannedFileSize < endpos) {
6491 in->variant.fileVariant.
6492 scannedFileSize = endpos;
6493 in->variant.fileVariant.
6495 in->variant.fileVariant.
6500 /* This chunk has been invalidated by a resize, so delete */
6501 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6505 /* chunkId == 0, so it is an ObjectHeader.
6506 * Thus, we read in the object header and make the object
6508 foundChunksInBlock = 1;
6510 yaffs_SetChunkBit(dev, blk, c);
6516 if (tags.extraHeaderInfoAvailable) {
6517 in = yaffs_FindOrCreateObjectByNumber
6518 (dev, tags.objectId,
6519 tags.extraObjectType);
6525 (!in->valid && dev->disableLazyLoad) ||
6526 tags.extraShadows ||
6528 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6529 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))) {
6531 /* If we don't have valid info then we need to read the chunk
6532 * TODO In future we can probably defer reading the chunk and
6533 * living with invalid data until needed.
6536 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6541 oh = (yaffs_ObjectHeader *) chunkData;
6543 if (dev->inbandTags) {
6544 /* Fix up the header if they got corrupted by inband tags */
6545 oh->shadowsObject = oh->inbandShadowsObject;
6546 oh->isShrink = oh->inbandIsShrink;
6550 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6558 /* TODO Hoosterman we have a problem! */
6559 T(YAFFS_TRACE_ERROR,
6561 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6562 TENDSTR), tags.objectId, chunk));
6567 /* We have already filled this one.
6568 * We have a duplicate that will be discarded, but
6569 * we first have to suck out resize info if it is a file.
6572 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6574 oh->type == YAFFS_OBJECT_TYPE_FILE) ||
6575 (tags.extraHeaderInfoAvailable &&
6576 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))) {
6578 (oh) ? oh->fileSize : tags.
6580 __u32 parentObjectId =
6582 parentObjectId : tags.
6583 extraParentObjectId;
6587 (oh) ? oh->isShrink : tags.
6588 extraIsShrinkHeader;
6590 /* If it is deleted (unlinked at start also means deleted)
6591 * we treat the file size as being zeroed at this point.
6593 if (parentObjectId ==
6594 YAFFS_OBJECTID_DELETED
6595 || parentObjectId ==
6596 YAFFS_OBJECTID_UNLINKED) {
6602 in->variant.fileVariant.
6603 shrinkSize > thisSize) {
6604 in->variant.fileVariant.
6610 bi->hasShrinkHeader = 1;
6613 /* Use existing - destroy this one. */
6614 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6618 if (!in->valid && in->variantType !=
6619 (oh ? oh->type : tags.extraObjectType))
6620 T(YAFFS_TRACE_ERROR, (
6621 TSTR("yaffs tragedy: Bad object type, "
6622 TCONT("%d != %d, for object %d at chunk ")
6623 TCONT("%d during scan")
6625 oh->type : tags.extraObjectType,
6626 in->variantType, tags.objectId,
6630 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6632 YAFFS_OBJECTID_LOSTNFOUND)) {
6633 /* We only load some info, don't fiddle with directory structure */
6637 in->variantType = oh->type;
6639 in->yst_mode = oh->yst_mode;
6640 #ifdef CONFIG_YAFFS_WINCE
6641 in->win_atime[0] = oh->win_atime[0];
6642 in->win_ctime[0] = oh->win_ctime[0];
6643 in->win_mtime[0] = oh->win_mtime[0];
6644 in->win_atime[1] = oh->win_atime[1];
6645 in->win_ctime[1] = oh->win_ctime[1];
6646 in->win_mtime[1] = oh->win_mtime[1];
6648 in->yst_uid = oh->yst_uid;
6649 in->yst_gid = oh->yst_gid;
6650 in->yst_atime = oh->yst_atime;
6651 in->yst_mtime = oh->yst_mtime;
6652 in->yst_ctime = oh->yst_ctime;
6653 in->yst_rdev = oh->yst_rdev;
6657 in->variantType = tags.extraObjectType;
6661 in->hdrChunk = chunk;
6663 } else if (!in->valid) {
6664 /* we need to load this info */
6667 in->hdrChunk = chunk;
6670 in->variantType = oh->type;
6672 in->yst_mode = oh->yst_mode;
6673 #ifdef CONFIG_YAFFS_WINCE
6674 in->win_atime[0] = oh->win_atime[0];
6675 in->win_ctime[0] = oh->win_ctime[0];
6676 in->win_mtime[0] = oh->win_mtime[0];
6677 in->win_atime[1] = oh->win_atime[1];
6678 in->win_ctime[1] = oh->win_ctime[1];
6679 in->win_mtime[1] = oh->win_mtime[1];
6681 in->yst_uid = oh->yst_uid;
6682 in->yst_gid = oh->yst_gid;
6683 in->yst_atime = oh->yst_atime;
6684 in->yst_mtime = oh->yst_mtime;
6685 in->yst_ctime = oh->yst_ctime;
6686 in->yst_rdev = oh->yst_rdev;
6689 if (oh->shadowsObject > 0)
6690 yaffs_HandleShadowedObject(dev,
6697 yaffs_SetObjectName(in, oh->name);
6699 yaffs_FindOrCreateObjectByNumber
6700 (dev, oh->parentObjectId,
6701 YAFFS_OBJECT_TYPE_DIRECTORY);
6703 fileSize = oh->fileSize;
6704 isShrink = oh->isShrink;
6705 equivalentObjectId = oh->equivalentObjectId;
6708 in->variantType = tags.extraObjectType;
6710 yaffs_FindOrCreateObjectByNumber
6711 (dev, tags.extraParentObjectId,
6712 YAFFS_OBJECT_TYPE_DIRECTORY);
6713 fileSize = tags.extraFileLength;
6714 isShrink = tags.extraIsShrinkHeader;
6715 equivalentObjectId = tags.extraEquivalentObjectId;
6724 /* directory stuff...
6728 if (parent && parent->variantType ==
6729 YAFFS_OBJECT_TYPE_UNKNOWN) {
6730 /* Set up as a directory */
6731 parent->variantType =
6732 YAFFS_OBJECT_TYPE_DIRECTORY;
6733 YINIT_LIST_HEAD(&parent->variant.
6736 } else if (!parent || parent->variantType !=
6737 YAFFS_OBJECT_TYPE_DIRECTORY) {
6738 /* Hoosterman, another problem....
6739 * We're trying to use a non-directory as a directory
6742 T(YAFFS_TRACE_ERROR,
6744 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6746 parent = dev->lostNFoundDir;
6749 yaffs_AddObjectToDirectory(parent, in);
6751 itsUnlinked = (parent == dev->deletedDir) ||
6752 (parent == dev->unlinkedDir);
6755 /* Mark the block as having a shrinkHeader */
6756 bi->hasShrinkHeader = 1;
6759 /* Note re hardlinks.
6760 * Since we might scan a hardlink before its equivalent object is scanned
6761 * we put them all in a list.
6762 * After scanning is complete, we should have all the objects, so we run
6763 * through this list and fix up all the chains.
6766 switch (in->variantType) {
6767 case YAFFS_OBJECT_TYPE_UNKNOWN:
6768 /* Todo got a problem */
6770 case YAFFS_OBJECT_TYPE_FILE:
6772 if (in->variant.fileVariant.
6773 scannedFileSize < fileSize) {
6774 /* This covers the case where the file size is greater
6775 * than where the data is
6776 * This will happen if the file is resized to be larger
6777 * than its current data extents.
6779 in->variant.fileVariant.fileSize = fileSize;
6780 in->variant.fileVariant.scannedFileSize =
6781 in->variant.fileVariant.fileSize;
6785 in->variant.fileVariant.shrinkSize > fileSize) {
6786 in->variant.fileVariant.shrinkSize = fileSize;
6790 case YAFFS_OBJECT_TYPE_HARDLINK:
6792 in->variant.hardLinkVariant.equivalentObjectId =
6794 in->hardLinks.next =
6795 (struct ylist_head *) hardList;
6799 case YAFFS_OBJECT_TYPE_DIRECTORY:
6802 case YAFFS_OBJECT_TYPE_SPECIAL:
6805 case YAFFS_OBJECT_TYPE_SYMLINK:
6807 in->variant.symLinkVariant.alias =
6808 yaffs_CloneString(oh->alias);
6809 if (!in->variant.symLinkVariant.alias)
6819 } /* End of scanning for each chunk */
6821 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6822 /* If we got this far while scanning, then the block is fully allocated. */
6823 state = YAFFS_BLOCK_STATE_FULL;
6827 bi->blockState = state;
6829 /* Now let's see if it was dirty */
6830 if (bi->pagesInUse == 0 &&
6831 !bi->hasShrinkHeader &&
6832 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6833 yaffs_BlockBecameDirty(dev, blk);
6838 yaffs_SkipRestOfBlock(dev);
6841 YFREE_ALT(blockIndex);
6845 /* Ok, we've done all the scanning.
6846 * Fix up the hard link chains.
6847 * We should now have scanned all the objects, now it's time to add these
6850 yaffs_HardlinkFixup(dev, hardList);
6853 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6858 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6863 /*------------------------------ Directory Functions ----------------------------- */
6865 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
6867 struct ylist_head *lh;
6868 yaffs_Object *listObj;
6873 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
6878 if (yaffs_SkipVerification(obj->myDev))
6882 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
6887 if (obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6888 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
6892 /* Iterate through the objects in each hash entry */
6894 ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
6896 listObj = ylist_entry(lh, yaffs_Object, siblings);
6897 yaffs_VerifyObject(listObj);
6904 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR), count));
6909 static void yaffs_VerifyDirectory(yaffs_Object *directory)
6911 struct ylist_head *lh;
6912 yaffs_Object *listObj;
6919 if (yaffs_SkipFullVerification(directory->myDev))
6922 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6923 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR), directory->variantType));
6927 /* Iterate through the objects in each hash entry */
6929 ylist_for_each(lh, &directory->variant.directoryVariant.children) {
6931 listObj = ylist_entry(lh, yaffs_Object, siblings);
6932 if (listObj->parent != directory) {
6933 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR), listObj->parent));
6936 yaffs_VerifyObjectInDirectory(listObj);
6942 *yaffs_UpdateParent() handles fixing a directories mtime and ctime when a new
6943 * link (ie. name) is created or deleted in the directory.
6946 * create dir/a : update dir's mtime/ctime
6947 * rm dir/a: update dir's mtime/ctime
6948 * modify dir/a: don't update dir's mtimme/ctime
6951 static void yaffs_UpdateParent(yaffs_Object *obj)
6957 obj->yst_mtime = obj->yst_ctime = Y_CURRENT_TIME;
6959 yaffs_UpdateObjectHeader(obj,NULL,0,0,0);
6962 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
6964 yaffs_Device *dev = obj->myDev;
6965 yaffs_Object *parent;
6967 yaffs_VerifyObjectInDirectory(obj);
6968 parent = obj->parent;
6970 yaffs_VerifyDirectory(parent);
6972 if (dev && dev->removeObjectCallback)
6973 dev->removeObjectCallback(obj);
6976 ylist_del_init(&obj->siblings);
6979 yaffs_VerifyDirectory(parent);
6982 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
6986 T(YAFFS_TRACE_ALWAYS,
6988 ("tragedy: Trying to add an object to a null pointer directory"
6993 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6994 T(YAFFS_TRACE_ALWAYS,
6996 ("tragedy: Trying to add an object to a non-directory"
7001 if (obj->siblings.prev == NULL) {
7002 /* Not initialised */
7007 yaffs_VerifyDirectory(directory);
7009 yaffs_RemoveObjectFromDirectory(obj);
7013 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
7014 obj->parent = directory;
7016 if (directory == obj->myDev->unlinkedDir
7017 || directory == obj->myDev->deletedDir) {
7019 obj->myDev->nUnlinkedFiles++;
7020 obj->renameAllowed = 0;
7023 yaffs_VerifyDirectory(directory);
7024 yaffs_VerifyObjectInDirectory(obj);
7027 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
7032 struct ylist_head *i;
7033 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
7041 T(YAFFS_TRACE_ALWAYS,
7043 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7048 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7049 T(YAFFS_TRACE_ALWAYS,
7051 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7055 sum = yaffs_CalcNameSum(name);
7057 ylist_for_each(i, &directory->variant.directoryVariant.children) {
7059 l = ylist_entry(i, yaffs_Object, siblings);
7061 if (l->parent != directory)
7064 yaffs_CheckObjectDetailsLoaded(l);
7066 /* Special case for lost-n-found */
7067 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7068 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
7070 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
7071 /* LostnFound chunk called Objxxx
7074 yaffs_GetObjectName(l, buffer,
7075 YAFFS_MAX_NAME_LENGTH + 1);
7076 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
7087 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
7088 int (*fn) (yaffs_Object *))
7090 struct ylist_head *i;
7094 T(YAFFS_TRACE_ALWAYS,
7096 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7101 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7102 T(YAFFS_TRACE_ALWAYS,
7104 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7109 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
7111 l = ylist_entry(i, yaffs_Object, siblings);
7122 /* GetEquivalentObject dereferences any hard links to get to the
7126 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
7128 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
7129 /* We want the object id of the equivalent object, not this one */
7130 obj = obj->variant.hardLinkVariant.equivalentObject;
7131 yaffs_CheckObjectDetailsLoaded(obj);
7136 int yaffs_GetObjectName(yaffs_Object *obj, YCHAR *name, int buffSize)
7138 memset(name, 0, buffSize * sizeof(YCHAR));
7140 yaffs_CheckObjectDetailsLoaded(obj);
7142 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7143 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
7144 } else if (obj->hdrChunk <= 0) {
7146 YCHAR numString[20];
7147 YCHAR *x = &numString[19];
7148 unsigned v = obj->objectId;
7152 *x = '0' + (v % 10);
7155 /* make up a name */
7156 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
7157 yaffs_strcat(locName, x);
7158 yaffs_strncpy(name, locName, buffSize - 1);
7161 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
7162 else if (obj->shortName[0])
7163 yaffs_strncpy(name, obj->shortName,YAFFS_SHORT_NAME_LENGTH+1);
7167 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
7169 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
7171 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
7173 if (obj->hdrChunk > 0) {
7174 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
7175 obj->hdrChunk, buffer,
7178 yaffs_strncpy(name, oh->name, buffSize - 1);
7181 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
7184 return yaffs_strnlen(name,buffSize-1);
7187 int yaffs_GetObjectFileLength(yaffs_Object *obj)
7189 /* Dereference any hard linking */
7190 obj = yaffs_GetEquivalentObject(obj);
7192 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
7193 return obj->variant.fileVariant.fileSize;
7194 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
7195 if(!obj->variant.symLinkVariant.alias)
7197 return yaffs_strnlen(obj->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
7199 /* Only a directory should drop through to here */
7200 return obj->myDev->nDataBytesPerChunk;
7204 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
7207 struct ylist_head *i;
7210 count++; /* the object itself */
7212 ylist_for_each(i, &obj->hardLinks)
7213 count++; /* add the hard links; */
7218 int yaffs_GetObjectInode(yaffs_Object *obj)
7220 obj = yaffs_GetEquivalentObject(obj);
7222 return obj->objectId;
7225 unsigned yaffs_GetObjectType(yaffs_Object *obj)
7227 obj = yaffs_GetEquivalentObject(obj);
7229 switch (obj->variantType) {
7230 case YAFFS_OBJECT_TYPE_FILE:
7233 case YAFFS_OBJECT_TYPE_DIRECTORY:
7236 case YAFFS_OBJECT_TYPE_SYMLINK:
7239 case YAFFS_OBJECT_TYPE_HARDLINK:
7242 case YAFFS_OBJECT_TYPE_SPECIAL:
7243 if (S_ISFIFO(obj->yst_mode))
7245 if (S_ISCHR(obj->yst_mode))
7247 if (S_ISBLK(obj->yst_mode))
7249 if (S_ISSOCK(obj->yst_mode))
7257 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
7259 obj = yaffs_GetEquivalentObject(obj);
7260 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
7261 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7263 return yaffs_CloneString(_Y(""));
7266 #ifndef CONFIG_YAFFS_WINCE
7268 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
7270 unsigned int valid = attr->ia_valid;
7272 if (valid & ATTR_MODE)
7273 obj->yst_mode = attr->ia_mode;
7274 if (valid & ATTR_UID)
7275 obj->yst_uid = attr->ia_uid;
7276 if (valid & ATTR_GID)
7277 obj->yst_gid = attr->ia_gid;
7279 if (valid & ATTR_ATIME)
7280 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7281 if (valid & ATTR_CTIME)
7282 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7283 if (valid & ATTR_MTIME)
7284 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7286 if (valid & ATTR_SIZE)
7287 yaffs_ResizeFile(obj, attr->ia_size);
7289 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7294 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
7296 unsigned int valid = 0;
7298 attr->ia_mode = obj->yst_mode;
7300 attr->ia_uid = obj->yst_uid;
7302 attr->ia_gid = obj->yst_gid;
7305 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7306 valid |= ATTR_ATIME;
7307 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7308 valid |= ATTR_CTIME;
7309 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7310 valid |= ATTR_MTIME;
7312 attr->ia_size = yaffs_GetFileSize(obj);
7315 attr->ia_valid = valid;
7323 int yaffs_DumpObject(yaffs_Object *obj)
7327 yaffs_GetObjectName(obj, name, YAFFS_MAX_NAME_LENGTH + 1);
7329 T(YAFFS_TRACE_ALWAYS,
7331 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7332 " chunk %d type %d size %d\n"
7333 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7334 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7335 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7341 /*---------------------------- Initialisation code -------------------------------------- */
7343 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
7346 /* Common functions, gotta have */
7347 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
7350 #ifdef CONFIG_YAFFS_YAFFS2
7352 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7353 if (dev->writeChunkWithTagsToNAND &&
7354 dev->readChunkWithTagsFromNAND &&
7355 !dev->writeChunkToNAND &&
7356 !dev->readChunkFromNAND &&
7357 dev->markNANDBlockBad && dev->queryNANDBlock)
7361 /* Can use the "spare" style interface for yaffs1 */
7362 if (!dev->isYaffs2 &&
7363 !dev->writeChunkWithTagsToNAND &&
7364 !dev->readChunkWithTagsFromNAND &&
7365 dev->writeChunkToNAND &&
7366 dev->readChunkFromNAND &&
7367 !dev->markNANDBlockBad && !dev->queryNANDBlock)
7374 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7376 /* Initialise the unlinked, deleted, root and lost and found directories */
7378 dev->lostNFoundDir = dev->rootDir = NULL;
7379 dev->unlinkedDir = dev->deletedDir = NULL;
7382 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7385 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7388 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7389 YAFFS_ROOT_MODE | S_IFDIR);
7390 dev->lostNFoundDir =
7391 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7392 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7394 if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
7395 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7402 int yaffs_GutsInitialise(yaffs_Device *dev)
7404 int init_failed = 0;
7408 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7410 /* Check stuff that must be set */
7413 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7417 dev->internalStartBlock = dev->startBlock;
7418 dev->internalEndBlock = dev->endBlock;
7419 dev->blockOffset = 0;
7420 dev->chunkOffset = 0;
7421 dev->nFreeChunks = 0;
7425 if (dev->startBlock == 0) {
7426 dev->internalStartBlock = dev->startBlock + 1;
7427 dev->internalEndBlock = dev->endBlock + 1;
7428 dev->blockOffset = 1;
7429 dev->chunkOffset = dev->nChunksPerBlock;
7432 /* Check geometry parameters. */
7434 if ((!dev->inbandTags && dev->isYaffs2 && dev->totalBytesPerChunk < 1024) ||
7435 (!dev->isYaffs2 && dev->totalBytesPerChunk < 512) ||
7436 (dev->inbandTags && !dev->isYaffs2) ||
7437 dev->nChunksPerBlock < 2 ||
7438 dev->nReservedBlocks < 2 ||
7439 dev->internalStartBlock <= 0 ||
7440 dev->internalEndBlock <= 0 ||
7441 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2)) { /* otherwise it is too small */
7442 T(YAFFS_TRACE_ALWAYS,
7444 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7445 TENDSTR), dev->totalBytesPerChunk, dev->isYaffs2 ? "2" : "", dev->inbandTags));
7449 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7450 T(YAFFS_TRACE_ALWAYS,
7451 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7455 /* Sort out space for inband tags, if required */
7456 if (dev->inbandTags)
7457 dev->nDataBytesPerChunk = dev->totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7459 dev->nDataBytesPerChunk = dev->totalBytesPerChunk;
7461 /* Got the right mix of functions? */
7462 if (!yaffs_CheckDevFunctions(dev)) {
7463 /* Function missing */
7464 T(YAFFS_TRACE_ALWAYS,
7466 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7471 /* This is really a compilation check. */
7472 if (!yaffs_CheckStructures()) {
7473 T(YAFFS_TRACE_ALWAYS,
7474 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7478 if (dev->isMounted) {
7479 T(YAFFS_TRACE_ALWAYS,
7480 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7484 /* Finished with most checks. One or two more checks happen later on too. */
7488 /* OK now calculate a few things for the device */
7491 * Calculate all the chunk size manipulation numbers:
7493 x = dev->nDataBytesPerChunk;
7494 /* We always use dev->chunkShift and dev->chunkDiv */
7495 dev->chunkShift = Shifts(x);
7496 x >>= dev->chunkShift;
7498 /* We only use chunk mask if chunkDiv is 1 */
7499 dev->chunkMask = (1<<dev->chunkShift) - 1;
7502 * Calculate chunkGroupBits.
7503 * We need to find the next power of 2 > than internalEndBlock
7506 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7510 /* Set up tnode width if wide tnodes are enabled. */
7511 if (!dev->wideTnodesDisabled) {
7512 /* bits must be even so that we end up with 32-bit words */
7516 dev->tnodeWidth = 16;
7518 dev->tnodeWidth = bits;
7520 dev->tnodeWidth = 16;
7522 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7524 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7525 * so if the bitwidth of the
7526 * chunk range we're using is greater than 16 we need
7527 * to figure out chunk shift and chunkGroupSize
7530 if (bits <= dev->tnodeWidth)
7531 dev->chunkGroupBits = 0;
7533 dev->chunkGroupBits = bits - dev->tnodeWidth;
7536 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7538 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7539 /* We have a problem because the soft delete won't work if
7540 * the chunk group size > chunks per block.
7541 * This can be remedied by using larger "virtual blocks".
7543 T(YAFFS_TRACE_ALWAYS,
7544 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7549 /* OK, we've finished verifying the device, lets continue with initialisation */
7551 /* More device initialisation */
7552 dev->garbageCollections = 0;
7553 dev->passiveGarbageCollections = 0;
7554 dev->currentDirtyChecker = 0;
7555 dev->bufferedBlock = -1;
7556 dev->doingBufferedBlockRewrite = 0;
7557 dev->nDeletedFiles = 0;
7558 dev->nBackgroundDeletions = 0;
7559 dev->nUnlinkedFiles = 0;
7561 dev->eccUnfixed = 0;
7562 dev->tagsEccFixed = 0;
7563 dev->tagsEccUnfixed = 0;
7564 dev->nErasureFailures = 0;
7565 dev->nErasedBlocks = 0;
7567 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7569 /* Initialise temporary buffers and caches. */
7570 if (!yaffs_InitialiseTempBuffers(dev))
7573 dev->srCache = NULL;
7574 dev->gcCleanupList = NULL;
7578 dev->nShortOpCaches > 0) {
7581 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7583 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
7584 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7586 dev->srCache = YMALLOC(srCacheBytes);
7588 buf = (__u8 *) dev->srCache;
7591 memset(dev->srCache, 0, srCacheBytes);
7593 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7594 dev->srCache[i].object = NULL;
7595 dev->srCache[i].lastUse = 0;
7596 dev->srCache[i].dirty = 0;
7597 dev->srCache[i].data = buf = YMALLOC_DMA(dev->totalBytesPerChunk);
7608 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7609 if (!dev->gcCleanupList)
7614 dev->useHeaderFileSize = 1;
7616 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7619 yaffs_InitialiseTnodes(dev);
7620 yaffs_InitialiseObjects(dev);
7622 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7627 /* Now scan the flash. */
7628 if (dev->isYaffs2) {
7629 if (yaffs_CheckpointRestore(dev)) {
7630 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7631 T(YAFFS_TRACE_ALWAYS,
7632 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7635 /* Clean up the mess caused by an aborted checkpoint load
7636 * and scan backwards.
7638 yaffs_DeinitialiseBlocks(dev);
7639 yaffs_DeinitialiseTnodes(dev);
7640 yaffs_DeinitialiseObjects(dev);
7643 dev->nErasedBlocks = 0;
7644 dev->nFreeChunks = 0;
7645 dev->allocationBlock = -1;
7646 dev->allocationPage = -1;
7647 dev->nDeletedFiles = 0;
7648 dev->nUnlinkedFiles = 0;
7649 dev->nBackgroundDeletions = 0;
7650 dev->oldestDirtySequence = 0;
7652 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7655 yaffs_InitialiseTnodes(dev);
7656 yaffs_InitialiseObjects(dev);
7658 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7661 if (!init_failed && !yaffs_ScanBackwards(dev))
7664 } else if (!yaffs_Scan(dev))
7667 yaffs_StripDeletedObjects(dev);
7668 yaffs_FixHangingObjects(dev);
7669 if(dev->emptyLostAndFound)
7670 yaffs_EmptyLostAndFound(dev);
7674 /* Clean up the mess */
7675 T(YAFFS_TRACE_TRACING,
7676 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7678 yaffs_Deinitialise(dev);
7682 /* Zero out stats */
7683 dev->nPageReads = 0;
7684 dev->nPageWrites = 0;
7685 dev->nBlockErasures = 0;
7687 dev->nRetriedWrites = 0;
7689 dev->nRetiredBlocks = 0;
7691 yaffs_VerifyFreeChunks(dev);
7692 yaffs_VerifyBlocks(dev);
7694 /* Clean up any aborted checkpoint data */
7695 if(!dev->isCheckpointed && dev->blocksInCheckpoint > 0)
7696 yaffs_InvalidateCheckpoint(dev);
7698 T(YAFFS_TRACE_TRACING,
7699 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7704 void yaffs_Deinitialise(yaffs_Device *dev)
7706 if (dev->isMounted) {
7709 yaffs_DeinitialiseBlocks(dev);
7710 yaffs_DeinitialiseTnodes(dev);
7711 yaffs_DeinitialiseObjects(dev);
7712 if (dev->nShortOpCaches > 0 &&
7715 for (i = 0; i < dev->nShortOpCaches; i++) {
7716 if (dev->srCache[i].data)
7717 YFREE(dev->srCache[i].data);
7718 dev->srCache[i].data = NULL;
7721 YFREE(dev->srCache);
7722 dev->srCache = NULL;
7725 YFREE(dev->gcCleanupList);
7727 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
7728 YFREE(dev->tempBuffer[i].buffer);
7732 if (dev->deinitialiseNAND)
7733 dev->deinitialiseNAND(dev);
7737 static int yaffs_CountFreeChunks(yaffs_Device *dev)
7742 yaffs_BlockInfo *blk;
7744 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7746 blk = yaffs_GetBlockInfo(dev, b);
7748 switch (blk->blockState) {
7749 case YAFFS_BLOCK_STATE_EMPTY:
7750 case YAFFS_BLOCK_STATE_ALLOCATING:
7751 case YAFFS_BLOCK_STATE_COLLECTING:
7752 case YAFFS_BLOCK_STATE_FULL:
7754 (dev->nChunksPerBlock - blk->pagesInUse +
7755 blk->softDeletions);
7765 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
7767 /* This is what we report to the outside world */
7770 int nDirtyCacheChunks;
7771 int blocksForCheckpoint;
7775 nFree = dev->nFreeChunks;
7777 nFree = yaffs_CountFreeChunks(dev);
7780 nFree += dev->nDeletedFiles;
7782 /* Now count the number of dirty chunks in the cache and subtract those */
7784 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7785 if (dev->srCache[i].dirty)
7786 nDirtyCacheChunks++;
7789 nFree -= nDirtyCacheChunks;
7791 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7793 /* Now we figure out how much to reserve for the checkpoint and report that... */
7794 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7795 if (blocksForCheckpoint < 0)
7796 blocksForCheckpoint = 0;
7798 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7807 static int yaffs_freeVerificationFailures;
7809 static void yaffs_VerifyFreeChunks(yaffs_Device *dev)
7814 if (yaffs_SkipVerification(dev))
7817 counted = yaffs_CountFreeChunks(dev);
7819 difference = dev->nFreeChunks - counted;
7822 T(YAFFS_TRACE_ALWAYS,
7823 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7824 dev->nFreeChunks, counted, difference));
7825 yaffs_freeVerificationFailures++;
7829 /*---------------------------------------- YAFFS test code ----------------------*/
7831 #define yaffs_CheckStruct(structure, syze, name) \
7833 if (sizeof(structure) != syze) { \
7834 T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
7835 name, syze, (int) sizeof(structure))); \
7836 return YAFFS_FAIL; \
7840 static int yaffs_CheckStructures(void)
7842 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
7843 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
7844 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
7845 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7846 /* yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode"); */
7848 #ifndef CONFIG_YAFFS_WINCE
7849 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");