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.107 2010-02-17 02:01:25 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
1192 static Y_INLINE int yaffs_CalcTnodeSize(yaffs_Device *dev)
1195 /* Calculate the tnode size in bytes for variable width tnode support.
1196 * Must be a multiple of 32-bits */
1197 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1199 if (tnodeSize < sizeof(yaffs_Tnode))
1200 tnodeSize = sizeof(yaffs_Tnode);
1204 static int yaffs_CreateTnodes(yaffs_Device *dev, int nTnodes)
1207 int tnodeSize = yaffs_CalcTnodeSize(dev);
1208 yaffs_Tnode *newTnodes;
1212 yaffs_TnodeList *tnl;
1218 /* make these things */
1220 newTnodes = YMALLOC(nTnodes * tnodeSize);
1221 mem = (__u8 *)newTnodes;
1224 T(YAFFS_TRACE_ERROR,
1225 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1229 /* Hook them into the free list */
1231 for (i = 0; i < nTnodes - 1; i++) {
1232 newTnodes[i].internal[0] = &newTnodes[i + 1];
1233 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1234 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1238 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1239 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1240 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1242 dev->freeTnodes = newTnodes;
1244 /* New hookup for wide tnodes */
1245 for (i = 0; i < nTnodes - 1; i++) {
1246 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1247 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1248 curr->internal[0] = next;
1251 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1252 curr->internal[0] = dev->freeTnodes;
1253 dev->freeTnodes = (yaffs_Tnode *)mem;
1258 dev->nFreeTnodes += nTnodes;
1259 dev->nTnodesCreated += nTnodes;
1261 /* Now add this bunch of tnodes to a list for freeing up.
1262 * NB If we can't add this to the management list it isn't fatal
1263 * but it just means we can't free this bunch of tnodes later.
1266 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1268 T(YAFFS_TRACE_ERROR,
1270 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1273 tnl->tnodes = newTnodes;
1274 tnl->next = dev->allocatedTnodeList;
1275 dev->allocatedTnodeList = tnl;
1278 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1283 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1285 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device *dev)
1287 yaffs_Tnode *tn = NULL;
1289 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1290 tn = YMALLOC(yaffs_CalcTnodeSize(dev));
1292 dev->nTnodesCreated++;
1294 /* If there are none left make more */
1295 if (!dev->freeTnodes)
1296 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1298 if (dev->freeTnodes) {
1299 tn = dev->freeTnodes;
1300 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1301 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1302 /* Hoosterman, this thing looks like it isn't in the list */
1303 T(YAFFS_TRACE_ALWAYS,
1304 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1307 dev->freeTnodes = dev->freeTnodes->internal[0];
1311 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1316 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
1318 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1319 int tnodeSize = yaffs_CalcTnodeSize(dev);
1322 memset(tn, 0, tnodeSize);
1327 /* FreeTnode frees up a tnode and puts it back on the free list */
1328 static void yaffs_FreeTnode(yaffs_Device *dev, yaffs_Tnode *tn)
1331 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1333 dev->nTnodesCreated--;
1335 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1336 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1337 /* Hoosterman, this thing looks like it is already in the list */
1338 T(YAFFS_TRACE_ALWAYS,
1339 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1341 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1343 tn->internal[0] = dev->freeTnodes;
1344 dev->freeTnodes = tn;
1348 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1351 static void yaffs_DeinitialiseTnodes(yaffs_Device *dev)
1353 /* Free the list of allocated tnodes */
1354 yaffs_TnodeList *tmp;
1356 while (dev->allocatedTnodeList) {
1357 tmp = dev->allocatedTnodeList->next;
1359 YFREE(dev->allocatedTnodeList->tnodes);
1360 YFREE(dev->allocatedTnodeList);
1361 dev->allocatedTnodeList = tmp;
1365 dev->freeTnodes = NULL;
1366 dev->nFreeTnodes = 0;
1367 dev->nTnodesCreated = 0;
1370 static void yaffs_InitialiseTnodes(yaffs_Device *dev)
1372 dev->allocatedTnodeList = NULL;
1373 dev->freeTnodes = NULL;
1374 dev->nFreeTnodes = 0;
1375 dev->nTnodesCreated = 0;
1379 void yaffs_LoadLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
1382 __u32 *map = (__u32 *)tn;
1388 pos &= YAFFS_TNODES_LEVEL0_MASK;
1389 val >>= dev->chunkGroupBits;
1391 bitInMap = pos * dev->tnodeWidth;
1392 wordInMap = bitInMap / 32;
1393 bitInWord = bitInMap & (32 - 1);
1395 mask = dev->tnodeMask << bitInWord;
1397 map[wordInMap] &= ~mask;
1398 map[wordInMap] |= (mask & (val << bitInWord));
1400 if (dev->tnodeWidth > (32 - bitInWord)) {
1401 bitInWord = (32 - bitInWord);
1403 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1404 map[wordInMap] &= ~mask;
1405 map[wordInMap] |= (mask & (val >> bitInWord));
1409 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
1412 __u32 *map = (__u32 *)tn;
1418 pos &= YAFFS_TNODES_LEVEL0_MASK;
1420 bitInMap = pos * dev->tnodeWidth;
1421 wordInMap = bitInMap / 32;
1422 bitInWord = bitInMap & (32 - 1);
1424 val = map[wordInMap] >> bitInWord;
1426 if (dev->tnodeWidth > (32 - bitInWord)) {
1427 bitInWord = (32 - bitInWord);
1429 val |= (map[wordInMap] << bitInWord);
1432 val &= dev->tnodeMask;
1433 val <<= dev->chunkGroupBits;
1438 /* ------------------- End of individual tnode manipulation -----------------*/
1440 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1441 * The look up tree is represented by the top tnode and the number of topLevel
1442 * in the tree. 0 means only the level 0 tnode is in the tree.
1445 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1446 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
1447 yaffs_FileStructure *fStruct,
1450 yaffs_Tnode *tn = fStruct->top;
1452 int requiredTallness;
1453 int level = fStruct->topLevel;
1455 /* Check sane level and chunk Id */
1456 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
1459 if (chunkId > YAFFS_MAX_CHUNK_ID)
1462 /* First check we're tall enough (ie enough topLevel) */
1464 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1465 requiredTallness = 0;
1467 i >>= YAFFS_TNODES_INTERNAL_BITS;
1471 if (requiredTallness > fStruct->topLevel)
1472 return NULL; /* Not tall enough, so we can't find it */
1474 /* Traverse down to level 0 */
1475 while (level > 0 && tn) {
1476 tn = tn->internal[(chunkId >>
1477 (YAFFS_TNODES_LEVEL0_BITS +
1479 YAFFS_TNODES_INTERNAL_BITS)) &
1480 YAFFS_TNODES_INTERNAL_MASK];
1487 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1488 * This happens in two steps:
1489 * 1. If the tree isn't tall enough, then make it taller.
1490 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1492 * Used when modifying the tree.
1494 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1495 * be plugged into the ttree.
1498 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
1499 yaffs_FileStructure *fStruct,
1501 yaffs_Tnode *passedTn)
1503 int requiredTallness;
1511 /* Check sane level and page Id */
1512 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
1515 if (chunkId > YAFFS_MAX_CHUNK_ID)
1518 /* First check we're tall enough (ie enough topLevel) */
1520 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1521 requiredTallness = 0;
1523 x >>= YAFFS_TNODES_INTERNAL_BITS;
1528 if (requiredTallness > fStruct->topLevel) {
1529 /* Not tall enough, gotta make the tree taller */
1530 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1532 tn = yaffs_GetTnode(dev);
1535 tn->internal[0] = fStruct->top;
1537 fStruct->topLevel++;
1539 T(YAFFS_TRACE_ERROR,
1540 (TSTR("yaffs: no more tnodes" TENDSTR)));
1546 /* Traverse down to level 0, adding anything we need */
1548 l = fStruct->topLevel;
1552 while (l > 0 && tn) {
1554 (YAFFS_TNODES_LEVEL0_BITS +
1555 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1556 YAFFS_TNODES_INTERNAL_MASK;
1559 if ((l > 1) && !tn->internal[x]) {
1560 /* Add missing non-level-zero tnode */
1561 tn->internal[x] = yaffs_GetTnode(dev);
1562 if(!tn->internal[x])
1564 } else if (l == 1) {
1565 /* Looking from level 1 at level 0 */
1567 /* If we already have one, then release it.*/
1568 if (tn->internal[x])
1569 yaffs_FreeTnode(dev, tn->internal[x]);
1570 tn->internal[x] = passedTn;
1572 } else if (!tn->internal[x]) {
1573 /* Don't have one, none passed in */
1574 tn->internal[x] = yaffs_GetTnode(dev);
1575 if(!tn->internal[x])
1580 tn = tn->internal[x];
1584 /* top is level 0 */
1586 memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1587 yaffs_FreeTnode(dev, passedTn);
1594 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
1595 yaffs_ExtendedTags *tags, int objectId,
1600 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1601 if (yaffs_CheckChunkBit(dev, theChunk / dev->nChunksPerBlock,
1602 theChunk % dev->nChunksPerBlock)) {
1604 if(dev->chunkGroupSize == 1)
1607 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1609 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1621 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1622 * chunks and tnodes in the file
1623 * Returns 1 if the tree was deleted.
1624 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1627 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
1628 int chunkOffset, int *limit)
1633 yaffs_ExtendedTags tags;
1635 yaffs_Device *dev = in->myDev;
1641 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1643 if (tn->internal[i]) {
1644 if (limit && (*limit) < 0) {
1648 yaffs_DeleteWorker(in,
1656 YAFFS_TNODES_INTERNAL_BITS)
1661 yaffs_FreeTnode(dev,
1664 tn->internal[i] = NULL;
1668 return (allDone) ? 1 : 0;
1669 } else if (level == 0) {
1672 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1674 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1677 chunkInInode = (chunkOffset <<
1678 YAFFS_TNODES_LEVEL0_BITS) + i;
1681 yaffs_FindChunkInGroup(dev,
1687 if (foundChunk > 0) {
1688 yaffs_DeleteChunk(dev,
1693 *limit = *limit - 1;
1700 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1704 return (i < 0) ? 1 : 0;
1714 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1716 yaffs_BlockInfo *theBlock;
1718 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1720 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1722 theBlock->softDeletions++;
1727 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1728 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1730 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1733 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1734 __u32 level, int chunkOffset)
1739 yaffs_Device *dev = in->myDev;
1744 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1746 if (tn->internal[i]) {
1748 yaffs_SoftDeleteWorker(in,
1754 YAFFS_TNODES_INTERNAL_BITS)
1757 yaffs_FreeTnode(dev,
1760 tn->internal[i] = NULL;
1762 /* Hoosterman... how could this happen? */
1766 return (allDone) ? 1 : 0;
1767 } else if (level == 0) {
1769 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1770 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1772 /* Note this does not find the real chunk, only the chunk group.
1773 * We make an assumption that a chunk group is not larger than
1776 yaffs_SoftDeleteChunk(dev, theChunk);
1777 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1791 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1794 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1795 if (obj->nDataChunks <= 0) {
1796 /* Empty file with no duplicate object headers, just delete it immediately */
1797 yaffs_FreeTnode(obj->myDev,
1798 obj->variant.fileVariant.top);
1799 obj->variant.fileVariant.top = NULL;
1800 T(YAFFS_TRACE_TRACING,
1801 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1803 yaffs_DoGenericObjectDeletion(obj);
1805 yaffs_SoftDeleteWorker(obj,
1806 obj->variant.fileVariant.top,
1807 obj->variant.fileVariant.
1809 obj->softDeleted = 1;
1814 /* Pruning removes any part of the file structure tree that is beyond the
1815 * bounds of the file (ie that does not point to chunks).
1817 * A file should only get pruned when its size is reduced.
1819 * Before pruning, the chunks must be pulled from the tree and the
1820 * level 0 tnode entries must be zeroed out.
1821 * Could also use this for file deletion, but that's probably better handled
1822 * by a special case.
1824 * This function is recursive. For levels > 0 the function is called again on
1825 * any sub-tree. For level == 0 we just check if the sub-tree has data.
1826 * If there is no data in a subtree then it is pruned.
1829 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1830 __u32 level, int del0)
1839 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1840 if (tn->internal[i]) {
1842 yaffs_PruneWorker(dev, tn->internal[i],
1844 (i == 0) ? del0 : 1);
1847 if (tn->internal[i])
1851 int tnodeSize_u32 = yaffs_CalcTnodeSize(dev)/sizeof(__u32);
1852 __u32 *map = (__u32 *)tn;
1854 for(i = 0; !hasData && i < tnodeSize_u32; i++){
1860 if (hasData == 0 && del0) {
1861 /* Free and return NULL */
1863 yaffs_FreeTnode(dev, tn);
1873 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1874 yaffs_FileStructure *fStruct)
1881 if (fStruct->topLevel > 0) {
1883 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1885 /* Now we have a tree with all the non-zero branches NULL but the height
1886 * is the same as it was.
1887 * Let's see if we can trim internal tnodes to shorten the tree.
1888 * We can do this if only the 0th element in the tnode is in use
1889 * (ie all the non-zero are NULL)
1892 while (fStruct->topLevel && !done) {
1896 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1897 if (tn->internal[i])
1902 fStruct->top = tn->internal[0];
1903 fStruct->topLevel--;
1904 yaffs_FreeTnode(dev, tn);
1914 /*-------------------- End of File Structure functions.-------------------*/
1916 /* yaffs_CreateFreeObjects creates a bunch more objects and
1917 * adds them to the object free list.
1919 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1922 yaffs_Object *newObjects;
1923 yaffs_ObjectList *list;
1928 /* make these things */
1929 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1930 list = YMALLOC(sizeof(yaffs_ObjectList));
1932 if (!newObjects || !list) {
1941 T(YAFFS_TRACE_ALLOCATE,
1942 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1946 /* Hook them into the free list */
1947 for (i = 0; i < nObjects - 1; i++) {
1948 newObjects[i].siblings.next =
1949 (struct ylist_head *)(&newObjects[i + 1]);
1952 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1953 dev->freeObjects = newObjects;
1954 dev->nFreeObjects += nObjects;
1955 dev->nObjectsCreated += nObjects;
1957 /* Now add this bunch of Objects to a list for freeing up. */
1959 list->objects = newObjects;
1960 list->next = dev->allocatedObjectList;
1961 dev->allocatedObjectList = list;
1967 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1968 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1970 yaffs_Object *tn = NULL;
1972 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1973 tn = YMALLOC(sizeof(yaffs_Object));
1975 dev->nObjectsCreated++;
1977 /* If there are none left make more */
1978 if (!dev->freeObjects)
1979 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1981 if (dev->freeObjects) {
1982 tn = dev->freeObjects;
1984 (yaffs_Object *) (dev->freeObjects->siblings.next);
1985 dev->nFreeObjects--;
1989 /* Now sweeten it up... */
1991 memset(tn, 0, sizeof(yaffs_Object));
1992 tn->beingCreated = 1;
1996 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1997 YINIT_LIST_HEAD(&(tn->hardLinks));
1998 YINIT_LIST_HEAD(&(tn->hashLink));
1999 YINIT_LIST_HEAD(&tn->siblings);
2002 /* Now make the directory sane */
2004 tn->parent = dev->rootDir;
2005 ylist_add(&(tn->siblings), &dev->rootDir->variant.directoryVariant.children);
2008 /* Add it to the lost and found directory.
2009 * NB Can't put root or lostNFound in lostNFound so
2010 * check if lostNFound exists first
2012 if (dev->lostNFoundDir)
2013 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
2015 tn->beingCreated = 0;
2018 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2023 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
2028 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
2030 obj->fake = 1; /* it is fake so it might have no NAND presence... */
2031 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
2032 obj->unlinkAllowed = 0; /* ... or unlink it */
2035 obj->yst_mode = mode;
2037 obj->hdrChunk = 0; /* Not a valid chunk. */
2044 static void yaffs_UnhashObject(yaffs_Object *tn)
2047 yaffs_Device *dev = tn->myDev;
2049 /* If it is still linked into the bucket list, free from the list */
2050 if (!ylist_empty(&tn->hashLink)) {
2051 ylist_del_init(&tn->hashLink);
2052 bucket = yaffs_HashFunction(tn->objectId);
2053 dev->objectBucket[bucket].count--;
2057 /* FreeObject frees up a Object and puts it back on the free list */
2058 static void yaffs_FreeObject(yaffs_Object *tn)
2060 yaffs_Device *dev = tn->myDev;
2062 T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), tn, tn->myInode));
2068 if (!ylist_empty(&tn->siblings))
2073 /* We're still hooked up to a cached inode.
2074 * Don't delete now, but mark for later deletion
2076 tn->deferedFree = 1;
2080 yaffs_UnhashObject(tn);
2082 #ifdef CONFIG_YAFFS_VALGRIND_TEST
2084 dev->nObjectsCreated--;
2087 /* Link into the free list. */
2088 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2089 dev->freeObjects = tn;
2090 dev->nFreeObjects++;
2092 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2097 void yaffs_HandleDeferedFree(yaffs_Object *obj)
2099 if (obj->deferedFree)
2100 yaffs_FreeObject(obj);
2105 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
2107 /* Free the list of allocated Objects */
2109 yaffs_ObjectList *tmp;
2111 while (dev->allocatedObjectList) {
2112 tmp = dev->allocatedObjectList->next;
2113 YFREE(dev->allocatedObjectList->objects);
2114 YFREE(dev->allocatedObjectList);
2116 dev->allocatedObjectList = tmp;
2119 dev->freeObjects = NULL;
2120 dev->nFreeObjects = 0;
2121 dev->nObjectsCreated = 0;
2124 static void yaffs_InitialiseObjects(yaffs_Device *dev)
2128 dev->allocatedObjectList = NULL;
2129 dev->freeObjects = NULL;
2130 dev->nFreeObjects = 0;
2132 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2133 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2134 dev->objectBucket[i].count = 0;
2138 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
2143 int lowest = 999999;
2145 /* First let's see if we can find one that's empty. */
2147 for (i = 0; i < 10 && lowest > 0; i++) {
2149 x %= YAFFS_NOBJECT_BUCKETS;
2150 if (dev->objectBucket[x].count < lowest) {
2151 lowest = dev->objectBucket[x].count;
2157 /* If we didn't find an empty list, then try
2158 * looking a bit further for a short one
2161 for (i = 0; i < 10 && lowest > 3; i++) {
2163 x %= YAFFS_NOBJECT_BUCKETS;
2164 if (dev->objectBucket[x].count < lowest) {
2165 lowest = dev->objectBucket[x].count;
2174 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
2176 int bucket = yaffs_FindNiceObjectBucket(dev);
2178 /* Now find an object value that has not already been taken
2179 * by scanning the list.
2183 struct ylist_head *i;
2185 __u32 n = (__u32) bucket;
2187 /* yaffs_CheckObjectHashSanity(); */
2191 n += YAFFS_NOBJECT_BUCKETS;
2192 if (1 || dev->objectBucket[bucket].count > 0) {
2193 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2194 /* If there is already one in the list */
2195 if (i && ylist_entry(i, yaffs_Object,
2196 hashLink)->objectId == n) {
2206 static void yaffs_HashObject(yaffs_Object *in)
2208 int bucket = yaffs_HashFunction(in->objectId);
2209 yaffs_Device *dev = in->myDev;
2211 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2212 dev->objectBucket[bucket].count++;
2215 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
2217 int bucket = yaffs_HashFunction(number);
2218 struct ylist_head *i;
2221 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2222 /* Look if it is in the list */
2224 in = ylist_entry(i, yaffs_Object, hashLink);
2225 if (in->objectId == number) {
2227 /* Don't tell the VFS about this one if it is defered free */
2228 if (in->deferedFree)
2240 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
2241 yaffs_ObjectType type)
2243 yaffs_Object *theObject=NULL;
2244 yaffs_Tnode *tn = NULL;
2247 number = yaffs_CreateNewObjectNumber(dev);
2249 if (type == YAFFS_OBJECT_TYPE_FILE) {
2250 tn = yaffs_GetTnode(dev);
2255 theObject = yaffs_AllocateEmptyObject(dev);
2258 yaffs_FreeTnode(dev,tn);
2264 theObject->fake = 0;
2265 theObject->renameAllowed = 1;
2266 theObject->unlinkAllowed = 1;
2267 theObject->objectId = number;
2268 yaffs_HashObject(theObject);
2269 theObject->variantType = type;
2270 #ifdef CONFIG_YAFFS_WINCE
2271 yfsd_WinFileTimeNow(theObject->win_atime);
2272 theObject->win_ctime[0] = theObject->win_mtime[0] =
2273 theObject->win_atime[0];
2274 theObject->win_ctime[1] = theObject->win_mtime[1] =
2275 theObject->win_atime[1];
2279 theObject->yst_atime = theObject->yst_mtime =
2280 theObject->yst_ctime = Y_CURRENT_TIME;
2283 case YAFFS_OBJECT_TYPE_FILE:
2284 theObject->variant.fileVariant.fileSize = 0;
2285 theObject->variant.fileVariant.scannedFileSize = 0;
2286 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2287 theObject->variant.fileVariant.topLevel = 0;
2288 theObject->variant.fileVariant.top = tn;
2290 case YAFFS_OBJECT_TYPE_DIRECTORY:
2291 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2294 case YAFFS_OBJECT_TYPE_SYMLINK:
2295 case YAFFS_OBJECT_TYPE_HARDLINK:
2296 case YAFFS_OBJECT_TYPE_SPECIAL:
2297 /* No action required */
2299 case YAFFS_OBJECT_TYPE_UNKNOWN:
2300 /* todo this should not happen */
2308 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
2310 yaffs_ObjectType type)
2312 yaffs_Object *theObject = NULL;
2315 theObject = yaffs_FindObjectByNumber(dev, number);
2318 theObject = yaffs_CreateNewObject(dev, number, type);
2325 static YCHAR *yaffs_CloneString(const YCHAR *str)
2327 YCHAR *newStr = NULL;
2333 len = yaffs_strnlen(str,YAFFS_MAX_ALIAS_LENGTH);
2334 newStr = YMALLOC((len + 1) * sizeof(YCHAR));
2336 yaffs_strncpy(newStr, str,len);
2344 * Mknod (create) a new object.
2345 * equivalentObject only has meaning for a hard link;
2346 * aliasString only has meaning for a symlink.
2347 * rdev only has meaning for devices (a subset of special objects)
2350 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2351 yaffs_Object *parent,
2356 yaffs_Object *equivalentObject,
2357 const YCHAR *aliasString, __u32 rdev)
2362 yaffs_Device *dev = parent->myDev;
2364 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2365 if (yaffs_FindObjectByName(parent, name))
2368 if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2369 str = yaffs_CloneString(aliasString);
2374 in = yaffs_CreateNewObject(dev, -1, type);
2389 in->variantType = type;
2391 in->yst_mode = mode;
2393 #ifdef CONFIG_YAFFS_WINCE
2394 yfsd_WinFileTimeNow(in->win_atime);
2395 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2396 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2399 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2401 in->yst_rdev = rdev;
2405 in->nDataChunks = 0;
2407 yaffs_SetObjectName(in, name);
2410 yaffs_AddObjectToDirectory(parent, in);
2412 in->myDev = parent->myDev;
2415 case YAFFS_OBJECT_TYPE_SYMLINK:
2416 in->variant.symLinkVariant.alias = str;
2418 case YAFFS_OBJECT_TYPE_HARDLINK:
2419 in->variant.hardLinkVariant.equivalentObject =
2421 in->variant.hardLinkVariant.equivalentObjectId =
2422 equivalentObject->objectId;
2423 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2425 case YAFFS_OBJECT_TYPE_FILE:
2426 case YAFFS_OBJECT_TYPE_DIRECTORY:
2427 case YAFFS_OBJECT_TYPE_SPECIAL:
2428 case YAFFS_OBJECT_TYPE_UNKNOWN:
2433 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2434 /* Could not create the object header, fail the creation */
2435 yaffs_DeleteObject(in);
2439 yaffs_UpdateParent(parent);
2445 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
2446 __u32 mode, __u32 uid, __u32 gid)
2448 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2449 uid, gid, NULL, NULL, 0);
2452 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
2453 __u32 mode, __u32 uid, __u32 gid)
2455 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2456 mode, uid, gid, NULL, NULL, 0);
2459 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
2460 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2462 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2463 uid, gid, NULL, NULL, rdev);
2466 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
2467 __u32 mode, __u32 uid, __u32 gid,
2470 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2471 uid, gid, NULL, alias, 0);
2474 /* yaffs_Link returns the object id of the equivalent object.*/
2475 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
2476 yaffs_Object *equivalentObject)
2478 /* Get the real object in case we were fed a hard link as an equivalent object */
2479 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2481 if (yaffs_MknodObject
2482 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2483 equivalentObject, NULL, 0)) {
2484 return equivalentObject;
2491 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
2492 const YCHAR *newName, int force, int shadows)
2497 yaffs_Object *existingTarget;
2500 newDir = obj->parent; /* use the old directory */
2502 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2503 T(YAFFS_TRACE_ALWAYS,
2505 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2510 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2511 if (obj->myDev->isYaffs2)
2512 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2514 unlinkOp = (newDir == obj->myDev->unlinkedDir
2515 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2517 deleteOp = (newDir == obj->myDev->deletedDir);
2519 existingTarget = yaffs_FindObjectByName(newDir, newName);
2521 /* If the object is a file going into the unlinked directory,
2522 * then it is OK to just stuff it in since duplicate names are allowed.
2523 * else only proceed if the new name does not exist and if we're putting
2524 * it into a directory.
2531 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2532 yaffs_SetObjectName(obj, newName);
2535 yaffs_AddObjectToDirectory(newDir, obj);
2540 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2541 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows) >= 0)
2548 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
2549 yaffs_Object *newDir, const YCHAR *newName)
2551 yaffs_Object *obj = NULL;
2552 yaffs_Object *existingTarget = NULL;
2558 if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2560 if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2563 dev = oldDir->myDev;
2565 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2566 /* Special case for case insemsitive systems (eg. WinCE).
2567 * While look-up is case insensitive, the name isn't.
2568 * Therefore we might want to change x.txt to X.txt
2570 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
2574 if(yaffs_strnlen(newName,YAFFS_MAX_NAME_LENGTH+1) > YAFFS_MAX_NAME_LENGTH)
2578 obj = yaffs_FindObjectByName(oldDir, oldName);
2580 if (obj && obj->renameAllowed) {
2582 /* Now do the handling for an existing target, if there is one */
2584 existingTarget = yaffs_FindObjectByName(newDir, newName);
2585 if (existingTarget &&
2586 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2587 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2588 /* There is a target that is a non-empty directory, so we fail */
2589 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2590 } else if (existingTarget && existingTarget != obj) {
2591 /* Nuke the target first, using shadowing,
2592 * but only if it isn't the same object.
2594 * Note we must disable gc otherwise it can mess up the shadowing.
2598 yaffs_ChangeObjectName(obj, newDir, newName, force,
2599 existingTarget->objectId);
2600 existingTarget->isShadowed = 1;
2601 yaffs_UnlinkObject(existingTarget);
2605 result = yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2607 yaffs_UpdateParent(oldDir);
2608 if(newDir != oldDir)
2609 yaffs_UpdateParent(newDir);
2616 /*------------------------- Block Management and Page Allocation ----------------*/
2618 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
2620 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2622 dev->blockInfo = NULL;
2623 dev->chunkBits = NULL;
2625 dev->allocationBlock = -1; /* force it to get a new one */
2627 /* If the first allocation strategy fails, thry the alternate one */
2628 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2629 if (!dev->blockInfo) {
2630 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2631 dev->blockInfoAlt = 1;
2633 dev->blockInfoAlt = 0;
2635 if (dev->blockInfo) {
2636 /* Set up dynamic blockinfo stuff. */
2637 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2638 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2639 if (!dev->chunkBits) {
2640 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2641 dev->chunkBitsAlt = 1;
2643 dev->chunkBitsAlt = 0;
2646 if (dev->blockInfo && dev->chunkBits) {
2647 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2648 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2655 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2657 if (dev->blockInfoAlt && dev->blockInfo)
2658 YFREE_ALT(dev->blockInfo);
2659 else if (dev->blockInfo)
2660 YFREE(dev->blockInfo);
2662 dev->blockInfoAlt = 0;
2664 dev->blockInfo = NULL;
2666 if (dev->chunkBitsAlt && dev->chunkBits)
2667 YFREE_ALT(dev->chunkBits);
2668 else if (dev->chunkBits)
2669 YFREE(dev->chunkBits);
2670 dev->chunkBitsAlt = 0;
2671 dev->chunkBits = NULL;
2674 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
2675 yaffs_BlockInfo *bi)
2682 return 1; /* disqualification only applies to yaffs2. */
2684 if (!bi->hasShrinkHeader)
2685 return 1; /* can gc */
2687 /* Find the oldest dirty sequence number if we don't know it and save it
2688 * so we don't have to keep recomputing it.
2690 if (!dev->oldestDirtySequence) {
2691 seq = dev->sequenceNumber;
2693 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2695 b = yaffs_GetBlockInfo(dev, i);
2696 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2697 (b->pagesInUse - b->softDeletions) <
2698 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2699 seq = b->sequenceNumber;
2702 dev->oldestDirtySequence = seq;
2705 /* Can't do gc of this block if there are any blocks older than this one that have
2708 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2711 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2712 * for garbage collection.
2715 static int yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
2718 int b = dev->currentDirtyChecker;
2724 int prioritised = 0;
2725 yaffs_BlockInfo *bi;
2726 int pendingPrioritisedExist = 0;
2728 /* First let's see if we need to grab a prioritised block */
2729 if (dev->hasPendingPrioritisedGCs) {
2730 for (i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++) {
2732 bi = yaffs_GetBlockInfo(dev, i);
2733 /* yaffs_VerifyBlock(dev,bi,i); */
2735 if (bi->gcPrioritise) {
2736 pendingPrioritisedExist = 1;
2737 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2738 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2739 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2742 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2747 if (!pendingPrioritisedExist) /* None found, so we can clear this */
2748 dev->hasPendingPrioritisedGCs = 0;
2751 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2753 * else (we're doing a leasurely gc), then we only bother to do this if the
2754 * block has only a few pages in use.
2757 dev->nonAggressiveSkip--;
2759 if (!aggressive && (dev->nonAggressiveSkip > 0))
2764 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2768 dev->internalEndBlock - dev->internalStartBlock + 1;
2771 dev->internalEndBlock - dev->internalStartBlock + 1;
2772 iterations = iterations / 16;
2773 if (iterations > 200)
2777 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2779 if (b < dev->internalStartBlock || b > dev->internalEndBlock)
2780 b = dev->internalStartBlock;
2782 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2783 T(YAFFS_TRACE_ERROR,
2784 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2788 bi = yaffs_GetBlockInfo(dev, b);
2790 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2791 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2792 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2794 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2798 dev->currentDirtyChecker = b;
2802 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2803 dev->nChunksPerBlock - pagesInUse, prioritised));
2806 dev->oldestDirtySequence = 0;
2809 dev->nonAggressiveSkip = 4;
2814 static void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
2816 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2820 /* If the block is still healthy erase it and mark as clean.
2821 * If the block has had a data failure, then retire it.
2824 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2825 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2826 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2828 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2830 if (!bi->needsRetiring) {
2831 yaffs_InvalidateCheckpoint(dev);
2832 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2834 dev->nErasureFailures++;
2835 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2836 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2841 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2843 for (i = 0; i < dev->nChunksPerBlock; i++) {
2844 if (!yaffs_CheckChunkErased
2845 (dev, blockNo * dev->nChunksPerBlock + i)) {
2846 T(YAFFS_TRACE_ERROR,
2848 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2849 TENDSTR), blockNo, i));
2855 /* Clean it up... */
2856 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2857 dev->nErasedBlocks++;
2859 bi->softDeletions = 0;
2860 bi->hasShrinkHeader = 0;
2861 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2862 bi->gcPrioritise = 0;
2863 yaffs_ClearChunkBits(dev, blockNo);
2865 T(YAFFS_TRACE_ERASE,
2866 (TSTR("Erased block %d" TENDSTR), blockNo));
2868 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2870 yaffs_RetireBlock(dev, blockNo);
2871 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2872 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2876 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2880 yaffs_BlockInfo *bi;
2882 if (dev->nErasedBlocks < 1) {
2883 /* Hoosterman we've got a problem.
2884 * Can't get space to gc
2886 T(YAFFS_TRACE_ERROR,
2887 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2892 /* Find an empty block. */
2894 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2895 dev->allocationBlockFinder++;
2896 if (dev->allocationBlockFinder < dev->internalStartBlock
2897 || dev->allocationBlockFinder > dev->internalEndBlock) {
2898 dev->allocationBlockFinder = dev->internalStartBlock;
2901 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2903 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2904 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2905 dev->sequenceNumber++;
2906 bi->sequenceNumber = dev->sequenceNumber;
2907 dev->nErasedBlocks--;
2908 T(YAFFS_TRACE_ALLOCATE,
2909 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2910 dev->allocationBlockFinder, dev->sequenceNumber,
2911 dev->nErasedBlocks));
2912 return dev->allocationBlockFinder;
2916 T(YAFFS_TRACE_ALWAYS,
2918 ("yaffs tragedy: no more erased blocks, but there should have been %d"
2919 TENDSTR), dev->nErasedBlocks));
2926 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2928 if (!dev->nCheckpointBlocksRequired &&
2930 /* Not a valid value so recalculate */
2933 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2934 int tnodeSize = yaffs_CalcTnodeSize(dev);
2936 nBytes += sizeof(yaffs_CheckpointValidity);
2937 nBytes += sizeof(yaffs_CheckpointDevice);
2938 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2939 nBytes += devBlocks * dev->chunkBitmapStride;
2940 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2941 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2942 nBytes += sizeof(yaffs_CheckpointValidity);
2943 nBytes += sizeof(__u32); /* checksum*/
2945 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2947 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2949 dev->nCheckpointBlocksRequired = nBlocks;
2952 return dev->nCheckpointBlocksRequired;
2956 * Check if there's space to allocate...
2957 * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2959 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev)
2962 int reservedBlocks = dev->nReservedBlocks;
2963 int checkpointBlocks;
2965 if (dev->isYaffs2) {
2966 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
2967 dev->blocksInCheckpoint;
2968 if (checkpointBlocks < 0)
2969 checkpointBlocks = 0;
2971 checkpointBlocks = 0;
2974 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2976 return (dev->nFreeChunks > reservedChunks);
2979 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
2980 yaffs_BlockInfo **blockUsedPtr)
2983 yaffs_BlockInfo *bi;
2985 if (dev->allocationBlock < 0) {
2986 /* Get next block to allocate off */
2987 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2988 dev->allocationPage = 0;
2991 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2992 /* Not enough space to allocate unless we're allowed to use the reserve. */
2996 if (dev->nErasedBlocks < dev->nReservedBlocks
2997 && dev->allocationPage == 0) {
2998 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
3001 /* Next page please.... */
3002 if (dev->allocationBlock >= 0) {
3003 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3005 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
3006 dev->allocationPage;
3008 yaffs_SetChunkBit(dev, dev->allocationBlock,
3009 dev->allocationPage);
3011 dev->allocationPage++;
3015 /* If the block is full set the state to full */
3016 if (dev->allocationPage >= dev->nChunksPerBlock) {
3017 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3018 dev->allocationBlock = -1;
3027 T(YAFFS_TRACE_ERROR,
3028 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
3033 static int yaffs_GetErasedChunks(yaffs_Device *dev)
3037 n = dev->nErasedBlocks * dev->nChunksPerBlock;
3039 if (dev->allocationBlock > 0)
3040 n += (dev->nChunksPerBlock - dev->allocationPage);
3047 * yaffs_SkipRestOfBlock() skips over the rest of the allocation block
3048 * if we don't want to write to it.
3050 static void yaffs_SkipRestOfBlock(yaffs_Device *dev)
3052 if(dev->allocationBlock > 0){
3053 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3054 if(bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING){
3055 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3056 dev->allocationBlock = -1;
3062 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
3068 int retVal = YAFFS_OK;
3071 int isCheckpointBlock;
3075 int chunksBefore = yaffs_GetErasedChunks(dev);
3078 yaffs_ExtendedTags tags;
3080 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3082 yaffs_Object *object;
3084 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3087 T(YAFFS_TRACE_TRACING,
3088 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3091 bi->hasShrinkHeader,
3094 /*yaffs_VerifyFreeChunks(dev); */
3096 if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
3097 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3099 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
3101 /* Take off the number of soft deleted entries because
3102 * they're going to get really deleted during GC.
3104 if(dev->gcChunk == 0) /* first time through for this block */
3105 dev->nFreeChunks -= bi->softDeletions;
3109 if (isCheckpointBlock ||
3110 !yaffs_StillSomeChunkBits(dev, block)) {
3111 T(YAFFS_TRACE_TRACING,
3113 ("Collecting block %d that has no chunks in use" TENDSTR),
3115 yaffs_BlockBecameDirty(dev, block);
3118 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3120 yaffs_VerifyBlock(dev, bi, block);
3122 maxCopies = (wholeBlock) ? dev->nChunksPerBlock : 10;
3123 oldChunk = block * dev->nChunksPerBlock + dev->gcChunk;
3125 for (/* init already done */;
3126 retVal == YAFFS_OK &&
3127 dev->gcChunk < dev->nChunksPerBlock &&
3128 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
3130 dev->gcChunk++, oldChunk++) {
3131 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3133 /* This page is in use and might need to be copied off */
3139 yaffs_InitialiseTags(&tags);
3141 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3145 yaffs_FindObjectByNumber(dev,
3148 T(YAFFS_TRACE_GC_DETAIL,
3150 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3151 dev->gcChunk, tags.objectId, tags.chunkId,
3154 if (object && !yaffs_SkipVerification(dev)) {
3155 if (tags.chunkId == 0)
3156 matchingChunk = object->hdrChunk;
3157 else if (object->softDeleted)
3158 matchingChunk = oldChunk; /* Defeat the test */
3160 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
3162 if (oldChunk != matchingChunk)
3163 T(YAFFS_TRACE_ERROR,
3164 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3165 oldChunk, matchingChunk, tags.objectId, tags.chunkId));
3170 T(YAFFS_TRACE_ERROR,
3172 ("page %d in gc has no object: %d %d %d "
3174 tags.objectId, tags.chunkId, tags.byteCount));
3179 object->softDeleted &&
3180 tags.chunkId != 0) {
3181 /* Data chunk in a soft deleted file, throw it away
3182 * It's a soft deleted data chunk,
3183 * No need to copy this, just forget about it and
3184 * fix up the object.
3187 object->nDataChunks--;
3189 if (object->nDataChunks <= 0) {
3190 /* remeber to clean up the object */
3191 dev->gcCleanupList[cleanups] =
3197 /* Todo object && object->deleted && object->nDataChunks == 0 */
3198 /* Deleted object header with no data chunks.
3199 * Can be discarded and the file deleted.
3201 object->hdrChunk = 0;
3202 yaffs_FreeTnode(object->myDev,
3205 object->variant.fileVariant.top = NULL;
3206 yaffs_DoGenericObjectDeletion(object);
3208 } else if (object) {
3209 /* It's either a data chunk in a live file or
3210 * an ObjectHeader, so we're interested in it.
3211 * NB Need to keep the ObjectHeaders of deleted files
3212 * until the whole file has been deleted off
3214 tags.serialNumber++;
3218 if (tags.chunkId == 0) {
3219 /* It is an object Id,
3220 * We need to nuke the shrinkheader flags first
3221 * Also need to clean up shadowing.
3222 * We no longer want the shrinkHeader flag since its work is done
3223 * and if it is left in place it will mess up scanning.
3226 yaffs_ObjectHeader *oh;
3227 oh = (yaffs_ObjectHeader *)buffer;
3229 tags.extraIsShrinkHeader = 0;
3230 oh->shadowsObject = 0;
3231 oh->inbandShadowsObject = 0;
3232 tags.extraShadows = 0;
3234 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
3238 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3241 retVal = YAFFS_FAIL;
3244 /* Ok, now fix up the Tnodes etc. */
3246 if (tags.chunkId == 0) {
3248 object->hdrChunk = newChunk;
3249 object->serial = tags.serialNumber;
3251 /* It's a data chunk */
3253 ok = yaffs_PutChunkIntoFile
3261 if (retVal == YAFFS_OK)
3262 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3267 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3270 /* Do any required cleanups */
3271 for (i = 0; i < cleanups; i++) {
3272 /* Time to delete the file too */
3274 yaffs_FindObjectByNumber(dev,
3275 dev->gcCleanupList[i]);
3277 yaffs_FreeTnode(dev,
3278 object->variant.fileVariant.
3280 object->variant.fileVariant.top = NULL;
3283 ("yaffs: About to finally delete object %d"
3284 TENDSTR), object->objectId));
3285 yaffs_DoGenericObjectDeletion(object);
3286 object->myDev->nDeletedFiles--;
3293 yaffs_VerifyCollectedBlock(dev, bi, block);
3295 chunksAfter = yaffs_GetErasedChunks(dev);
3296 if (chunksBefore >= chunksAfter) {
3299 ("gc did not increase free chunks before %d after %d"
3300 TENDSTR), chunksBefore, chunksAfter));
3303 /* If the gc completed then clear the current gcBlock so that we find another. */
3304 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING) {
3314 /* New garbage collector
3315 * If we're very low on erased blocks then we do aggressive garbage collection
3316 * otherwise we do "leasurely" garbage collection.
3317 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3318 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3320 * The idea is to help clear out space in a more spread-out manner.
3321 * Dunno if it really does anything useful.
3323 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
3327 int gcOk = YAFFS_OK;
3330 int checkpointBlockAdjust;
3332 if (dev->isDoingGC) {
3333 /* Bail out so we don't get recursive gc */
3337 /* This loop should pass the first time.
3338 * We'll only see looping here if the erase of the collected block fails.
3344 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3345 if (checkpointBlockAdjust < 0)
3346 checkpointBlockAdjust = 0;
3348 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3349 /* We need a block soon...*/
3352 /* We're in no hurry */
3356 if (dev->gcBlock <= 0) {
3357 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3361 block = dev->gcBlock;
3364 dev->garbageCollections++;
3366 dev->passiveGarbageCollections++;
3370 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3371 dev->nErasedBlocks, aggressive));
3373 gcOk = yaffs_GarbageCollectBlock(dev, block, aggressive);
3376 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3379 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3380 TENDSTR), dev->nErasedBlocks, maxTries, block));
3382 } while ((dev->nErasedBlocks < dev->nReservedBlocks) &&
3386 return aggressive ? gcOk : YAFFS_OK;
3389 /*------------------------- TAGS --------------------------------*/
3391 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
3394 return (tags->chunkId == chunkInObject &&
3395 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3400 /*-------------------- Data file manipulation -----------------*/
3402 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
3403 yaffs_ExtendedTags *tags)
3405 /*Get the Tnode, then get the level 0 offset chunk offset */
3408 yaffs_ExtendedTags localTags;
3411 yaffs_Device *dev = in->myDev;
3414 /* Passed a NULL, so use our own tags space */
3418 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3421 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3424 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3430 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
3431 yaffs_ExtendedTags *tags)
3433 /* Get the Tnode, then get the level 0 offset chunk offset */
3436 yaffs_ExtendedTags localTags;
3438 yaffs_Device *dev = in->myDev;
3442 /* Passed a NULL, so use our own tags space */
3446 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3450 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3453 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3456 /* Delete the entry in the filestructure (if found) */
3458 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, 0);
3464 #ifdef YAFFS_PARANOID
3466 static int yaffs_CheckFileSanity(yaffs_Object *in)
3474 yaffs_Tags localTags;
3475 yaffs_Tags *tags = &localTags;
3479 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3482 objId = in->objectId;
3483 fSize = in->variant.fileVariant.fileSize;
3485 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3487 for (chunk = 1; chunk <= nChunks; chunk++) {
3488 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3493 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunk);
3495 if (yaffs_CheckChunkBits
3496 (dev, theChunk / dev->nChunksPerBlock,
3497 theChunk % dev->nChunksPerBlock)) {
3499 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3503 (tags, in->objectId, chunk, chunkDeleted)) {
3513 /* T(("No level 0 found for %d\n", chunk)); */
3517 return failed ? YAFFS_FAIL : YAFFS_OK;
3522 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
3523 int chunkInNAND, int inScan)
3525 /* NB inScan is zero unless scanning.
3526 * For forward scanning, inScan is > 0;
3527 * for backward scanning inScan is < 0
3529 * chunkInNAND = 0 is a dummy insert to make sure the tnodes are there.
3533 yaffs_Device *dev = in->myDev;
3535 yaffs_ExtendedTags existingTags;
3536 yaffs_ExtendedTags newTags;
3537 unsigned existingSerial, newSerial;
3539 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3540 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3541 * If it is not during Scanning then something went wrong!
3544 T(YAFFS_TRACE_ERROR,
3546 ("yaffs tragedy:attempt to put data chunk into a non-file"
3551 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3555 tn = yaffs_AddOrFindLevel0Tnode(dev,
3556 &in->variant.fileVariant,
3563 /* Dummy insert, bail now */
3566 existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3569 /* If we're scanning then we need to test for duplicates
3570 * NB This does not need to be efficient since it should only ever
3571 * happen when the power fails during a write, then only one
3572 * chunk should ever be affected.
3574 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3575 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3578 if (existingChunk > 0) {
3579 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3580 * thus we have to do a FindChunkInFile to get the real chunk id.
3582 * We have a duplicate now we need to decide which one to use:
3584 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3585 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3586 * YAFFS1: Get both sets of tags and compare serial numbers.
3590 /* Only do this for forward scanning */
3591 yaffs_ReadChunkWithTagsFromNAND(dev,
3595 /* Do a proper find */
3597 yaffs_FindChunkInFile(in, chunkInInode,
3601 if (existingChunk <= 0) {
3602 /*Hoosterman - how did this happen? */
3604 T(YAFFS_TRACE_ERROR,
3606 ("yaffs tragedy: existing chunk < 0 in scan"
3611 /* NB The deleted flags should be false, otherwise the chunks will
3612 * not be loaded during a scan
3616 newSerial = newTags.serialNumber;
3617 existingSerial = existingTags.serialNumber;
3621 (in->myDev->isYaffs2 ||
3622 existingChunk <= 0 ||
3623 ((existingSerial + 1) & 3) == newSerial)) {
3624 /* Forward scanning.
3626 * Delete the old one and drop through to update the tnode
3628 yaffs_DeleteChunk(dev, existingChunk, 1,
3631 /* Backward scanning or we want to use the existing one
3633 * Delete the new one and return early so that the tnode isn't changed
3635 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3643 if (existingChunk == 0)
3646 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
3651 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
3654 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3656 if (chunkInNAND >= 0)
3657 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3660 T(YAFFS_TRACE_NANDACCESS,
3661 (TSTR("Chunk %d not found zero instead" TENDSTR),
3663 /* get sane (zero) data if you read a hole */
3664 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3670 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
3674 yaffs_ExtendedTags tags;
3675 yaffs_BlockInfo *bi;
3681 block = chunkId / dev->nChunksPerBlock;
3682 page = chunkId % dev->nChunksPerBlock;
3685 if (!yaffs_CheckChunkBit(dev, block, page))
3686 T(YAFFS_TRACE_VERIFY,
3687 (TSTR("Deleting invalid chunk %d"TENDSTR),
3690 bi = yaffs_GetBlockInfo(dev, block);
3692 T(YAFFS_TRACE_DELETION,
3693 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3696 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3698 yaffs_InitialiseTags(&tags);
3700 tags.chunkDeleted = 1;
3702 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3703 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3705 dev->nUnmarkedDeletions++;
3708 /* Pull out of the management area.
3709 * If the whole block became dirty, this will kick off an erasure.
3711 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3712 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3713 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3714 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3717 yaffs_ClearChunkBit(dev, block, page);
3721 if (bi->pagesInUse == 0 &&
3722 !bi->hasShrinkHeader &&
3723 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3724 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3725 yaffs_BlockBecameDirty(dev, block);
3732 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
3733 const __u8 *buffer, int nBytes,
3736 /* Find old chunk Need to do this to get serial number
3737 * Write new one and patch into tree.
3738 * Invalidate old tags.
3742 yaffs_ExtendedTags prevTags;
3745 yaffs_ExtendedTags newTags;
3747 yaffs_Device *dev = in->myDev;
3749 yaffs_CheckGarbageCollection(dev);
3751 /* Get the previous chunk at this location in the file if it exists.
3752 * If it does not exist then put a zero into the tree. This creates
3753 * the tnode now, rather than later when it is harder to clean up.
3755 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3756 if(prevChunkId <= 0 &&
3757 !yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0)){
3760 /* Set up new tags */
3761 yaffs_InitialiseTags(&newTags);
3763 newTags.chunkId = chunkInInode;
3764 newTags.objectId = in->objectId;
3765 newTags.serialNumber =
3766 (prevChunkId > 0) ? prevTags.serialNumber + 1 : 1;
3767 newTags.byteCount = nBytes;
3769 if (nBytes < 1 || nBytes > dev->totalBytesPerChunk) {
3770 T(YAFFS_TRACE_ERROR,
3771 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3776 * If there isn't already a chunk there then do a dummy
3777 * insert to make sue we have the desired tnode structure.
3779 if(prevChunkId < 1 &&
3780 yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0) != YAFFS_OK)
3784 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3787 if (newChunkId > 0) {
3788 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3790 if (prevChunkId > 0)
3791 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3793 yaffs_CheckFileSanity(in);
3799 /* UpdateObjectHeader updates the header on NAND for an object.
3800 * If name is not NULL, then that new name is used.
3802 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
3803 int isShrink, int shadows)
3806 yaffs_BlockInfo *bi;
3808 yaffs_Device *dev = in->myDev;
3815 yaffs_ExtendedTags newTags;
3816 yaffs_ExtendedTags oldTags;
3817 YCHAR *alias = NULL;
3819 __u8 *buffer = NULL;
3820 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3822 yaffs_ObjectHeader *oh = NULL;
3824 yaffs_strcpy(oldName, _Y("silly old name"));
3828 in == dev->rootDir || /* The rootDir should also be saved */
3831 yaffs_CheckGarbageCollection(dev);
3832 yaffs_CheckObjectDetailsLoaded(in);
3834 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3835 oh = (yaffs_ObjectHeader *) buffer;
3837 prevChunkId = in->hdrChunk;
3839 if (prevChunkId > 0) {
3840 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3843 yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
3845 memcpy(oldName, oh->name, sizeof(oh->name));
3848 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3850 oh->type = in->variantType;
3851 oh->yst_mode = in->yst_mode;
3852 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3854 #ifdef CONFIG_YAFFS_WINCE
3855 oh->win_atime[0] = in->win_atime[0];
3856 oh->win_ctime[0] = in->win_ctime[0];
3857 oh->win_mtime[0] = in->win_mtime[0];
3858 oh->win_atime[1] = in->win_atime[1];
3859 oh->win_ctime[1] = in->win_ctime[1];
3860 oh->win_mtime[1] = in->win_mtime[1];
3862 oh->yst_uid = in->yst_uid;
3863 oh->yst_gid = in->yst_gid;
3864 oh->yst_atime = in->yst_atime;
3865 oh->yst_mtime = in->yst_mtime;
3866 oh->yst_ctime = in->yst_ctime;
3867 oh->yst_rdev = in->yst_rdev;
3870 oh->parentObjectId = in->parent->objectId;
3872 oh->parentObjectId = 0;
3874 if (name && *name) {
3875 memset(oh->name, 0, sizeof(oh->name));
3876 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3877 } else if (prevChunkId > 0)
3878 memcpy(oh->name, oldName, sizeof(oh->name));
3880 memset(oh->name, 0, sizeof(oh->name));
3882 oh->isShrink = isShrink;
3884 switch (in->variantType) {
3885 case YAFFS_OBJECT_TYPE_UNKNOWN:
3886 /* Should not happen */
3888 case YAFFS_OBJECT_TYPE_FILE:
3890 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3891 || oh->parentObjectId ==
3892 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3893 fileVariant.fileSize;
3895 case YAFFS_OBJECT_TYPE_HARDLINK:
3896 oh->equivalentObjectId =
3897 in->variant.hardLinkVariant.equivalentObjectId;
3899 case YAFFS_OBJECT_TYPE_SPECIAL:
3902 case YAFFS_OBJECT_TYPE_DIRECTORY:
3905 case YAFFS_OBJECT_TYPE_SYMLINK:
3906 alias = in->variant.symLinkVariant.alias;
3908 alias = _Y("no alias");
3909 yaffs_strncpy(oh->alias,
3911 YAFFS_MAX_ALIAS_LENGTH);
3912 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3917 yaffs_InitialiseTags(&newTags);
3919 newTags.chunkId = 0;
3920 newTags.objectId = in->objectId;
3921 newTags.serialNumber = in->serial;
3923 /* Add extra info for file header */
3925 newTags.extraHeaderInfoAvailable = 1;
3926 newTags.extraParentObjectId = oh->parentObjectId;
3927 newTags.extraFileLength = oh->fileSize;
3928 newTags.extraIsShrinkHeader = oh->isShrink;
3929 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3930 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3931 newTags.extraObjectType = in->variantType;
3933 yaffs_VerifyObjectHeader(in, oh, &newTags, 1);
3935 /* Create new chunk in NAND */
3937 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3938 (prevChunkId > 0) ? 1 : 0);
3940 if (newChunkId >= 0) {
3942 in->hdrChunk = newChunkId;
3944 if (prevChunkId > 0) {
3945 yaffs_DeleteChunk(dev, prevChunkId, 1,
3949 if (!yaffs_ObjectHasCachedWriteData(in))
3952 /* If this was a shrink, then mark the block that the chunk lives on */
3954 bi = yaffs_GetBlockInfo(in->myDev,
3955 newChunkId / in->myDev->nChunksPerBlock);
3956 bi->hasShrinkHeader = 1;
3961 retVal = newChunkId;
3966 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3971 /*------------------------ Short Operations Cache ----------------------------------------
3972 * In many situations where there is no high level buffering (eg WinCE) a lot of
3973 * reads might be short sequential reads, and a lot of writes may be short
3974 * sequential writes. eg. scanning/writing a jpeg file.
3975 * In these cases, a short read/write cache can provide a huge perfomance benefit
3976 * with dumb-as-a-rock code.
3977 * In Linux, the page cache provides read buffering aand the short op cache provides write
3980 * There are a limited number (~10) of cache chunks per device so that we don't
3981 * need a very intelligent search.
3984 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3986 yaffs_Device *dev = obj->myDev;
3988 yaffs_ChunkCache *cache;
3989 int nCaches = obj->myDev->nShortOpCaches;
3991 for (i = 0; i < nCaches; i++) {
3992 cache = &dev->srCache[i];
3993 if (cache->object == obj &&
4002 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
4004 yaffs_Device *dev = obj->myDev;
4005 int lowest = -99; /* Stop compiler whining. */
4007 yaffs_ChunkCache *cache;
4008 int chunkWritten = 0;
4009 int nCaches = obj->myDev->nShortOpCaches;
4015 /* Find the dirty cache for this object with the lowest chunk id. */
4016 for (i = 0; i < nCaches; i++) {
4017 if (dev->srCache[i].object == obj &&
4018 dev->srCache[i].dirty) {
4020 || dev->srCache[i].chunkId <
4022 cache = &dev->srCache[i];
4023 lowest = cache->chunkId;
4028 if (cache && !cache->locked) {
4029 /* Write it out and free it up */
4032 yaffs_WriteChunkDataToObject(cache->object,
4038 cache->object = NULL;
4041 } while (cache && chunkWritten > 0);
4044 /* Hoosterman, disk full while writing cache out. */
4045 T(YAFFS_TRACE_ERROR,
4046 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
4053 /*yaffs_FlushEntireDeviceCache(dev)
4058 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
4061 int nCaches = dev->nShortOpCaches;
4064 /* Find a dirty object in the cache and flush it...
4065 * until there are no further dirty objects.
4069 for (i = 0; i < nCaches && !obj; i++) {
4070 if (dev->srCache[i].object &&
4071 dev->srCache[i].dirty)
4072 obj = dev->srCache[i].object;
4076 yaffs_FlushFilesChunkCache(obj);
4083 /* Grab us a cache chunk for use.
4084 * First look for an empty one.
4085 * Then look for the least recently used non-dirty one.
4086 * Then look for the least recently used dirty one...., flush and look again.
4088 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
4092 if (dev->nShortOpCaches > 0) {
4093 for (i = 0; i < dev->nShortOpCaches; i++) {
4094 if (!dev->srCache[i].object)
4095 return &dev->srCache[i];
4102 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
4104 yaffs_ChunkCache *cache;
4105 yaffs_Object *theObj;
4110 if (dev->nShortOpCaches > 0) {
4111 /* Try find a non-dirty one... */
4113 cache = yaffs_GrabChunkCacheWorker(dev);
4116 /* They were all dirty, find the last recently used object and flush
4117 * its cache, then find again.
4118 * NB what's here is not very accurate, we actually flush the object
4119 * the last recently used page.
4122 /* With locking we can't assume we can use entry zero */
4129 for (i = 0; i < dev->nShortOpCaches; i++) {
4130 if (dev->srCache[i].object &&
4131 !dev->srCache[i].locked &&
4132 (dev->srCache[i].lastUse < usage || !cache)) {
4133 usage = dev->srCache[i].lastUse;
4134 theObj = dev->srCache[i].object;
4135 cache = &dev->srCache[i];
4140 if (!cache || cache->dirty) {
4141 /* Flush and try again */
4142 yaffs_FlushFilesChunkCache(theObj);
4143 cache = yaffs_GrabChunkCacheWorker(dev);
4153 /* Find a cached chunk */
4154 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj,
4157 yaffs_Device *dev = obj->myDev;
4159 if (dev->nShortOpCaches > 0) {
4160 for (i = 0; i < dev->nShortOpCaches; i++) {
4161 if (dev->srCache[i].object == obj &&
4162 dev->srCache[i].chunkId == chunkId) {
4165 return &dev->srCache[i];
4172 /* Mark the chunk for the least recently used algorithym */
4173 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache,
4177 if (dev->nShortOpCaches > 0) {
4178 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4179 /* Reset the cache usages */
4181 for (i = 1; i < dev->nShortOpCaches; i++)
4182 dev->srCache[i].lastUse = 0;
4189 cache->lastUse = dev->srLastUse;
4196 /* Invalidate a single cache page.
4197 * Do this when a whole page gets written,
4198 * ie the short cache for this page is no longer valid.
4200 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
4202 if (object->myDev->nShortOpCaches > 0) {
4203 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4206 cache->object = NULL;
4210 /* Invalidate all the cache pages associated with this object
4211 * Do this whenever ther file is deleted or resized.
4213 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
4216 yaffs_Device *dev = in->myDev;
4218 if (dev->nShortOpCaches > 0) {
4219 /* Invalidate it. */
4220 for (i = 0; i < dev->nShortOpCaches; i++) {
4221 if (dev->srCache[i].object == in)
4222 dev->srCache[i].object = NULL;
4227 /*--------------------- Checkpointing --------------------*/
4230 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev, int head)
4232 yaffs_CheckpointValidity cp;
4234 memset(&cp, 0, sizeof(cp));
4236 cp.structType = sizeof(cp);
4237 cp.magic = YAFFS_MAGIC;
4238 cp.version = YAFFS_CHECKPOINT_VERSION;
4239 cp.head = (head) ? 1 : 0;
4241 return (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp)) ?
4245 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4247 yaffs_CheckpointValidity cp;
4250 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4253 ok = (cp.structType == sizeof(cp)) &&
4254 (cp.magic == YAFFS_MAGIC) &&
4255 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4256 (cp.head == ((head) ? 1 : 0));
4260 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4263 cp->nErasedBlocks = dev->nErasedBlocks;
4264 cp->allocationBlock = dev->allocationBlock;
4265 cp->allocationPage = dev->allocationPage;
4266 cp->nFreeChunks = dev->nFreeChunks;
4268 cp->nDeletedFiles = dev->nDeletedFiles;
4269 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4270 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4271 cp->sequenceNumber = dev->sequenceNumber;
4272 cp->oldestDirtySequence = dev->oldestDirtySequence;
4276 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4277 yaffs_CheckpointDevice *cp)
4279 dev->nErasedBlocks = cp->nErasedBlocks;
4280 dev->allocationBlock = cp->allocationBlock;
4281 dev->allocationPage = cp->allocationPage;
4282 dev->nFreeChunks = cp->nFreeChunks;
4284 dev->nDeletedFiles = cp->nDeletedFiles;
4285 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4286 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4287 dev->sequenceNumber = cp->sequenceNumber;
4288 dev->oldestDirtySequence = cp->oldestDirtySequence;
4292 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4294 yaffs_CheckpointDevice cp;
4296 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4300 /* Write device runtime values*/
4301 yaffs_DeviceToCheckpointDevice(&cp, dev);
4302 cp.structType = sizeof(cp);
4304 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4306 /* Write block info */
4308 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4309 ok = (yaffs_CheckpointWrite(dev, dev->blockInfo, nBytes) == nBytes);
4312 /* Write chunk bits */
4314 nBytes = nBlocks * dev->chunkBitmapStride;
4315 ok = (yaffs_CheckpointWrite(dev, dev->chunkBits, nBytes) == nBytes);
4321 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4323 yaffs_CheckpointDevice cp;
4325 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4329 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4333 if (cp.structType != sizeof(cp))
4337 yaffs_CheckpointDeviceToDevice(dev, &cp);
4339 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4341 ok = (yaffs_CheckpointRead(dev, dev->blockInfo, nBytes) == nBytes);
4345 nBytes = nBlocks * dev->chunkBitmapStride;
4347 ok = (yaffs_CheckpointRead(dev, dev->chunkBits, nBytes) == nBytes);
4352 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4356 cp->objectId = obj->objectId;
4357 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4358 cp->hdrChunk = obj->hdrChunk;
4359 cp->variantType = obj->variantType;
4360 cp->deleted = obj->deleted;
4361 cp->softDeleted = obj->softDeleted;
4362 cp->unlinked = obj->unlinked;
4363 cp->fake = obj->fake;
4364 cp->renameAllowed = obj->renameAllowed;
4365 cp->unlinkAllowed = obj->unlinkAllowed;
4366 cp->serial = obj->serial;
4367 cp->nDataChunks = obj->nDataChunks;
4369 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4370 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4371 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4372 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4375 static int yaffs_CheckpointObjectToObject(yaffs_Object *obj, yaffs_CheckpointObject *cp)
4378 yaffs_Object *parent;
4380 if (obj->variantType != cp->variantType) {
4381 T(YAFFS_TRACE_ERROR, (TSTR("Checkpoint read object %d type %d "
4382 TCONT("chunk %d does not match existing object type %d")
4383 TENDSTR), cp->objectId, cp->variantType, cp->hdrChunk,
4388 obj->objectId = cp->objectId;
4391 parent = yaffs_FindOrCreateObjectByNumber(
4394 YAFFS_OBJECT_TYPE_DIRECTORY);
4399 if (parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4400 T(YAFFS_TRACE_ALWAYS, (TSTR("Checkpoint read object %d parent %d type %d"
4401 TCONT(" chunk %d Parent type, %d, not directory")
4403 cp->objectId, cp->parentId, cp->variantType,
4404 cp->hdrChunk, parent->variantType));
4407 yaffs_AddObjectToDirectory(parent, obj);
4410 obj->hdrChunk = cp->hdrChunk;
4411 obj->variantType = cp->variantType;
4412 obj->deleted = cp->deleted;
4413 obj->softDeleted = cp->softDeleted;
4414 obj->unlinked = cp->unlinked;
4415 obj->fake = cp->fake;
4416 obj->renameAllowed = cp->renameAllowed;
4417 obj->unlinkAllowed = cp->unlinkAllowed;
4418 obj->serial = cp->serial;
4419 obj->nDataChunks = cp->nDataChunks;
4421 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4422 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4423 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4424 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4426 if (obj->hdrChunk > 0)
4427 obj->lazyLoaded = 1;
4433 static int yaffs_CheckpointTnodeWorker(yaffs_Object *in, yaffs_Tnode *tn,
4434 __u32 level, int chunkOffset)
4437 yaffs_Device *dev = in->myDev;
4439 int tnodeSize = yaffs_CalcTnodeSize(dev);
4444 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
4445 if (tn->internal[i]) {
4446 ok = yaffs_CheckpointTnodeWorker(in,
4449 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4452 } else if (level == 0) {
4453 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4454 ok = (yaffs_CheckpointWrite(dev, &baseOffset, sizeof(baseOffset)) == sizeof(baseOffset));
4456 ok = (yaffs_CheckpointWrite(dev, tn, tnodeSize) == tnodeSize);
4464 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4466 __u32 endMarker = ~0;
4469 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4470 ok = yaffs_CheckpointTnodeWorker(obj,
4471 obj->variant.fileVariant.top,
4472 obj->variant.fileVariant.topLevel,
4475 ok = (yaffs_CheckpointWrite(obj->myDev, &endMarker, sizeof(endMarker)) ==
4482 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4486 yaffs_Device *dev = obj->myDev;
4487 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4490 int tnodeSize = yaffs_CalcTnodeSize(dev);
4492 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4494 while (ok && (~baseChunk)) {
4496 /* Read level 0 tnode */
4499 tn = yaffs_GetTnodeRaw(dev);
4501 ok = (yaffs_CheckpointRead(dev, tn, tnodeSize) == tnodeSize);
4506 ok = yaffs_AddOrFindLevel0Tnode(dev,
4512 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4516 T(YAFFS_TRACE_CHECKPOINT, (
4517 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4518 nread, baseChunk, ok));
4524 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4527 yaffs_CheckpointObject cp;
4530 struct ylist_head *lh;
4533 /* Iterate through the objects in each hash entry,
4534 * dumping them to the checkpointing stream.
4537 for (i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++) {
4538 ylist_for_each(lh, &dev->objectBucket[i].list) {
4540 obj = ylist_entry(lh, yaffs_Object, hashLink);
4541 if (!obj->deferedFree) {
4542 yaffs_ObjectToCheckpointObject(&cp, obj);
4543 cp.structType = sizeof(cp);
4545 T(YAFFS_TRACE_CHECKPOINT, (
4546 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %p" TENDSTR),
4547 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk, obj));
4549 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4551 if (ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4552 ok = yaffs_WriteCheckpointTnodes(obj);
4558 /* Dump end of list */
4559 memset(&cp, 0xFF, sizeof(yaffs_CheckpointObject));
4560 cp.structType = sizeof(cp);
4563 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4568 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4571 yaffs_CheckpointObject cp;
4574 yaffs_Object *hardList = NULL;
4576 while (ok && !done) {
4577 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4578 if (cp.structType != sizeof(cp)) {
4579 T(YAFFS_TRACE_CHECKPOINT, (TSTR("struct size %d instead of %d ok %d"TENDSTR),
4580 cp.structType, (int)sizeof(cp), ok));
4584 T(YAFFS_TRACE_CHECKPOINT, (TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4585 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk));
4587 if (ok && cp.objectId == ~0)
4590 obj = yaffs_FindOrCreateObjectByNumber(dev, cp.objectId, cp.variantType);
4592 ok = yaffs_CheckpointObjectToObject(obj, &cp);
4595 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4596 ok = yaffs_ReadCheckpointTnodes(obj);
4597 } else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4598 obj->hardLinks.next =
4599 (struct ylist_head *) hardList;
4608 yaffs_HardlinkFixup(dev, hardList);
4613 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4615 __u32 checkpointSum;
4618 yaffs_GetCheckpointSum(dev, &checkpointSum);
4620 ok = (yaffs_CheckpointWrite(dev, &checkpointSum, sizeof(checkpointSum)) == sizeof(checkpointSum));
4628 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4630 __u32 checkpointSum0;
4631 __u32 checkpointSum1;
4634 yaffs_GetCheckpointSum(dev, &checkpointSum0);
4636 ok = (yaffs_CheckpointRead(dev, &checkpointSum1, sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4641 if (checkpointSum0 != checkpointSum1)
4648 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4652 if (dev->skipCheckpointWrite || !dev->isYaffs2) {
4653 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint write" TENDSTR)));
4658 ok = yaffs_CheckpointOpen(dev, 1);
4661 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4662 ok = yaffs_WriteCheckpointValidityMarker(dev, 1);
4665 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint device" TENDSTR)));
4666 ok = yaffs_WriteCheckpointDevice(dev);
4669 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint objects" TENDSTR)));
4670 ok = yaffs_WriteCheckpointObjects(dev);
4673 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4674 ok = yaffs_WriteCheckpointValidityMarker(dev, 0);
4678 ok = yaffs_WriteCheckpointSum(dev);
4680 if (!yaffs_CheckpointClose(dev))
4684 dev->isCheckpointed = 1;
4686 dev->isCheckpointed = 0;
4688 return dev->isCheckpointed;
4691 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4695 if (dev->skipCheckpointRead || !dev->isYaffs2) {
4696 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint read" TENDSTR)));
4701 ok = yaffs_CheckpointOpen(dev, 0); /* open for read */
4704 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4705 ok = yaffs_ReadCheckpointValidityMarker(dev, 1);
4708 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint device" TENDSTR)));
4709 ok = yaffs_ReadCheckpointDevice(dev);
4712 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint objects" TENDSTR)));
4713 ok = yaffs_ReadCheckpointObjects(dev);
4716 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4717 ok = yaffs_ReadCheckpointValidityMarker(dev, 0);
4721 ok = yaffs_ReadCheckpointSum(dev);
4722 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint checksum %d" TENDSTR), ok));
4725 if (!yaffs_CheckpointClose(dev))
4729 dev->isCheckpointed = 1;
4731 dev->isCheckpointed = 0;
4737 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4739 if (dev->isCheckpointed ||
4740 dev->blocksInCheckpoint > 0) {
4741 dev->isCheckpointed = 0;
4742 yaffs_CheckpointInvalidateStream(dev);
4743 if (dev->superBlock && dev->markSuperBlockDirty)
4744 dev->markSuperBlockDirty(dev->superBlock);
4749 int yaffs_CheckpointSave(yaffs_Device *dev)
4752 T(YAFFS_TRACE_CHECKPOINT, (TSTR("save entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4754 yaffs_VerifyObjects(dev);
4755 yaffs_VerifyBlocks(dev);
4756 yaffs_VerifyFreeChunks(dev);
4758 if (!dev->isCheckpointed) {
4759 yaffs_InvalidateCheckpoint(dev);
4760 yaffs_WriteCheckpointData(dev);
4763 T(YAFFS_TRACE_ALWAYS, (TSTR("save exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4765 return dev->isCheckpointed;
4768 int yaffs_CheckpointRestore(yaffs_Device *dev)
4771 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4773 retval = yaffs_ReadCheckpointData(dev);
4775 if (dev->isCheckpointed) {
4776 yaffs_VerifyObjects(dev);
4777 yaffs_VerifyBlocks(dev);
4778 yaffs_VerifyFreeChunks(dev);
4781 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4786 /*--------------------- File read/write ------------------------
4787 * Read and write have very similar structures.
4788 * In general the read/write has three parts to it
4789 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4790 * Some complete chunks
4791 * An incomplete chunk to end off with
4793 * Curve-balls: the first chunk might also be the last chunk.
4796 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 *buffer, loff_t offset,
4805 yaffs_ChunkCache *cache;
4812 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4813 /* start = offset % dev->nDataBytesPerChunk; */
4814 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4817 /* OK now check for the curveball where the start and end are in
4820 if ((start + n) < dev->nDataBytesPerChunk)
4823 nToCopy = dev->nDataBytesPerChunk - start;
4825 cache = yaffs_FindChunkCache(in, chunk);
4827 /* If the chunk is already in the cache or it is less than a whole chunk
4828 * or we're using inband tags then use the cache (if there is caching)
4829 * else bypass the cache.
4831 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4832 if (dev->nShortOpCaches > 0) {
4834 /* If we can't find the data in the cache, then load it up. */
4837 cache = yaffs_GrabChunkCache(in->myDev);
4839 cache->chunkId = chunk;
4842 yaffs_ReadChunkDataFromObject(in, chunk,
4848 yaffs_UseChunkCache(dev, cache, 0);
4853 memcpy(buffer, &cache->data[start], nToCopy);
4857 /* Read into the local buffer then copy..*/
4860 yaffs_GetTempBuffer(dev, __LINE__);
4861 yaffs_ReadChunkDataFromObject(in, chunk,
4864 memcpy(buffer, &localBuffer[start], nToCopy);
4867 yaffs_ReleaseTempBuffer(dev, localBuffer,
4873 /* A full chunk. Read directly into the supplied buffer. */
4874 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4888 int yaffs_WriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
4889 int nBytes, int writeThrough)
4898 int startOfWrite = offset;
4899 int chunkWritten = 0;
4907 while (n > 0 && chunkWritten >= 0) {
4908 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4909 /* start = offset % dev->nDataBytesPerChunk; */
4910 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4912 if (chunk * dev->nDataBytesPerChunk + start != offset ||
4913 start >= dev->nDataBytesPerChunk) {
4914 T(YAFFS_TRACE_ERROR, (
4915 TSTR("AddrToChunk of offset %d gives chunk %d start %d"
4917 (int)offset, chunk, start));
4921 /* OK now check for the curveball where the start and end are in
4925 if ((start + n) < dev->nDataBytesPerChunk) {
4928 /* Now folks, to calculate how many bytes to write back....
4929 * If we're overwriting and not writing to then end of file then
4930 * we need to write back as much as was there before.
4933 chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
4935 if (chunkStart > in->variant.fileVariant.fileSize)
4936 nBytesRead = 0; /* Past end of file */
4938 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
4940 if (nBytesRead > dev->nDataBytesPerChunk)
4941 nBytesRead = dev->nDataBytesPerChunk;
4945 (start + n)) ? nBytesRead : (start + n);
4947 if (nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
4951 nToCopy = dev->nDataBytesPerChunk - start;
4952 nToWriteBack = dev->nDataBytesPerChunk;
4955 if (nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4956 /* An incomplete start or end chunk (or maybe both start and end chunk),
4957 * or we're using inband tags, so we want to use the cache buffers.
4959 if (dev->nShortOpCaches > 0) {
4960 yaffs_ChunkCache *cache;
4961 /* If we can't find the data in the cache, then load the cache */
4962 cache = yaffs_FindChunkCache(in, chunk);
4965 && yaffs_CheckSpaceForAllocation(in->
4967 cache = yaffs_GrabChunkCache(in->myDev);
4969 cache->chunkId = chunk;
4972 yaffs_ReadChunkDataFromObject(in, chunk,
4977 !yaffs_CheckSpaceForAllocation(in->myDev)) {
4978 /* Drop the cache if it was a read cache item and
4979 * no space check has been made for it.
4985 yaffs_UseChunkCache(dev, cache, 1);
4989 memcpy(&cache->data[start], buffer,
4994 cache->nBytes = nToWriteBack;
4998 yaffs_WriteChunkDataToObject
5001 cache->data, cache->nBytes,
5007 chunkWritten = -1; /* fail the write */
5010 /* An incomplete start or end chunk (or maybe both start and end chunk)
5011 * Read into the local buffer then copy, then copy over and write back.
5015 yaffs_GetTempBuffer(dev, __LINE__);
5017 yaffs_ReadChunkDataFromObject(in, chunk,
5022 memcpy(&localBuffer[start], buffer, nToCopy);
5025 yaffs_WriteChunkDataToObject(in, chunk,
5030 yaffs_ReleaseTempBuffer(dev, localBuffer,
5036 /* A full chunk. Write directly from the supplied buffer. */
5041 yaffs_WriteChunkDataToObject(in, chunk, buffer,
5042 dev->nDataBytesPerChunk,
5045 /* Since we've overwritten the cached data, we better invalidate it. */
5046 yaffs_InvalidateChunkCache(in, chunk);
5049 if (chunkWritten >= 0) {
5058 /* Update file object */
5060 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
5061 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
5069 /* ---------------------- File resizing stuff ------------------ */
5071 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
5074 yaffs_Device *dev = in->myDev;
5075 int oldFileSize = in->variant.fileVariant.fileSize;
5077 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
5079 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
5080 dev->nDataBytesPerChunk;
5084 /* Delete backwards so that we don't end up with holes if
5085 * power is lost part-way through the operation.
5087 for (i = lastDel; i >= startDel; i--) {
5088 /* NB this could be optimised somewhat,
5089 * eg. could retrieve the tags and write them without
5090 * using yaffs_DeleteChunk
5093 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5096 (dev->internalStartBlock * dev->nChunksPerBlock)
5098 ((dev->internalEndBlock +
5099 1) * dev->nChunksPerBlock)) {
5100 T(YAFFS_TRACE_ALWAYS,
5101 (TSTR("Found daft chunkId %d for %d" TENDSTR),
5105 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5112 int yaffs_ResizeFile(yaffs_Object *in, loff_t newSize)
5115 int oldFileSize = in->variant.fileVariant.fileSize;
5116 __u32 newSizeOfPartialChunk;
5119 yaffs_Device *dev = in->myDev;
5121 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5123 yaffs_FlushFilesChunkCache(in);
5124 yaffs_InvalidateWholeChunkCache(in);
5126 yaffs_CheckGarbageCollection(dev);
5128 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
5131 if (newSize == oldFileSize)
5134 if (newSize < oldFileSize) {
5136 yaffs_PruneResizedChunks(in, newSize);
5138 if (newSizeOfPartialChunk != 0) {
5139 int lastChunk = 1 + newFullChunks;
5141 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5143 /* Got to read and rewrite the last chunk with its new size and zero pad */
5144 yaffs_ReadChunkDataFromObject(in, lastChunk,
5147 memset(localBuffer + newSizeOfPartialChunk, 0,
5148 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5150 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5151 newSizeOfPartialChunk, 1);
5153 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5156 in->variant.fileVariant.fileSize = newSize;
5158 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5160 /* newsSize > oldFileSize */
5161 in->variant.fileVariant.fileSize = newSize;
5165 /* Write a new object header to reflect the resize.
5166 * show we've shrunk the file, if need be
5167 * Do this only if the file is not in the deleted directories
5168 * and is not shadowed.
5172 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5173 in->parent->objectId != YAFFS_OBJECTID_DELETED)
5174 yaffs_UpdateObjectHeader(in, NULL, 0,
5175 (newSize < oldFileSize) ? 1 : 0, 0);
5180 loff_t yaffs_GetFileSize(yaffs_Object *obj)
5182 YCHAR *alias = NULL;
5183 obj = yaffs_GetEquivalentObject(obj);
5185 switch (obj->variantType) {
5186 case YAFFS_OBJECT_TYPE_FILE:
5187 return obj->variant.fileVariant.fileSize;
5188 case YAFFS_OBJECT_TYPE_SYMLINK:
5189 alias = obj->variant.symLinkVariant.alias;
5192 return yaffs_strnlen(alias,YAFFS_MAX_ALIAS_LENGTH);
5200 int yaffs_FlushFile(yaffs_Object *in, int updateTime, int dataSync)
5204 yaffs_FlushFilesChunkCache(in);
5205 if(dataSync) /* Only sync data */
5209 #ifdef CONFIG_YAFFS_WINCE
5210 yfsd_WinFileTimeNow(in->win_mtime);
5213 in->yst_mtime = Y_CURRENT_TIME;
5218 retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5219 0) ? YAFFS_OK : YAFFS_FAIL;
5229 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
5232 /* First off, invalidate the file's data in the cache, without flushing. */
5233 yaffs_InvalidateWholeChunkCache(in);
5235 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5236 /* Move to the unlinked directory so we have a record that it was deleted. */
5237 yaffs_ChangeObjectName(in, in->myDev->deletedDir, _Y("deleted"), 0, 0);
5241 yaffs_RemoveObjectFromDirectory(in);
5242 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5245 yaffs_FreeObject(in);
5250 /* yaffs_DeleteFile deletes the whole file data
5251 * and the inode associated with the file.
5252 * It does not delete the links associated with the file.
5254 static int yaffs_UnlinkFileIfNeeded(yaffs_Object *in)
5258 int immediateDeletion = 0;
5261 immediateDeletion = 1;
5263 if (immediateDeletion) {
5265 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5266 _Y("deleted"), 0, 0);
5267 T(YAFFS_TRACE_TRACING,
5268 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5271 in->myDev->nDeletedFiles++;
5272 if (1 || in->myDev->isYaffs2)
5273 yaffs_ResizeFile(in, 0);
5274 yaffs_SoftDeleteFile(in);
5277 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5278 _Y("unlinked"), 0, 0);
5285 int yaffs_DeleteFile(yaffs_Object *in)
5287 int retVal = YAFFS_OK;
5288 int deleted = in->deleted;
5290 yaffs_ResizeFile(in, 0);
5292 if (in->nDataChunks > 0) {
5293 /* Use soft deletion if there is data in the file.
5294 * That won't be the case if it has been resized to zero.
5297 retVal = yaffs_UnlinkFileIfNeeded(in);
5299 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5302 in->myDev->nDeletedFiles++;
5303 yaffs_SoftDeleteFile(in);
5305 return deleted ? YAFFS_OK : YAFFS_FAIL;
5307 /* The file has no data chunks so we toss it immediately */
5308 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5309 in->variant.fileVariant.top = NULL;
5310 yaffs_DoGenericObjectDeletion(in);
5316 static int yaffs_IsNonEmptyDirectory(yaffs_Object *obj)
5318 return (obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) &&
5319 !(ylist_empty(&obj->variant.directoryVariant.children));
5322 static int yaffs_DeleteDirectory(yaffs_Object *obj)
5324 /* First check that the directory is empty. */
5325 if (yaffs_IsNonEmptyDirectory(obj))
5328 return yaffs_DoGenericObjectDeletion(obj);
5331 static int yaffs_DeleteSymLink(yaffs_Object *in)
5333 if(in->variant.symLinkVariant.alias)
5334 YFREE(in->variant.symLinkVariant.alias);
5335 in->variant.symLinkVariant.alias=NULL;
5337 return yaffs_DoGenericObjectDeletion(in);
5340 static int yaffs_DeleteHardLink(yaffs_Object *in)
5342 /* remove this hardlink from the list assocaited with the equivalent
5345 ylist_del_init(&in->hardLinks);
5346 return yaffs_DoGenericObjectDeletion(in);
5349 int yaffs_DeleteObject(yaffs_Object *obj)
5352 switch (obj->variantType) {
5353 case YAFFS_OBJECT_TYPE_FILE:
5354 retVal = yaffs_DeleteFile(obj);
5356 case YAFFS_OBJECT_TYPE_DIRECTORY:
5357 return yaffs_DeleteDirectory(obj);
5359 case YAFFS_OBJECT_TYPE_SYMLINK:
5360 retVal = yaffs_DeleteSymLink(obj);
5362 case YAFFS_OBJECT_TYPE_HARDLINK:
5363 retVal = yaffs_DeleteHardLink(obj);
5365 case YAFFS_OBJECT_TYPE_SPECIAL:
5366 retVal = yaffs_DoGenericObjectDeletion(obj);
5368 case YAFFS_OBJECT_TYPE_UNKNOWN:
5370 break; /* should not happen. */
5376 static int yaffs_UnlinkWorker(yaffs_Object *obj)
5379 int immediateDeletion = 0;
5382 immediateDeletion = 1;
5385 yaffs_UpdateParent(obj->parent);
5387 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5388 return yaffs_DeleteHardLink(obj);
5389 } else if (!ylist_empty(&obj->hardLinks)) {
5390 /* Curve ball: We're unlinking an object that has a hardlink.
5392 * This problem arises because we are not strictly following
5393 * The Linux link/inode model.
5395 * We can't really delete the object.
5396 * Instead, we do the following:
5397 * - Select a hardlink.
5398 * - Unhook it from the hard links
5399 * - Move it from its parent directory (so that the rename can work)
5400 * - Rename the object to the hardlink's name.
5401 * - Delete the hardlink
5405 yaffs_Object *parent;
5407 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5409 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5411 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5412 parent = hl->parent;
5414 ylist_del_init(&hl->hardLinks);
5416 yaffs_AddObjectToDirectory(obj->myDev->unlinkedDir, hl);
5418 retVal = yaffs_ChangeObjectName(obj,parent, name, 0, 0);
5420 if (retVal == YAFFS_OK)
5421 retVal = yaffs_DoGenericObjectDeletion(hl);
5425 } else if (immediateDeletion) {
5426 switch (obj->variantType) {
5427 case YAFFS_OBJECT_TYPE_FILE:
5428 return yaffs_DeleteFile(obj);
5430 case YAFFS_OBJECT_TYPE_DIRECTORY:
5431 return yaffs_DeleteDirectory(obj);
5433 case YAFFS_OBJECT_TYPE_SYMLINK:
5434 return yaffs_DeleteSymLink(obj);
5436 case YAFFS_OBJECT_TYPE_SPECIAL:
5437 return yaffs_DoGenericObjectDeletion(obj);
5439 case YAFFS_OBJECT_TYPE_HARDLINK:
5440 case YAFFS_OBJECT_TYPE_UNKNOWN:
5444 } else if(yaffs_IsNonEmptyDirectory(obj))
5447 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
5448 _Y("unlinked"), 0, 0);
5452 static int yaffs_UnlinkObject(yaffs_Object *obj)
5455 if (obj && obj->unlinkAllowed)
5456 return yaffs_UnlinkWorker(obj);
5461 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
5465 obj = yaffs_FindObjectByName(dir, name);
5466 return yaffs_UnlinkObject(obj);
5469 /*----------------------- Initialisation Scanning ---------------------- */
5471 static void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
5472 int backwardScanning)
5476 if (!backwardScanning) {
5477 /* Handle YAFFS1 forward scanning case
5478 * For YAFFS1 we always do the deletion
5482 /* Handle YAFFS2 case (backward scanning)
5483 * If the shadowed object exists then ignore.
5485 obj = yaffs_FindObjectByNumber(dev, objId);
5490 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5491 * We put it in unlinked dir to be cleaned up after the scanning
5494 yaffs_FindOrCreateObjectByNumber(dev, objId,
5495 YAFFS_OBJECT_TYPE_FILE);
5498 obj->isShadowed = 1;
5499 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5500 obj->variant.fileVariant.shrinkSize = 0;
5501 obj->valid = 1; /* So that we don't read any other info for this file */
5511 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5518 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5520 in = yaffs_FindObjectByNumber(dev,
5521 hl->variant.hardLinkVariant.
5522 equivalentObjectId);
5525 /* Add the hardlink pointers */
5526 hl->variant.hardLinkVariant.equivalentObject = in;
5527 ylist_add(&hl->hardLinks, &in->hardLinks);
5529 /* Todo Need to report/handle this better.
5530 * Got a problem... hardlink to a non-existant object
5532 hl->variant.hardLinkVariant.equivalentObject = NULL;
5533 YINIT_LIST_HEAD(&hl->hardLinks);
5543 static int ybicmp(const void *a, const void *b)
5545 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5546 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5547 register int ablock = ((yaffs_BlockIndex *)a)->block;
5548 register int bblock = ((yaffs_BlockIndex *)b)->block;
5550 return ablock - bblock;
5556 struct yaffs_ShadowFixerStruct {
5559 struct yaffs_ShadowFixerStruct *next;
5563 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5566 * Sort out state of unlinked and deleted objects after scanning.
5568 struct ylist_head *i;
5569 struct ylist_head *n;
5572 /* Soft delete all the unlinked files */
5573 ylist_for_each_safe(i, n,
5574 &dev->unlinkedDir->variant.directoryVariant.children) {
5576 l = ylist_entry(i, yaffs_Object, siblings);
5577 yaffs_DeleteObject(l);
5581 ylist_for_each_safe(i, n,
5582 &dev->deletedDir->variant.directoryVariant.children) {
5584 l = ylist_entry(i, yaffs_Object, siblings);
5585 yaffs_DeleteObject(l);
5592 * This code iterates through all the objects making sure that they are rooted.
5593 * Any unrooted objects are re-rooted in lost+found.
5594 * An object needs to be in one of:
5595 * - Directly under deleted, unlinked
5596 * - Directly or indirectly under root.
5599 * This code assumes that we don't ever change the current relationships between
5601 * rootDir->parent == unlinkedDir->parent == deletedDir->parent == NULL
5602 * lostNfound->parent == rootDir
5604 * This fixes the problem where directories might have inadvertently been deleted
5605 * leaving the object "hanging" without being rooted in the directory tree.
5608 static int yaffs_HasNULLParent(yaffs_Device *dev, yaffs_Object *obj)
5610 return (obj == dev->deletedDir ||
5611 obj == dev->unlinkedDir||
5612 obj == dev->rootDir);
5615 static void yaffs_FixHangingObjects(yaffs_Device *dev)
5618 yaffs_Object *parent;
5620 struct ylist_head *lh;
5621 struct ylist_head *n;
5626 /* Iterate through the objects in each hash entry,
5627 * looking at each object.
5628 * Make sure it is rooted.
5631 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
5632 ylist_for_each_safe(lh, n, &dev->objectBucket[i].list) {
5634 obj = ylist_entry(lh, yaffs_Object, hashLink);
5635 parent= obj->parent;
5637 if(yaffs_HasNULLParent(dev,obj)){
5638 /* These directories are not hanging */
5641 else if(!parent || parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5643 else if(yaffs_HasNULLParent(dev,parent))
5647 * Need to follow the parent chain to see if it is hanging.
5652 while(parent != dev->rootDir &&
5654 parent->parent->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
5656 parent = parent->parent;
5659 if(parent != dev->rootDir)
5664 (TSTR("Hanging object %d moved to lost and found" TENDSTR),
5666 yaffs_AddObjectToDirectory(dev->lostNFoundDir,obj);
5675 * Delete directory contents for cleaning up lost and found.
5677 static void yaffs_DeleteDirectoryContents(yaffs_Object *dir)
5680 struct ylist_head *lh;
5681 struct ylist_head *n;
5683 if(dir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5686 ylist_for_each_safe(lh, n, &dir->variant.directoryVariant.children) {
5688 obj = ylist_entry(lh, yaffs_Object, siblings);
5689 if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
5690 yaffs_DeleteDirectoryContents(obj);
5693 (TSTR("Deleting lost_found object %d" TENDSTR),
5696 /* Need to use UnlinkObject since Delete would not handle
5697 * hardlinked objects correctly.
5699 yaffs_UnlinkObject(obj);
5705 static void yaffs_EmptyLostAndFound(yaffs_Device *dev)
5707 yaffs_DeleteDirectoryContents(dev->lostNFoundDir);
5710 static int yaffs_Scan(yaffs_Device *dev)
5712 yaffs_ExtendedTags tags;
5722 yaffs_BlockState state;
5723 yaffs_Object *hardList = NULL;
5724 yaffs_BlockInfo *bi;
5725 __u32 sequenceNumber;
5726 yaffs_ObjectHeader *oh;
5728 yaffs_Object *parent;
5730 int alloc_failed = 0;
5732 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5740 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5741 dev->internalStartBlock, dev->internalEndBlock));
5743 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5745 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5747 /* Scan all the blocks to determine their state */
5748 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5749 bi = yaffs_GetBlockInfo(dev, blk);
5750 yaffs_ClearChunkBits(dev, blk);
5752 bi->softDeletions = 0;
5754 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5756 bi->blockState = state;
5757 bi->sequenceNumber = sequenceNumber;
5759 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
5760 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
5762 T(YAFFS_TRACE_SCAN_DEBUG,
5763 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5764 state, sequenceNumber));
5766 if (state == YAFFS_BLOCK_STATE_DEAD) {
5767 T(YAFFS_TRACE_BAD_BLOCKS,
5768 (TSTR("block %d is bad" TENDSTR), blk));
5769 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5770 T(YAFFS_TRACE_SCAN_DEBUG,
5771 (TSTR("Block empty " TENDSTR)));
5772 dev->nErasedBlocks++;
5773 dev->nFreeChunks += dev->nChunksPerBlock;
5777 startIterator = dev->internalStartBlock;
5778 endIterator = dev->internalEndBlock;
5780 /* For each block.... */
5781 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5788 blk = blockIterator;
5790 bi = yaffs_GetBlockInfo(dev, blk);
5791 state = bi->blockState;
5795 /* For each chunk in each block that needs scanning....*/
5796 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5797 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5798 /* Read the tags and decide what to do */
5799 chunk = blk * dev->nChunksPerBlock + c;
5801 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5804 /* Let's have a good look at this chunk... */
5806 if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
5812 /*T((" %d %d deleted\n",blk,c)); */
5813 } else if (!tags.chunkUsed) {
5814 /* An unassigned chunk in the block
5815 * This means that either the block is empty or
5816 * this is the one being allocated from
5820 /* We're looking at the first chunk in the block so the block is unused */
5821 state = YAFFS_BLOCK_STATE_EMPTY;
5822 dev->nErasedBlocks++;
5824 /* this is the block being allocated from */
5827 (" Allocating from %d %d" TENDSTR),
5829 state = YAFFS_BLOCK_STATE_ALLOCATING;
5830 dev->allocationBlock = blk;
5831 dev->allocationPage = c;
5832 dev->allocationBlockFinder = blk;
5833 /* Set block finder here to encourage the allocator to go forth from here. */
5837 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5838 } else if (tags.chunkId > 0) {
5839 /* chunkId > 0 so it is a data chunk... */
5840 unsigned int endpos;
5842 yaffs_SetChunkBit(dev, blk, c);
5845 in = yaffs_FindOrCreateObjectByNumber(dev,
5848 YAFFS_OBJECT_TYPE_FILE);
5849 /* PutChunkIntoFile checks for a clash (two data chunks with
5850 * the same chunkId).
5857 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, 1))
5862 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5865 in->variantType == YAFFS_OBJECT_TYPE_FILE
5866 && in->variant.fileVariant.scannedFileSize <
5868 in->variant.fileVariant.
5869 scannedFileSize = endpos;
5870 if (!dev->useHeaderFileSize) {
5871 in->variant.fileVariant.
5873 in->variant.fileVariant.
5878 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
5880 /* chunkId == 0, so it is an ObjectHeader.
5881 * Thus, we read in the object header and make the object
5883 yaffs_SetChunkBit(dev, blk, c);
5886 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5890 oh = (yaffs_ObjectHeader *) chunkData;
5892 in = yaffs_FindObjectByNumber(dev,
5894 if (in && in->variantType != oh->type) {
5895 /* This should not happen, but somehow
5896 * Wev'e ended up with an objectId that has been reused but not yet
5897 * deleted, and worse still it has changed type. Delete the old object.
5900 yaffs_DeleteObject(in);
5905 in = yaffs_FindOrCreateObjectByNumber(dev,
5913 if (in && oh->shadowsObject > 0) {
5915 struct yaffs_ShadowFixerStruct *fixer;
5916 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
5918 fixer->next = shadowFixerList;
5919 shadowFixerList = fixer;
5920 fixer->objectId = tags.objectId;
5921 fixer->shadowedId = oh->shadowsObject;
5926 if (in && in->valid) {
5927 /* We have already filled this one. We have a duplicate and need to resolve it. */
5929 unsigned existingSerial = in->serial;
5930 unsigned newSerial = tags.serialNumber;
5932 if (((existingSerial + 1) & 3) == newSerial) {
5933 /* Use new one - destroy the exisiting one */
5934 yaffs_DeleteChunk(dev,
5939 /* Use existing - destroy this one. */
5940 yaffs_DeleteChunk(dev, chunk, 1,
5945 if (in && !in->valid &&
5946 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5947 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5948 /* We only load some info, don't fiddle with directory structure */
5950 in->variantType = oh->type;
5952 in->yst_mode = oh->yst_mode;
5953 #ifdef CONFIG_YAFFS_WINCE
5954 in->win_atime[0] = oh->win_atime[0];
5955 in->win_ctime[0] = oh->win_ctime[0];
5956 in->win_mtime[0] = oh->win_mtime[0];
5957 in->win_atime[1] = oh->win_atime[1];
5958 in->win_ctime[1] = oh->win_ctime[1];
5959 in->win_mtime[1] = oh->win_mtime[1];
5961 in->yst_uid = oh->yst_uid;
5962 in->yst_gid = oh->yst_gid;
5963 in->yst_atime = oh->yst_atime;
5964 in->yst_mtime = oh->yst_mtime;
5965 in->yst_ctime = oh->yst_ctime;
5966 in->yst_rdev = oh->yst_rdev;
5968 in->hdrChunk = chunk;
5969 in->serial = tags.serialNumber;
5971 } else if (in && !in->valid) {
5972 /* we need to load this info */
5975 in->variantType = oh->type;
5977 in->yst_mode = oh->yst_mode;
5978 #ifdef CONFIG_YAFFS_WINCE
5979 in->win_atime[0] = oh->win_atime[0];
5980 in->win_ctime[0] = oh->win_ctime[0];
5981 in->win_mtime[0] = oh->win_mtime[0];
5982 in->win_atime[1] = oh->win_atime[1];
5983 in->win_ctime[1] = oh->win_ctime[1];
5984 in->win_mtime[1] = oh->win_mtime[1];
5986 in->yst_uid = oh->yst_uid;
5987 in->yst_gid = oh->yst_gid;
5988 in->yst_atime = oh->yst_atime;
5989 in->yst_mtime = oh->yst_mtime;
5990 in->yst_ctime = oh->yst_ctime;
5991 in->yst_rdev = oh->yst_rdev;
5993 in->hdrChunk = chunk;
5994 in->serial = tags.serialNumber;
5996 yaffs_SetObjectName(in, oh->name);
5999 /* directory stuff...
6004 yaffs_FindOrCreateObjectByNumber
6005 (dev, oh->parentObjectId,
6006 YAFFS_OBJECT_TYPE_DIRECTORY);
6009 if (parent && parent->variantType ==
6010 YAFFS_OBJECT_TYPE_UNKNOWN) {
6011 /* Set up as a directory */
6012 parent->variantType =
6013 YAFFS_OBJECT_TYPE_DIRECTORY;
6014 YINIT_LIST_HEAD(&parent->variant.
6017 } else if (!parent || parent->variantType !=
6018 YAFFS_OBJECT_TYPE_DIRECTORY) {
6019 /* Hoosterman, another problem....
6020 * We're trying to use a non-directory as a directory
6023 T(YAFFS_TRACE_ERROR,
6025 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6027 parent = dev->lostNFoundDir;
6030 yaffs_AddObjectToDirectory(parent, in);
6032 if (0 && (parent == dev->deletedDir ||
6033 parent == dev->unlinkedDir)) {
6034 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
6035 dev->nDeletedFiles++;
6037 /* Note re hardlinks.
6038 * Since we might scan a hardlink before its equivalent object is scanned
6039 * we put them all in a list.
6040 * After scanning is complete, we should have all the objects, so we run through this
6041 * list and fix up all the chains.
6044 switch (in->variantType) {
6045 case YAFFS_OBJECT_TYPE_UNKNOWN:
6046 /* Todo got a problem */
6048 case YAFFS_OBJECT_TYPE_FILE:
6049 if (dev->useHeaderFileSize)
6051 in->variant.fileVariant.
6056 case YAFFS_OBJECT_TYPE_HARDLINK:
6057 in->variant.hardLinkVariant.
6058 equivalentObjectId =
6059 oh->equivalentObjectId;
6060 in->hardLinks.next =
6061 (struct ylist_head *)
6065 case YAFFS_OBJECT_TYPE_DIRECTORY:
6068 case YAFFS_OBJECT_TYPE_SPECIAL:
6071 case YAFFS_OBJECT_TYPE_SYMLINK:
6072 in->variant.symLinkVariant.alias =
6073 yaffs_CloneString(oh->alias);
6074 if (!in->variant.symLinkVariant.alias)
6083 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6084 /* If we got this far while scanning, then the block is fully allocated.*/
6085 state = YAFFS_BLOCK_STATE_FULL;
6088 if (state == YAFFS_BLOCK_STATE_ALLOCATING) {
6089 /* If the block was partially allocated then treat it as fully allocated.*/
6090 state = YAFFS_BLOCK_STATE_FULL;
6091 dev->allocationBlock = -1;
6094 bi->blockState = state;
6096 /* Now let's see if it was dirty */
6097 if (bi->pagesInUse == 0 &&
6098 !bi->hasShrinkHeader &&
6099 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6100 yaffs_BlockBecameDirty(dev, blk);
6106 /* Ok, we've done all the scanning.
6107 * Fix up the hard link chains.
6108 * We should now have scanned all the objects, now it's time to add these
6112 yaffs_HardlinkFixup(dev, hardList);
6114 /* Fix up any shadowed objects */
6116 struct yaffs_ShadowFixerStruct *fixer;
6119 while (shadowFixerList) {
6120 fixer = shadowFixerList;
6121 shadowFixerList = fixer->next;
6122 /* Complete the rename transaction by deleting the shadowed object
6123 * then setting the object header to unshadowed.
6125 obj = yaffs_FindObjectByNumber(dev, fixer->shadowedId);
6127 yaffs_DeleteObject(obj);
6129 obj = yaffs_FindObjectByNumber(dev, fixer->objectId);
6132 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6138 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6143 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
6149 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
6152 yaffs_ObjectHeader *oh;
6154 yaffs_ExtendedTags tags;
6156 int alloc_failed = 0;
6164 T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
6166 in->lazyLoaded ? "not yet" : "already"));
6169 if (in->lazyLoaded && in->hdrChunk > 0) {
6171 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6173 result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
6174 oh = (yaffs_ObjectHeader *) chunkData;
6176 in->yst_mode = oh->yst_mode;
6177 #ifdef CONFIG_YAFFS_WINCE
6178 in->win_atime[0] = oh->win_atime[0];
6179 in->win_ctime[0] = oh->win_ctime[0];
6180 in->win_mtime[0] = oh->win_mtime[0];
6181 in->win_atime[1] = oh->win_atime[1];
6182 in->win_ctime[1] = oh->win_ctime[1];
6183 in->win_mtime[1] = oh->win_mtime[1];
6185 in->yst_uid = oh->yst_uid;
6186 in->yst_gid = oh->yst_gid;
6187 in->yst_atime = oh->yst_atime;
6188 in->yst_mtime = oh->yst_mtime;
6189 in->yst_ctime = oh->yst_ctime;
6190 in->yst_rdev = oh->yst_rdev;
6193 yaffs_SetObjectName(in, oh->name);
6195 if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6196 in->variant.symLinkVariant.alias =
6197 yaffs_CloneString(oh->alias);
6198 if (!in->variant.symLinkVariant.alias)
6199 alloc_failed = 1; /* Not returned to caller */
6202 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6206 static int yaffs_ScanBackwards(yaffs_Device *dev)
6208 yaffs_ExtendedTags tags;
6213 int nBlocksToScan = 0;
6219 yaffs_BlockState state;
6220 yaffs_Object *hardList = NULL;
6221 yaffs_BlockInfo *bi;
6222 __u32 sequenceNumber;
6223 yaffs_ObjectHeader *oh;
6225 yaffs_Object *parent;
6226 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6232 int foundChunksInBlock;
6233 int equivalentObjectId;
6234 int alloc_failed = 0;
6237 yaffs_BlockIndex *blockIndex = NULL;
6238 int altBlockIndex = 0;
6240 if (!dev->isYaffs2) {
6242 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6248 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
6249 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6252 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6254 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6257 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6263 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6267 dev->blocksInCheckpoint = 0;
6269 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6271 /* Scan all the blocks to determine their state */
6272 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6273 bi = yaffs_GetBlockInfo(dev, blk);
6274 yaffs_ClearChunkBits(dev, blk);
6276 bi->softDeletions = 0;
6278 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6280 bi->blockState = state;
6281 bi->sequenceNumber = sequenceNumber;
6283 if (bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6284 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6285 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6286 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6288 T(YAFFS_TRACE_SCAN_DEBUG,
6289 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6290 state, sequenceNumber));
6293 if (state == YAFFS_BLOCK_STATE_CHECKPOINT) {
6294 dev->blocksInCheckpoint++;
6296 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6297 T(YAFFS_TRACE_BAD_BLOCKS,
6298 (TSTR("block %d is bad" TENDSTR), blk));
6299 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6300 T(YAFFS_TRACE_SCAN_DEBUG,
6301 (TSTR("Block empty " TENDSTR)));
6302 dev->nErasedBlocks++;
6303 dev->nFreeChunks += dev->nChunksPerBlock;
6304 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6306 /* Determine the highest sequence number */
6307 if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6308 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6310 blockIndex[nBlocksToScan].seq = sequenceNumber;
6311 blockIndex[nBlocksToScan].block = blk;
6315 if (sequenceNumber >= dev->sequenceNumber)
6316 dev->sequenceNumber = sequenceNumber;
6318 /* TODO: Nasty sequence number! */
6321 ("Block scanning block %d has bad sequence number %d"
6322 TENDSTR), blk, sequenceNumber));
6329 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6335 /* Sort the blocks */
6336 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6338 /* Use qsort now. */
6339 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6343 /* Dungy old bubble sort... */
6345 yaffs_BlockIndex temp;
6349 for (i = 0; i < nBlocksToScan; i++)
6350 for (j = i + 1; j < nBlocksToScan; j++)
6351 if (blockIndex[i].seq > blockIndex[j].seq) {
6352 temp = blockIndex[j];
6353 blockIndex[j] = blockIndex[i];
6354 blockIndex[i] = temp;
6361 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6363 /* Now scan the blocks looking at the data. */
6365 endIterator = nBlocksToScan - 1;
6366 T(YAFFS_TRACE_SCAN_DEBUG,
6367 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6369 /* For each block.... backwards */
6370 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6372 /* Cooperative multitasking! This loop can run for so
6373 long that watchdog timers expire. */
6376 /* get the block to scan in the correct order */
6377 blk = blockIndex[blockIterator].block;
6379 bi = yaffs_GetBlockInfo(dev, blk);
6382 state = bi->blockState;
6386 /* For each chunk in each block that needs scanning.... */
6387 foundChunksInBlock = 0;
6388 for (c = dev->nChunksPerBlock - 1;
6389 !alloc_failed && c >= 0 &&
6390 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6391 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6392 /* Scan backwards...
6393 * Read the tags and decide what to do
6396 chunk = blk * dev->nChunksPerBlock + c;
6398 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6401 /* Let's have a good look at this chunk... */
6403 if (!tags.chunkUsed) {
6404 /* An unassigned chunk in the block.
6405 * If there are used chunks after this one, then
6406 * it is a chunk that was skipped due to failing the erased
6407 * check. Just skip it so that it can be deleted.
6408 * But, more typically, We get here when this is an unallocated
6409 * chunk and his means that either the block is empty or
6410 * this is the one being allocated from
6413 if (foundChunksInBlock) {
6414 /* This is a chunk that was skipped due to failing the erased check */
6415 } else if (c == 0) {
6416 /* We're looking at the first chunk in the block so the block is unused */
6417 state = YAFFS_BLOCK_STATE_EMPTY;
6418 dev->nErasedBlocks++;
6420 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6421 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6422 if (dev->sequenceNumber == bi->sequenceNumber) {
6423 /* this is the block being allocated from */
6427 (" Allocating from %d %d"
6430 state = YAFFS_BLOCK_STATE_ALLOCATING;
6431 dev->allocationBlock = blk;
6432 dev->allocationPage = c;
6433 dev->allocationBlockFinder = blk;
6435 /* This is a partially written block that is not
6436 * the current allocation block.
6439 T(YAFFS_TRACE_ALWAYS,
6440 (TSTR("Partially written block %d detected" TENDSTR),
6448 } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED) {
6450 (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
6455 } else if (tags.chunkId > 0) {
6456 /* chunkId > 0 so it is a data chunk... */
6457 unsigned int endpos;
6459 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6461 foundChunksInBlock = 1;
6464 yaffs_SetChunkBit(dev, blk, c);
6467 in = yaffs_FindOrCreateObjectByNumber(dev,
6470 YAFFS_OBJECT_TYPE_FILE);
6477 in->variantType == YAFFS_OBJECT_TYPE_FILE
6479 in->variant.fileVariant.shrinkSize) {
6480 /* This has not been invalidated by a resize */
6481 if (!yaffs_PutChunkIntoFile(in, tags.chunkId,
6486 /* File size is calculated by looking at the data chunks if we have not
6487 * seen an object header yet. Stop this practice once we find an object header.
6491 1) * dev->nDataBytesPerChunk +
6494 if (!in->valid && /* have not got an object header yet */
6495 in->variant.fileVariant.
6496 scannedFileSize < endpos) {
6497 in->variant.fileVariant.
6498 scannedFileSize = endpos;
6499 in->variant.fileVariant.
6501 in->variant.fileVariant.
6506 /* This chunk has been invalidated by a resize, so delete */
6507 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6511 /* chunkId == 0, so it is an ObjectHeader.
6512 * Thus, we read in the object header and make the object
6514 foundChunksInBlock = 1;
6516 yaffs_SetChunkBit(dev, blk, c);
6522 if (tags.extraHeaderInfoAvailable) {
6523 in = yaffs_FindOrCreateObjectByNumber
6524 (dev, tags.objectId,
6525 tags.extraObjectType);
6531 (!in->valid && dev->disableLazyLoad) ||
6532 tags.extraShadows ||
6534 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6535 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))) {
6537 /* If we don't have valid info then we need to read the chunk
6538 * TODO In future we can probably defer reading the chunk and
6539 * living with invalid data until needed.
6542 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6547 oh = (yaffs_ObjectHeader *) chunkData;
6549 if (dev->inbandTags) {
6550 /* Fix up the header if they got corrupted by inband tags */
6551 oh->shadowsObject = oh->inbandShadowsObject;
6552 oh->isShrink = oh->inbandIsShrink;
6556 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6564 /* TODO Hoosterman we have a problem! */
6565 T(YAFFS_TRACE_ERROR,
6567 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6568 TENDSTR), tags.objectId, chunk));
6573 /* We have already filled this one.
6574 * We have a duplicate that will be discarded, but
6575 * we first have to suck out resize info if it is a file.
6578 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6580 oh->type == YAFFS_OBJECT_TYPE_FILE) ||
6581 (tags.extraHeaderInfoAvailable &&
6582 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))) {
6584 (oh) ? oh->fileSize : tags.
6586 __u32 parentObjectId =
6588 parentObjectId : tags.
6589 extraParentObjectId;
6593 (oh) ? oh->isShrink : tags.
6594 extraIsShrinkHeader;
6596 /* If it is deleted (unlinked at start also means deleted)
6597 * we treat the file size as being zeroed at this point.
6599 if (parentObjectId ==
6600 YAFFS_OBJECTID_DELETED
6601 || parentObjectId ==
6602 YAFFS_OBJECTID_UNLINKED) {
6608 in->variant.fileVariant.
6609 shrinkSize > thisSize) {
6610 in->variant.fileVariant.
6616 bi->hasShrinkHeader = 1;
6619 /* Use existing - destroy this one. */
6620 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6624 if (!in->valid && in->variantType !=
6625 (oh ? oh->type : tags.extraObjectType))
6626 T(YAFFS_TRACE_ERROR, (
6627 TSTR("yaffs tragedy: Bad object type, "
6628 TCONT("%d != %d, for object %d at chunk ")
6629 TCONT("%d during scan")
6631 oh->type : tags.extraObjectType,
6632 in->variantType, tags.objectId,
6636 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6638 YAFFS_OBJECTID_LOSTNFOUND)) {
6639 /* We only load some info, don't fiddle with directory structure */
6643 in->variantType = oh->type;
6645 in->yst_mode = oh->yst_mode;
6646 #ifdef CONFIG_YAFFS_WINCE
6647 in->win_atime[0] = oh->win_atime[0];
6648 in->win_ctime[0] = oh->win_ctime[0];
6649 in->win_mtime[0] = oh->win_mtime[0];
6650 in->win_atime[1] = oh->win_atime[1];
6651 in->win_ctime[1] = oh->win_ctime[1];
6652 in->win_mtime[1] = oh->win_mtime[1];
6654 in->yst_uid = oh->yst_uid;
6655 in->yst_gid = oh->yst_gid;
6656 in->yst_atime = oh->yst_atime;
6657 in->yst_mtime = oh->yst_mtime;
6658 in->yst_ctime = oh->yst_ctime;
6659 in->yst_rdev = oh->yst_rdev;
6663 in->variantType = tags.extraObjectType;
6667 in->hdrChunk = chunk;
6669 } else if (!in->valid) {
6670 /* we need to load this info */
6673 in->hdrChunk = chunk;
6676 in->variantType = oh->type;
6678 in->yst_mode = oh->yst_mode;
6679 #ifdef CONFIG_YAFFS_WINCE
6680 in->win_atime[0] = oh->win_atime[0];
6681 in->win_ctime[0] = oh->win_ctime[0];
6682 in->win_mtime[0] = oh->win_mtime[0];
6683 in->win_atime[1] = oh->win_atime[1];
6684 in->win_ctime[1] = oh->win_ctime[1];
6685 in->win_mtime[1] = oh->win_mtime[1];
6687 in->yst_uid = oh->yst_uid;
6688 in->yst_gid = oh->yst_gid;
6689 in->yst_atime = oh->yst_atime;
6690 in->yst_mtime = oh->yst_mtime;
6691 in->yst_ctime = oh->yst_ctime;
6692 in->yst_rdev = oh->yst_rdev;
6695 if (oh->shadowsObject > 0)
6696 yaffs_HandleShadowedObject(dev,
6703 yaffs_SetObjectName(in, oh->name);
6705 yaffs_FindOrCreateObjectByNumber
6706 (dev, oh->parentObjectId,
6707 YAFFS_OBJECT_TYPE_DIRECTORY);
6709 fileSize = oh->fileSize;
6710 isShrink = oh->isShrink;
6711 equivalentObjectId = oh->equivalentObjectId;
6714 in->variantType = tags.extraObjectType;
6716 yaffs_FindOrCreateObjectByNumber
6717 (dev, tags.extraParentObjectId,
6718 YAFFS_OBJECT_TYPE_DIRECTORY);
6719 fileSize = tags.extraFileLength;
6720 isShrink = tags.extraIsShrinkHeader;
6721 equivalentObjectId = tags.extraEquivalentObjectId;
6730 /* directory stuff...
6734 if (parent && parent->variantType ==
6735 YAFFS_OBJECT_TYPE_UNKNOWN) {
6736 /* Set up as a directory */
6737 parent->variantType =
6738 YAFFS_OBJECT_TYPE_DIRECTORY;
6739 YINIT_LIST_HEAD(&parent->variant.
6742 } else if (!parent || parent->variantType !=
6743 YAFFS_OBJECT_TYPE_DIRECTORY) {
6744 /* Hoosterman, another problem....
6745 * We're trying to use a non-directory as a directory
6748 T(YAFFS_TRACE_ERROR,
6750 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6752 parent = dev->lostNFoundDir;
6755 yaffs_AddObjectToDirectory(parent, in);
6757 itsUnlinked = (parent == dev->deletedDir) ||
6758 (parent == dev->unlinkedDir);
6761 /* Mark the block as having a shrinkHeader */
6762 bi->hasShrinkHeader = 1;
6765 /* Note re hardlinks.
6766 * Since we might scan a hardlink before its equivalent object is scanned
6767 * we put them all in a list.
6768 * After scanning is complete, we should have all the objects, so we run
6769 * through this list and fix up all the chains.
6772 switch (in->variantType) {
6773 case YAFFS_OBJECT_TYPE_UNKNOWN:
6774 /* Todo got a problem */
6776 case YAFFS_OBJECT_TYPE_FILE:
6778 if (in->variant.fileVariant.
6779 scannedFileSize < fileSize) {
6780 /* This covers the case where the file size is greater
6781 * than where the data is
6782 * This will happen if the file is resized to be larger
6783 * than its current data extents.
6785 in->variant.fileVariant.fileSize = fileSize;
6786 in->variant.fileVariant.scannedFileSize =
6787 in->variant.fileVariant.fileSize;
6791 in->variant.fileVariant.shrinkSize > fileSize) {
6792 in->variant.fileVariant.shrinkSize = fileSize;
6796 case YAFFS_OBJECT_TYPE_HARDLINK:
6798 in->variant.hardLinkVariant.equivalentObjectId =
6800 in->hardLinks.next =
6801 (struct ylist_head *) hardList;
6805 case YAFFS_OBJECT_TYPE_DIRECTORY:
6808 case YAFFS_OBJECT_TYPE_SPECIAL:
6811 case YAFFS_OBJECT_TYPE_SYMLINK:
6813 in->variant.symLinkVariant.alias =
6814 yaffs_CloneString(oh->alias);
6815 if (!in->variant.symLinkVariant.alias)
6825 } /* End of scanning for each chunk */
6827 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6828 /* If we got this far while scanning, then the block is fully allocated. */
6829 state = YAFFS_BLOCK_STATE_FULL;
6833 bi->blockState = state;
6835 /* Now let's see if it was dirty */
6836 if (bi->pagesInUse == 0 &&
6837 !bi->hasShrinkHeader &&
6838 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6839 yaffs_BlockBecameDirty(dev, blk);
6844 yaffs_SkipRestOfBlock(dev);
6847 YFREE_ALT(blockIndex);
6851 /* Ok, we've done all the scanning.
6852 * Fix up the hard link chains.
6853 * We should now have scanned all the objects, now it's time to add these
6856 yaffs_HardlinkFixup(dev, hardList);
6859 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6864 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6869 /*------------------------------ Directory Functions ----------------------------- */
6871 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
6873 struct ylist_head *lh;
6874 yaffs_Object *listObj;
6879 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
6884 if (yaffs_SkipVerification(obj->myDev))
6888 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
6893 if (obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6894 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
6898 /* Iterate through the objects in each hash entry */
6900 ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
6902 listObj = ylist_entry(lh, yaffs_Object, siblings);
6903 yaffs_VerifyObject(listObj);
6910 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR), count));
6915 static void yaffs_VerifyDirectory(yaffs_Object *directory)
6917 struct ylist_head *lh;
6918 yaffs_Object *listObj;
6925 if (yaffs_SkipFullVerification(directory->myDev))
6928 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6929 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR), directory->variantType));
6933 /* Iterate through the objects in each hash entry */
6935 ylist_for_each(lh, &directory->variant.directoryVariant.children) {
6937 listObj = ylist_entry(lh, yaffs_Object, siblings);
6938 if (listObj->parent != directory) {
6939 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR), listObj->parent));
6942 yaffs_VerifyObjectInDirectory(listObj);
6948 *yaffs_UpdateParent() handles fixing a directories mtime and ctime when a new
6949 * link (ie. name) is created or deleted in the directory.
6952 * create dir/a : update dir's mtime/ctime
6953 * rm dir/a: update dir's mtime/ctime
6954 * modify dir/a: don't update dir's mtimme/ctime
6957 static void yaffs_UpdateParent(yaffs_Object *obj)
6963 obj->yst_mtime = obj->yst_ctime = Y_CURRENT_TIME;
6965 yaffs_UpdateObjectHeader(obj,NULL,0,0,0);
6968 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
6970 yaffs_Device *dev = obj->myDev;
6971 yaffs_Object *parent;
6973 yaffs_VerifyObjectInDirectory(obj);
6974 parent = obj->parent;
6976 yaffs_VerifyDirectory(parent);
6978 if (dev && dev->removeObjectCallback)
6979 dev->removeObjectCallback(obj);
6982 ylist_del_init(&obj->siblings);
6985 yaffs_VerifyDirectory(parent);
6988 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
6992 T(YAFFS_TRACE_ALWAYS,
6994 ("tragedy: Trying to add an object to a null pointer directory"
6999 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7000 T(YAFFS_TRACE_ALWAYS,
7002 ("tragedy: Trying to add an object to a non-directory"
7007 if (obj->siblings.prev == NULL) {
7008 /* Not initialised */
7013 yaffs_VerifyDirectory(directory);
7015 yaffs_RemoveObjectFromDirectory(obj);
7019 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
7020 obj->parent = directory;
7022 if (directory == obj->myDev->unlinkedDir
7023 || directory == obj->myDev->deletedDir) {
7025 obj->myDev->nUnlinkedFiles++;
7026 obj->renameAllowed = 0;
7029 yaffs_VerifyDirectory(directory);
7030 yaffs_VerifyObjectInDirectory(obj);
7033 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
7038 struct ylist_head *i;
7039 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
7047 T(YAFFS_TRACE_ALWAYS,
7049 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7054 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7055 T(YAFFS_TRACE_ALWAYS,
7057 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7061 sum = yaffs_CalcNameSum(name);
7063 ylist_for_each(i, &directory->variant.directoryVariant.children) {
7065 l = ylist_entry(i, yaffs_Object, siblings);
7067 if (l->parent != directory)
7070 yaffs_CheckObjectDetailsLoaded(l);
7072 /* Special case for lost-n-found */
7073 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7074 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
7076 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
7077 /* LostnFound chunk called Objxxx
7080 yaffs_GetObjectName(l, buffer,
7081 YAFFS_MAX_NAME_LENGTH + 1);
7082 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
7093 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
7094 int (*fn) (yaffs_Object *))
7096 struct ylist_head *i;
7100 T(YAFFS_TRACE_ALWAYS,
7102 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7107 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7108 T(YAFFS_TRACE_ALWAYS,
7110 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7115 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
7117 l = ylist_entry(i, yaffs_Object, siblings);
7128 /* GetEquivalentObject dereferences any hard links to get to the
7132 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
7134 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
7135 /* We want the object id of the equivalent object, not this one */
7136 obj = obj->variant.hardLinkVariant.equivalentObject;
7137 yaffs_CheckObjectDetailsLoaded(obj);
7142 int yaffs_GetObjectName(yaffs_Object *obj, YCHAR *name, int buffSize)
7144 memset(name, 0, buffSize * sizeof(YCHAR));
7146 yaffs_CheckObjectDetailsLoaded(obj);
7148 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7149 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
7150 } else if (obj->hdrChunk <= 0) {
7152 YCHAR numString[20];
7153 YCHAR *x = &numString[19];
7154 unsigned v = obj->objectId;
7158 *x = '0' + (v % 10);
7161 /* make up a name */
7162 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
7163 yaffs_strcat(locName, x);
7164 yaffs_strncpy(name, locName, buffSize - 1);
7167 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
7168 else if (obj->shortName[0])
7169 yaffs_strncpy(name, obj->shortName,YAFFS_SHORT_NAME_LENGTH+1);
7173 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
7175 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
7177 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
7179 if (obj->hdrChunk > 0) {
7180 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
7181 obj->hdrChunk, buffer,
7184 yaffs_strncpy(name, oh->name, buffSize - 1);
7187 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
7190 return yaffs_strnlen(name,buffSize-1);
7193 int yaffs_GetObjectFileLength(yaffs_Object *obj)
7195 /* Dereference any hard linking */
7196 obj = yaffs_GetEquivalentObject(obj);
7198 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
7199 return obj->variant.fileVariant.fileSize;
7200 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
7201 if(!obj->variant.symLinkVariant.alias)
7203 return yaffs_strnlen(obj->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
7205 /* Only a directory should drop through to here */
7206 return obj->myDev->nDataBytesPerChunk;
7210 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
7213 struct ylist_head *i;
7216 count++; /* the object itself */
7218 ylist_for_each(i, &obj->hardLinks)
7219 count++; /* add the hard links; */
7224 int yaffs_GetObjectInode(yaffs_Object *obj)
7226 obj = yaffs_GetEquivalentObject(obj);
7228 return obj->objectId;
7231 unsigned yaffs_GetObjectType(yaffs_Object *obj)
7233 obj = yaffs_GetEquivalentObject(obj);
7235 switch (obj->variantType) {
7236 case YAFFS_OBJECT_TYPE_FILE:
7239 case YAFFS_OBJECT_TYPE_DIRECTORY:
7242 case YAFFS_OBJECT_TYPE_SYMLINK:
7245 case YAFFS_OBJECT_TYPE_HARDLINK:
7248 case YAFFS_OBJECT_TYPE_SPECIAL:
7249 if (S_ISFIFO(obj->yst_mode))
7251 if (S_ISCHR(obj->yst_mode))
7253 if (S_ISBLK(obj->yst_mode))
7255 if (S_ISSOCK(obj->yst_mode))
7263 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
7265 obj = yaffs_GetEquivalentObject(obj);
7266 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
7267 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7269 return yaffs_CloneString(_Y(""));
7272 #ifndef CONFIG_YAFFS_WINCE
7274 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
7276 unsigned int valid = attr->ia_valid;
7278 if (valid & ATTR_MODE)
7279 obj->yst_mode = attr->ia_mode;
7280 if (valid & ATTR_UID)
7281 obj->yst_uid = attr->ia_uid;
7282 if (valid & ATTR_GID)
7283 obj->yst_gid = attr->ia_gid;
7285 if (valid & ATTR_ATIME)
7286 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7287 if (valid & ATTR_CTIME)
7288 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7289 if (valid & ATTR_MTIME)
7290 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7292 if (valid & ATTR_SIZE)
7293 yaffs_ResizeFile(obj, attr->ia_size);
7295 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7300 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
7302 unsigned int valid = 0;
7304 attr->ia_mode = obj->yst_mode;
7306 attr->ia_uid = obj->yst_uid;
7308 attr->ia_gid = obj->yst_gid;
7311 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7312 valid |= ATTR_ATIME;
7313 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7314 valid |= ATTR_CTIME;
7315 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7316 valid |= ATTR_MTIME;
7318 attr->ia_size = yaffs_GetFileSize(obj);
7321 attr->ia_valid = valid;
7329 int yaffs_DumpObject(yaffs_Object *obj)
7333 yaffs_GetObjectName(obj, name, YAFFS_MAX_NAME_LENGTH + 1);
7335 T(YAFFS_TRACE_ALWAYS,
7337 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7338 " chunk %d type %d size %d\n"
7339 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7340 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7341 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7347 /*---------------------------- Initialisation code -------------------------------------- */
7349 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
7352 /* Common functions, gotta have */
7353 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
7356 #ifdef CONFIG_YAFFS_YAFFS2
7358 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7359 if (dev->writeChunkWithTagsToNAND &&
7360 dev->readChunkWithTagsFromNAND &&
7361 !dev->writeChunkToNAND &&
7362 !dev->readChunkFromNAND &&
7363 dev->markNANDBlockBad && dev->queryNANDBlock)
7367 /* Can use the "spare" style interface for yaffs1 */
7368 if (!dev->isYaffs2 &&
7369 !dev->writeChunkWithTagsToNAND &&
7370 !dev->readChunkWithTagsFromNAND &&
7371 dev->writeChunkToNAND &&
7372 dev->readChunkFromNAND &&
7373 !dev->markNANDBlockBad && !dev->queryNANDBlock)
7380 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7382 /* Initialise the unlinked, deleted, root and lost and found directories */
7384 dev->lostNFoundDir = dev->rootDir = NULL;
7385 dev->unlinkedDir = dev->deletedDir = NULL;
7388 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7391 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7394 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7395 YAFFS_ROOT_MODE | S_IFDIR);
7396 dev->lostNFoundDir =
7397 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7398 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7400 if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
7401 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7408 int yaffs_GutsInitialise(yaffs_Device *dev)
7410 int init_failed = 0;
7414 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7416 /* Check stuff that must be set */
7419 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7423 dev->internalStartBlock = dev->startBlock;
7424 dev->internalEndBlock = dev->endBlock;
7425 dev->blockOffset = 0;
7426 dev->chunkOffset = 0;
7427 dev->nFreeChunks = 0;
7431 if (dev->startBlock == 0) {
7432 dev->internalStartBlock = dev->startBlock + 1;
7433 dev->internalEndBlock = dev->endBlock + 1;
7434 dev->blockOffset = 1;
7435 dev->chunkOffset = dev->nChunksPerBlock;
7438 /* Check geometry parameters. */
7440 if ((!dev->inbandTags && dev->isYaffs2 && dev->totalBytesPerChunk < 1024) ||
7441 (!dev->isYaffs2 && dev->totalBytesPerChunk < 512) ||
7442 (dev->inbandTags && !dev->isYaffs2) ||
7443 dev->nChunksPerBlock < 2 ||
7444 dev->nReservedBlocks < 2 ||
7445 dev->internalStartBlock <= 0 ||
7446 dev->internalEndBlock <= 0 ||
7447 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2)) { /* otherwise it is too small */
7448 T(YAFFS_TRACE_ALWAYS,
7450 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7451 TENDSTR), dev->totalBytesPerChunk, dev->isYaffs2 ? "2" : "", dev->inbandTags));
7455 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7456 T(YAFFS_TRACE_ALWAYS,
7457 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7461 /* Sort out space for inband tags, if required */
7462 if (dev->inbandTags)
7463 dev->nDataBytesPerChunk = dev->totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7465 dev->nDataBytesPerChunk = dev->totalBytesPerChunk;
7467 /* Got the right mix of functions? */
7468 if (!yaffs_CheckDevFunctions(dev)) {
7469 /* Function missing */
7470 T(YAFFS_TRACE_ALWAYS,
7472 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7477 /* This is really a compilation check. */
7478 if (!yaffs_CheckStructures()) {
7479 T(YAFFS_TRACE_ALWAYS,
7480 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7484 if (dev->isMounted) {
7485 T(YAFFS_TRACE_ALWAYS,
7486 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7490 /* Finished with most checks. One or two more checks happen later on too. */
7494 /* OK now calculate a few things for the device */
7497 * Calculate all the chunk size manipulation numbers:
7499 x = dev->nDataBytesPerChunk;
7500 /* We always use dev->chunkShift and dev->chunkDiv */
7501 dev->chunkShift = Shifts(x);
7502 x >>= dev->chunkShift;
7504 /* We only use chunk mask if chunkDiv is 1 */
7505 dev->chunkMask = (1<<dev->chunkShift) - 1;
7508 * Calculate chunkGroupBits.
7509 * We need to find the next power of 2 > than internalEndBlock
7512 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7516 /* Set up tnode width if wide tnodes are enabled. */
7517 if (!dev->wideTnodesDisabled) {
7518 /* bits must be even so that we end up with 32-bit words */
7522 dev->tnodeWidth = 16;
7524 dev->tnodeWidth = bits;
7526 dev->tnodeWidth = 16;
7528 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7530 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7531 * so if the bitwidth of the
7532 * chunk range we're using is greater than 16 we need
7533 * to figure out chunk shift and chunkGroupSize
7536 if (bits <= dev->tnodeWidth)
7537 dev->chunkGroupBits = 0;
7539 dev->chunkGroupBits = bits - dev->tnodeWidth;
7542 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7544 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7545 /* We have a problem because the soft delete won't work if
7546 * the chunk group size > chunks per block.
7547 * This can be remedied by using larger "virtual blocks".
7549 T(YAFFS_TRACE_ALWAYS,
7550 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7555 /* OK, we've finished verifying the device, lets continue with initialisation */
7557 /* More device initialisation */
7558 dev->garbageCollections = 0;
7559 dev->passiveGarbageCollections = 0;
7560 dev->currentDirtyChecker = 0;
7561 dev->bufferedBlock = -1;
7562 dev->doingBufferedBlockRewrite = 0;
7563 dev->nDeletedFiles = 0;
7564 dev->nBackgroundDeletions = 0;
7565 dev->nUnlinkedFiles = 0;
7567 dev->eccUnfixed = 0;
7568 dev->tagsEccFixed = 0;
7569 dev->tagsEccUnfixed = 0;
7570 dev->nErasureFailures = 0;
7571 dev->nErasedBlocks = 0;
7573 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7575 /* Initialise temporary buffers and caches. */
7576 if (!yaffs_InitialiseTempBuffers(dev))
7579 dev->srCache = NULL;
7580 dev->gcCleanupList = NULL;
7584 dev->nShortOpCaches > 0) {
7587 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7589 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
7590 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7592 dev->srCache = YMALLOC(srCacheBytes);
7594 buf = (__u8 *) dev->srCache;
7597 memset(dev->srCache, 0, srCacheBytes);
7599 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7600 dev->srCache[i].object = NULL;
7601 dev->srCache[i].lastUse = 0;
7602 dev->srCache[i].dirty = 0;
7603 dev->srCache[i].data = buf = YMALLOC_DMA(dev->totalBytesPerChunk);
7614 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7615 if (!dev->gcCleanupList)
7620 dev->useHeaderFileSize = 1;
7622 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7625 yaffs_InitialiseTnodes(dev);
7626 yaffs_InitialiseObjects(dev);
7628 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7633 /* Now scan the flash. */
7634 if (dev->isYaffs2) {
7635 if (yaffs_CheckpointRestore(dev)) {
7636 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7637 T(YAFFS_TRACE_ALWAYS,
7638 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7641 /* Clean up the mess caused by an aborted checkpoint load
7642 * and scan backwards.
7644 yaffs_DeinitialiseBlocks(dev);
7645 yaffs_DeinitialiseTnodes(dev);
7646 yaffs_DeinitialiseObjects(dev);
7649 dev->nErasedBlocks = 0;
7650 dev->nFreeChunks = 0;
7651 dev->allocationBlock = -1;
7652 dev->allocationPage = -1;
7653 dev->nDeletedFiles = 0;
7654 dev->nUnlinkedFiles = 0;
7655 dev->nBackgroundDeletions = 0;
7656 dev->oldestDirtySequence = 0;
7658 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7661 yaffs_InitialiseTnodes(dev);
7662 yaffs_InitialiseObjects(dev);
7664 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7667 if (!init_failed && !yaffs_ScanBackwards(dev))
7670 } else if (!yaffs_Scan(dev))
7673 yaffs_StripDeletedObjects(dev);
7674 yaffs_FixHangingObjects(dev);
7675 if(dev->emptyLostAndFound)
7676 yaffs_EmptyLostAndFound(dev);
7680 /* Clean up the mess */
7681 T(YAFFS_TRACE_TRACING,
7682 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7684 yaffs_Deinitialise(dev);
7688 /* Zero out stats */
7689 dev->nPageReads = 0;
7690 dev->nPageWrites = 0;
7691 dev->nBlockErasures = 0;
7693 dev->nRetriedWrites = 0;
7695 dev->nRetiredBlocks = 0;
7697 yaffs_VerifyFreeChunks(dev);
7698 yaffs_VerifyBlocks(dev);
7700 /* Clean up any aborted checkpoint data */
7701 if(!dev->isCheckpointed && dev->blocksInCheckpoint > 0)
7702 yaffs_InvalidateCheckpoint(dev);
7704 T(YAFFS_TRACE_TRACING,
7705 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7710 void yaffs_Deinitialise(yaffs_Device *dev)
7712 if (dev->isMounted) {
7715 yaffs_DeinitialiseBlocks(dev);
7716 yaffs_DeinitialiseTnodes(dev);
7717 yaffs_DeinitialiseObjects(dev);
7718 if (dev->nShortOpCaches > 0 &&
7721 for (i = 0; i < dev->nShortOpCaches; i++) {
7722 if (dev->srCache[i].data)
7723 YFREE(dev->srCache[i].data);
7724 dev->srCache[i].data = NULL;
7727 YFREE(dev->srCache);
7728 dev->srCache = NULL;
7731 YFREE(dev->gcCleanupList);
7733 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
7734 YFREE(dev->tempBuffer[i].buffer);
7738 if (dev->deinitialiseNAND)
7739 dev->deinitialiseNAND(dev);
7743 static int yaffs_CountFreeChunks(yaffs_Device *dev)
7748 yaffs_BlockInfo *blk;
7750 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7752 blk = yaffs_GetBlockInfo(dev, b);
7754 switch (blk->blockState) {
7755 case YAFFS_BLOCK_STATE_EMPTY:
7756 case YAFFS_BLOCK_STATE_ALLOCATING:
7757 case YAFFS_BLOCK_STATE_COLLECTING:
7758 case YAFFS_BLOCK_STATE_FULL:
7760 (dev->nChunksPerBlock - blk->pagesInUse +
7761 blk->softDeletions);
7771 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
7773 /* This is what we report to the outside world */
7776 int nDirtyCacheChunks;
7777 int blocksForCheckpoint;
7781 nFree = dev->nFreeChunks;
7783 nFree = yaffs_CountFreeChunks(dev);
7786 nFree += dev->nDeletedFiles;
7788 /* Now count the number of dirty chunks in the cache and subtract those */
7790 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7791 if (dev->srCache[i].dirty)
7792 nDirtyCacheChunks++;
7795 nFree -= nDirtyCacheChunks;
7797 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7799 /* Now we figure out how much to reserve for the checkpoint and report that... */
7800 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7801 if (blocksForCheckpoint < 0)
7802 blocksForCheckpoint = 0;
7804 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7813 static int yaffs_freeVerificationFailures;
7815 static void yaffs_VerifyFreeChunks(yaffs_Device *dev)
7820 if (yaffs_SkipVerification(dev))
7823 counted = yaffs_CountFreeChunks(dev);
7825 difference = dev->nFreeChunks - counted;
7828 T(YAFFS_TRACE_ALWAYS,
7829 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7830 dev->nFreeChunks, counted, difference));
7831 yaffs_freeVerificationFailures++;
7835 /*---------------------------------------- YAFFS test code ----------------------*/
7837 #define yaffs_CheckStruct(structure, syze, name) \
7839 if (sizeof(structure) != syze) { \
7840 T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
7841 name, syze, (int) sizeof(structure))); \
7842 return YAFFS_FAIL; \
7846 static int yaffs_CheckStructures(void)
7848 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
7849 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
7850 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
7851 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7852 /* yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode"); */
7854 #ifndef CONFIG_YAFFS_WINCE
7855 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");