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.120 2010-03-15 23:10:34 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
38 #define YAFFS_SMALL_HOLE_THRESHOLD 3
40 #include "yaffs_ecc.h"
43 /* Robustification (if it ever comes about...) */
44 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND);
45 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
47 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
49 const yaffs_ExtendedTags *tags);
50 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
51 const yaffs_ExtendedTags *tags);
53 /* Other local prototypes */
54 static void yaffs_UpdateParent(yaffs_Object *obj);
55 static int yaffs_UnlinkObject(yaffs_Object *obj);
56 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
58 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
60 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev,
62 yaffs_ExtendedTags *tags,
64 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
65 int chunkInNAND, int inScan);
67 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
68 yaffs_ObjectType type);
69 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
71 static int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name,
72 int force, int isShrink, int shadows);
73 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
74 static int yaffs_CheckStructures(void);
75 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
76 int chunkOffset, int *limit);
77 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
79 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev, int blockNo);
82 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
85 static int yaffs_UnlinkWorker(yaffs_Object *obj);
87 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
90 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
91 yaffs_BlockInfo **blockUsedPtr);
93 static void yaffs_VerifyFreeChunks(yaffs_Device *dev);
95 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
97 static void yaffs_VerifyDirectory(yaffs_Object *directory);
99 static int yaffs_CheckFileSanity(yaffs_Object *in);
101 #define yaffs_CheckFileSanity(in)
104 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
105 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
107 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
109 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
110 yaffs_ExtendedTags *tags);
112 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
114 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
115 yaffs_FileStructure *fStruct,
118 static int yaffs_HandleHole(yaffs_Object *obj, loff_t newSize);
119 static void yaffs_SkipRestOfBlock(yaffs_Device *dev);
120 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
123 yaffs_ExtendedTags *tags);
125 /* Function to calculate chunk and offset */
127 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut,
133 chunk = (__u32)(addr >> dev->chunkShift);
135 if (dev->chunkDiv == 1) {
136 /* easy power of 2 case */
137 offset = (__u32)(addr & dev->chunkMask);
139 /* Non power-of-2 case */
143 chunk /= dev->chunkDiv;
145 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
146 offset = (__u32)(addr - chunkBase);
153 /* Function to return the number of shifts for a power of 2 greater than or
154 * equal to the given number
155 * Note we don't try to cater for all possible numbers and this does not have to
156 * be hellishly efficient.
159 static __u32 ShiftsGE(__u32 x)
164 nShifts = extraBits = 0;
179 /* Function to return the number of shifts to get a 1 in bit 0
182 static __u32 Shifts(__u32 x)
202 * Temporary buffer manipulations.
205 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
208 __u8 *buf = (__u8 *)1;
210 memset(dev->tempBuffer, 0, sizeof(dev->tempBuffer));
212 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
213 dev->tempBuffer[i].line = 0; /* not in use */
214 dev->tempBuffer[i].buffer = buf =
215 YMALLOC_DMA(dev->param.totalBytesPerChunk);
218 return buf ? YAFFS_OK : YAFFS_FAIL;
221 __u8 *yaffs_GetTempBuffer(yaffs_Device *dev, int lineNo)
226 if (dev->tempInUse > dev->maxTemp)
227 dev->maxTemp = dev->tempInUse;
229 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
230 if (dev->tempBuffer[i].line == 0) {
231 dev->tempBuffer[i].line = lineNo;
232 if ((i + 1) > dev->maxTemp) {
233 dev->maxTemp = i + 1;
234 for (j = 0; j <= i; j++)
235 dev->tempBuffer[j].maxLine =
236 dev->tempBuffer[j].line;
239 return dev->tempBuffer[i].buffer;
243 T(YAFFS_TRACE_BUFFERS,
244 (TSTR("Out of temp buffers at line %d, other held by lines:"),
246 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
247 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
249 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
252 * If we got here then we have to allocate an unmanaged one
256 dev->unmanagedTempAllocations++;
257 return YMALLOC(dev->nDataBytesPerChunk);
261 void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer,
268 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
269 if (dev->tempBuffer[i].buffer == buffer) {
270 dev->tempBuffer[i].line = 0;
276 /* assume it is an unmanaged one. */
277 T(YAFFS_TRACE_BUFFERS,
278 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
281 dev->unmanagedTempDeallocations++;
287 * Determine if we have a managed buffer.
289 int yaffs_IsManagedTempBuffer(yaffs_Device *dev, const __u8 *buffer)
293 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
294 if (dev->tempBuffer[i].buffer == buffer)
298 for (i = 0; i < dev->param.nShortOpCaches; i++) {
299 if (dev->srCache[i].data == buffer)
303 if (buffer == dev->checkpointBuffer)
306 T(YAFFS_TRACE_ALWAYS,
307 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
314 * Chunk bitmap manipulations
317 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
319 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
321 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
325 return dev->chunkBits +
326 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
329 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
331 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
332 chunk < 0 || chunk >= dev->param.nChunksPerBlock) {
334 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),
340 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device *dev, int blk)
342 __u8 *blkBits = yaffs_BlockBits(dev, blk);
344 memset(blkBits, 0, dev->chunkBitmapStride);
347 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device *dev, int blk, int chunk)
349 __u8 *blkBits = yaffs_BlockBits(dev, blk);
351 yaffs_VerifyChunkBitId(dev, blk, chunk);
353 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
356 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device *dev, int blk, int chunk)
358 __u8 *blkBits = yaffs_BlockBits(dev, blk);
360 yaffs_VerifyChunkBitId(dev, blk, chunk);
362 blkBits[chunk / 8] |= (1 << (chunk & 7));
365 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device *dev, int blk, int chunk)
367 __u8 *blkBits = yaffs_BlockBits(dev, blk);
368 yaffs_VerifyChunkBitId(dev, blk, chunk);
370 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
373 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device *dev, int blk)
375 __u8 *blkBits = yaffs_BlockBits(dev, blk);
377 for (i = 0; i < dev->chunkBitmapStride; i++) {
385 static int yaffs_CountChunkBits(yaffs_Device *dev, int blk)
387 __u8 *blkBits = yaffs_BlockBits(dev, blk);
390 for (i = 0; i < dev->chunkBitmapStride; i++) {
407 static int yaffs_SkipVerification(yaffs_Device *dev)
410 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
413 static int yaffs_SkipFullVerification(yaffs_Device *dev)
416 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
419 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
422 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
425 static const char *blockStateName[] = {
438 static void yaffs_VerifyBlock(yaffs_Device *dev, yaffs_BlockInfo *bi, int n)
443 if (yaffs_SkipVerification(dev))
446 /* Report illegal runtime states */
447 if (bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
448 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has undefined state %d"TENDSTR), n, bi->blockState));
450 switch (bi->blockState) {
451 case YAFFS_BLOCK_STATE_UNKNOWN:
452 case YAFFS_BLOCK_STATE_SCANNING:
453 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
454 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has bad run-state %s"TENDSTR),
455 n, blockStateName[bi->blockState]));
458 /* Check pages in use and soft deletions are legal */
460 actuallyUsed = bi->pagesInUse - bi->softDeletions;
462 if (bi->pagesInUse < 0 || bi->pagesInUse > dev->param.nChunksPerBlock ||
463 bi->softDeletions < 0 || bi->softDeletions > dev->param.nChunksPerBlock ||
464 actuallyUsed < 0 || actuallyUsed > dev->param.nChunksPerBlock)
465 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
466 n, bi->pagesInUse, bi->softDeletions));
469 /* Check chunk bitmap legal */
470 inUse = yaffs_CountChunkBits(dev, n);
471 if (inUse != bi->pagesInUse)
472 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
473 n, bi->pagesInUse, inUse));
475 /* Check that the sequence number is valid.
476 * Ten million is legal, but is very unlikely
478 if (dev->param.isYaffs2 &&
479 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
480 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000))
481 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has suspect sequence number of %d"TENDSTR),
482 n, bi->sequenceNumber));
485 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev, yaffs_BlockInfo *bi,
488 yaffs_VerifyBlock(dev, bi, n);
490 /* After collection the block should be in the erased state */
491 /* This will need to change if we do partial gc */
493 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
494 bi->blockState != YAFFS_BLOCK_STATE_EMPTY) {
495 T(YAFFS_TRACE_ERROR, (TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
500 static void yaffs_VerifyBlocks(yaffs_Device *dev)
503 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
504 int nIllegalBlockStates = 0;
506 if (yaffs_SkipVerification(dev))
509 memset(nBlocksPerState, 0, sizeof(nBlocksPerState));
511 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
512 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, i);
513 yaffs_VerifyBlock(dev, bi, i);
515 if (bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
516 nBlocksPerState[bi->blockState]++;
518 nIllegalBlockStates++;
521 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
522 T(YAFFS_TRACE_VERIFY, (TSTR("Block summary"TENDSTR)));
524 T(YAFFS_TRACE_VERIFY, (TSTR("%d blocks have illegal states"TENDSTR), nIllegalBlockStates));
525 if (nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
526 T(YAFFS_TRACE_VERIFY, (TSTR("Too many allocating blocks"TENDSTR)));
528 for (i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
529 T(YAFFS_TRACE_VERIFY,
530 (TSTR("%s %d blocks"TENDSTR),
531 blockStateName[i], nBlocksPerState[i]));
533 if (dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
534 T(YAFFS_TRACE_VERIFY,
535 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
536 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
538 if (dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
539 T(YAFFS_TRACE_VERIFY,
540 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
541 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
543 if (nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
544 T(YAFFS_TRACE_VERIFY,
545 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
546 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
548 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
553 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
554 * case those tests will not be performed.
556 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
558 if (obj && yaffs_SkipVerification(obj->myDev))
561 if (!(tags && obj && oh)) {
562 T(YAFFS_TRACE_VERIFY,
563 (TSTR("Verifying object header tags %p obj %p oh %p"TENDSTR),
568 if (oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
569 oh->type > YAFFS_OBJECT_TYPE_MAX)
570 T(YAFFS_TRACE_VERIFY,
571 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
572 tags->objectId, oh->type));
574 if (tags->objectId != obj->objectId)
575 T(YAFFS_TRACE_VERIFY,
576 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
577 tags->objectId, obj->objectId));
581 * Check that the object's parent ids match if parentCheck requested.
583 * Tests do not apply to the root object.
586 if (parentCheck && tags->objectId > 1 && !obj->parent)
587 T(YAFFS_TRACE_VERIFY,
588 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
589 tags->objectId, oh->parentObjectId));
591 if (parentCheck && obj->parent &&
592 oh->parentObjectId != obj->parent->objectId &&
593 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
594 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
595 T(YAFFS_TRACE_VERIFY,
596 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
597 tags->objectId, oh->parentObjectId, obj->parent->objectId));
599 if (tags->objectId > 1 && oh->name[0] == 0) /* Null name */
600 T(YAFFS_TRACE_VERIFY,
601 (TSTR("Obj %d header name is NULL"TENDSTR),
604 if (tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
605 T(YAFFS_TRACE_VERIFY,
606 (TSTR("Obj %d header name is 0xFF"TENDSTR),
612 static int yaffs_VerifyTnodeWorker(yaffs_Object *obj, yaffs_Tnode *tn,
613 __u32 level, int chunkOffset)
616 yaffs_Device *dev = obj->myDev;
622 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
623 if (tn->internal[i]) {
624 ok = yaffs_VerifyTnodeWorker(obj,
627 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
630 } else if (level == 0) {
631 yaffs_ExtendedTags tags;
632 __u32 objectId = obj->objectId;
634 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
636 for (i = 0; i < YAFFS_NTNODES_LEVEL0; i++) {
637 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
640 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
641 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
642 if (tags.objectId != objectId || tags.chunkId != chunkOffset) {
643 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
644 objectId, chunkOffset, theChunk,
645 tags.objectId, tags.chunkId));
658 static void yaffs_VerifyFile(yaffs_Object *obj)
660 int requiredTallness;
666 yaffs_ExtendedTags tags;
673 if (yaffs_SkipVerification(obj->myDev))
677 objectId = obj->objectId;
679 /* Check file size is consistent with tnode depth */
680 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
681 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
682 requiredTallness = 0;
684 x >>= YAFFS_TNODES_INTERNAL_BITS;
688 actualTallness = obj->variant.fileVariant.topLevel;
690 /* Check that the chunks in the tnode tree are all correct.
691 * We do this by scanning through the tnode tree and
692 * checking the tags for every chunk match.
695 if (yaffs_SkipNANDVerification(dev))
698 for (i = 1; i <= lastChunk; i++) {
699 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant, i);
702 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
704 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
705 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
706 if (tags.objectId != objectId || tags.chunkId != i) {
707 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
708 objectId, i, theChunk,
709 tags.objectId, tags.chunkId));
717 static void yaffs_VerifyHardLink(yaffs_Object *obj)
719 if (obj && yaffs_SkipVerification(obj->myDev))
722 /* Verify sane equivalent object */
725 static void yaffs_VerifySymlink(yaffs_Object *obj)
727 if (obj && yaffs_SkipVerification(obj->myDev))
730 /* Verify symlink string */
733 static void yaffs_VerifySpecial(yaffs_Object *obj)
735 if (obj && yaffs_SkipVerification(obj->myDev))
739 static void yaffs_VerifyObject(yaffs_Object *obj)
748 __u32 chunkShouldNotBeDeleted;
754 if (obj->beingCreated)
759 if (yaffs_SkipVerification(dev))
762 /* Check sane object header chunk */
764 chunkMin = dev->internalStartBlock * dev->param.nChunksPerBlock;
765 chunkMax = (dev->internalEndBlock+1) * dev->param.nChunksPerBlock - 1;
767 chunkInRange = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
768 chunkIdOk = chunkInRange || (obj->hdrChunk == 0);
769 chunkValid = chunkInRange &&
770 yaffs_CheckChunkBit(dev,
771 obj->hdrChunk / dev->param.nChunksPerBlock,
772 obj->hdrChunk % dev->param.nChunksPerBlock);
773 chunkShouldNotBeDeleted = chunkInRange && !chunkValid;
776 (!chunkIdOk || chunkShouldNotBeDeleted)) {
777 T(YAFFS_TRACE_VERIFY,
778 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
779 obj->objectId, obj->hdrChunk,
780 chunkIdOk ? "" : ",out of range",
781 chunkShouldNotBeDeleted ? ",marked as deleted" : ""));
784 if (chunkValid && !yaffs_SkipNANDVerification(dev)) {
785 yaffs_ExtendedTags tags;
786 yaffs_ObjectHeader *oh;
787 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
789 oh = (yaffs_ObjectHeader *)buffer;
791 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk, buffer,
794 yaffs_VerifyObjectHeader(obj, oh, &tags, 1);
796 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
799 /* Verify it has a parent */
800 if (obj && !obj->fake &&
801 (!obj->parent || obj->parent->myDev != dev)) {
802 T(YAFFS_TRACE_VERIFY,
803 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
804 obj->objectId, obj->parent));
807 /* Verify parent is a directory */
808 if (obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
809 T(YAFFS_TRACE_VERIFY,
810 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
811 obj->objectId, obj->parent->variantType));
814 switch (obj->variantType) {
815 case YAFFS_OBJECT_TYPE_FILE:
816 yaffs_VerifyFile(obj);
818 case YAFFS_OBJECT_TYPE_SYMLINK:
819 yaffs_VerifySymlink(obj);
821 case YAFFS_OBJECT_TYPE_DIRECTORY:
822 yaffs_VerifyDirectory(obj);
824 case YAFFS_OBJECT_TYPE_HARDLINK:
825 yaffs_VerifyHardLink(obj);
827 case YAFFS_OBJECT_TYPE_SPECIAL:
828 yaffs_VerifySpecial(obj);
830 case YAFFS_OBJECT_TYPE_UNKNOWN:
832 T(YAFFS_TRACE_VERIFY,
833 (TSTR("Obj %d has illegaltype %d"TENDSTR),
834 obj->objectId, obj->variantType));
839 static void yaffs_VerifyObjects(yaffs_Device *dev)
843 struct ylist_head *lh;
845 if (yaffs_SkipVerification(dev))
848 /* Iterate through the objects in each hash entry */
850 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
851 ylist_for_each(lh, &dev->objectBucket[i].list) {
853 obj = ylist_entry(lh, yaffs_Object, hashLink);
854 yaffs_VerifyObject(obj);
862 * Simple hash function. Needs to have a reasonable spread
865 static Y_INLINE int yaffs_HashFunction(int n)
868 return n % YAFFS_NOBJECT_BUCKETS;
872 * Access functions to useful fake objects.
873 * Note that root might have a presence in NAND if permissions are set.
876 yaffs_Object *yaffs_Root(yaffs_Device *dev)
881 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
883 return dev->lostNFoundDir;
888 * Erased NAND checking functions
891 int yaffs_CheckFF(__u8 *buffer, int nBytes)
893 /* Horrible, slow implementation */
902 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
905 int retval = YAFFS_OK;
906 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
907 yaffs_ExtendedTags tags;
910 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
912 if (tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
915 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
916 T(YAFFS_TRACE_NANDACCESS,
917 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
921 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
928 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
931 yaffs_ExtendedTags *tags)
933 int retval = YAFFS_OK;
934 yaffs_ExtendedTags tempTags;
935 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
938 result = yaffs_ReadChunkWithTagsFromNAND(dev,chunkInNAND,buffer,&tempTags);
939 if(memcmp(buffer,data,dev->nDataBytesPerChunk) ||
940 tempTags.objectId != tags->objectId ||
941 tempTags.chunkId != tags->chunkId ||
942 tempTags.byteCount != tags->byteCount)
945 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
950 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
952 yaffs_ExtendedTags *tags,
959 yaffs_InvalidateCheckpoint(dev);
962 yaffs_BlockInfo *bi = 0;
965 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
971 /* First check this chunk is erased, if it needs
972 * checking. The checking policy (unless forced
973 * always on) is as follows:
975 * Check the first page we try to write in a block.
976 * If the check passes then we don't need to check any
977 * more. If the check fails, we check again...
978 * If the block has been erased, we don't need to check.
980 * However, if the block has been prioritised for gc,
981 * then we think there might be something odd about
982 * this block and stop using it.
984 * Rationale: We should only ever see chunks that have
985 * not been erased if there was a partially written
986 * chunk due to power loss. This checking policy should
987 * catch that case with very few checks and thus save a
988 * lot of checks that are most likely not needed.
991 * If an erase check fails or the write fails we skip the
995 /* let's give it a try */
998 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
999 bi->skipErasedCheck = 0;
1001 if (!bi->skipErasedCheck) {
1002 erasedOk = yaffs_CheckChunkErased(dev, chunk);
1003 if (erasedOk != YAFFS_OK) {
1004 T(YAFFS_TRACE_ERROR,
1005 (TSTR("**>> yaffs chunk %d was not erased"
1008 /* If not erased, delete this one,
1009 * skip rest of block and
1010 * try another chunk */
1011 yaffs_DeleteChunk(dev,chunk,1,__LINE__);
1012 yaffs_SkipRestOfBlock(dev);
1017 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
1020 if(!bi->skipErasedCheck)
1021 writeOk = yaffs_VerifyChunkWritten(dev, chunk, data, tags);
1023 if (writeOk != YAFFS_OK) {
1024 /* Clean up aborted write, skip to next block and
1025 * try another chunk */
1026 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
1030 bi->skipErasedCheck = 1;
1032 /* Copy the data into the robustification buffer */
1033 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1035 } while (writeOk != YAFFS_OK &&
1036 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1042 T(YAFFS_TRACE_ERROR,
1043 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1046 dev->nRetriedWrites += (attempts - 1);
1054 * Oldest Dirty Sequence Number handling.
1057 /* yaffs_CalcOldestDirtySequence()
1058 * yaffs_FindOldestDirtySequence()
1059 * Calculate the oldest dirty sequence number if we don't know it.
1061 static int yaffs_CalcOldestDirtySequence(yaffs_Device *dev)
1067 if(!dev->param.isYaffs2)
1070 /* Find the oldest dirty sequence number. */
1071 seq = dev->sequenceNumber;
1073 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
1074 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
1075 (b->pagesInUse - b->softDeletions) < dev->param.nChunksPerBlock &&
1076 b->sequenceNumber < seq)
1077 seq = b->sequenceNumber;
1084 static void yaffs_FindOldestDirtySequence(yaffs_Device *dev)
1086 if(dev->param.isYaffs2 && !dev->oldestDirtySequence)
1087 dev->oldestDirtySequence =
1088 yaffs_CalcOldestDirtySequence(dev);
1091 if(!yaffs_SkipVerification(dev) &&
1092 dev->oldestDirtySequence != yaffs_CalcOldestDirtySequence(dev))
1099 * yaffs_ClearOldestDirtySequence()
1100 * Called when a block is erased or marked bad. (ie. when its sequenceNumber
1101 * becomes invalid). If the value matches the oldest then we clear
1102 * dev->oldestDirtySequence to force its recomputation.
1104 static void yaffs_ClearOldestDirtySequence(yaffs_Device *dev, yaffs_BlockInfo *bi)
1107 if(!dev->param.isYaffs2)
1110 if(!bi || bi->sequenceNumber == dev->oldestDirtySequence)
1111 dev->oldestDirtySequence = 0;
1115 * yaffs_UpdateOldestDirtySequence()
1116 * Update the oldest dirty sequence number whenever we dirty a block.
1117 * Only do this if the oldestDirtySequence is actually being tracked.
1119 static void yaffs_UpdateOldestDirtySequence(yaffs_Device *dev, yaffs_BlockInfo *bi)
1121 if(dev->param.isYaffs2 && dev->oldestDirtySequence){
1122 if(dev->oldestDirtySequence > bi->sequenceNumber)
1123 dev->oldestDirtySequence = bi->sequenceNumber;
1128 * Block retiring for handling a broken block.
1131 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND)
1133 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1135 yaffs_InvalidateCheckpoint(dev);
1137 yaffs_ClearOldestDirtySequence(dev,bi);
1139 if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
1140 if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
1141 T(YAFFS_TRACE_ALWAYS, (TSTR(
1142 "yaffs: Failed to mark bad and erase block %d"
1143 TENDSTR), blockInNAND));
1145 yaffs_ExtendedTags tags;
1146 int chunkId = blockInNAND * dev->param.nChunksPerBlock;
1148 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
1150 memset(buffer, 0xff, dev->nDataBytesPerChunk);
1151 yaffs_InitialiseTags(&tags);
1152 tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
1153 if (dev->param.writeChunkWithTagsToNAND(dev, chunkId -
1154 dev->chunkOffset, buffer, &tags) != YAFFS_OK)
1155 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
1156 TCONT("write bad block marker to block %d")
1157 TENDSTR), blockInNAND));
1159 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
1163 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1164 bi->gcPrioritise = 0;
1165 bi->needsRetiring = 0;
1167 dev->nRetiredBlocks++;
1171 * Functions for robustisizing TODO
1175 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
1177 const yaffs_ExtendedTags *tags)
1180 chunkInNAND=chunkInNAND;
1185 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
1186 const yaffs_ExtendedTags *tags)
1189 chunkInNAND=chunkInNAND;
1193 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1195 if (!bi->gcPrioritise) {
1196 bi->gcPrioritise = 1;
1197 dev->hasPendingPrioritisedGCs = 1;
1198 bi->chunkErrorStrikes++;
1200 if (bi->chunkErrorStrikes > 3) {
1201 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1202 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1208 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
1211 int blockInNAND = chunkInNAND / dev->param.nChunksPerBlock;
1212 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1214 yaffs_HandleChunkError(dev, bi);
1217 /* Was an actual write failure, so mark the block for retirement */
1218 bi->needsRetiring = 1;
1219 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1220 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1223 /* Delete the chunk */
1224 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1225 yaffs_SkipRestOfBlock(dev);
1229 /*---------------- Name handling functions ------------*/
1231 static __u16 yaffs_CalcNameSum(const YCHAR *name)
1236 const YUCHAR *bname = (const YUCHAR *) name;
1238 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1240 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1241 sum += yaffs_toupper(*bname) * i;
1243 sum += (*bname) * i;
1252 static void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
1254 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1255 memset(obj->shortName, 0, sizeof(YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1256 if (name && yaffs_strnlen(name,YAFFS_SHORT_NAME_LENGTH+1) <= YAFFS_SHORT_NAME_LENGTH)
1257 yaffs_strcpy(obj->shortName, name);
1259 obj->shortName[0] = _Y('\0');
1261 obj->sum = yaffs_CalcNameSum(name);
1264 /*-------------------- TNODES -------------------
1266 * List of spare tnodes
1267 * The list is hooked together using the first pointer
1271 /* yaffs_CreateTnodes creates a bunch more tnodes and
1272 * adds them to the tnode free list.
1273 * Don't use this function directly
1275 static Y_INLINE int yaffs_CalcTnodeSize(yaffs_Device *dev)
1278 /* Calculate the tnode size in bytes for variable width tnode support.
1279 * Must be a multiple of 32-bits */
1280 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1282 if (tnodeSize < sizeof(yaffs_Tnode))
1283 tnodeSize = sizeof(yaffs_Tnode);
1287 static int yaffs_CreateTnodes(yaffs_Device *dev, int nTnodes)
1290 int tnodeSize = yaffs_CalcTnodeSize(dev);
1291 yaffs_Tnode *newTnodes;
1295 yaffs_TnodeList *tnl;
1301 /* make these things */
1303 newTnodes = YMALLOC(nTnodes * tnodeSize);
1304 mem = (__u8 *)newTnodes;
1307 T(YAFFS_TRACE_ERROR,
1308 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1312 /* Hook them into the free list */
1314 for (i = 0; i < nTnodes - 1; i++) {
1315 newTnodes[i].internal[0] = &newTnodes[i + 1];
1316 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1317 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1321 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1322 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1323 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1325 dev->freeTnodes = newTnodes;
1327 /* New hookup for wide tnodes */
1328 for (i = 0; i < nTnodes - 1; i++) {
1329 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1330 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1331 curr->internal[0] = next;
1334 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1335 curr->internal[0] = dev->freeTnodes;
1336 dev->freeTnodes = (yaffs_Tnode *)mem;
1341 dev->nFreeTnodes += nTnodes;
1342 dev->nTnodesCreated += nTnodes;
1344 /* Now add this bunch of tnodes to a list for freeing up.
1345 * NB If we can't add this to the management list it isn't fatal
1346 * but it just means we can't free this bunch of tnodes later.
1349 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1351 T(YAFFS_TRACE_ERROR,
1353 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1356 tnl->tnodes = newTnodes;
1357 tnl->next = dev->allocatedTnodeList;
1358 dev->allocatedTnodeList = tnl;
1361 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1366 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1368 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device *dev)
1370 yaffs_Tnode *tn = NULL;
1372 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1373 tn = YMALLOC(yaffs_CalcTnodeSize(dev));
1375 dev->nTnodesCreated++;
1377 /* If there are none left make more */
1378 if (!dev->freeTnodes)
1379 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1381 if (dev->freeTnodes) {
1382 tn = dev->freeTnodes;
1383 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1384 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1385 /* Hoosterman, this thing looks like it isn't in the list */
1386 T(YAFFS_TRACE_ALWAYS,
1387 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1390 dev->freeTnodes = dev->freeTnodes->internal[0];
1394 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1399 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
1401 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1402 int tnodeSize = yaffs_CalcTnodeSize(dev);
1405 memset(tn, 0, tnodeSize);
1410 /* FreeTnode frees up a tnode and puts it back on the free list */
1411 static void yaffs_FreeTnode(yaffs_Device *dev, yaffs_Tnode *tn)
1414 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1416 dev->nTnodesCreated--;
1418 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1419 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1420 /* Hoosterman, this thing looks like it is already in the list */
1421 T(YAFFS_TRACE_ALWAYS,
1422 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1424 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1426 tn->internal[0] = dev->freeTnodes;
1427 dev->freeTnodes = tn;
1431 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1434 static void yaffs_DeinitialiseTnodes(yaffs_Device *dev)
1436 /* Free the list of allocated tnodes */
1437 yaffs_TnodeList *tmp;
1439 while (dev->allocatedTnodeList) {
1440 tmp = dev->allocatedTnodeList->next;
1442 YFREE(dev->allocatedTnodeList->tnodes);
1443 YFREE(dev->allocatedTnodeList);
1444 dev->allocatedTnodeList = tmp;
1448 dev->freeTnodes = NULL;
1449 dev->nFreeTnodes = 0;
1450 dev->nTnodesCreated = 0;
1453 static void yaffs_InitialiseTnodes(yaffs_Device *dev)
1455 dev->allocatedTnodeList = NULL;
1456 dev->freeTnodes = NULL;
1457 dev->nFreeTnodes = 0;
1458 dev->nTnodesCreated = 0;
1462 void yaffs_LoadLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
1465 __u32 *map = (__u32 *)tn;
1471 pos &= YAFFS_TNODES_LEVEL0_MASK;
1472 val >>= dev->chunkGroupBits;
1474 bitInMap = pos * dev->tnodeWidth;
1475 wordInMap = bitInMap / 32;
1476 bitInWord = bitInMap & (32 - 1);
1478 mask = dev->tnodeMask << bitInWord;
1480 map[wordInMap] &= ~mask;
1481 map[wordInMap] |= (mask & (val << bitInWord));
1483 if (dev->tnodeWidth > (32 - bitInWord)) {
1484 bitInWord = (32 - bitInWord);
1486 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1487 map[wordInMap] &= ~mask;
1488 map[wordInMap] |= (mask & (val >> bitInWord));
1492 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
1495 __u32 *map = (__u32 *)tn;
1501 pos &= YAFFS_TNODES_LEVEL0_MASK;
1503 bitInMap = pos * dev->tnodeWidth;
1504 wordInMap = bitInMap / 32;
1505 bitInWord = bitInMap & (32 - 1);
1507 val = map[wordInMap] >> bitInWord;
1509 if (dev->tnodeWidth > (32 - bitInWord)) {
1510 bitInWord = (32 - bitInWord);
1512 val |= (map[wordInMap] << bitInWord);
1515 val &= dev->tnodeMask;
1516 val <<= dev->chunkGroupBits;
1521 /* ------------------- End of individual tnode manipulation -----------------*/
1523 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1524 * The look up tree is represented by the top tnode and the number of topLevel
1525 * in the tree. 0 means only the level 0 tnode is in the tree.
1528 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1529 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
1530 yaffs_FileStructure *fStruct,
1533 yaffs_Tnode *tn = fStruct->top;
1535 int requiredTallness;
1536 int level = fStruct->topLevel;
1540 /* Check sane level and chunk Id */
1541 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
1544 if (chunkId > YAFFS_MAX_CHUNK_ID)
1547 /* First check we're tall enough (ie enough topLevel) */
1549 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1550 requiredTallness = 0;
1552 i >>= YAFFS_TNODES_INTERNAL_BITS;
1556 if (requiredTallness > fStruct->topLevel)
1557 return NULL; /* Not tall enough, so we can't find it */
1559 /* Traverse down to level 0 */
1560 while (level > 0 && tn) {
1561 tn = tn->internal[(chunkId >>
1562 (YAFFS_TNODES_LEVEL0_BITS +
1564 YAFFS_TNODES_INTERNAL_BITS)) &
1565 YAFFS_TNODES_INTERNAL_MASK];
1572 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1573 * This happens in two steps:
1574 * 1. If the tree isn't tall enough, then make it taller.
1575 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1577 * Used when modifying the tree.
1579 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1580 * be plugged into the ttree.
1583 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
1584 yaffs_FileStructure *fStruct,
1586 yaffs_Tnode *passedTn)
1588 int requiredTallness;
1596 /* Check sane level and page Id */
1597 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
1600 if (chunkId > YAFFS_MAX_CHUNK_ID)
1603 /* First check we're tall enough (ie enough topLevel) */
1605 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1606 requiredTallness = 0;
1608 x >>= YAFFS_TNODES_INTERNAL_BITS;
1613 if (requiredTallness > fStruct->topLevel) {
1614 /* Not tall enough, gotta make the tree taller */
1615 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1617 tn = yaffs_GetTnode(dev);
1620 tn->internal[0] = fStruct->top;
1622 fStruct->topLevel++;
1624 T(YAFFS_TRACE_ERROR,
1625 (TSTR("yaffs: no more tnodes" TENDSTR)));
1631 /* Traverse down to level 0, adding anything we need */
1633 l = fStruct->topLevel;
1637 while (l > 0 && tn) {
1639 (YAFFS_TNODES_LEVEL0_BITS +
1640 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1641 YAFFS_TNODES_INTERNAL_MASK;
1644 if ((l > 1) && !tn->internal[x]) {
1645 /* Add missing non-level-zero tnode */
1646 tn->internal[x] = yaffs_GetTnode(dev);
1647 if(!tn->internal[x])
1649 } else if (l == 1) {
1650 /* Looking from level 1 at level 0 */
1652 /* If we already have one, then release it.*/
1653 if (tn->internal[x])
1654 yaffs_FreeTnode(dev, tn->internal[x]);
1655 tn->internal[x] = passedTn;
1657 } else if (!tn->internal[x]) {
1658 /* Don't have one, none passed in */
1659 tn->internal[x] = yaffs_GetTnode(dev);
1660 if(!tn->internal[x])
1665 tn = tn->internal[x];
1669 /* top is level 0 */
1671 memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1672 yaffs_FreeTnode(dev, passedTn);
1679 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
1680 yaffs_ExtendedTags *tags, int objectId,
1685 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1686 if (yaffs_CheckChunkBit(dev, theChunk / dev->param.nChunksPerBlock,
1687 theChunk % dev->param.nChunksPerBlock)) {
1689 if(dev->chunkGroupSize == 1)
1692 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1694 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1706 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1707 * chunks and tnodes in the file
1708 * Returns 1 if the tree was deleted.
1709 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1712 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
1713 int chunkOffset, int *limit)
1718 yaffs_ExtendedTags tags;
1720 yaffs_Device *dev = in->myDev;
1726 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1728 if (tn->internal[i]) {
1729 if (limit && (*limit) < 0) {
1733 yaffs_DeleteWorker(in,
1741 YAFFS_TNODES_INTERNAL_BITS)
1746 yaffs_FreeTnode(dev,
1749 tn->internal[i] = NULL;
1753 return (allDone) ? 1 : 0;
1754 } else if (level == 0) {
1757 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1759 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1762 chunkInInode = (chunkOffset <<
1763 YAFFS_TNODES_LEVEL0_BITS) + i;
1766 yaffs_FindChunkInGroup(dev,
1772 if (foundChunk > 0) {
1773 yaffs_DeleteChunk(dev,
1778 *limit = *limit - 1;
1785 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1789 return (i < 0) ? 1 : 0;
1799 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1801 yaffs_BlockInfo *theBlock;
1803 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1805 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->param.nChunksPerBlock);
1807 theBlock->softDeletions++;
1809 yaffs_UpdateOldestDirtySequence(dev,theBlock);
1813 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1814 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1816 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1819 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1820 __u32 level, int chunkOffset)
1825 yaffs_Device *dev = in->myDev;
1830 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1832 if (tn->internal[i]) {
1834 yaffs_SoftDeleteWorker(in,
1840 YAFFS_TNODES_INTERNAL_BITS)
1843 yaffs_FreeTnode(dev,
1846 tn->internal[i] = NULL;
1848 /* Hoosterman... how could this happen? */
1852 return (allDone) ? 1 : 0;
1853 } else if (level == 0) {
1855 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1856 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1858 /* Note this does not find the real chunk, only the chunk group.
1859 * We make an assumption that a chunk group is not larger than
1862 yaffs_SoftDeleteChunk(dev, theChunk);
1863 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1877 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1880 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1881 if (obj->nDataChunks <= 0) {
1882 /* Empty file with no duplicate object headers, just delete it immediately */
1883 yaffs_FreeTnode(obj->myDev,
1884 obj->variant.fileVariant.top);
1885 obj->variant.fileVariant.top = NULL;
1886 T(YAFFS_TRACE_TRACING,
1887 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1889 yaffs_DoGenericObjectDeletion(obj);
1891 yaffs_SoftDeleteWorker(obj,
1892 obj->variant.fileVariant.top,
1893 obj->variant.fileVariant.
1895 obj->softDeleted = 1;
1900 /* Pruning removes any part of the file structure tree that is beyond the
1901 * bounds of the file (ie that does not point to chunks).
1903 * A file should only get pruned when its size is reduced.
1905 * Before pruning, the chunks must be pulled from the tree and the
1906 * level 0 tnode entries must be zeroed out.
1907 * Could also use this for file deletion, but that's probably better handled
1908 * by a special case.
1910 * This function is recursive. For levels > 0 the function is called again on
1911 * any sub-tree. For level == 0 we just check if the sub-tree has data.
1912 * If there is no data in a subtree then it is pruned.
1915 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1916 __u32 level, int del0)
1925 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1926 if (tn->internal[i]) {
1928 yaffs_PruneWorker(dev, tn->internal[i],
1930 (i == 0) ? del0 : 1);
1933 if (tn->internal[i])
1937 int tnodeSize_u32 = yaffs_CalcTnodeSize(dev)/sizeof(__u32);
1938 __u32 *map = (__u32 *)tn;
1940 for(i = 0; !hasData && i < tnodeSize_u32; i++){
1946 if (hasData == 0 && del0) {
1947 /* Free and return NULL */
1949 yaffs_FreeTnode(dev, tn);
1959 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1960 yaffs_FileStructure *fStruct)
1967 if (fStruct->topLevel > 0) {
1969 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1971 /* Now we have a tree with all the non-zero branches NULL but the height
1972 * is the same as it was.
1973 * Let's see if we can trim internal tnodes to shorten the tree.
1974 * We can do this if only the 0th element in the tnode is in use
1975 * (ie all the non-zero are NULL)
1978 while (fStruct->topLevel && !done) {
1982 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1983 if (tn->internal[i])
1988 fStruct->top = tn->internal[0];
1989 fStruct->topLevel--;
1990 yaffs_FreeTnode(dev, tn);
2000 /*-------------------- End of File Structure functions.-------------------*/
2002 /* yaffs_CreateFreeObjects creates a bunch more objects and
2003 * adds them to the object free list.
2005 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
2008 yaffs_Object *newObjects;
2009 yaffs_ObjectList *list;
2014 /* make these things */
2015 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
2016 list = YMALLOC(sizeof(yaffs_ObjectList));
2018 if (!newObjects || !list) {
2027 T(YAFFS_TRACE_ALLOCATE,
2028 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
2032 /* Hook them into the free list */
2033 for (i = 0; i < nObjects - 1; i++) {
2034 newObjects[i].siblings.next =
2035 (struct ylist_head *)(&newObjects[i + 1]);
2038 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
2039 dev->freeObjects = newObjects;
2040 dev->nFreeObjects += nObjects;
2041 dev->nObjectsCreated += nObjects;
2043 /* Now add this bunch of Objects to a list for freeing up. */
2045 list->objects = newObjects;
2046 list->next = dev->allocatedObjectList;
2047 dev->allocatedObjectList = list;
2053 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
2054 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
2056 yaffs_Object *tn = NULL;
2058 #ifdef CONFIG_YAFFS_VALGRIND_TEST
2059 tn = YMALLOC(sizeof(yaffs_Object));
2061 dev->nObjectsCreated++;
2063 /* If there are none left make more */
2064 if (!dev->freeObjects)
2065 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
2067 if (dev->freeObjects) {
2068 tn = dev->freeObjects;
2070 (yaffs_Object *) (dev->freeObjects->siblings.next);
2071 dev->nFreeObjects--;
2075 /* Now sweeten it up... */
2077 memset(tn, 0, sizeof(yaffs_Object));
2078 tn->beingCreated = 1;
2082 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
2083 YINIT_LIST_HEAD(&(tn->hardLinks));
2084 YINIT_LIST_HEAD(&(tn->hashLink));
2085 YINIT_LIST_HEAD(&tn->siblings);
2088 /* Now make the directory sane */
2090 tn->parent = dev->rootDir;
2091 ylist_add(&(tn->siblings), &dev->rootDir->variant.directoryVariant.children);
2094 /* Add it to the lost and found directory.
2095 * NB Can't put root or lostNFound in lostNFound so
2096 * check if lostNFound exists first
2098 if (dev->lostNFoundDir)
2099 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
2101 tn->beingCreated = 0;
2104 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2109 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
2114 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
2116 obj->fake = 1; /* it is fake so it might have no NAND presence... */
2117 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
2118 obj->unlinkAllowed = 0; /* ... or unlink it */
2121 obj->yst_mode = mode;
2123 obj->hdrChunk = 0; /* Not a valid chunk. */
2130 static void yaffs_UnhashObject(yaffs_Object *tn)
2133 yaffs_Device *dev = tn->myDev;
2135 /* If it is still linked into the bucket list, free from the list */
2136 if (!ylist_empty(&tn->hashLink)) {
2137 ylist_del_init(&tn->hashLink);
2138 bucket = yaffs_HashFunction(tn->objectId);
2139 dev->objectBucket[bucket].count--;
2143 /* FreeObject frees up a Object and puts it back on the free list */
2144 static void yaffs_FreeObject(yaffs_Object *tn)
2146 yaffs_Device *dev = tn->myDev;
2148 T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), tn, tn->myInode));
2154 if (!ylist_empty(&tn->siblings))
2159 /* We're still hooked up to a cached inode.
2160 * Don't delete now, but mark for later deletion
2162 tn->deferedFree = 1;
2166 yaffs_UnhashObject(tn);
2168 #ifdef CONFIG_YAFFS_VALGRIND_TEST
2170 dev->nObjectsCreated--;
2173 /* Link into the free list. */
2174 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2175 dev->freeObjects = tn;
2176 dev->nFreeObjects++;
2178 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2182 void yaffs_HandleDeferedFree(yaffs_Object *obj)
2184 if (obj->deferedFree)
2185 yaffs_FreeObject(obj);
2189 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
2191 /* Free the list of allocated Objects */
2193 yaffs_ObjectList *tmp;
2195 while (dev->allocatedObjectList) {
2196 tmp = dev->allocatedObjectList->next;
2197 YFREE(dev->allocatedObjectList->objects);
2198 YFREE(dev->allocatedObjectList);
2200 dev->allocatedObjectList = tmp;
2203 dev->freeObjects = NULL;
2204 dev->nFreeObjects = 0;
2205 dev->nObjectsCreated = 0;
2208 static void yaffs_InitialiseObjects(yaffs_Device *dev)
2212 dev->allocatedObjectList = NULL;
2213 dev->freeObjects = NULL;
2214 dev->nFreeObjects = 0;
2216 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2217 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2218 dev->objectBucket[i].count = 0;
2222 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
2226 int lowest = 999999;
2229 /* Search for the shortest list or one that
2233 for (i = 0; i < 10 && lowest > 4; i++) {
2234 dev->bucketFinder++;
2235 dev->bucketFinder %= YAFFS_NOBJECT_BUCKETS;
2236 if (dev->objectBucket[dev->bucketFinder].count < lowest) {
2237 lowest = dev->objectBucket[dev->bucketFinder].count;
2238 l = dev->bucketFinder;
2246 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
2248 int bucket = yaffs_FindNiceObjectBucket(dev);
2250 /* Now find an object value that has not already been taken
2251 * by scanning the list.
2255 struct ylist_head *i;
2257 __u32 n = (__u32) bucket;
2259 /* yaffs_CheckObjectHashSanity(); */
2263 n += YAFFS_NOBJECT_BUCKETS;
2264 if (1 || dev->objectBucket[bucket].count > 0) {
2265 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2266 /* If there is already one in the list */
2267 if (i && ylist_entry(i, yaffs_Object,
2268 hashLink)->objectId == n) {
2278 static void yaffs_HashObject(yaffs_Object *in)
2280 int bucket = yaffs_HashFunction(in->objectId);
2281 yaffs_Device *dev = in->myDev;
2283 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2284 dev->objectBucket[bucket].count++;
2287 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
2289 int bucket = yaffs_HashFunction(number);
2290 struct ylist_head *i;
2293 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2294 /* Look if it is in the list */
2296 in = ylist_entry(i, yaffs_Object, hashLink);
2297 if (in->objectId == number) {
2299 /* Don't tell the VFS about this one if it is defered free */
2300 if (in->deferedFree)
2311 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
2312 yaffs_ObjectType type)
2314 yaffs_Object *theObject=NULL;
2315 yaffs_Tnode *tn = NULL;
2318 number = yaffs_CreateNewObjectNumber(dev);
2320 if (type == YAFFS_OBJECT_TYPE_FILE) {
2321 tn = yaffs_GetTnode(dev);
2326 theObject = yaffs_AllocateEmptyObject(dev);
2329 yaffs_FreeTnode(dev,tn);
2335 theObject->fake = 0;
2336 theObject->renameAllowed = 1;
2337 theObject->unlinkAllowed = 1;
2338 theObject->objectId = number;
2339 yaffs_HashObject(theObject);
2340 theObject->variantType = type;
2341 #ifdef CONFIG_YAFFS_WINCE
2342 yfsd_WinFileTimeNow(theObject->win_atime);
2343 theObject->win_ctime[0] = theObject->win_mtime[0] =
2344 theObject->win_atime[0];
2345 theObject->win_ctime[1] = theObject->win_mtime[1] =
2346 theObject->win_atime[1];
2350 theObject->yst_atime = theObject->yst_mtime =
2351 theObject->yst_ctime = Y_CURRENT_TIME;
2354 case YAFFS_OBJECT_TYPE_FILE:
2355 theObject->variant.fileVariant.fileSize = 0;
2356 theObject->variant.fileVariant.scannedFileSize = 0;
2357 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2358 theObject->variant.fileVariant.topLevel = 0;
2359 theObject->variant.fileVariant.top = tn;
2361 case YAFFS_OBJECT_TYPE_DIRECTORY:
2362 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2364 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2367 case YAFFS_OBJECT_TYPE_SYMLINK:
2368 case YAFFS_OBJECT_TYPE_HARDLINK:
2369 case YAFFS_OBJECT_TYPE_SPECIAL:
2370 /* No action required */
2372 case YAFFS_OBJECT_TYPE_UNKNOWN:
2373 /* todo this should not happen */
2381 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
2383 yaffs_ObjectType type)
2385 yaffs_Object *theObject = NULL;
2388 theObject = yaffs_FindObjectByNumber(dev, number);
2391 theObject = yaffs_CreateNewObject(dev, number, type);
2398 static YCHAR *yaffs_CloneString(const YCHAR *str)
2400 YCHAR *newStr = NULL;
2406 len = yaffs_strnlen(str,YAFFS_MAX_ALIAS_LENGTH);
2407 newStr = YMALLOC((len + 1) * sizeof(YCHAR));
2409 yaffs_strncpy(newStr, str,len);
2417 * Mknod (create) a new object.
2418 * equivalentObject only has meaning for a hard link;
2419 * aliasString only has meaning for a symlink.
2420 * rdev only has meaning for devices (a subset of special objects)
2423 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2424 yaffs_Object *parent,
2429 yaffs_Object *equivalentObject,
2430 const YCHAR *aliasString, __u32 rdev)
2435 yaffs_Device *dev = parent->myDev;
2437 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2438 if (yaffs_FindObjectByName(parent, name))
2441 if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2442 str = yaffs_CloneString(aliasString);
2447 in = yaffs_CreateNewObject(dev, -1, type);
2462 in->variantType = type;
2464 in->yst_mode = mode;
2466 #ifdef CONFIG_YAFFS_WINCE
2467 yfsd_WinFileTimeNow(in->win_atime);
2468 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2469 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2472 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2474 in->yst_rdev = rdev;
2478 in->nDataChunks = 0;
2480 yaffs_SetObjectName(in, name);
2483 yaffs_AddObjectToDirectory(parent, in);
2485 in->myDev = parent->myDev;
2488 case YAFFS_OBJECT_TYPE_SYMLINK:
2489 in->variant.symLinkVariant.alias = str;
2491 case YAFFS_OBJECT_TYPE_HARDLINK:
2492 in->variant.hardLinkVariant.equivalentObject =
2494 in->variant.hardLinkVariant.equivalentObjectId =
2495 equivalentObject->objectId;
2496 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2498 case YAFFS_OBJECT_TYPE_FILE:
2499 case YAFFS_OBJECT_TYPE_DIRECTORY:
2500 case YAFFS_OBJECT_TYPE_SPECIAL:
2501 case YAFFS_OBJECT_TYPE_UNKNOWN:
2506 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2507 /* Could not create the object header, fail the creation */
2508 yaffs_DeleteObject(in);
2512 yaffs_UpdateParent(parent);
2518 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
2519 __u32 mode, __u32 uid, __u32 gid)
2521 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2522 uid, gid, NULL, NULL, 0);
2525 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
2526 __u32 mode, __u32 uid, __u32 gid)
2528 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2529 mode, uid, gid, NULL, NULL, 0);
2532 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
2533 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2535 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2536 uid, gid, NULL, NULL, rdev);
2539 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
2540 __u32 mode, __u32 uid, __u32 gid,
2543 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2544 uid, gid, NULL, alias, 0);
2547 /* yaffs_Link returns the object id of the equivalent object.*/
2548 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
2549 yaffs_Object *equivalentObject)
2551 /* Get the real object in case we were fed a hard link as an equivalent object */
2552 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2554 if (yaffs_MknodObject
2555 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2556 equivalentObject, NULL, 0)) {
2557 return equivalentObject;
2564 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
2565 const YCHAR *newName, int force, int shadows)
2570 yaffs_Object *existingTarget;
2573 newDir = obj->parent; /* use the old directory */
2575 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2576 T(YAFFS_TRACE_ALWAYS,
2578 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2583 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2584 if (obj->myDev->param.isYaffs2)
2585 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2587 unlinkOp = (newDir == obj->myDev->unlinkedDir
2588 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2590 deleteOp = (newDir == obj->myDev->deletedDir);
2592 existingTarget = yaffs_FindObjectByName(newDir, newName);
2594 /* If the object is a file going into the unlinked directory,
2595 * then it is OK to just stuff it in since duplicate names are allowed.
2596 * else only proceed if the new name does not exist and if we're putting
2597 * it into a directory.
2604 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2605 yaffs_SetObjectName(obj, newName);
2608 yaffs_AddObjectToDirectory(newDir, obj);
2613 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2614 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows) >= 0)
2621 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
2622 yaffs_Object *newDir, const YCHAR *newName)
2624 yaffs_Object *obj = NULL;
2625 yaffs_Object *existingTarget = NULL;
2631 if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2633 if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2636 dev = oldDir->myDev;
2638 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2639 /* Special case for case insemsitive systems (eg. WinCE).
2640 * While look-up is case insensitive, the name isn't.
2641 * Therefore we might want to change x.txt to X.txt
2643 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
2647 if(yaffs_strnlen(newName,YAFFS_MAX_NAME_LENGTH+1) > YAFFS_MAX_NAME_LENGTH)
2651 obj = yaffs_FindObjectByName(oldDir, oldName);
2653 if (obj && obj->renameAllowed) {
2655 /* Now do the handling for an existing target, if there is one */
2657 existingTarget = yaffs_FindObjectByName(newDir, newName);
2658 if (existingTarget &&
2659 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2660 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2661 /* There is a target that is a non-empty directory, so we fail */
2662 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2663 } else if (existingTarget && existingTarget != obj) {
2664 /* Nuke the target first, using shadowing,
2665 * but only if it isn't the same object.
2667 * Note we must disable gc otherwise it can mess up the shadowing.
2671 yaffs_ChangeObjectName(obj, newDir, newName, force,
2672 existingTarget->objectId);
2673 existingTarget->isShadowed = 1;
2674 yaffs_UnlinkObject(existingTarget);
2678 result = yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2680 yaffs_UpdateParent(oldDir);
2681 if(newDir != oldDir)
2682 yaffs_UpdateParent(newDir);
2689 /*------------------------- Block Management and Page Allocation ----------------*/
2691 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
2693 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2695 dev->blockInfo = NULL;
2696 dev->chunkBits = NULL;
2698 dev->allocationBlock = -1; /* force it to get a new one */
2700 /* If the first allocation strategy fails, thry the alternate one */
2701 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2702 if (!dev->blockInfo) {
2703 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2704 dev->blockInfoAlt = 1;
2706 dev->blockInfoAlt = 0;
2708 if (dev->blockInfo) {
2709 /* Set up dynamic blockinfo stuff. */
2710 dev->chunkBitmapStride = (dev->param.nChunksPerBlock + 7) / 8; /* round up bytes */
2711 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2712 if (!dev->chunkBits) {
2713 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2714 dev->chunkBitsAlt = 1;
2716 dev->chunkBitsAlt = 0;
2719 if (dev->blockInfo && dev->chunkBits) {
2720 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2721 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2728 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2730 if (dev->blockInfoAlt && dev->blockInfo)
2731 YFREE_ALT(dev->blockInfo);
2732 else if (dev->blockInfo)
2733 YFREE(dev->blockInfo);
2735 dev->blockInfoAlt = 0;
2737 dev->blockInfo = NULL;
2739 if (dev->chunkBitsAlt && dev->chunkBits)
2740 YFREE_ALT(dev->chunkBits);
2741 else if (dev->chunkBits)
2742 YFREE(dev->chunkBits);
2743 dev->chunkBitsAlt = 0;
2744 dev->chunkBits = NULL;
2747 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
2748 yaffs_BlockInfo *bi)
2751 if (!dev->param.isYaffs2)
2752 return 1; /* disqualification only applies to yaffs2. */
2754 if (!bi->hasShrinkHeader)
2755 return 1; /* can gc */
2757 yaffs_FindOldestDirtySequence(dev);
2759 /* Can't do gc of this block if there are any blocks older than this one that have
2762 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2766 * yaffs_FindRefreshBlock()
2767 * periodically finds the oldest full block by sequence number for refreshing.
2770 static __u32 yaffs_FindRefreshBlock(yaffs_Device *dev)
2775 __u32 oldestSequence = 0;
2777 yaffs_BlockInfo *bi;
2780 * If refresh period < 10 then refreshing is disabled.
2782 if(dev->param.refreshPeriod < 10 ||
2783 !dev->param.isYaffs2)
2787 * Fix broken values.
2789 if(dev->refreshSkip > dev->param.refreshPeriod)
2790 dev->refreshSkip = dev->param.refreshPeriod;
2792 if(dev->refreshSkip > 0){
2798 * Refresh skip is now zero.
2799 * We'll do a refresh this time around....
2800 * Update the refresh skip and find the oldest block.
2802 dev->refreshSkip = dev->param.refreshPeriod;
2803 dev->refreshCount++;
2804 bi = dev->blockInfo;
2805 for (b = dev->internalStartBlock; b <=dev->internalEndBlock; b++){
2807 if (bi->blockState == YAFFS_BLOCK_STATE_FULL){
2810 bi->sequenceNumber < oldestSequence){
2812 oldestSequence = bi->sequenceNumber;
2820 (TSTR("GC refresh count %d selected block %d with sequenceNumber %d" TENDSTR),
2821 dev->refreshCount, oldest, oldestSequence));
2828 * FindDiretiestBlock is used to select the dirtiest block (or close enough)
2829 * for garbage collection.
2832 static int yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
2835 int b = dev->currentDirtyChecker;
2841 int prioritised = 0;
2842 yaffs_BlockInfo *bi;
2843 int pendingPrioritisedExist = 0;
2845 /* First let's see if we need to grab a prioritised block */
2846 if (dev->hasPendingPrioritisedGCs) {
2847 bi = dev->blockInfo;
2848 for (i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++) {
2850 if (bi->gcPrioritise) {
2851 pendingPrioritisedExist = 1;
2852 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2853 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2854 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2857 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2863 if (!pendingPrioritisedExist) /* None found, so we can clear this */
2864 dev->hasPendingPrioritisedGCs = 0;
2867 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2869 * else (we're doing a leasurely gc), then we only bother to do this if the
2870 * block has only a few pages in use.
2873 dev->nonAggressiveSkip--;
2875 if (!aggressive && (dev->nonAggressiveSkip > 0))
2880 (aggressive) ? dev->param.nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2884 dev->internalEndBlock - dev->internalStartBlock + 1;
2887 dev->internalEndBlock - dev->internalStartBlock + 1;
2888 iterations = iterations / 16;
2889 if (iterations > 200)
2893 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2895 if (b < dev->internalStartBlock || b > dev->internalEndBlock)
2896 b = dev->internalStartBlock;
2898 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2899 T(YAFFS_TRACE_ERROR,
2900 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2904 bi = yaffs_GetBlockInfo(dev, b);
2906 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2907 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2908 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2910 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2914 dev->currentDirtyChecker = b;
2918 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2919 dev->param.nChunksPerBlock - pagesInUse, prioritised));
2923 dev->nonAggressiveSkip = 4;
2928 static void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
2930 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2934 /* If the block is still healthy erase it and mark as clean.
2935 * If the block has had a data failure, then retire it.
2938 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2939 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2940 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2942 yaffs_ClearOldestDirtySequence(dev,bi);
2944 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2946 /* If this is the block being garbage collected then stop gc'ing this block */
2947 if(blockNo == dev->gcBlock)
2950 if (!bi->needsRetiring) {
2951 yaffs_InvalidateCheckpoint(dev);
2952 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2954 dev->nErasureFailures++;
2955 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2956 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2961 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2963 for (i = 0; i < dev->param.nChunksPerBlock; i++) {
2964 if (!yaffs_CheckChunkErased
2965 (dev, blockNo * dev->param.nChunksPerBlock + i)) {
2966 T(YAFFS_TRACE_ERROR,
2968 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2969 TENDSTR), blockNo, i));
2975 /* Clean it up... */
2976 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2977 bi->sequenceNumber = 0;
2978 dev->nErasedBlocks++;
2980 bi->softDeletions = 0;
2981 bi->hasShrinkHeader = 0;
2982 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2983 bi->gcPrioritise = 0;
2984 yaffs_ClearChunkBits(dev, blockNo);
2986 T(YAFFS_TRACE_ERASE,
2987 (TSTR("Erased block %d" TENDSTR), blockNo));
2989 dev->nFreeChunks -= dev->param.nChunksPerBlock; /* We lost a block of free space */
2991 yaffs_RetireBlock(dev, blockNo);
2992 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2993 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2997 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
3001 yaffs_BlockInfo *bi;
3003 if (dev->nErasedBlocks < 1) {
3004 /* Hoosterman we've got a problem.
3005 * Can't get space to gc
3007 T(YAFFS_TRACE_ERROR,
3008 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
3013 /* Find an empty block. */
3015 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
3016 dev->allocationBlockFinder++;
3017 if (dev->allocationBlockFinder < dev->internalStartBlock
3018 || dev->allocationBlockFinder > dev->internalEndBlock) {
3019 dev->allocationBlockFinder = dev->internalStartBlock;
3022 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
3024 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
3025 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
3026 dev->sequenceNumber++;
3027 bi->sequenceNumber = dev->sequenceNumber;
3028 dev->nErasedBlocks--;
3029 T(YAFFS_TRACE_ALLOCATE,
3030 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
3031 dev->allocationBlockFinder, dev->sequenceNumber,
3032 dev->nErasedBlocks));
3033 return dev->allocationBlockFinder;
3037 T(YAFFS_TRACE_ALWAYS,
3039 ("yaffs tragedy: no more erased blocks, but there should have been %d"
3040 TENDSTR), dev->nErasedBlocks));
3047 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
3049 if (!dev->nCheckpointBlocksRequired &&
3050 dev->param.isYaffs2) {
3051 /* Not a valid value so recalculate */
3054 int devBlocks = (dev->param.endBlock - dev->param.startBlock + 1);
3055 int tnodeSize = yaffs_CalcTnodeSize(dev);
3057 nBytes += sizeof(yaffs_CheckpointValidity);
3058 nBytes += sizeof(yaffs_CheckpointDevice);
3059 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
3060 nBytes += devBlocks * dev->chunkBitmapStride;
3061 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
3062 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
3063 nBytes += sizeof(yaffs_CheckpointValidity);
3064 nBytes += sizeof(__u32); /* checksum*/
3066 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
3068 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->param.nChunksPerBlock)) + 3;
3070 dev->nCheckpointBlocksRequired = nBlocks;
3073 return dev->nCheckpointBlocksRequired;
3077 * Check if there's space to allocate...
3078 * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
3080 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev, int nChunks)
3083 int reservedBlocks = dev->param.nReservedBlocks;
3084 int checkpointBlocks;
3086 if (dev->param.isYaffs2) {
3087 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
3088 dev->blocksInCheckpoint;
3089 if (checkpointBlocks < 0)
3090 checkpointBlocks = 0;
3092 checkpointBlocks = 0;
3095 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->param.nChunksPerBlock);
3097 return (dev->nFreeChunks > (reservedChunks + nChunks));
3100 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
3101 yaffs_BlockInfo **blockUsedPtr)
3104 yaffs_BlockInfo *bi;
3106 if (dev->allocationBlock < 0) {
3107 /* Get next block to allocate off */
3108 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
3109 dev->allocationPage = 0;
3112 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev, 1)) {
3113 /* Not enough space to allocate unless we're allowed to use the reserve. */
3117 if (dev->nErasedBlocks < dev->param.nReservedBlocks
3118 && dev->allocationPage == 0) {
3119 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
3122 /* Next page please.... */
3123 if (dev->allocationBlock >= 0) {
3124 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3126 retVal = (dev->allocationBlock * dev->param.nChunksPerBlock) +
3127 dev->allocationPage;
3129 yaffs_SetChunkBit(dev, dev->allocationBlock,
3130 dev->allocationPage);
3132 dev->allocationPage++;
3136 /* If the block is full set the state to full */
3137 if (dev->allocationPage >= dev->param.nChunksPerBlock) {
3138 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3139 dev->allocationBlock = -1;
3148 T(YAFFS_TRACE_ERROR,
3149 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
3154 static int yaffs_GetErasedChunks(yaffs_Device *dev)
3158 n = dev->nErasedBlocks * dev->param.nChunksPerBlock;
3160 if (dev->allocationBlock > 0)
3161 n += (dev->param.nChunksPerBlock - dev->allocationPage);
3168 * yaffs_SkipRestOfBlock() skips over the rest of the allocation block
3169 * if we don't want to write to it.
3171 static void yaffs_SkipRestOfBlock(yaffs_Device *dev)
3173 if(dev->allocationBlock > 0){
3174 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3175 if(bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING){
3176 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3177 dev->allocationBlock = -1;
3183 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
3189 int retVal = YAFFS_OK;
3192 int isCheckpointBlock;
3196 int chunksBefore = yaffs_GetErasedChunks(dev);
3199 yaffs_ExtendedTags tags;
3201 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3203 yaffs_Object *object;
3205 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3208 T(YAFFS_TRACE_TRACING,
3209 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3212 bi->hasShrinkHeader,
3215 /*yaffs_VerifyFreeChunks(dev); */
3217 if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
3218 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3220 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
3224 if (isCheckpointBlock ||
3225 !yaffs_StillSomeChunkBits(dev, block)) {
3226 T(YAFFS_TRACE_TRACING,
3228 ("Collecting block %d that has no chunks in use" TENDSTR),
3230 yaffs_BlockBecameDirty(dev, block);
3233 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3235 yaffs_VerifyBlock(dev, bi, block);
3237 maxCopies = (wholeBlock) ? dev->param.nChunksPerBlock : 10;
3238 oldChunk = block * dev->param.nChunksPerBlock + dev->gcChunk;
3240 for (/* init already done */;
3241 retVal == YAFFS_OK &&
3242 dev->gcChunk < dev->param.nChunksPerBlock &&
3243 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
3245 dev->gcChunk++, oldChunk++) {
3246 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3248 /* This page is in use and might need to be copied off */
3254 yaffs_InitialiseTags(&tags);
3256 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3260 yaffs_FindObjectByNumber(dev,
3263 T(YAFFS_TRACE_GC_DETAIL,
3265 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3266 dev->gcChunk, tags.objectId, tags.chunkId,
3269 if (object && !yaffs_SkipVerification(dev)) {
3270 if (tags.chunkId == 0)
3271 matchingChunk = object->hdrChunk;
3272 else if (object->softDeleted)
3273 matchingChunk = oldChunk; /* Defeat the test */
3275 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
3277 if (oldChunk != matchingChunk)
3278 T(YAFFS_TRACE_ERROR,
3279 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3280 oldChunk, matchingChunk, tags.objectId, tags.chunkId));
3285 T(YAFFS_TRACE_ERROR,
3287 ("page %d in gc has no object: %d %d %d "
3289 tags.objectId, tags.chunkId, tags.byteCount));
3294 object->softDeleted &&
3295 tags.chunkId != 0) {
3296 /* Data chunk in a soft deleted file, throw it away
3297 * It's a soft deleted data chunk,
3298 * No need to copy this, just forget about it and
3299 * fix up the object.
3302 /* Free chunks already includes softdeleted chunks.
3303 * How ever this chunk is going to soon be really deleted
3304 * which will increment free chunks.
3305 * We have to decrement free chunks so this works out properly.
3309 object->nDataChunks--;
3311 if (object->nDataChunks <= 0) {
3312 /* remeber to clean up the object */
3313 dev->gcCleanupList[cleanups] =
3319 /* Todo object && object->deleted && object->nDataChunks == 0 */
3320 /* Deleted object header with no data chunks.
3321 * Can be discarded and the file deleted.
3323 object->hdrChunk = 0;
3324 yaffs_FreeTnode(object->myDev,
3327 object->variant.fileVariant.top = NULL;
3328 yaffs_DoGenericObjectDeletion(object);
3330 } else if (object) {
3331 /* It's either a data chunk in a live file or
3332 * an ObjectHeader, so we're interested in it.
3333 * NB Need to keep the ObjectHeaders of deleted files
3334 * until the whole file has been deleted off
3336 tags.serialNumber++;
3340 if (tags.chunkId == 0) {
3341 /* It is an object Id,
3342 * We need to nuke the shrinkheader flags first
3343 * Also need to clean up shadowing.
3344 * We no longer want the shrinkHeader flag since its work is done
3345 * and if it is left in place it will mess up scanning.
3348 yaffs_ObjectHeader *oh;
3349 oh = (yaffs_ObjectHeader *)buffer;
3352 tags.extraIsShrinkHeader = 0;
3354 oh->shadowsObject = 0;
3355 oh->inbandShadowsObject = 0;
3356 tags.extraShadows = 0;
3358 /* Update file size */
3359 if(object->variantType == YAFFS_OBJECT_TYPE_FILE){
3360 oh->fileSize = object->variant.fileVariant.fileSize;
3361 tags.extraFileLength = oh->fileSize;
3364 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
3366 yaffs_WriteNewChunkWithTagsToNAND(dev,(__u8 *) oh, &tags, 1);
3369 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3372 retVal = YAFFS_FAIL;
3375 /* Ok, now fix up the Tnodes etc. */
3377 if (tags.chunkId == 0) {
3379 object->hdrChunk = newChunk;
3380 object->serial = tags.serialNumber;
3382 /* It's a data chunk */
3384 ok = yaffs_PutChunkIntoFile
3392 if (retVal == YAFFS_OK)
3393 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3398 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3401 /* Do any required cleanups */
3402 for (i = 0; i < cleanups; i++) {
3403 /* Time to delete the file too */
3405 yaffs_FindObjectByNumber(dev,
3406 dev->gcCleanupList[i]);
3408 yaffs_FreeTnode(dev,
3409 object->variant.fileVariant.
3411 object->variant.fileVariant.top = NULL;
3414 ("yaffs: About to finally delete object %d"
3415 TENDSTR), object->objectId));
3416 yaffs_DoGenericObjectDeletion(object);
3417 object->myDev->nDeletedFiles--;
3424 yaffs_VerifyCollectedBlock(dev, bi, block);
3428 if (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3430 * The gc did not complete. Set block state back to FULL
3431 * because checkpointing does not restore gc.
3433 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3435 /* The gc completed. */
3436 chunksAfter = yaffs_GetErasedChunks(dev);
3437 if (chunksBefore >= chunksAfter) {
3440 ("gc did not increase free chunks before %d after %d"
3441 TENDSTR), chunksBefore, chunksAfter));
3452 /* New garbage collector
3453 * If we're very low on erased blocks then we do aggressive garbage collection
3454 * otherwise we do "leasurely" garbage collection.
3455 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3456 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3458 * The idea is to help clear out space in a more spread-out manner.
3459 * Dunno if it really does anything useful.
3461 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
3465 int gcOk = YAFFS_OK;
3468 int checkpointBlockAdjust;
3470 if(dev->param.gcControl &&
3471 (dev->param.gcControl(dev) & 1) == 0)
3474 if (dev->isDoingGC) {
3475 /* Bail out so we don't get recursive gc */
3479 /* This loop should pass the first time.
3480 * We'll only see looping here if the erase of the collected block fails.
3486 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3487 if (checkpointBlockAdjust < 0)
3488 checkpointBlockAdjust = 0;
3490 /* If we need a block soon then do aggressive gc.*/
3491 if (dev->nErasedBlocks < (dev->param.nReservedBlocks + checkpointBlockAdjust + 2))
3496 /* If we don't already have a block being gc'd then see if we should start another */
3498 if (dev->gcBlock < 1 && !aggressive) {
3499 dev->gcBlock = yaffs_FindRefreshBlock(dev);
3502 if (dev->gcBlock < 1) {
3503 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3507 block = dev->gcBlock;
3510 dev->garbageCollections++;
3512 dev->passiveGarbageCollections++;
3516 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3517 dev->nErasedBlocks, aggressive));
3519 gcOk = yaffs_GarbageCollectBlock(dev, block, aggressive);
3522 if (dev->nErasedBlocks < (dev->param.nReservedBlocks) && block > 0) {
3525 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3526 TENDSTR), dev->nErasedBlocks, maxTries, block));
3528 } while ((dev->nErasedBlocks < dev->param.nReservedBlocks) &&
3532 return aggressive ? gcOk : YAFFS_OK;
3535 /*------------------------- TAGS --------------------------------*/
3537 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
3540 return (tags->chunkId == chunkInObject &&
3541 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3546 /*-------------------- Data file manipulation -----------------*/
3548 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
3549 yaffs_ExtendedTags *tags)
3551 /*Get the Tnode, then get the level 0 offset chunk offset */
3554 yaffs_ExtendedTags localTags;
3557 yaffs_Device *dev = in->myDev;
3560 /* Passed a NULL, so use our own tags space */
3564 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3567 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3570 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3576 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
3577 yaffs_ExtendedTags *tags)
3579 /* Get the Tnode, then get the level 0 offset chunk offset */
3582 yaffs_ExtendedTags localTags;
3584 yaffs_Device *dev = in->myDev;
3588 /* Passed a NULL, so use our own tags space */
3592 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3596 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3599 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3602 /* Delete the entry in the filestructure (if found) */
3604 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, 0);
3610 #ifdef YAFFS_PARANOID
3612 static int yaffs_CheckFileSanity(yaffs_Object *in)
3620 yaffs_Tags localTags;
3621 yaffs_Tags *tags = &localTags;
3625 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3628 objId = in->objectId;
3629 fSize = in->variant.fileVariant.fileSize;
3631 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3633 for (chunk = 1; chunk <= nChunks; chunk++) {
3634 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3639 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunk);
3641 if (yaffs_CheckChunkBits
3642 (dev, theChunk / dev->param.nChunksPerBlock,
3643 theChunk % dev->param.nChunksPerBlock)) {
3645 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3649 (tags, in->objectId, chunk, chunkDeleted)) {
3659 /* T(("No level 0 found for %d\n", chunk)); */
3663 return failed ? YAFFS_FAIL : YAFFS_OK;
3668 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
3669 int chunkInNAND, int inScan)
3671 /* NB inScan is zero unless scanning.
3672 * For forward scanning, inScan is > 0;
3673 * for backward scanning inScan is < 0
3675 * chunkInNAND = 0 is a dummy insert to make sure the tnodes are there.
3679 yaffs_Device *dev = in->myDev;
3681 yaffs_ExtendedTags existingTags;
3682 yaffs_ExtendedTags newTags;
3683 unsigned existingSerial, newSerial;
3685 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3686 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3687 * If it is not during Scanning then something went wrong!
3690 T(YAFFS_TRACE_ERROR,
3692 ("yaffs tragedy:attempt to put data chunk into a non-file"
3697 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3701 tn = yaffs_AddOrFindLevel0Tnode(dev,
3702 &in->variant.fileVariant,
3709 /* Dummy insert, bail now */
3712 existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3715 /* If we're scanning then we need to test for duplicates
3716 * NB This does not need to be efficient since it should only ever
3717 * happen when the power fails during a write, then only one
3718 * chunk should ever be affected.
3720 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3721 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3724 if (existingChunk > 0) {
3725 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3726 * thus we have to do a FindChunkInFile to get the real chunk id.
3728 * We have a duplicate now we need to decide which one to use:
3730 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3731 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3732 * YAFFS1: Get both sets of tags and compare serial numbers.
3736 /* Only do this for forward scanning */
3737 yaffs_ReadChunkWithTagsFromNAND(dev,
3741 /* Do a proper find */
3743 yaffs_FindChunkInFile(in, chunkInInode,
3747 if (existingChunk <= 0) {
3748 /*Hoosterman - how did this happen? */
3750 T(YAFFS_TRACE_ERROR,
3752 ("yaffs tragedy: existing chunk < 0 in scan"
3757 /* NB The deleted flags should be false, otherwise the chunks will
3758 * not be loaded during a scan
3762 newSerial = newTags.serialNumber;
3763 existingSerial = existingTags.serialNumber;
3767 (in->myDev->param.isYaffs2 ||
3768 existingChunk <= 0 ||
3769 ((existingSerial + 1) & 3) == newSerial)) {
3770 /* Forward scanning.
3772 * Delete the old one and drop through to update the tnode
3774 yaffs_DeleteChunk(dev, existingChunk, 1,
3777 /* Backward scanning or we want to use the existing one
3779 * Delete the new one and return early so that the tnode isn't changed
3781 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3789 if (existingChunk == 0)
3792 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
3797 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
3800 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3802 if (chunkInNAND >= 0)
3803 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3806 T(YAFFS_TRACE_NANDACCESS,
3807 (TSTR("Chunk %d not found zero instead" TENDSTR),
3809 /* get sane (zero) data if you read a hole */
3810 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3816 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
3820 yaffs_ExtendedTags tags;
3821 yaffs_BlockInfo *bi;
3827 block = chunkId / dev->param.nChunksPerBlock;
3828 page = chunkId % dev->param.nChunksPerBlock;
3831 if (!yaffs_CheckChunkBit(dev, block, page))
3832 T(YAFFS_TRACE_VERIFY,
3833 (TSTR("Deleting invalid chunk %d"TENDSTR),
3836 bi = yaffs_GetBlockInfo(dev, block);
3838 yaffs_UpdateOldestDirtySequence(dev,bi);
3840 T(YAFFS_TRACE_DELETION,
3841 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3844 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->param.isYaffs2) {
3846 yaffs_InitialiseTags(&tags);
3848 tags.chunkDeleted = 1;
3850 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3851 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3853 dev->nUnmarkedDeletions++;
3856 /* Pull out of the management area.
3857 * If the whole block became dirty, this will kick off an erasure.
3859 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3860 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3861 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3862 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3865 yaffs_ClearChunkBit(dev, block, page);
3869 if (bi->pagesInUse == 0 &&
3870 !bi->hasShrinkHeader &&
3871 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3872 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3873 yaffs_BlockBecameDirty(dev, block);
3880 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
3881 const __u8 *buffer, int nBytes,
3884 /* Find old chunk Need to do this to get serial number
3885 * Write new one and patch into tree.
3886 * Invalidate old tags.
3890 yaffs_ExtendedTags prevTags;
3893 yaffs_ExtendedTags newTags;
3895 yaffs_Device *dev = in->myDev;
3897 yaffs_CheckGarbageCollection(dev);
3899 /* Get the previous chunk at this location in the file if it exists.
3900 * If it does not exist then put a zero into the tree. This creates
3901 * the tnode now, rather than later when it is harder to clean up.
3903 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3904 if(prevChunkId < 1 &&
3905 !yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0))
3908 /* Set up new tags */
3909 yaffs_InitialiseTags(&newTags);
3911 newTags.chunkId = chunkInInode;
3912 newTags.objectId = in->objectId;
3913 newTags.serialNumber =
3914 (prevChunkId > 0) ? prevTags.serialNumber + 1 : 1;
3915 newTags.byteCount = nBytes;
3917 if (nBytes < 1 || nBytes > dev->param.totalBytesPerChunk) {
3918 T(YAFFS_TRACE_ERROR,
3919 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3925 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3928 if (newChunkId > 0) {
3929 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3931 if (prevChunkId > 0)
3932 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3934 yaffs_CheckFileSanity(in);
3940 /* UpdateObjectHeader updates the header on NAND for an object.
3941 * If name is not NULL, then that new name is used.
3943 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
3944 int isShrink, int shadows)
3947 yaffs_BlockInfo *bi;
3949 yaffs_Device *dev = in->myDev;
3956 yaffs_ExtendedTags newTags;
3957 yaffs_ExtendedTags oldTags;
3958 YCHAR *alias = NULL;
3960 __u8 *buffer = NULL;
3961 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3963 yaffs_ObjectHeader *oh = NULL;
3965 yaffs_strcpy(oldName, _Y("silly old name"));
3969 in == dev->rootDir || /* The rootDir should also be saved */
3972 yaffs_CheckGarbageCollection(dev);
3973 yaffs_CheckObjectDetailsLoaded(in);
3975 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3976 oh = (yaffs_ObjectHeader *) buffer;
3978 prevChunkId = in->hdrChunk;
3980 if (prevChunkId > 0) {
3981 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3984 yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
3986 memcpy(oldName, oh->name, sizeof(oh->name));
3989 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3991 oh->type = in->variantType;
3992 oh->yst_mode = in->yst_mode;
3993 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3995 #ifdef CONFIG_YAFFS_WINCE
3996 oh->win_atime[0] = in->win_atime[0];
3997 oh->win_ctime[0] = in->win_ctime[0];
3998 oh->win_mtime[0] = in->win_mtime[0];
3999 oh->win_atime[1] = in->win_atime[1];
4000 oh->win_ctime[1] = in->win_ctime[1];
4001 oh->win_mtime[1] = in->win_mtime[1];
4003 oh->yst_uid = in->yst_uid;
4004 oh->yst_gid = in->yst_gid;
4005 oh->yst_atime = in->yst_atime;
4006 oh->yst_mtime = in->yst_mtime;
4007 oh->yst_ctime = in->yst_ctime;
4008 oh->yst_rdev = in->yst_rdev;
4011 oh->parentObjectId = in->parent->objectId;
4013 oh->parentObjectId = 0;
4015 if (name && *name) {
4016 memset(oh->name, 0, sizeof(oh->name));
4017 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
4018 } else if (prevChunkId > 0)
4019 memcpy(oh->name, oldName, sizeof(oh->name));
4021 memset(oh->name, 0, sizeof(oh->name));
4023 oh->isShrink = isShrink;
4025 switch (in->variantType) {
4026 case YAFFS_OBJECT_TYPE_UNKNOWN:
4027 /* Should not happen */
4029 case YAFFS_OBJECT_TYPE_FILE:
4031 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
4032 || oh->parentObjectId ==
4033 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
4034 fileVariant.fileSize;
4036 case YAFFS_OBJECT_TYPE_HARDLINK:
4037 oh->equivalentObjectId =
4038 in->variant.hardLinkVariant.equivalentObjectId;
4040 case YAFFS_OBJECT_TYPE_SPECIAL:
4043 case YAFFS_OBJECT_TYPE_DIRECTORY:
4046 case YAFFS_OBJECT_TYPE_SYMLINK:
4047 alias = in->variant.symLinkVariant.alias;
4049 alias = _Y("no alias");
4050 yaffs_strncpy(oh->alias,
4052 YAFFS_MAX_ALIAS_LENGTH);
4053 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
4058 yaffs_InitialiseTags(&newTags);
4060 newTags.chunkId = 0;
4061 newTags.objectId = in->objectId;
4062 newTags.serialNumber = in->serial;
4064 /* Add extra info for file header */
4066 newTags.extraHeaderInfoAvailable = 1;
4067 newTags.extraParentObjectId = oh->parentObjectId;
4068 newTags.extraFileLength = oh->fileSize;
4069 newTags.extraIsShrinkHeader = oh->isShrink;
4070 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
4071 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
4072 newTags.extraObjectType = in->variantType;
4074 yaffs_VerifyObjectHeader(in, oh, &newTags, 1);
4076 /* Create new chunk in NAND */
4078 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
4079 (prevChunkId > 0) ? 1 : 0);
4081 if (newChunkId >= 0) {
4083 in->hdrChunk = newChunkId;
4085 if (prevChunkId > 0) {
4086 yaffs_DeleteChunk(dev, prevChunkId, 1,
4090 if (!yaffs_ObjectHasCachedWriteData(in))
4093 /* If this was a shrink, then mark the block that the chunk lives on */
4095 bi = yaffs_GetBlockInfo(in->myDev,
4096 newChunkId / in->myDev->param.nChunksPerBlock);
4097 bi->hasShrinkHeader = 1;
4102 retVal = newChunkId;
4107 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
4112 /*------------------------ Short Operations Cache ----------------------------------------
4113 * In many situations where there is no high level buffering (eg WinCE) a lot of
4114 * reads might be short sequential reads, and a lot of writes may be short
4115 * sequential writes. eg. scanning/writing a jpeg file.
4116 * In these cases, a short read/write cache can provide a huge perfomance benefit
4117 * with dumb-as-a-rock code.
4118 * In Linux, the page cache provides read buffering aand the short op cache provides write
4121 * There are a limited number (~10) of cache chunks per device so that we don't
4122 * need a very intelligent search.
4125 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
4127 yaffs_Device *dev = obj->myDev;
4129 yaffs_ChunkCache *cache;
4130 int nCaches = obj->myDev->param.nShortOpCaches;
4132 for (i = 0; i < nCaches; i++) {
4133 cache = &dev->srCache[i];
4134 if (cache->object == obj &&
4143 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
4145 yaffs_Device *dev = obj->myDev;
4146 int lowest = -99; /* Stop compiler whining. */
4148 yaffs_ChunkCache *cache;
4149 int chunkWritten = 0;
4150 int nCaches = obj->myDev->param.nShortOpCaches;
4156 /* Find the dirty cache for this object with the lowest chunk id. */
4157 for (i = 0; i < nCaches; i++) {
4158 if (dev->srCache[i].object == obj &&
4159 dev->srCache[i].dirty) {
4161 || dev->srCache[i].chunkId <
4163 cache = &dev->srCache[i];
4164 lowest = cache->chunkId;
4169 if (cache && !cache->locked) {
4170 /* Write it out and free it up */
4173 yaffs_WriteChunkDataToObject(cache->object,
4179 cache->object = NULL;
4182 } while (cache && chunkWritten > 0);
4185 /* Hoosterman, disk full while writing cache out. */
4186 T(YAFFS_TRACE_ERROR,
4187 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
4194 /*yaffs_FlushEntireDeviceCache(dev)
4199 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
4202 int nCaches = dev->param.nShortOpCaches;
4205 /* Find a dirty object in the cache and flush it...
4206 * until there are no further dirty objects.
4210 for (i = 0; i < nCaches && !obj; i++) {
4211 if (dev->srCache[i].object &&
4212 dev->srCache[i].dirty)
4213 obj = dev->srCache[i].object;
4217 yaffs_FlushFilesChunkCache(obj);
4224 /* Grab us a cache chunk for use.
4225 * First look for an empty one.
4226 * Then look for the least recently used non-dirty one.
4227 * Then look for the least recently used dirty one...., flush and look again.
4229 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
4233 if (dev->param.nShortOpCaches > 0) {
4234 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4235 if (!dev->srCache[i].object)
4236 return &dev->srCache[i];
4243 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
4245 yaffs_ChunkCache *cache;
4246 yaffs_Object *theObj;
4251 if (dev->param.nShortOpCaches > 0) {
4252 /* Try find a non-dirty one... */
4254 cache = yaffs_GrabChunkCacheWorker(dev);
4257 /* They were all dirty, find the last recently used object and flush
4258 * its cache, then find again.
4259 * NB what's here is not very accurate, we actually flush the object
4260 * the last recently used page.
4263 /* With locking we can't assume we can use entry zero */
4270 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4271 if (dev->srCache[i].object &&
4272 !dev->srCache[i].locked &&
4273 (dev->srCache[i].lastUse < usage || !cache)) {
4274 usage = dev->srCache[i].lastUse;
4275 theObj = dev->srCache[i].object;
4276 cache = &dev->srCache[i];
4281 if (!cache || cache->dirty) {
4282 /* Flush and try again */
4283 yaffs_FlushFilesChunkCache(theObj);
4284 cache = yaffs_GrabChunkCacheWorker(dev);
4294 /* Find a cached chunk */
4295 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj,
4298 yaffs_Device *dev = obj->myDev;
4300 if (dev->param.nShortOpCaches > 0) {
4301 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4302 if (dev->srCache[i].object == obj &&
4303 dev->srCache[i].chunkId == chunkId) {
4306 return &dev->srCache[i];
4313 /* Mark the chunk for the least recently used algorithym */
4314 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache,
4318 if (dev->param.nShortOpCaches > 0) {
4319 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4320 /* Reset the cache usages */
4322 for (i = 1; i < dev->param.nShortOpCaches; i++)
4323 dev->srCache[i].lastUse = 0;
4330 cache->lastUse = dev->srLastUse;
4337 /* Invalidate a single cache page.
4338 * Do this when a whole page gets written,
4339 * ie the short cache for this page is no longer valid.
4341 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
4343 if (object->myDev->param.nShortOpCaches > 0) {
4344 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4347 cache->object = NULL;
4351 /* Invalidate all the cache pages associated with this object
4352 * Do this whenever ther file is deleted or resized.
4354 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
4357 yaffs_Device *dev = in->myDev;
4359 if (dev->param.nShortOpCaches > 0) {
4360 /* Invalidate it. */
4361 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4362 if (dev->srCache[i].object == in)
4363 dev->srCache[i].object = NULL;
4368 /*--------------------- Checkpointing --------------------*/
4371 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev, int head)
4373 yaffs_CheckpointValidity cp;
4375 memset(&cp, 0, sizeof(cp));
4377 cp.structType = sizeof(cp);
4378 cp.magic = YAFFS_MAGIC;
4379 cp.version = YAFFS_CHECKPOINT_VERSION;
4380 cp.head = (head) ? 1 : 0;
4382 return (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp)) ?
4386 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4388 yaffs_CheckpointValidity cp;
4391 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4394 ok = (cp.structType == sizeof(cp)) &&
4395 (cp.magic == YAFFS_MAGIC) &&
4396 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4397 (cp.head == ((head) ? 1 : 0));
4401 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4404 cp->nErasedBlocks = dev->nErasedBlocks;
4405 cp->allocationBlock = dev->allocationBlock;
4406 cp->allocationPage = dev->allocationPage;
4407 cp->nFreeChunks = dev->nFreeChunks;
4409 cp->nDeletedFiles = dev->nDeletedFiles;
4410 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4411 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4412 cp->sequenceNumber = dev->sequenceNumber;
4416 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4417 yaffs_CheckpointDevice *cp)
4419 dev->nErasedBlocks = cp->nErasedBlocks;
4420 dev->allocationBlock = cp->allocationBlock;
4421 dev->allocationPage = cp->allocationPage;
4422 dev->nFreeChunks = cp->nFreeChunks;
4424 dev->nDeletedFiles = cp->nDeletedFiles;
4425 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4426 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4427 dev->sequenceNumber = cp->sequenceNumber;
4431 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4433 yaffs_CheckpointDevice cp;
4435 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4439 /* Write device runtime values*/
4440 yaffs_DeviceToCheckpointDevice(&cp, dev);
4441 cp.structType = sizeof(cp);
4443 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4445 /* Write block info */
4447 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4448 ok = (yaffs_CheckpointWrite(dev, dev->blockInfo, nBytes) == nBytes);
4451 /* Write chunk bits */
4453 nBytes = nBlocks * dev->chunkBitmapStride;
4454 ok = (yaffs_CheckpointWrite(dev, dev->chunkBits, nBytes) == nBytes);
4460 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4462 yaffs_CheckpointDevice cp;
4464 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4468 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4472 if (cp.structType != sizeof(cp))
4476 yaffs_CheckpointDeviceToDevice(dev, &cp);
4478 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4480 ok = (yaffs_CheckpointRead(dev, dev->blockInfo, nBytes) == nBytes);
4484 nBytes = nBlocks * dev->chunkBitmapStride;
4486 ok = (yaffs_CheckpointRead(dev, dev->chunkBits, nBytes) == nBytes);
4491 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4495 cp->objectId = obj->objectId;
4496 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4497 cp->hdrChunk = obj->hdrChunk;
4498 cp->variantType = obj->variantType;
4499 cp->deleted = obj->deleted;
4500 cp->softDeleted = obj->softDeleted;
4501 cp->unlinked = obj->unlinked;
4502 cp->fake = obj->fake;
4503 cp->renameAllowed = obj->renameAllowed;
4504 cp->unlinkAllowed = obj->unlinkAllowed;
4505 cp->serial = obj->serial;
4506 cp->nDataChunks = obj->nDataChunks;
4508 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4509 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4510 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4511 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4514 static int yaffs_CheckpointObjectToObject(yaffs_Object *obj, yaffs_CheckpointObject *cp)
4517 yaffs_Object *parent;
4519 if (obj->variantType != cp->variantType) {
4520 T(YAFFS_TRACE_ERROR, (TSTR("Checkpoint read object %d type %d "
4521 TCONT("chunk %d does not match existing object type %d")
4522 TENDSTR), cp->objectId, cp->variantType, cp->hdrChunk,
4527 obj->objectId = cp->objectId;
4530 parent = yaffs_FindOrCreateObjectByNumber(
4533 YAFFS_OBJECT_TYPE_DIRECTORY);
4538 if (parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4539 T(YAFFS_TRACE_ALWAYS, (TSTR("Checkpoint read object %d parent %d type %d"
4540 TCONT(" chunk %d Parent type, %d, not directory")
4542 cp->objectId, cp->parentId, cp->variantType,
4543 cp->hdrChunk, parent->variantType));
4546 yaffs_AddObjectToDirectory(parent, obj);
4549 obj->hdrChunk = cp->hdrChunk;
4550 obj->variantType = cp->variantType;
4551 obj->deleted = cp->deleted;
4552 obj->softDeleted = cp->softDeleted;
4553 obj->unlinked = cp->unlinked;
4554 obj->fake = cp->fake;
4555 obj->renameAllowed = cp->renameAllowed;
4556 obj->unlinkAllowed = cp->unlinkAllowed;
4557 obj->serial = cp->serial;
4558 obj->nDataChunks = cp->nDataChunks;
4560 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4561 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4562 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4563 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4565 if (obj->hdrChunk > 0)
4566 obj->lazyLoaded = 1;
4572 static int yaffs_CheckpointTnodeWorker(yaffs_Object *in, yaffs_Tnode *tn,
4573 __u32 level, int chunkOffset)
4576 yaffs_Device *dev = in->myDev;
4578 int tnodeSize = yaffs_CalcTnodeSize(dev);
4583 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
4584 if (tn->internal[i]) {
4585 ok = yaffs_CheckpointTnodeWorker(in,
4588 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4591 } else if (level == 0) {
4592 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4593 ok = (yaffs_CheckpointWrite(dev, &baseOffset, sizeof(baseOffset)) == sizeof(baseOffset));
4595 ok = (yaffs_CheckpointWrite(dev, tn, tnodeSize) == tnodeSize);
4603 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4605 __u32 endMarker = ~0;
4608 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4609 ok = yaffs_CheckpointTnodeWorker(obj,
4610 obj->variant.fileVariant.top,
4611 obj->variant.fileVariant.topLevel,
4614 ok = (yaffs_CheckpointWrite(obj->myDev, &endMarker, sizeof(endMarker)) ==
4621 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4625 yaffs_Device *dev = obj->myDev;
4626 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4629 int tnodeSize = yaffs_CalcTnodeSize(dev);
4631 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4633 while (ok && (~baseChunk)) {
4635 /* Read level 0 tnode */
4638 tn = yaffs_GetTnodeRaw(dev);
4640 ok = (yaffs_CheckpointRead(dev, tn, tnodeSize) == tnodeSize);
4645 ok = yaffs_AddOrFindLevel0Tnode(dev,
4651 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4655 T(YAFFS_TRACE_CHECKPOINT, (
4656 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4657 nread, baseChunk, ok));
4663 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4666 yaffs_CheckpointObject cp;
4669 struct ylist_head *lh;
4672 /* Iterate through the objects in each hash entry,
4673 * dumping them to the checkpointing stream.
4676 for (i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++) {
4677 ylist_for_each(lh, &dev->objectBucket[i].list) {
4679 obj = ylist_entry(lh, yaffs_Object, hashLink);
4680 if (!obj->deferedFree) {
4681 yaffs_ObjectToCheckpointObject(&cp, obj);
4682 cp.structType = sizeof(cp);
4684 T(YAFFS_TRACE_CHECKPOINT, (
4685 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %p" TENDSTR),
4686 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk, obj));
4688 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4690 if (ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4691 ok = yaffs_WriteCheckpointTnodes(obj);
4697 /* Dump end of list */
4698 memset(&cp, 0xFF, sizeof(yaffs_CheckpointObject));
4699 cp.structType = sizeof(cp);
4702 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4707 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4710 yaffs_CheckpointObject cp;
4713 yaffs_Object *hardList = NULL;
4715 while (ok && !done) {
4716 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4717 if (cp.structType != sizeof(cp)) {
4718 T(YAFFS_TRACE_CHECKPOINT, (TSTR("struct size %d instead of %d ok %d"TENDSTR),
4719 cp.structType, (int)sizeof(cp), ok));
4723 T(YAFFS_TRACE_CHECKPOINT, (TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4724 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk));
4726 if (ok && cp.objectId == ~0)
4729 obj = yaffs_FindOrCreateObjectByNumber(dev, cp.objectId, cp.variantType);
4731 ok = yaffs_CheckpointObjectToObject(obj, &cp);
4734 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4735 ok = yaffs_ReadCheckpointTnodes(obj);
4736 } else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4737 obj->hardLinks.next =
4738 (struct ylist_head *) hardList;
4747 yaffs_HardlinkFixup(dev, hardList);
4752 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4754 __u32 checkpointSum;
4757 yaffs_GetCheckpointSum(dev, &checkpointSum);
4759 ok = (yaffs_CheckpointWrite(dev, &checkpointSum, sizeof(checkpointSum)) == sizeof(checkpointSum));
4767 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4769 __u32 checkpointSum0;
4770 __u32 checkpointSum1;
4773 yaffs_GetCheckpointSum(dev, &checkpointSum0);
4775 ok = (yaffs_CheckpointRead(dev, &checkpointSum1, sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4780 if (checkpointSum0 != checkpointSum1)
4787 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4791 if (dev->param.skipCheckpointWrite || !dev->param.isYaffs2) {
4792 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint write" TENDSTR)));
4797 ok = yaffs_CheckpointOpen(dev, 1);
4800 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4801 ok = yaffs_WriteCheckpointValidityMarker(dev, 1);
4804 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint device" TENDSTR)));
4805 ok = yaffs_WriteCheckpointDevice(dev);
4808 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint objects" TENDSTR)));
4809 ok = yaffs_WriteCheckpointObjects(dev);
4812 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4813 ok = yaffs_WriteCheckpointValidityMarker(dev, 0);
4817 ok = yaffs_WriteCheckpointSum(dev);
4819 if (!yaffs_CheckpointClose(dev))
4823 dev->isCheckpointed = 1;
4825 dev->isCheckpointed = 0;
4827 return dev->isCheckpointed;
4830 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4834 if (dev->param.skipCheckpointRead || !dev->param.isYaffs2) {
4835 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint read" TENDSTR)));
4840 ok = yaffs_CheckpointOpen(dev, 0); /* open for read */
4843 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4844 ok = yaffs_ReadCheckpointValidityMarker(dev, 1);
4847 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint device" TENDSTR)));
4848 ok = yaffs_ReadCheckpointDevice(dev);
4851 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint objects" TENDSTR)));
4852 ok = yaffs_ReadCheckpointObjects(dev);
4855 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4856 ok = yaffs_ReadCheckpointValidityMarker(dev, 0);
4860 ok = yaffs_ReadCheckpointSum(dev);
4861 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint checksum %d" TENDSTR), ok));
4864 if (!yaffs_CheckpointClose(dev))
4868 dev->isCheckpointed = 1;
4870 dev->isCheckpointed = 0;
4876 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4878 if (dev->isCheckpointed ||
4879 dev->blocksInCheckpoint > 0) {
4880 dev->isCheckpointed = 0;
4881 yaffs_CheckpointInvalidateStream(dev);
4883 if (dev->param.markSuperBlockDirty)
4884 dev->param.markSuperBlockDirty(dev);
4888 int yaffs_CheckpointSave(yaffs_Device *dev)
4891 T(YAFFS_TRACE_CHECKPOINT, (TSTR("save entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4893 yaffs_VerifyObjects(dev);
4894 yaffs_VerifyBlocks(dev);
4895 yaffs_VerifyFreeChunks(dev);
4897 if (!dev->isCheckpointed) {
4898 yaffs_InvalidateCheckpoint(dev);
4899 yaffs_WriteCheckpointData(dev);
4902 T(YAFFS_TRACE_ALWAYS, (TSTR("save exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4904 return dev->isCheckpointed;
4907 int yaffs_CheckpointRestore(yaffs_Device *dev)
4910 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4912 retval = yaffs_ReadCheckpointData(dev);
4914 if (dev->isCheckpointed) {
4915 yaffs_VerifyObjects(dev);
4916 yaffs_VerifyBlocks(dev);
4917 yaffs_VerifyFreeChunks(dev);
4920 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4925 /*--------------------- File read/write ------------------------
4926 * Read and write have very similar structures.
4927 * In general the read/write has three parts to it
4928 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4929 * Some complete chunks
4930 * An incomplete chunk to end off with
4932 * Curve-balls: the first chunk might also be the last chunk.
4935 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 *buffer, loff_t offset,
4944 yaffs_ChunkCache *cache;
4951 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4952 /* start = offset % dev->nDataBytesPerChunk; */
4953 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4956 /* OK now check for the curveball where the start and end are in
4959 if ((start + n) < dev->nDataBytesPerChunk)
4962 nToCopy = dev->nDataBytesPerChunk - start;
4964 cache = yaffs_FindChunkCache(in, chunk);
4966 /* If the chunk is already in the cache or it is less than a whole chunk
4967 * or we're using inband tags then use the cache (if there is caching)
4968 * else bypass the cache.
4970 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
4971 if (dev->param.nShortOpCaches > 0) {
4973 /* If we can't find the data in the cache, then load it up. */
4976 cache = yaffs_GrabChunkCache(in->myDev);
4978 cache->chunkId = chunk;
4981 yaffs_ReadChunkDataFromObject(in, chunk,
4987 yaffs_UseChunkCache(dev, cache, 0);
4992 memcpy(buffer, &cache->data[start], nToCopy);
4996 /* Read into the local buffer then copy..*/
4999 yaffs_GetTempBuffer(dev, __LINE__);
5000 yaffs_ReadChunkDataFromObject(in, chunk,
5003 memcpy(buffer, &localBuffer[start], nToCopy);
5006 yaffs_ReleaseTempBuffer(dev, localBuffer,
5012 /* A full chunk. Read directly into the supplied buffer. */
5013 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
5027 int yaffs_DoWriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
5028 int nBytes, int writeThrough)
5037 int startOfWrite = offset;
5038 int chunkWritten = 0;
5046 while (n > 0 && chunkWritten >= 0) {
5047 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
5048 /* start = offset % dev->nDataBytesPerChunk; */
5049 yaffs_AddrToChunk(dev, offset, &chunk, &start);
5051 if (chunk * dev->nDataBytesPerChunk + start != offset ||
5052 start >= dev->nDataBytesPerChunk) {
5053 T(YAFFS_TRACE_ERROR, (
5054 TSTR("AddrToChunk of offset %d gives chunk %d start %d"
5056 (int)offset, chunk, start));
5060 /* OK now check for the curveball where the start and end are in
5064 if ((start + n) < dev->nDataBytesPerChunk) {
5067 /* Now folks, to calculate how many bytes to write back....
5068 * If we're overwriting and not writing to then end of file then
5069 * we need to write back as much as was there before.
5072 chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
5074 if (chunkStart > in->variant.fileVariant.fileSize)
5075 nBytesRead = 0; /* Past end of file */
5077 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
5079 if (nBytesRead > dev->nDataBytesPerChunk)
5080 nBytesRead = dev->nDataBytesPerChunk;
5084 (start + n)) ? nBytesRead : (start + n);
5086 if (nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
5090 nToCopy = dev->nDataBytesPerChunk - start;
5091 nToWriteBack = dev->nDataBytesPerChunk;
5094 if (nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
5095 /* An incomplete start or end chunk (or maybe both start and end chunk),
5096 * or we're using inband tags, so we want to use the cache buffers.
5098 if (dev->param.nShortOpCaches > 0) {
5099 yaffs_ChunkCache *cache;
5100 /* If we can't find the data in the cache, then load the cache */
5101 cache = yaffs_FindChunkCache(in, chunk);
5104 && yaffs_CheckSpaceForAllocation(dev, 1)) {
5105 cache = yaffs_GrabChunkCache(dev);
5107 cache->chunkId = chunk;
5110 yaffs_ReadChunkDataFromObject(in, chunk,
5114 !yaffs_CheckSpaceForAllocation(dev, 1)) {
5115 /* Drop the cache if it was a read cache item and
5116 * no space check has been made for it.
5122 yaffs_UseChunkCache(dev, cache, 1);
5126 memcpy(&cache->data[start], buffer,
5131 cache->nBytes = nToWriteBack;
5135 yaffs_WriteChunkDataToObject
5138 cache->data, cache->nBytes,
5144 chunkWritten = -1; /* fail the write */
5147 /* An incomplete start or end chunk (or maybe both start and end chunk)
5148 * Read into the local buffer then copy, then copy over and write back.
5152 yaffs_GetTempBuffer(dev, __LINE__);
5154 yaffs_ReadChunkDataFromObject(in, chunk,
5159 memcpy(&localBuffer[start], buffer, nToCopy);
5162 yaffs_WriteChunkDataToObject(in, chunk,
5167 yaffs_ReleaseTempBuffer(dev, localBuffer,
5173 /* A full chunk. Write directly from the supplied buffer. */
5178 yaffs_WriteChunkDataToObject(in, chunk, buffer,
5179 dev->nDataBytesPerChunk,
5182 /* Since we've overwritten the cached data, we better invalidate it. */
5183 yaffs_InvalidateChunkCache(in, chunk);
5186 if (chunkWritten >= 0) {
5195 /* Update file object */
5197 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
5198 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
5205 int yaffs_WriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
5206 int nBytes, int writeThrough)
5208 yaffs_HandleHole(in,offset);
5209 return yaffs_DoWriteDataToFile(in,buffer,offset,nBytes,writeThrough);
5214 /* ---------------------- File resizing stuff ------------------ */
5216 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
5219 yaffs_Device *dev = in->myDev;
5220 int oldFileSize = in->variant.fileVariant.fileSize;
5222 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
5224 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
5225 dev->nDataBytesPerChunk;
5229 /* Delete backwards so that we don't end up with holes if
5230 * power is lost part-way through the operation.
5232 for (i = lastDel; i >= startDel; i--) {
5233 /* NB this could be optimised somewhat,
5234 * eg. could retrieve the tags and write them without
5235 * using yaffs_DeleteChunk
5238 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5241 (dev->internalStartBlock * dev->param.nChunksPerBlock)
5243 ((dev->internalEndBlock +
5244 1) * dev->param.nChunksPerBlock)) {
5245 T(YAFFS_TRACE_ALWAYS,
5246 (TSTR("Found daft chunkId %d for %d" TENDSTR),
5250 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5258 static void yaffs_ResizeDown( yaffs_Object *obj, loff_t newSize)
5261 __u32 newSizeOfPartialChunk;
5262 yaffs_Device *dev = obj->myDev;
5264 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5266 yaffs_PruneResizedChunks(obj, newSize);
5268 if (newSizeOfPartialChunk != 0) {
5269 int lastChunk = 1 + newFullChunks;
5270 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5272 /* Got to read and rewrite the last chunk with its new size and zero pad */
5273 yaffs_ReadChunkDataFromObject(obj, lastChunk, localBuffer);
5274 memset(localBuffer + newSizeOfPartialChunk, 0,
5275 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5277 yaffs_WriteChunkDataToObject(obj, lastChunk, localBuffer,
5278 newSizeOfPartialChunk, 1);
5280 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5283 obj->variant.fileVariant.fileSize = newSize;
5285 yaffs_PruneFileStructure(dev, &obj->variant.fileVariant);
5289 static int yaffs_HandleHole(yaffs_Object *obj, loff_t newSize)
5291 /* if newsSize > oldFileSize.
5292 * We're going to be writing a hole.
5293 * If the hole is small then write zeros otherwise write a start of hole marker.
5300 int result = YAFFS_OK;
5301 yaffs_Device *dev = NULL;
5303 __u8 *localBuffer = NULL;
5305 int smallIncreaseOk = 0;
5310 if(obj->variantType != YAFFS_OBJECT_TYPE_FILE)
5315 /* Bail out if not yaffs2 mode */
5316 if(!dev->param.isYaffs2)
5319 oldFileSize = obj->variant.fileVariant.fileSize;
5321 if (newSize <= oldFileSize)
5324 increase = newSize - oldFileSize;
5326 if(increase < YAFFS_SMALL_HOLE_THRESHOLD * dev->nDataBytesPerChunk &&
5327 yaffs_CheckSpaceForAllocation(dev, YAFFS_SMALL_HOLE_THRESHOLD + 1))
5333 localBuffer= yaffs_GetTempBuffer(dev, __LINE__);
5336 /* fill hole with zero bytes */
5337 int pos = oldFileSize;
5340 memset(localBuffer,0,dev->nDataBytesPerChunk);
5341 smallIncreaseOk = 1;
5343 while(increase > 0 && smallIncreaseOk){
5344 thisWrite = increase;
5345 if(thisWrite > dev->nDataBytesPerChunk)
5346 thisWrite = dev->nDataBytesPerChunk;
5347 written = yaffs_DoWriteDataToFile(obj,localBuffer,pos,thisWrite,0);
5348 if(written == thisWrite){
5350 increase -= thisWrite;
5352 smallIncreaseOk = 0;
5355 yaffs_ReleaseTempBuffer(dev,localBuffer,__LINE__);
5357 /* If we were out of space then reverse any chunks we've added */
5358 if(!smallIncreaseOk)
5359 yaffs_ResizeDown(obj, oldFileSize);
5362 if (!smallIncreaseOk &&
5364 obj->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5365 obj->parent->objectId != YAFFS_OBJECTID_DELETED){
5366 /* Write a hole start header with the old file size */
5367 yaffs_UpdateObjectHeader(obj, NULL, 0,1,0);
5374 int yaffs_ResizeFile(yaffs_Object *in, loff_t newSize)
5376 yaffs_Device *dev = in->myDev;
5377 int oldFileSize = in->variant.fileVariant.fileSize;
5379 yaffs_FlushFilesChunkCache(in);
5380 yaffs_InvalidateWholeChunkCache(in);
5382 yaffs_CheckGarbageCollection(dev);
5384 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
5387 if (newSize == oldFileSize)
5390 if(newSize > oldFileSize){
5391 yaffs_HandleHole(in,newSize);
5392 in->variant.fileVariant.fileSize = newSize;
5394 /* newSize < oldFileSize */
5395 yaffs_ResizeDown(in, newSize);
5398 /* Write a new object header to reflect the resize.
5399 * show we've shrunk the file, if need be
5400 * Do this only if the file is not in the deleted directories
5401 * and is not shadowed.
5405 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5406 in->parent->objectId != YAFFS_OBJECTID_DELETED)
5407 yaffs_UpdateObjectHeader(in, NULL, 0,0,0);
5413 loff_t yaffs_GetFileSize(yaffs_Object *obj)
5415 YCHAR *alias = NULL;
5416 obj = yaffs_GetEquivalentObject(obj);
5418 switch (obj->variantType) {
5419 case YAFFS_OBJECT_TYPE_FILE:
5420 return obj->variant.fileVariant.fileSize;
5421 case YAFFS_OBJECT_TYPE_SYMLINK:
5422 alias = obj->variant.symLinkVariant.alias;
5425 return yaffs_strnlen(alias,YAFFS_MAX_ALIAS_LENGTH);
5433 int yaffs_FlushFile(yaffs_Object *in, int updateTime, int dataSync)
5437 yaffs_FlushFilesChunkCache(in);
5438 if(dataSync) /* Only sync data */
5442 #ifdef CONFIG_YAFFS_WINCE
5443 yfsd_WinFileTimeNow(in->win_mtime);
5446 in->yst_mtime = Y_CURRENT_TIME;
5451 retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5452 0) ? YAFFS_OK : YAFFS_FAIL;
5462 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
5465 /* First off, invalidate the file's data in the cache, without flushing. */
5466 yaffs_InvalidateWholeChunkCache(in);
5468 if (in->myDev->param.isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5469 /* Move to the unlinked directory so we have a record that it was deleted. */
5470 yaffs_ChangeObjectName(in, in->myDev->deletedDir, _Y("deleted"), 0, 0);
5474 yaffs_RemoveObjectFromDirectory(in);
5475 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5478 yaffs_FreeObject(in);
5483 /* yaffs_DeleteFile deletes the whole file data
5484 * and the inode associated with the file.
5485 * It does not delete the links associated with the file.
5487 static int yaffs_UnlinkFileIfNeeded(yaffs_Object *in)
5491 int immediateDeletion = 0;
5492 yaffs_Device *dev = in->myDev;
5495 immediateDeletion = 1;
5497 if (immediateDeletion) {
5499 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5500 _Y("deleted"), 0, 0);
5501 T(YAFFS_TRACE_TRACING,
5502 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5505 in->myDev->nDeletedFiles++;
5506 if (dev->param.disableSoftDelete || dev->param.isYaffs2)
5507 yaffs_ResizeFile(in, 0);
5508 yaffs_SoftDeleteFile(in);
5511 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5512 _Y("unlinked"), 0, 0);
5519 int yaffs_DeleteFile(yaffs_Object *in)
5521 int retVal = YAFFS_OK;
5522 int deleted = in->deleted;
5523 yaffs_Device *dev = in->myDev;
5525 if (dev->param.disableSoftDelete || dev->param.isYaffs2)
5526 yaffs_ResizeFile(in, 0);
5528 if (in->nDataChunks > 0) {
5529 /* Use soft deletion if there is data in the file.
5530 * That won't be the case if it has been resized to zero.
5533 retVal = yaffs_UnlinkFileIfNeeded(in);
5535 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5538 in->myDev->nDeletedFiles++;
5539 yaffs_SoftDeleteFile(in);
5541 return deleted ? YAFFS_OK : YAFFS_FAIL;
5543 /* The file has no data chunks so we toss it immediately */
5544 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5545 in->variant.fileVariant.top = NULL;
5546 yaffs_DoGenericObjectDeletion(in);
5552 static int yaffs_IsNonEmptyDirectory(yaffs_Object *obj)
5554 return (obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) &&
5555 !(ylist_empty(&obj->variant.directoryVariant.children));
5558 static int yaffs_DeleteDirectory(yaffs_Object *obj)
5560 /* First check that the directory is empty. */
5561 if (yaffs_IsNonEmptyDirectory(obj))
5564 return yaffs_DoGenericObjectDeletion(obj);
5567 static int yaffs_DeleteSymLink(yaffs_Object *in)
5569 if(in->variant.symLinkVariant.alias)
5570 YFREE(in->variant.symLinkVariant.alias);
5571 in->variant.symLinkVariant.alias=NULL;
5573 return yaffs_DoGenericObjectDeletion(in);
5576 static int yaffs_DeleteHardLink(yaffs_Object *in)
5578 /* remove this hardlink from the list assocaited with the equivalent
5581 ylist_del_init(&in->hardLinks);
5582 return yaffs_DoGenericObjectDeletion(in);
5585 int yaffs_DeleteObject(yaffs_Object *obj)
5588 switch (obj->variantType) {
5589 case YAFFS_OBJECT_TYPE_FILE:
5590 retVal = yaffs_DeleteFile(obj);
5592 case YAFFS_OBJECT_TYPE_DIRECTORY:
5593 if(!ylist_empty(&obj->variant.directoryVariant.dirty)){
5594 T(YAFFS_TRACE_BACKGROUND, (TSTR("Remove object %d from dirty directories" TENDSTR),obj->objectId));
5595 ylist_del_init(&obj->variant.directoryVariant.dirty);
5597 return yaffs_DeleteDirectory(obj);
5599 case YAFFS_OBJECT_TYPE_SYMLINK:
5600 retVal = yaffs_DeleteSymLink(obj);
5602 case YAFFS_OBJECT_TYPE_HARDLINK:
5603 retVal = yaffs_DeleteHardLink(obj);
5605 case YAFFS_OBJECT_TYPE_SPECIAL:
5606 retVal = yaffs_DoGenericObjectDeletion(obj);
5608 case YAFFS_OBJECT_TYPE_UNKNOWN:
5610 break; /* should not happen. */
5616 static int yaffs_UnlinkWorker(yaffs_Object *obj)
5619 int immediateDeletion = 0;
5622 immediateDeletion = 1;
5625 yaffs_UpdateParent(obj->parent);
5627 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5628 return yaffs_DeleteHardLink(obj);
5629 } else if (!ylist_empty(&obj->hardLinks)) {
5630 /* Curve ball: We're unlinking an object that has a hardlink.
5632 * This problem arises because we are not strictly following
5633 * The Linux link/inode model.
5635 * We can't really delete the object.
5636 * Instead, we do the following:
5637 * - Select a hardlink.
5638 * - Unhook it from the hard links
5639 * - Move it from its parent directory (so that the rename can work)
5640 * - Rename the object to the hardlink's name.
5641 * - Delete the hardlink
5645 yaffs_Object *parent;
5647 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5649 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5651 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5652 parent = hl->parent;
5654 ylist_del_init(&hl->hardLinks);
5656 yaffs_AddObjectToDirectory(obj->myDev->unlinkedDir, hl);
5658 retVal = yaffs_ChangeObjectName(obj,parent, name, 0, 0);
5660 if (retVal == YAFFS_OK)
5661 retVal = yaffs_DoGenericObjectDeletion(hl);
5665 } else if (immediateDeletion) {
5666 switch (obj->variantType) {
5667 case YAFFS_OBJECT_TYPE_FILE:
5668 return yaffs_DeleteFile(obj);
5670 case YAFFS_OBJECT_TYPE_DIRECTORY:
5671 ylist_del_init(&obj->variant.directoryVariant.dirty);
5672 return yaffs_DeleteDirectory(obj);
5674 case YAFFS_OBJECT_TYPE_SYMLINK:
5675 return yaffs_DeleteSymLink(obj);
5677 case YAFFS_OBJECT_TYPE_SPECIAL:
5678 return yaffs_DoGenericObjectDeletion(obj);
5680 case YAFFS_OBJECT_TYPE_HARDLINK:
5681 case YAFFS_OBJECT_TYPE_UNKNOWN:
5685 } else if(yaffs_IsNonEmptyDirectory(obj))
5688 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
5689 _Y("unlinked"), 0, 0);
5693 static int yaffs_UnlinkObject(yaffs_Object *obj)
5696 if (obj && obj->unlinkAllowed)
5697 return yaffs_UnlinkWorker(obj);
5702 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
5706 obj = yaffs_FindObjectByName(dir, name);
5707 return yaffs_UnlinkObject(obj);
5710 /*----------------------- Initialisation Scanning ---------------------- */
5712 static void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
5713 int backwardScanning)
5717 if (!backwardScanning) {
5718 /* Handle YAFFS1 forward scanning case
5719 * For YAFFS1 we always do the deletion
5723 /* Handle YAFFS2 case (backward scanning)
5724 * If the shadowed object exists then ignore.
5726 obj = yaffs_FindObjectByNumber(dev, objId);
5731 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5732 * We put it in unlinked dir to be cleaned up after the scanning
5735 yaffs_FindOrCreateObjectByNumber(dev, objId,
5736 YAFFS_OBJECT_TYPE_FILE);
5739 obj->isShadowed = 1;
5740 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5741 obj->variant.fileVariant.shrinkSize = 0;
5742 obj->valid = 1; /* So that we don't read any other info for this file */
5752 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5759 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5761 in = yaffs_FindObjectByNumber(dev,
5762 hl->variant.hardLinkVariant.
5763 equivalentObjectId);
5766 /* Add the hardlink pointers */
5767 hl->variant.hardLinkVariant.equivalentObject = in;
5768 ylist_add(&hl->hardLinks, &in->hardLinks);
5770 /* Todo Need to report/handle this better.
5771 * Got a problem... hardlink to a non-existant object
5773 hl->variant.hardLinkVariant.equivalentObject = NULL;
5774 YINIT_LIST_HEAD(&hl->hardLinks);
5784 static int ybicmp(const void *a, const void *b)
5786 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5787 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5788 register int ablock = ((yaffs_BlockIndex *)a)->block;
5789 register int bblock = ((yaffs_BlockIndex *)b)->block;
5791 return ablock - bblock;
5797 struct yaffs_ShadowFixerStruct {
5800 struct yaffs_ShadowFixerStruct *next;
5804 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5807 * Sort out state of unlinked and deleted objects after scanning.
5809 struct ylist_head *i;
5810 struct ylist_head *n;
5813 /* Soft delete all the unlinked files */
5814 ylist_for_each_safe(i, n,
5815 &dev->unlinkedDir->variant.directoryVariant.children) {
5817 l = ylist_entry(i, yaffs_Object, siblings);
5818 yaffs_DeleteObject(l);
5822 ylist_for_each_safe(i, n,
5823 &dev->deletedDir->variant.directoryVariant.children) {
5825 l = ylist_entry(i, yaffs_Object, siblings);
5826 yaffs_DeleteObject(l);
5833 * This code iterates through all the objects making sure that they are rooted.
5834 * Any unrooted objects are re-rooted in lost+found.
5835 * An object needs to be in one of:
5836 * - Directly under deleted, unlinked
5837 * - Directly or indirectly under root.
5840 * This code assumes that we don't ever change the current relationships between
5842 * rootDir->parent == unlinkedDir->parent == deletedDir->parent == NULL
5843 * lostNfound->parent == rootDir
5845 * This fixes the problem where directories might have inadvertently been deleted
5846 * leaving the object "hanging" without being rooted in the directory tree.
5849 static int yaffs_HasNULLParent(yaffs_Device *dev, yaffs_Object *obj)
5851 return (obj == dev->deletedDir ||
5852 obj == dev->unlinkedDir||
5853 obj == dev->rootDir);
5856 static void yaffs_FixHangingObjects(yaffs_Device *dev)
5859 yaffs_Object *parent;
5861 struct ylist_head *lh;
5862 struct ylist_head *n;
5867 /* Iterate through the objects in each hash entry,
5868 * looking at each object.
5869 * Make sure it is rooted.
5872 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
5873 ylist_for_each_safe(lh, n, &dev->objectBucket[i].list) {
5875 obj = ylist_entry(lh, yaffs_Object, hashLink);
5876 parent= obj->parent;
5878 if(yaffs_HasNULLParent(dev,obj)){
5879 /* These directories are not hanging */
5882 else if(!parent || parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5884 else if(yaffs_HasNULLParent(dev,parent))
5888 * Need to follow the parent chain to see if it is hanging.
5893 while(parent != dev->rootDir &&
5895 parent->parent->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
5897 parent = parent->parent;
5900 if(parent != dev->rootDir)
5905 (TSTR("Hanging object %d moved to lost and found" TENDSTR),
5907 yaffs_AddObjectToDirectory(dev->lostNFoundDir,obj);
5916 * Delete directory contents for cleaning up lost and found.
5918 static void yaffs_DeleteDirectoryContents(yaffs_Object *dir)
5921 struct ylist_head *lh;
5922 struct ylist_head *n;
5924 if(dir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5927 ylist_for_each_safe(lh, n, &dir->variant.directoryVariant.children) {
5929 obj = ylist_entry(lh, yaffs_Object, siblings);
5930 if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
5931 yaffs_DeleteDirectoryContents(obj);
5934 (TSTR("Deleting lost_found object %d" TENDSTR),
5937 /* Need to use UnlinkObject since Delete would not handle
5938 * hardlinked objects correctly.
5940 yaffs_UnlinkObject(obj);
5946 static void yaffs_EmptyLostAndFound(yaffs_Device *dev)
5948 yaffs_DeleteDirectoryContents(dev->lostNFoundDir);
5951 static int yaffs_Scan(yaffs_Device *dev)
5953 yaffs_ExtendedTags tags;
5963 yaffs_BlockState state;
5964 yaffs_Object *hardList = NULL;
5965 yaffs_BlockInfo *bi;
5966 __u32 sequenceNumber;
5967 yaffs_ObjectHeader *oh;
5969 yaffs_Object *parent;
5971 int alloc_failed = 0;
5973 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5981 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5982 dev->internalStartBlock, dev->internalEndBlock));
5984 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5986 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5988 /* Scan all the blocks to determine their state */
5989 bi = dev->blockInfo;
5990 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5991 yaffs_ClearChunkBits(dev, blk);
5993 bi->softDeletions = 0;
5995 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5997 bi->blockState = state;
5998 bi->sequenceNumber = sequenceNumber;
6000 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6001 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6003 T(YAFFS_TRACE_SCAN_DEBUG,
6004 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6005 state, sequenceNumber));
6007 if (state == YAFFS_BLOCK_STATE_DEAD) {
6008 T(YAFFS_TRACE_BAD_BLOCKS,
6009 (TSTR("block %d is bad" TENDSTR), blk));
6010 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6011 T(YAFFS_TRACE_SCAN_DEBUG,
6012 (TSTR("Block empty " TENDSTR)));
6013 dev->nErasedBlocks++;
6014 dev->nFreeChunks += dev->param.nChunksPerBlock;
6019 startIterator = dev->internalStartBlock;
6020 endIterator = dev->internalEndBlock;
6022 /* For each block.... */
6023 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
6030 blk = blockIterator;
6032 bi = yaffs_GetBlockInfo(dev, blk);
6033 state = bi->blockState;
6037 /* For each chunk in each block that needs scanning....*/
6038 for (c = 0; !alloc_failed && c < dev->param.nChunksPerBlock &&
6039 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
6040 /* Read the tags and decide what to do */
6041 chunk = blk * dev->param.nChunksPerBlock + c;
6043 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6046 /* Let's have a good look at this chunk... */
6048 if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
6054 /*T((" %d %d deleted\n",blk,c)); */
6055 } else if (!tags.chunkUsed) {
6056 /* An unassigned chunk in the block
6057 * This means that either the block is empty or
6058 * this is the one being allocated from
6062 /* We're looking at the first chunk in the block so the block is unused */
6063 state = YAFFS_BLOCK_STATE_EMPTY;
6064 dev->nErasedBlocks++;
6066 /* this is the block being allocated from */
6069 (" Allocating from %d %d" TENDSTR),
6071 state = YAFFS_BLOCK_STATE_ALLOCATING;
6072 dev->allocationBlock = blk;
6073 dev->allocationPage = c;
6074 dev->allocationBlockFinder = blk;
6075 /* Set block finder here to encourage the allocator to go forth from here. */
6079 dev->nFreeChunks += (dev->param.nChunksPerBlock - c);
6080 } else if (tags.chunkId > 0) {
6081 /* chunkId > 0 so it is a data chunk... */
6082 unsigned int endpos;
6084 yaffs_SetChunkBit(dev, blk, c);
6087 in = yaffs_FindOrCreateObjectByNumber(dev,
6090 YAFFS_OBJECT_TYPE_FILE);
6091 /* PutChunkIntoFile checks for a clash (two data chunks with
6092 * the same chunkId).
6099 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, 1))
6104 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
6107 in->variantType == YAFFS_OBJECT_TYPE_FILE
6108 && in->variant.fileVariant.scannedFileSize <
6110 in->variant.fileVariant.
6111 scannedFileSize = endpos;
6112 if (!dev->param.useHeaderFileSize) {
6113 in->variant.fileVariant.
6115 in->variant.fileVariant.
6120 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
6122 /* chunkId == 0, so it is an ObjectHeader.
6123 * Thus, we read in the object header and make the object
6125 yaffs_SetChunkBit(dev, blk, c);
6128 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
6132 oh = (yaffs_ObjectHeader *) chunkData;
6134 in = yaffs_FindObjectByNumber(dev,
6136 if (in && in->variantType != oh->type) {
6137 /* This should not happen, but somehow
6138 * Wev'e ended up with an objectId that has been reused but not yet
6139 * deleted, and worse still it has changed type. Delete the old object.
6142 yaffs_DeleteObject(in);
6147 in = yaffs_FindOrCreateObjectByNumber(dev,
6155 if (in && oh->shadowsObject > 0) {
6157 struct yaffs_ShadowFixerStruct *fixer;
6158 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
6160 fixer->next = shadowFixerList;
6161 shadowFixerList = fixer;
6162 fixer->objectId = tags.objectId;
6163 fixer->shadowedId = oh->shadowsObject;
6168 if (in && in->valid) {
6169 /* We have already filled this one. We have a duplicate and need to resolve it. */
6171 unsigned existingSerial = in->serial;
6172 unsigned newSerial = tags.serialNumber;
6174 if (((existingSerial + 1) & 3) == newSerial) {
6175 /* Use new one - destroy the exisiting one */
6176 yaffs_DeleteChunk(dev,
6181 /* Use existing - destroy this one. */
6182 yaffs_DeleteChunk(dev, chunk, 1,
6187 if (in && !in->valid &&
6188 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6189 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
6190 /* We only load some info, don't fiddle with directory structure */
6192 in->variantType = oh->type;
6194 in->yst_mode = oh->yst_mode;
6195 #ifdef CONFIG_YAFFS_WINCE
6196 in->win_atime[0] = oh->win_atime[0];
6197 in->win_ctime[0] = oh->win_ctime[0];
6198 in->win_mtime[0] = oh->win_mtime[0];
6199 in->win_atime[1] = oh->win_atime[1];
6200 in->win_ctime[1] = oh->win_ctime[1];
6201 in->win_mtime[1] = oh->win_mtime[1];
6203 in->yst_uid = oh->yst_uid;
6204 in->yst_gid = oh->yst_gid;
6205 in->yst_atime = oh->yst_atime;
6206 in->yst_mtime = oh->yst_mtime;
6207 in->yst_ctime = oh->yst_ctime;
6208 in->yst_rdev = oh->yst_rdev;
6210 in->hdrChunk = chunk;
6211 in->serial = tags.serialNumber;
6213 } else if (in && !in->valid) {
6214 /* we need to load this info */
6217 in->variantType = oh->type;
6219 in->yst_mode = oh->yst_mode;
6220 #ifdef CONFIG_YAFFS_WINCE
6221 in->win_atime[0] = oh->win_atime[0];
6222 in->win_ctime[0] = oh->win_ctime[0];
6223 in->win_mtime[0] = oh->win_mtime[0];
6224 in->win_atime[1] = oh->win_atime[1];
6225 in->win_ctime[1] = oh->win_ctime[1];
6226 in->win_mtime[1] = oh->win_mtime[1];
6228 in->yst_uid = oh->yst_uid;
6229 in->yst_gid = oh->yst_gid;
6230 in->yst_atime = oh->yst_atime;
6231 in->yst_mtime = oh->yst_mtime;
6232 in->yst_ctime = oh->yst_ctime;
6233 in->yst_rdev = oh->yst_rdev;
6235 in->hdrChunk = chunk;
6236 in->serial = tags.serialNumber;
6238 yaffs_SetObjectName(in, oh->name);
6241 /* directory stuff...
6246 yaffs_FindOrCreateObjectByNumber
6247 (dev, oh->parentObjectId,
6248 YAFFS_OBJECT_TYPE_DIRECTORY);
6251 if (parent && parent->variantType ==
6252 YAFFS_OBJECT_TYPE_UNKNOWN) {
6253 /* Set up as a directory */
6254 parent->variantType =
6255 YAFFS_OBJECT_TYPE_DIRECTORY;
6256 YINIT_LIST_HEAD(&parent->variant.
6259 } else if (!parent || parent->variantType !=
6260 YAFFS_OBJECT_TYPE_DIRECTORY) {
6261 /* Hoosterman, another problem....
6262 * We're trying to use a non-directory as a directory
6265 T(YAFFS_TRACE_ERROR,
6267 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6269 parent = dev->lostNFoundDir;
6272 yaffs_AddObjectToDirectory(parent, in);
6274 if (0 && (parent == dev->deletedDir ||
6275 parent == dev->unlinkedDir)) {
6276 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
6277 dev->nDeletedFiles++;
6279 /* Note re hardlinks.
6280 * Since we might scan a hardlink before its equivalent object is scanned
6281 * we put them all in a list.
6282 * After scanning is complete, we should have all the objects, so we run through this
6283 * list and fix up all the chains.
6286 switch (in->variantType) {
6287 case YAFFS_OBJECT_TYPE_UNKNOWN:
6288 /* Todo got a problem */
6290 case YAFFS_OBJECT_TYPE_FILE:
6291 if (dev->param.useHeaderFileSize)
6293 in->variant.fileVariant.
6298 case YAFFS_OBJECT_TYPE_HARDLINK:
6299 in->variant.hardLinkVariant.
6300 equivalentObjectId =
6301 oh->equivalentObjectId;
6302 in->hardLinks.next =
6303 (struct ylist_head *)
6307 case YAFFS_OBJECT_TYPE_DIRECTORY:
6310 case YAFFS_OBJECT_TYPE_SPECIAL:
6313 case YAFFS_OBJECT_TYPE_SYMLINK:
6314 in->variant.symLinkVariant.alias =
6315 yaffs_CloneString(oh->alias);
6316 if (!in->variant.symLinkVariant.alias)
6325 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6326 /* If we got this far while scanning, then the block is fully allocated.*/
6327 state = YAFFS_BLOCK_STATE_FULL;
6330 if (state == YAFFS_BLOCK_STATE_ALLOCATING) {
6331 /* If the block was partially allocated then treat it as fully allocated.*/
6332 state = YAFFS_BLOCK_STATE_FULL;
6333 dev->allocationBlock = -1;
6336 bi->blockState = state;
6338 /* Now let's see if it was dirty */
6339 if (bi->pagesInUse == 0 &&
6340 !bi->hasShrinkHeader &&
6341 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6342 yaffs_BlockBecameDirty(dev, blk);
6348 /* Ok, we've done all the scanning.
6349 * Fix up the hard link chains.
6350 * We should now have scanned all the objects, now it's time to add these
6354 yaffs_HardlinkFixup(dev, hardList);
6356 /* Fix up any shadowed objects */
6358 struct yaffs_ShadowFixerStruct *fixer;
6361 while (shadowFixerList) {
6362 fixer = shadowFixerList;
6363 shadowFixerList = fixer->next;
6364 /* Complete the rename transaction by deleting the shadowed object
6365 * then setting the object header to unshadowed.
6367 obj = yaffs_FindObjectByNumber(dev, fixer->shadowedId);
6369 yaffs_DeleteObject(obj);
6371 obj = yaffs_FindObjectByNumber(dev, fixer->objectId);
6374 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6380 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6385 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
6391 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
6394 yaffs_ObjectHeader *oh;
6396 yaffs_ExtendedTags tags;
6398 int alloc_failed = 0;
6406 T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
6408 in->lazyLoaded ? "not yet" : "already"));
6411 if (in->lazyLoaded && in->hdrChunk > 0) {
6413 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6415 result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
6416 oh = (yaffs_ObjectHeader *) chunkData;
6418 in->yst_mode = oh->yst_mode;
6419 #ifdef CONFIG_YAFFS_WINCE
6420 in->win_atime[0] = oh->win_atime[0];
6421 in->win_ctime[0] = oh->win_ctime[0];
6422 in->win_mtime[0] = oh->win_mtime[0];
6423 in->win_atime[1] = oh->win_atime[1];
6424 in->win_ctime[1] = oh->win_ctime[1];
6425 in->win_mtime[1] = oh->win_mtime[1];
6427 in->yst_uid = oh->yst_uid;
6428 in->yst_gid = oh->yst_gid;
6429 in->yst_atime = oh->yst_atime;
6430 in->yst_mtime = oh->yst_mtime;
6431 in->yst_ctime = oh->yst_ctime;
6432 in->yst_rdev = oh->yst_rdev;
6435 yaffs_SetObjectName(in, oh->name);
6437 if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6438 in->variant.symLinkVariant.alias =
6439 yaffs_CloneString(oh->alias);
6440 if (!in->variant.symLinkVariant.alias)
6441 alloc_failed = 1; /* Not returned to caller */
6444 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6448 static int yaffs_ScanBackwards(yaffs_Device *dev)
6450 yaffs_ExtendedTags tags;
6455 int nBlocksToScan = 0;
6461 yaffs_BlockState state;
6462 yaffs_Object *hardList = NULL;
6463 yaffs_BlockInfo *bi;
6464 __u32 sequenceNumber;
6465 yaffs_ObjectHeader *oh;
6467 yaffs_Object *parent;
6468 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6474 int foundChunksInBlock;
6475 int equivalentObjectId;
6476 int alloc_failed = 0;
6479 yaffs_BlockIndex *blockIndex = NULL;
6480 int altBlockIndex = 0;
6482 if (!dev->param.isYaffs2) {
6484 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6490 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
6491 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6494 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6496 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6499 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6505 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6509 dev->blocksInCheckpoint = 0;
6511 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6513 /* Scan all the blocks to determine their state */
6514 bi = dev->blockInfo;
6515 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6516 yaffs_ClearChunkBits(dev, blk);
6518 bi->softDeletions = 0;
6520 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6522 bi->blockState = state;
6523 bi->sequenceNumber = sequenceNumber;
6525 if (bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6526 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6527 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6528 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6530 T(YAFFS_TRACE_SCAN_DEBUG,
6531 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6532 state, sequenceNumber));
6535 if (state == YAFFS_BLOCK_STATE_CHECKPOINT) {
6536 dev->blocksInCheckpoint++;
6538 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6539 T(YAFFS_TRACE_BAD_BLOCKS,
6540 (TSTR("block %d is bad" TENDSTR), blk));
6541 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6542 T(YAFFS_TRACE_SCAN_DEBUG,
6543 (TSTR("Block empty " TENDSTR)));
6544 dev->nErasedBlocks++;
6545 dev->nFreeChunks += dev->param.nChunksPerBlock;
6546 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6548 /* Determine the highest sequence number */
6549 if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6550 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6552 blockIndex[nBlocksToScan].seq = sequenceNumber;
6553 blockIndex[nBlocksToScan].block = blk;
6557 if (sequenceNumber >= dev->sequenceNumber)
6558 dev->sequenceNumber = sequenceNumber;
6560 /* TODO: Nasty sequence number! */
6563 ("Block scanning block %d has bad sequence number %d"
6564 TENDSTR), blk, sequenceNumber));
6572 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6578 /* Sort the blocks */
6579 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6581 /* Use qsort now. */
6582 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6586 /* Dungy old bubble sort... */
6588 yaffs_BlockIndex temp;
6592 for (i = 0; i < nBlocksToScan; i++)
6593 for (j = i + 1; j < nBlocksToScan; j++)
6594 if (blockIndex[i].seq > blockIndex[j].seq) {
6595 temp = blockIndex[j];
6596 blockIndex[j] = blockIndex[i];
6597 blockIndex[i] = temp;
6604 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6606 /* Now scan the blocks looking at the data. */
6608 endIterator = nBlocksToScan - 1;
6609 T(YAFFS_TRACE_SCAN_DEBUG,
6610 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6612 /* For each block.... backwards */
6613 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6615 /* Cooperative multitasking! This loop can run for so
6616 long that watchdog timers expire. */
6619 /* get the block to scan in the correct order */
6620 blk = blockIndex[blockIterator].block;
6622 bi = yaffs_GetBlockInfo(dev, blk);
6625 state = bi->blockState;
6629 /* For each chunk in each block that needs scanning.... */
6630 foundChunksInBlock = 0;
6631 for (c = dev->param.nChunksPerBlock - 1;
6632 !alloc_failed && c >= 0 &&
6633 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6634 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6635 /* Scan backwards...
6636 * Read the tags and decide what to do
6639 chunk = blk * dev->param.nChunksPerBlock + c;
6641 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6644 /* Let's have a good look at this chunk... */
6646 if (!tags.chunkUsed) {
6647 /* An unassigned chunk in the block.
6648 * If there are used chunks after this one, then
6649 * it is a chunk that was skipped due to failing the erased
6650 * check. Just skip it so that it can be deleted.
6651 * But, more typically, We get here when this is an unallocated
6652 * chunk and his means that either the block is empty or
6653 * this is the one being allocated from
6656 if (foundChunksInBlock) {
6657 /* This is a chunk that was skipped due to failing the erased check */
6658 } else if (c == 0) {
6659 /* We're looking at the first chunk in the block so the block is unused */
6660 state = YAFFS_BLOCK_STATE_EMPTY;
6661 dev->nErasedBlocks++;
6663 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6664 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6665 if (dev->sequenceNumber == bi->sequenceNumber) {
6666 /* this is the block being allocated from */
6670 (" Allocating from %d %d"
6673 state = YAFFS_BLOCK_STATE_ALLOCATING;
6674 dev->allocationBlock = blk;
6675 dev->allocationPage = c;
6676 dev->allocationBlockFinder = blk;
6678 /* This is a partially written block that is not
6679 * the current allocation block.
6682 T(YAFFS_TRACE_ALWAYS,
6683 (TSTR("Partially written block %d detected" TENDSTR),
6691 } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED) {
6693 (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
6698 } else if (tags.chunkId > 0) {
6699 /* chunkId > 0 so it is a data chunk... */
6700 unsigned int endpos;
6702 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6704 foundChunksInBlock = 1;
6707 yaffs_SetChunkBit(dev, blk, c);
6710 in = yaffs_FindOrCreateObjectByNumber(dev,
6713 YAFFS_OBJECT_TYPE_FILE);
6720 in->variantType == YAFFS_OBJECT_TYPE_FILE
6721 && chunkBase < in->variant.fileVariant.shrinkSize) {
6722 /* This has not been invalidated by a resize */
6723 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, -1)) {
6727 /* File size is calculated by looking at the data chunks if we have not
6728 * seen an object header yet. Stop this practice once we find an object header.
6730 endpos = chunkBase + tags.byteCount;
6732 if (!in->valid && /* have not got an object header yet */
6733 in->variant.fileVariant.scannedFileSize < endpos) {
6734 in->variant.fileVariant.scannedFileSize = endpos;
6735 in->variant.fileVariant.fileSize = endpos;
6739 /* This chunk has been invalidated by a resize, or a past file deletion
6740 * so delete the chunk*/
6741 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6745 /* chunkId == 0, so it is an ObjectHeader.
6746 * Thus, we read in the object header and make the object
6748 foundChunksInBlock = 1;
6750 yaffs_SetChunkBit(dev, blk, c);
6756 if (tags.extraHeaderInfoAvailable) {
6757 in = yaffs_FindOrCreateObjectByNumber(dev,
6759 tags.extraObjectType);
6765 (!in->valid && dev->param.disableLazyLoad) ||
6766 tags.extraShadows ||
6768 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6769 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))) {
6771 /* If we don't have valid info then we need to read the chunk
6772 * TODO In future we can probably defer reading the chunk and
6773 * living with invalid data until needed.
6776 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6781 oh = (yaffs_ObjectHeader *) chunkData;
6783 if (dev->param.inbandTags) {
6784 /* Fix up the header if they got corrupted by inband tags */
6785 oh->shadowsObject = oh->inbandShadowsObject;
6786 oh->isShrink = oh->inbandIsShrink;
6790 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6798 /* TODO Hoosterman we have a problem! */
6799 T(YAFFS_TRACE_ERROR,
6801 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6802 TENDSTR), tags.objectId, chunk));
6807 /* We have already filled this one.
6808 * We have a duplicate that will be discarded, but
6809 * we first have to suck out resize info if it is a file.
6812 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6814 oh->type == YAFFS_OBJECT_TYPE_FILE) ||
6815 (tags.extraHeaderInfoAvailable &&
6816 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))) {
6818 (oh) ? oh->fileSize : tags.
6820 __u32 parentObjectId =
6822 parentObjectId : tags.
6823 extraParentObjectId;
6827 (oh) ? oh->isShrink : tags.
6828 extraIsShrinkHeader;
6830 /* If it is deleted (unlinked at start also means deleted)
6831 * we treat the file size as being zeroed at this point.
6833 if (parentObjectId ==
6834 YAFFS_OBJECTID_DELETED
6835 || parentObjectId ==
6836 YAFFS_OBJECTID_UNLINKED) {
6841 if (isShrink && in->variant.fileVariant.shrinkSize > thisSize)
6842 in->variant.fileVariant.shrinkSize = thisSize;
6845 bi->hasShrinkHeader = 1;
6848 /* Use existing - destroy this one. */
6849 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6853 if (!in->valid && in->variantType !=
6854 (oh ? oh->type : tags.extraObjectType))
6855 T(YAFFS_TRACE_ERROR, (
6856 TSTR("yaffs tragedy: Bad object type, "
6857 TCONT("%d != %d, for object %d at chunk ")
6858 TCONT("%d during scan")
6860 oh->type : tags.extraObjectType,
6861 in->variantType, tags.objectId,
6865 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6867 YAFFS_OBJECTID_LOSTNFOUND)) {
6868 /* We only load some info, don't fiddle with directory structure */
6872 in->variantType = oh->type;
6874 in->yst_mode = oh->yst_mode;
6875 #ifdef CONFIG_YAFFS_WINCE
6876 in->win_atime[0] = oh->win_atime[0];
6877 in->win_ctime[0] = oh->win_ctime[0];
6878 in->win_mtime[0] = oh->win_mtime[0];
6879 in->win_atime[1] = oh->win_atime[1];
6880 in->win_ctime[1] = oh->win_ctime[1];
6881 in->win_mtime[1] = oh->win_mtime[1];
6883 in->yst_uid = oh->yst_uid;
6884 in->yst_gid = oh->yst_gid;
6885 in->yst_atime = oh->yst_atime;
6886 in->yst_mtime = oh->yst_mtime;
6887 in->yst_ctime = oh->yst_ctime;
6888 in->yst_rdev = oh->yst_rdev;
6892 in->variantType = tags.extraObjectType;
6896 in->hdrChunk = chunk;
6898 } else if (!in->valid) {
6899 /* we need to load this info */
6902 in->hdrChunk = chunk;
6905 in->variantType = oh->type;
6907 in->yst_mode = oh->yst_mode;
6908 #ifdef CONFIG_YAFFS_WINCE
6909 in->win_atime[0] = oh->win_atime[0];
6910 in->win_ctime[0] = oh->win_ctime[0];
6911 in->win_mtime[0] = oh->win_mtime[0];
6912 in->win_atime[1] = oh->win_atime[1];
6913 in->win_ctime[1] = oh->win_ctime[1];
6914 in->win_mtime[1] = oh->win_mtime[1];
6916 in->yst_uid = oh->yst_uid;
6917 in->yst_gid = oh->yst_gid;
6918 in->yst_atime = oh->yst_atime;
6919 in->yst_mtime = oh->yst_mtime;
6920 in->yst_ctime = oh->yst_ctime;
6921 in->yst_rdev = oh->yst_rdev;
6924 if (oh->shadowsObject > 0)
6925 yaffs_HandleShadowedObject(dev,
6932 yaffs_SetObjectName(in, oh->name);
6934 yaffs_FindOrCreateObjectByNumber
6935 (dev, oh->parentObjectId,
6936 YAFFS_OBJECT_TYPE_DIRECTORY);
6938 fileSize = oh->fileSize;
6939 isShrink = oh->isShrink;
6940 equivalentObjectId = oh->equivalentObjectId;
6943 in->variantType = tags.extraObjectType;
6945 yaffs_FindOrCreateObjectByNumber
6946 (dev, tags.extraParentObjectId,
6947 YAFFS_OBJECT_TYPE_DIRECTORY);
6948 fileSize = tags.extraFileLength;
6949 isShrink = tags.extraIsShrinkHeader;
6950 equivalentObjectId = tags.extraEquivalentObjectId;
6959 /* directory stuff...
6963 if (parent && parent->variantType ==
6964 YAFFS_OBJECT_TYPE_UNKNOWN) {
6965 /* Set up as a directory */
6966 parent->variantType =
6967 YAFFS_OBJECT_TYPE_DIRECTORY;
6968 YINIT_LIST_HEAD(&parent->variant.
6971 } else if (!parent || parent->variantType !=
6972 YAFFS_OBJECT_TYPE_DIRECTORY) {
6973 /* Hoosterman, another problem....
6974 * We're trying to use a non-directory as a directory
6977 T(YAFFS_TRACE_ERROR,
6979 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6981 parent = dev->lostNFoundDir;
6984 yaffs_AddObjectToDirectory(parent, in);
6986 itsUnlinked = (parent == dev->deletedDir) ||
6987 (parent == dev->unlinkedDir);
6990 /* Mark the block as having a shrinkHeader */
6991 bi->hasShrinkHeader = 1;
6994 /* Note re hardlinks.
6995 * Since we might scan a hardlink before its equivalent object is scanned
6996 * we put them all in a list.
6997 * After scanning is complete, we should have all the objects, so we run
6998 * through this list and fix up all the chains.
7001 switch (in->variantType) {
7002 case YAFFS_OBJECT_TYPE_UNKNOWN:
7003 /* Todo got a problem */
7005 case YAFFS_OBJECT_TYPE_FILE:
7007 if (in->variant.fileVariant.
7008 scannedFileSize < fileSize) {
7009 /* This covers the case where the file size is greater
7010 * than where the data is
7011 * This will happen if the file is resized to be larger
7012 * than its current data extents.
7014 in->variant.fileVariant.fileSize = fileSize;
7015 in->variant.fileVariant.scannedFileSize = fileSize;
7018 if (in->variant.fileVariant.shrinkSize > fileSize)
7019 in->variant.fileVariant.shrinkSize = fileSize;
7023 case YAFFS_OBJECT_TYPE_HARDLINK:
7025 in->variant.hardLinkVariant.equivalentObjectId =
7027 in->hardLinks.next =
7028 (struct ylist_head *) hardList;
7032 case YAFFS_OBJECT_TYPE_DIRECTORY:
7035 case YAFFS_OBJECT_TYPE_SPECIAL:
7038 case YAFFS_OBJECT_TYPE_SYMLINK:
7040 in->variant.symLinkVariant.alias =
7041 yaffs_CloneString(oh->alias);
7042 if (!in->variant.symLinkVariant.alias)
7052 } /* End of scanning for each chunk */
7054 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
7055 /* If we got this far while scanning, then the block is fully allocated. */
7056 state = YAFFS_BLOCK_STATE_FULL;
7060 bi->blockState = state;
7062 /* Now let's see if it was dirty */
7063 if (bi->pagesInUse == 0 &&
7064 !bi->hasShrinkHeader &&
7065 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
7066 yaffs_BlockBecameDirty(dev, blk);
7071 yaffs_SkipRestOfBlock(dev);
7074 YFREE_ALT(blockIndex);
7078 /* Ok, we've done all the scanning.
7079 * Fix up the hard link chains.
7080 * We should now have scanned all the objects, now it's time to add these
7083 yaffs_HardlinkFixup(dev, hardList);
7086 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
7091 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
7096 /*------------------------------ Directory Functions ----------------------------- */
7098 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
7100 struct ylist_head *lh;
7101 yaffs_Object *listObj;
7106 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
7111 if (yaffs_SkipVerification(obj->myDev))
7115 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
7120 if (obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7121 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
7125 /* Iterate through the objects in each hash entry */
7127 ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
7129 listObj = ylist_entry(lh, yaffs_Object, siblings);
7130 yaffs_VerifyObject(listObj);
7137 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR), count));
7142 static void yaffs_VerifyDirectory(yaffs_Object *directory)
7144 struct ylist_head *lh;
7145 yaffs_Object *listObj;
7152 if (yaffs_SkipFullVerification(directory->myDev))
7155 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7156 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR), directory->variantType));
7160 /* Iterate through the objects in each hash entry */
7162 ylist_for_each(lh, &directory->variant.directoryVariant.children) {
7164 listObj = ylist_entry(lh, yaffs_Object, siblings);
7165 if (listObj->parent != directory) {
7166 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR), listObj->parent));
7169 yaffs_VerifyObjectInDirectory(listObj);
7175 *yaffs_UpdateParent() handles fixing a directories mtime and ctime when a new
7176 * link (ie. name) is created or deleted in the directory.
7179 * create dir/a : update dir's mtime/ctime
7180 * rm dir/a: update dir's mtime/ctime
7181 * modify dir/a: don't update dir's mtimme/ctime
7183 * This can be handled immediately or defered. Defering helps reduce the number
7184 * of updates when many files in a directory are changed within a brief period.
7186 * If the directory updating is defered then yaffs_UpdateDirtyDirecories must be
7187 * called periodically.
7190 static void yaffs_UpdateParent(yaffs_Object *obj)
7198 obj->yst_mtime = obj->yst_ctime = Y_CURRENT_TIME;
7199 if(dev->param.deferDirectoryUpdate){
7200 struct ylist_head *link = &obj->variant.directoryVariant.dirty;
7202 if(ylist_empty(link)){
7203 ylist_add(link,&dev->dirtyDirectories);
7204 T(YAFFS_TRACE_BACKGROUND, (TSTR("Added object %d to dirty directories" TENDSTR),obj->objectId));
7208 yaffs_UpdateObjectHeader(obj,NULL,0,0,0);
7211 void yaffs_UpdateDirtyDirectories(yaffs_Device *dev)
7213 struct ylist_head *link;
7215 yaffs_DirectoryStructure *dS;
7216 yaffs_ObjectVariant *oV;
7218 T(YAFFS_TRACE_BACKGROUND, (TSTR("Update dirty directories" TENDSTR)));
7220 while(!ylist_empty(&dev->dirtyDirectories)){
7221 link = dev->dirtyDirectories.next;
7222 ylist_del_init(link);
7224 dS=ylist_entry(link,yaffs_DirectoryStructure,dirty);
7225 oV = ylist_entry(dS,yaffs_ObjectVariant,directoryVariant);
7226 obj = ylist_entry(oV,yaffs_Object,variant);
7228 T(YAFFS_TRACE_BACKGROUND, (TSTR("Update directory %d" TENDSTR), obj->objectId));
7231 yaffs_UpdateObjectHeader(obj,NULL,0,0,0);
7235 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
7237 yaffs_Device *dev = obj->myDev;
7238 yaffs_Object *parent;
7240 yaffs_VerifyObjectInDirectory(obj);
7241 parent = obj->parent;
7243 yaffs_VerifyDirectory(parent);
7245 if (dev && dev->param.removeObjectCallback)
7246 dev->param.removeObjectCallback(obj);
7249 ylist_del_init(&obj->siblings);
7252 yaffs_VerifyDirectory(parent);
7255 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
7259 T(YAFFS_TRACE_ALWAYS,
7261 ("tragedy: Trying to add an object to a null pointer directory"
7266 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7267 T(YAFFS_TRACE_ALWAYS,
7269 ("tragedy: Trying to add an object to a non-directory"
7274 if (obj->siblings.prev == NULL) {
7275 /* Not initialised */
7280 yaffs_VerifyDirectory(directory);
7282 yaffs_RemoveObjectFromDirectory(obj);
7286 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
7287 obj->parent = directory;
7289 if (directory == obj->myDev->unlinkedDir
7290 || directory == obj->myDev->deletedDir) {
7292 obj->myDev->nUnlinkedFiles++;
7293 obj->renameAllowed = 0;
7296 yaffs_VerifyDirectory(directory);
7297 yaffs_VerifyObjectInDirectory(obj);
7300 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
7305 struct ylist_head *i;
7306 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
7314 T(YAFFS_TRACE_ALWAYS,
7316 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7321 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7322 T(YAFFS_TRACE_ALWAYS,
7324 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7328 sum = yaffs_CalcNameSum(name);
7330 ylist_for_each(i, &directory->variant.directoryVariant.children) {
7332 l = ylist_entry(i, yaffs_Object, siblings);
7334 if (l->parent != directory)
7337 yaffs_CheckObjectDetailsLoaded(l);
7339 /* Special case for lost-n-found */
7340 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7341 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
7343 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
7344 /* LostnFound chunk called Objxxx
7347 yaffs_GetObjectName(l, buffer,
7348 YAFFS_MAX_NAME_LENGTH + 1);
7349 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
7360 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
7361 int (*fn) (yaffs_Object *))
7363 struct ylist_head *i;
7367 T(YAFFS_TRACE_ALWAYS,
7369 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7374 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7375 T(YAFFS_TRACE_ALWAYS,
7377 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7382 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
7384 l = ylist_entry(i, yaffs_Object, siblings);
7395 /* GetEquivalentObject dereferences any hard links to get to the
7399 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
7401 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
7402 /* We want the object id of the equivalent object, not this one */
7403 obj = obj->variant.hardLinkVariant.equivalentObject;
7404 yaffs_CheckObjectDetailsLoaded(obj);
7409 int yaffs_GetObjectName(yaffs_Object *obj, YCHAR *name, int buffSize)
7411 memset(name, 0, buffSize * sizeof(YCHAR));
7413 yaffs_CheckObjectDetailsLoaded(obj);
7415 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7416 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
7417 } else if (obj->hdrChunk <= 0) {
7419 YCHAR numString[20];
7420 YCHAR *x = &numString[19];
7421 unsigned v = obj->objectId;
7425 *x = '0' + (v % 10);
7428 /* make up a name */
7429 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
7430 yaffs_strcat(locName, x);
7431 yaffs_strncpy(name, locName, buffSize - 1);
7434 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
7435 else if (obj->shortName[0])
7436 yaffs_strncpy(name, obj->shortName,YAFFS_SHORT_NAME_LENGTH+1);
7440 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
7442 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
7444 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
7446 if (obj->hdrChunk > 0) {
7447 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
7448 obj->hdrChunk, buffer,
7451 yaffs_strncpy(name, oh->name, buffSize - 1);
7454 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
7457 return yaffs_strnlen(name,buffSize-1);
7460 int yaffs_GetObjectFileLength(yaffs_Object *obj)
7462 /* Dereference any hard linking */
7463 obj = yaffs_GetEquivalentObject(obj);
7465 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
7466 return obj->variant.fileVariant.fileSize;
7467 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
7468 if(!obj->variant.symLinkVariant.alias)
7470 return yaffs_strnlen(obj->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
7472 /* Only a directory should drop through to here */
7473 return obj->myDev->nDataBytesPerChunk;
7477 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
7480 struct ylist_head *i;
7483 count++; /* the object itself */
7485 ylist_for_each(i, &obj->hardLinks)
7486 count++; /* add the hard links; */
7491 int yaffs_GetObjectInode(yaffs_Object *obj)
7493 obj = yaffs_GetEquivalentObject(obj);
7495 return obj->objectId;
7498 unsigned yaffs_GetObjectType(yaffs_Object *obj)
7500 obj = yaffs_GetEquivalentObject(obj);
7502 switch (obj->variantType) {
7503 case YAFFS_OBJECT_TYPE_FILE:
7506 case YAFFS_OBJECT_TYPE_DIRECTORY:
7509 case YAFFS_OBJECT_TYPE_SYMLINK:
7512 case YAFFS_OBJECT_TYPE_HARDLINK:
7515 case YAFFS_OBJECT_TYPE_SPECIAL:
7516 if (S_ISFIFO(obj->yst_mode))
7518 if (S_ISCHR(obj->yst_mode))
7520 if (S_ISBLK(obj->yst_mode))
7522 if (S_ISSOCK(obj->yst_mode))
7530 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
7532 obj = yaffs_GetEquivalentObject(obj);
7533 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
7534 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7536 return yaffs_CloneString(_Y(""));
7539 #ifndef CONFIG_YAFFS_WINCE
7541 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
7543 unsigned int valid = attr->ia_valid;
7545 if (valid & ATTR_MODE)
7546 obj->yst_mode = attr->ia_mode;
7547 if (valid & ATTR_UID)
7548 obj->yst_uid = attr->ia_uid;
7549 if (valid & ATTR_GID)
7550 obj->yst_gid = attr->ia_gid;
7552 if (valid & ATTR_ATIME)
7553 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7554 if (valid & ATTR_CTIME)
7555 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7556 if (valid & ATTR_MTIME)
7557 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7559 if (valid & ATTR_SIZE)
7560 yaffs_ResizeFile(obj, attr->ia_size);
7562 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7567 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
7569 unsigned int valid = 0;
7571 attr->ia_mode = obj->yst_mode;
7573 attr->ia_uid = obj->yst_uid;
7575 attr->ia_gid = obj->yst_gid;
7578 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7579 valid |= ATTR_ATIME;
7580 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7581 valid |= ATTR_CTIME;
7582 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7583 valid |= ATTR_MTIME;
7585 attr->ia_size = yaffs_GetFileSize(obj);
7588 attr->ia_valid = valid;
7596 int yaffs_DumpObject(yaffs_Object *obj)
7600 yaffs_GetObjectName(obj, name, YAFFS_MAX_NAME_LENGTH + 1);
7602 T(YAFFS_TRACE_ALWAYS,
7604 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7605 " chunk %d type %d size %d\n"
7606 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7607 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7608 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7614 /*---------------------------- Initialisation code -------------------------------------- */
7616 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
7619 /* Common functions, gotta have */
7620 if (!dev->param.eraseBlockInNAND || !dev->param.initialiseNAND)
7623 #ifdef CONFIG_YAFFS_YAFFS2
7625 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7626 if (dev->param.writeChunkWithTagsToNAND &&
7627 dev->param.readChunkWithTagsFromNAND &&
7628 !dev->param.writeChunkToNAND &&
7629 !dev->param.readChunkFromNAND &&
7630 dev->param.markNANDBlockBad &&
7631 dev->param.queryNANDBlock)
7635 /* Can use the "spare" style interface for yaffs1 */
7636 if (!dev->param.isYaffs2 &&
7637 !dev->param.writeChunkWithTagsToNAND &&
7638 !dev->param.readChunkWithTagsFromNAND &&
7639 dev->param.writeChunkToNAND &&
7640 dev->param.readChunkFromNAND &&
7641 !dev->param.markNANDBlockBad &&
7642 !dev->param.queryNANDBlock)
7649 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7651 /* Initialise the unlinked, deleted, root and lost and found directories */
7653 dev->lostNFoundDir = dev->rootDir = NULL;
7654 dev->unlinkedDir = dev->deletedDir = NULL;
7657 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7660 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7663 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7664 YAFFS_ROOT_MODE | S_IFDIR);
7665 dev->lostNFoundDir =
7666 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7667 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7669 if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
7670 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7677 int yaffs_GutsInitialise(yaffs_Device *dev)
7679 int init_failed = 0;
7683 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7685 /* Check stuff that must be set */
7688 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7692 dev->internalStartBlock = dev->param.startBlock;
7693 dev->internalEndBlock = dev->param.endBlock;
7694 dev->blockOffset = 0;
7695 dev->chunkOffset = 0;
7696 dev->nFreeChunks = 0;
7700 if (dev->param.startBlock == 0) {
7701 dev->internalStartBlock = dev->param.startBlock + 1;
7702 dev->internalEndBlock = dev->param.endBlock + 1;
7703 dev->blockOffset = 1;
7704 dev->chunkOffset = dev->param.nChunksPerBlock;
7707 /* Check geometry parameters. */
7709 if ((!dev->param.inbandTags && dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 1024) ||
7710 (!dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 512) ||
7711 (dev->param.inbandTags && !dev->param.isYaffs2) ||
7712 dev->param.nChunksPerBlock < 2 ||
7713 dev->param.nReservedBlocks < 2 ||
7714 dev->internalStartBlock <= 0 ||
7715 dev->internalEndBlock <= 0 ||
7716 dev->internalEndBlock <= (dev->internalStartBlock + dev->param.nReservedBlocks + 2)) { /* otherwise it is too small */
7717 T(YAFFS_TRACE_ALWAYS,
7719 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7720 TENDSTR), dev->param.totalBytesPerChunk, dev->param.isYaffs2 ? "2" : "", dev->param.inbandTags));
7724 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7725 T(YAFFS_TRACE_ALWAYS,
7726 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7730 /* Sort out space for inband tags, if required */
7731 if (dev->param.inbandTags)
7732 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7734 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk;
7736 /* Got the right mix of functions? */
7737 if (!yaffs_CheckDevFunctions(dev)) {
7738 /* Function missing */
7739 T(YAFFS_TRACE_ALWAYS,
7741 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7746 /* This is really a compilation check. */
7747 if (!yaffs_CheckStructures()) {
7748 T(YAFFS_TRACE_ALWAYS,
7749 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7753 if (dev->isMounted) {
7754 T(YAFFS_TRACE_ALWAYS,
7755 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7759 /* Finished with most checks. One or two more checks happen later on too. */
7763 /* OK now calculate a few things for the device */
7766 * Calculate all the chunk size manipulation numbers:
7768 x = dev->nDataBytesPerChunk;
7769 /* We always use dev->chunkShift and dev->chunkDiv */
7770 dev->chunkShift = Shifts(x);
7771 x >>= dev->chunkShift;
7773 /* We only use chunk mask if chunkDiv is 1 */
7774 dev->chunkMask = (1<<dev->chunkShift) - 1;
7777 * Calculate chunkGroupBits.
7778 * We need to find the next power of 2 > than internalEndBlock
7781 x = dev->param.nChunksPerBlock * (dev->internalEndBlock + 1);
7785 /* Set up tnode width if wide tnodes are enabled. */
7786 if (!dev->param.wideTnodesDisabled) {
7787 /* bits must be even so that we end up with 32-bit words */
7791 dev->tnodeWidth = 16;
7793 dev->tnodeWidth = bits;
7795 dev->tnodeWidth = 16;
7797 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7799 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7800 * so if the bitwidth of the
7801 * chunk range we're using is greater than 16 we need
7802 * to figure out chunk shift and chunkGroupSize
7805 if (bits <= dev->tnodeWidth)
7806 dev->chunkGroupBits = 0;
7808 dev->chunkGroupBits = bits - dev->tnodeWidth;
7811 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7813 if (dev->param.nChunksPerBlock < dev->chunkGroupSize) {
7814 /* We have a problem because the soft delete won't work if
7815 * the chunk group size > chunks per block.
7816 * This can be remedied by using larger "virtual blocks".
7818 T(YAFFS_TRACE_ALWAYS,
7819 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7824 /* OK, we've finished verifying the device, lets continue with initialisation */
7826 /* More device initialisation */
7827 dev->garbageCollections = 0;
7828 dev->passiveGarbageCollections = 0;
7829 dev->currentDirtyChecker = 0;
7830 dev->bufferedBlock = -1;
7831 dev->doingBufferedBlockRewrite = 0;
7832 dev->nDeletedFiles = 0;
7833 dev->nBackgroundDeletions = 0;
7834 dev->nUnlinkedFiles = 0;
7836 dev->eccUnfixed = 0;
7837 dev->tagsEccFixed = 0;
7838 dev->tagsEccUnfixed = 0;
7839 dev->nErasureFailures = 0;
7840 dev->nErasedBlocks = 0;
7842 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7843 YINIT_LIST_HEAD(&dev->dirtyDirectories);
7844 dev->oldestDirtySequence = 0;
7846 /* Initialise temporary buffers and caches. */
7847 if (!yaffs_InitialiseTempBuffers(dev))
7850 dev->srCache = NULL;
7851 dev->gcCleanupList = NULL;
7855 dev->param.nShortOpCaches > 0) {
7858 int srCacheBytes = dev->param.nShortOpCaches * sizeof(yaffs_ChunkCache);
7860 if (dev->param.nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
7861 dev->param.nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7863 dev->srCache = YMALLOC(srCacheBytes);
7865 buf = (__u8 *) dev->srCache;
7868 memset(dev->srCache, 0, srCacheBytes);
7870 for (i = 0; i < dev->param.nShortOpCaches && buf; i++) {
7871 dev->srCache[i].object = NULL;
7872 dev->srCache[i].lastUse = 0;
7873 dev->srCache[i].dirty = 0;
7874 dev->srCache[i].data = buf = YMALLOC_DMA(dev->param.totalBytesPerChunk);
7885 dev->gcCleanupList = YMALLOC(dev->param.nChunksPerBlock * sizeof(__u32));
7886 if (!dev->gcCleanupList)
7890 if (dev->param.isYaffs2)
7891 dev->param.useHeaderFileSize = 1;
7893 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7896 yaffs_InitialiseTnodes(dev);
7897 yaffs_InitialiseObjects(dev);
7899 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7904 /* Now scan the flash. */
7905 if (dev->param.isYaffs2) {
7906 if (yaffs_CheckpointRestore(dev)) {
7907 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7908 T(YAFFS_TRACE_ALWAYS,
7909 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7912 /* Clean up the mess caused by an aborted checkpoint load
7913 * and scan backwards.
7915 yaffs_DeinitialiseBlocks(dev);
7916 yaffs_DeinitialiseTnodes(dev);
7917 yaffs_DeinitialiseObjects(dev);
7920 dev->nErasedBlocks = 0;
7921 dev->nFreeChunks = 0;
7922 dev->allocationBlock = -1;
7923 dev->allocationPage = -1;
7924 dev->nDeletedFiles = 0;
7925 dev->nUnlinkedFiles = 0;
7926 dev->nBackgroundDeletions = 0;
7928 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7931 yaffs_InitialiseTnodes(dev);
7932 yaffs_InitialiseObjects(dev);
7934 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7937 if (!init_failed && !yaffs_ScanBackwards(dev))
7940 } else if (!yaffs_Scan(dev))
7943 yaffs_StripDeletedObjects(dev);
7944 yaffs_FixHangingObjects(dev);
7945 if(dev->param.emptyLostAndFound)
7946 yaffs_EmptyLostAndFound(dev);
7950 /* Clean up the mess */
7951 T(YAFFS_TRACE_TRACING,
7952 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7954 yaffs_Deinitialise(dev);
7958 /* Zero out stats */
7959 dev->nPageReads = 0;
7960 dev->nPageWrites = 0;
7961 dev->nBlockErasures = 0;
7963 dev->nRetriedWrites = 0;
7965 dev->nRetiredBlocks = 0;
7967 yaffs_VerifyFreeChunks(dev);
7968 yaffs_VerifyBlocks(dev);
7970 /* Clean up any aborted checkpoint data */
7971 if(!dev->isCheckpointed && dev->blocksInCheckpoint > 0)
7972 yaffs_InvalidateCheckpoint(dev);
7974 T(YAFFS_TRACE_TRACING,
7975 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7980 void yaffs_Deinitialise(yaffs_Device *dev)
7982 if (dev->isMounted) {
7985 yaffs_DeinitialiseBlocks(dev);
7986 yaffs_DeinitialiseTnodes(dev);
7987 yaffs_DeinitialiseObjects(dev);
7988 if (dev->param.nShortOpCaches > 0 &&
7991 for (i = 0; i < dev->param.nShortOpCaches; i++) {
7992 if (dev->srCache[i].data)
7993 YFREE(dev->srCache[i].data);
7994 dev->srCache[i].data = NULL;
7997 YFREE(dev->srCache);
7998 dev->srCache = NULL;
8001 YFREE(dev->gcCleanupList);
8003 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
8004 YFREE(dev->tempBuffer[i].buffer);
8008 if (dev->param.deinitialiseNAND)
8009 dev->param.deinitialiseNAND(dev);
8013 static int yaffs_CountFreeChunks(yaffs_Device *dev)
8018 yaffs_BlockInfo *blk;
8020 blk = dev->blockInfo;
8021 for (b = dev->internalStartBlock; b <= dev->internalEndBlock; b++) {
8022 switch (blk->blockState) {
8023 case YAFFS_BLOCK_STATE_EMPTY:
8024 case YAFFS_BLOCK_STATE_ALLOCATING:
8025 case YAFFS_BLOCK_STATE_COLLECTING:
8026 case YAFFS_BLOCK_STATE_FULL:
8028 (dev->param.nChunksPerBlock - blk->pagesInUse +
8029 blk->softDeletions);
8040 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
8042 /* This is what we report to the outside world */
8045 int nDirtyCacheChunks;
8046 int blocksForCheckpoint;
8050 nFree = dev->nFreeChunks;
8052 nFree = yaffs_CountFreeChunks(dev);
8055 nFree += dev->nDeletedFiles;
8057 /* Now count the number of dirty chunks in the cache and subtract those */
8059 for (nDirtyCacheChunks = 0, i = 0; i < dev->param.nShortOpCaches; i++) {
8060 if (dev->srCache[i].dirty)
8061 nDirtyCacheChunks++;
8064 nFree -= nDirtyCacheChunks;
8066 nFree -= ((dev->param.nReservedBlocks + 1) * dev->param.nChunksPerBlock);
8068 /* Now we figure out how much to reserve for the checkpoint and report that... */
8069 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
8070 if (blocksForCheckpoint < 0)
8071 blocksForCheckpoint = 0;
8073 nFree -= (blocksForCheckpoint * dev->param.nChunksPerBlock);
8082 static int yaffs_freeVerificationFailures;
8084 static void yaffs_VerifyFreeChunks(yaffs_Device *dev)
8089 if (yaffs_SkipVerification(dev))
8092 counted = yaffs_CountFreeChunks(dev);
8094 difference = dev->nFreeChunks - counted;
8097 T(YAFFS_TRACE_ALWAYS,
8098 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
8099 dev->nFreeChunks, counted, difference));
8100 yaffs_freeVerificationFailures++;
8104 /*---------------------------------------- YAFFS test code ----------------------*/
8106 #define yaffs_CheckStruct(structure, syze, name) \
8108 if (sizeof(structure) != syze) { \
8109 T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
8110 name, syze, (int) sizeof(structure))); \
8111 return YAFFS_FAIL; \
8115 static int yaffs_CheckStructures(void)
8117 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
8118 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
8119 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
8120 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
8121 /* yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode"); */
8123 #ifndef CONFIG_YAFFS_WINCE
8124 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");