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.117 2010-03-11 02:44:43 charles Exp $";
18 #include "yaffs_trace.h"
20 #include "yaffsinterface.h"
21 #include "yaffs_guts.h"
22 #include "yaffs_tagsvalidity.h"
23 #include "yaffs_getblockinfo.h"
25 #include "yaffs_tagscompat.h"
26 #ifndef CONFIG_YAFFS_USE_OWN_SORT
27 #include "yaffs_qsort.h"
29 #include "yaffs_nand.h"
31 #include "yaffs_checkptrw.h"
33 #include "yaffs_nand.h"
34 #include "yaffs_packedtags2.h"
37 #define YAFFS_PASSIVE_GC_CHUNKS 2
39 #include "yaffs_ecc.h"
42 /* Robustification (if it ever comes about...) */
43 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND);
44 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
46 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
48 const yaffs_ExtendedTags *tags);
49 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
50 const yaffs_ExtendedTags *tags);
52 /* Other local prototypes */
53 static void yaffs_UpdateParent(yaffs_Object *obj);
54 static int yaffs_UnlinkObject(yaffs_Object *obj);
55 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
57 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
59 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev,
61 yaffs_ExtendedTags *tags,
63 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
64 int chunkInNAND, int inScan);
66 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
67 yaffs_ObjectType type);
68 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
70 static int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name,
71 int force, int isShrink, int shadows);
72 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
73 static int yaffs_CheckStructures(void);
74 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
75 int chunkOffset, int *limit);
76 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
78 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev, int blockNo);
81 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
84 static int yaffs_UnlinkWorker(yaffs_Object *obj);
86 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
89 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
90 yaffs_BlockInfo **blockUsedPtr);
92 static void yaffs_VerifyFreeChunks(yaffs_Device *dev);
94 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
96 static void yaffs_VerifyDirectory(yaffs_Object *directory);
98 static int yaffs_CheckFileSanity(yaffs_Object *in);
100 #define yaffs_CheckFileSanity(in)
103 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
104 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
106 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
108 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
109 yaffs_ExtendedTags *tags);
111 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
113 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
114 yaffs_FileStructure *fStruct,
117 static void yaffs_SkipRestOfBlock(yaffs_Device *dev);
118 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
121 yaffs_ExtendedTags *tags);
123 /* Function to calculate chunk and offset */
125 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut,
131 chunk = (__u32)(addr >> dev->chunkShift);
133 if (dev->chunkDiv == 1) {
134 /* easy power of 2 case */
135 offset = (__u32)(addr & dev->chunkMask);
137 /* Non power-of-2 case */
141 chunk /= dev->chunkDiv;
143 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
144 offset = (__u32)(addr - chunkBase);
151 /* Function to return the number of shifts for a power of 2 greater than or
152 * equal to the given number
153 * Note we don't try to cater for all possible numbers and this does not have to
154 * be hellishly efficient.
157 static __u32 ShiftsGE(__u32 x)
162 nShifts = extraBits = 0;
177 /* Function to return the number of shifts to get a 1 in bit 0
180 static __u32 Shifts(__u32 x)
200 * Temporary buffer manipulations.
203 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
206 __u8 *buf = (__u8 *)1;
208 memset(dev->tempBuffer, 0, sizeof(dev->tempBuffer));
210 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
211 dev->tempBuffer[i].line = 0; /* not in use */
212 dev->tempBuffer[i].buffer = buf =
213 YMALLOC_DMA(dev->param.totalBytesPerChunk);
216 return buf ? YAFFS_OK : YAFFS_FAIL;
219 __u8 *yaffs_GetTempBuffer(yaffs_Device *dev, int lineNo)
224 if (dev->tempInUse > dev->maxTemp)
225 dev->maxTemp = dev->tempInUse;
227 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
228 if (dev->tempBuffer[i].line == 0) {
229 dev->tempBuffer[i].line = lineNo;
230 if ((i + 1) > dev->maxTemp) {
231 dev->maxTemp = i + 1;
232 for (j = 0; j <= i; j++)
233 dev->tempBuffer[j].maxLine =
234 dev->tempBuffer[j].line;
237 return dev->tempBuffer[i].buffer;
241 T(YAFFS_TRACE_BUFFERS,
242 (TSTR("Out of temp buffers at line %d, other held by lines:"),
244 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
245 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
247 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
250 * If we got here then we have to allocate an unmanaged one
254 dev->unmanagedTempAllocations++;
255 return YMALLOC(dev->nDataBytesPerChunk);
259 void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer,
266 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
267 if (dev->tempBuffer[i].buffer == buffer) {
268 dev->tempBuffer[i].line = 0;
274 /* assume it is an unmanaged one. */
275 T(YAFFS_TRACE_BUFFERS,
276 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
279 dev->unmanagedTempDeallocations++;
285 * Determine if we have a managed buffer.
287 int yaffs_IsManagedTempBuffer(yaffs_Device *dev, const __u8 *buffer)
291 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
292 if (dev->tempBuffer[i].buffer == buffer)
296 for (i = 0; i < dev->param.nShortOpCaches; i++) {
297 if (dev->srCache[i].data == buffer)
301 if (buffer == dev->checkpointBuffer)
304 T(YAFFS_TRACE_ALWAYS,
305 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
312 * Chunk bitmap manipulations
315 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
317 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
319 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
323 return dev->chunkBits +
324 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
327 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
329 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
330 chunk < 0 || chunk >= dev->param.nChunksPerBlock) {
332 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),
338 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device *dev, int blk)
340 __u8 *blkBits = yaffs_BlockBits(dev, blk);
342 memset(blkBits, 0, dev->chunkBitmapStride);
345 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device *dev, int blk, int chunk)
347 __u8 *blkBits = yaffs_BlockBits(dev, blk);
349 yaffs_VerifyChunkBitId(dev, blk, chunk);
351 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
354 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device *dev, int blk, int chunk)
356 __u8 *blkBits = yaffs_BlockBits(dev, blk);
358 yaffs_VerifyChunkBitId(dev, blk, chunk);
360 blkBits[chunk / 8] |= (1 << (chunk & 7));
363 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device *dev, int blk, int chunk)
365 __u8 *blkBits = yaffs_BlockBits(dev, blk);
366 yaffs_VerifyChunkBitId(dev, blk, chunk);
368 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
371 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device *dev, int blk)
373 __u8 *blkBits = yaffs_BlockBits(dev, blk);
375 for (i = 0; i < dev->chunkBitmapStride; i++) {
383 static int yaffs_CountChunkBits(yaffs_Device *dev, int blk)
385 __u8 *blkBits = yaffs_BlockBits(dev, blk);
388 for (i = 0; i < dev->chunkBitmapStride; i++) {
405 static int yaffs_SkipVerification(yaffs_Device *dev)
408 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
411 static int yaffs_SkipFullVerification(yaffs_Device *dev)
414 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
417 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
420 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
423 static const char *blockStateName[] = {
436 static void yaffs_VerifyBlock(yaffs_Device *dev, yaffs_BlockInfo *bi, int n)
441 if (yaffs_SkipVerification(dev))
444 /* Report illegal runtime states */
445 if (bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
446 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has undefined state %d"TENDSTR), n, bi->blockState));
448 switch (bi->blockState) {
449 case YAFFS_BLOCK_STATE_UNKNOWN:
450 case YAFFS_BLOCK_STATE_SCANNING:
451 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
452 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has bad run-state %s"TENDSTR),
453 n, blockStateName[bi->blockState]));
456 /* Check pages in use and soft deletions are legal */
458 actuallyUsed = bi->pagesInUse - bi->softDeletions;
460 if (bi->pagesInUse < 0 || bi->pagesInUse > dev->param.nChunksPerBlock ||
461 bi->softDeletions < 0 || bi->softDeletions > dev->param.nChunksPerBlock ||
462 actuallyUsed < 0 || actuallyUsed > dev->param.nChunksPerBlock)
463 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
464 n, bi->pagesInUse, bi->softDeletions));
467 /* Check chunk bitmap legal */
468 inUse = yaffs_CountChunkBits(dev, n);
469 if (inUse != bi->pagesInUse)
470 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
471 n, bi->pagesInUse, inUse));
473 /* Check that the sequence number is valid.
474 * Ten million is legal, but is very unlikely
476 if (dev->param.isYaffs2 &&
477 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
478 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000))
479 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has suspect sequence number of %d"TENDSTR),
480 n, bi->sequenceNumber));
483 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev, yaffs_BlockInfo *bi,
486 yaffs_VerifyBlock(dev, bi, n);
488 /* After collection the block should be in the erased state */
489 /* This will need to change if we do partial gc */
491 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
492 bi->blockState != YAFFS_BLOCK_STATE_EMPTY) {
493 T(YAFFS_TRACE_ERROR, (TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
498 static void yaffs_VerifyBlocks(yaffs_Device *dev)
501 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
502 int nIllegalBlockStates = 0;
504 if (yaffs_SkipVerification(dev))
507 memset(nBlocksPerState, 0, sizeof(nBlocksPerState));
509 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
510 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, i);
511 yaffs_VerifyBlock(dev, bi, i);
513 if (bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
514 nBlocksPerState[bi->blockState]++;
516 nIllegalBlockStates++;
519 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
520 T(YAFFS_TRACE_VERIFY, (TSTR("Block summary"TENDSTR)));
522 T(YAFFS_TRACE_VERIFY, (TSTR("%d blocks have illegal states"TENDSTR), nIllegalBlockStates));
523 if (nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
524 T(YAFFS_TRACE_VERIFY, (TSTR("Too many allocating blocks"TENDSTR)));
526 for (i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
527 T(YAFFS_TRACE_VERIFY,
528 (TSTR("%s %d blocks"TENDSTR),
529 blockStateName[i], nBlocksPerState[i]));
531 if (dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
532 T(YAFFS_TRACE_VERIFY,
533 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
534 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
536 if (dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
537 T(YAFFS_TRACE_VERIFY,
538 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
539 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
541 if (nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
542 T(YAFFS_TRACE_VERIFY,
543 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
544 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
546 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
551 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
552 * case those tests will not be performed.
554 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
556 if (obj && yaffs_SkipVerification(obj->myDev))
559 if (!(tags && obj && oh)) {
560 T(YAFFS_TRACE_VERIFY,
561 (TSTR("Verifying object header tags %p obj %p oh %p"TENDSTR),
566 if (oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
567 oh->type > YAFFS_OBJECT_TYPE_MAX)
568 T(YAFFS_TRACE_VERIFY,
569 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
570 tags->objectId, oh->type));
572 if (tags->objectId != obj->objectId)
573 T(YAFFS_TRACE_VERIFY,
574 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
575 tags->objectId, obj->objectId));
579 * Check that the object's parent ids match if parentCheck requested.
581 * Tests do not apply to the root object.
584 if (parentCheck && tags->objectId > 1 && !obj->parent)
585 T(YAFFS_TRACE_VERIFY,
586 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
587 tags->objectId, oh->parentObjectId));
589 if (parentCheck && obj->parent &&
590 oh->parentObjectId != obj->parent->objectId &&
591 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
592 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
593 T(YAFFS_TRACE_VERIFY,
594 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
595 tags->objectId, oh->parentObjectId, obj->parent->objectId));
597 if (tags->objectId > 1 && oh->name[0] == 0) /* Null name */
598 T(YAFFS_TRACE_VERIFY,
599 (TSTR("Obj %d header name is NULL"TENDSTR),
602 if (tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
603 T(YAFFS_TRACE_VERIFY,
604 (TSTR("Obj %d header name is 0xFF"TENDSTR),
610 static int yaffs_VerifyTnodeWorker(yaffs_Object *obj, yaffs_Tnode *tn,
611 __u32 level, int chunkOffset)
614 yaffs_Device *dev = obj->myDev;
620 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
621 if (tn->internal[i]) {
622 ok = yaffs_VerifyTnodeWorker(obj,
625 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
628 } else if (level == 0) {
629 yaffs_ExtendedTags tags;
630 __u32 objectId = obj->objectId;
632 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
634 for (i = 0; i < YAFFS_NTNODES_LEVEL0; i++) {
635 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
638 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
639 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
640 if (tags.objectId != objectId || tags.chunkId != chunkOffset) {
641 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
642 objectId, chunkOffset, theChunk,
643 tags.objectId, tags.chunkId));
656 static void yaffs_VerifyFile(yaffs_Object *obj)
658 int requiredTallness;
664 yaffs_ExtendedTags tags;
671 if (yaffs_SkipVerification(obj->myDev))
675 objectId = obj->objectId;
677 /* Check file size is consistent with tnode depth */
678 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
679 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
680 requiredTallness = 0;
682 x >>= YAFFS_TNODES_INTERNAL_BITS;
686 actualTallness = obj->variant.fileVariant.topLevel;
688 /* Check that the chunks in the tnode tree are all correct.
689 * We do this by scanning through the tnode tree and
690 * checking the tags for every chunk match.
693 if (yaffs_SkipNANDVerification(dev))
696 for (i = 1; i <= lastChunk; i++) {
697 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant, i);
700 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
702 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
703 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
704 if (tags.objectId != objectId || tags.chunkId != i) {
705 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
706 objectId, i, theChunk,
707 tags.objectId, tags.chunkId));
715 static void yaffs_VerifyHardLink(yaffs_Object *obj)
717 if (obj && yaffs_SkipVerification(obj->myDev))
720 /* Verify sane equivalent object */
723 static void yaffs_VerifySymlink(yaffs_Object *obj)
725 if (obj && yaffs_SkipVerification(obj->myDev))
728 /* Verify symlink string */
731 static void yaffs_VerifySpecial(yaffs_Object *obj)
733 if (obj && yaffs_SkipVerification(obj->myDev))
737 static void yaffs_VerifyObject(yaffs_Object *obj)
746 __u32 chunkShouldNotBeDeleted;
752 if (obj->beingCreated)
757 if (yaffs_SkipVerification(dev))
760 /* Check sane object header chunk */
762 chunkMin = dev->internalStartBlock * dev->param.nChunksPerBlock;
763 chunkMax = (dev->internalEndBlock+1) * dev->param.nChunksPerBlock - 1;
765 chunkInRange = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
766 chunkIdOk = chunkInRange || (obj->hdrChunk == 0);
767 chunkValid = chunkInRange &&
768 yaffs_CheckChunkBit(dev,
769 obj->hdrChunk / dev->param.nChunksPerBlock,
770 obj->hdrChunk % dev->param.nChunksPerBlock);
771 chunkShouldNotBeDeleted = chunkInRange && !chunkValid;
774 (!chunkIdOk || chunkShouldNotBeDeleted)) {
775 T(YAFFS_TRACE_VERIFY,
776 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
777 obj->objectId, obj->hdrChunk,
778 chunkIdOk ? "" : ",out of range",
779 chunkShouldNotBeDeleted ? ",marked as deleted" : ""));
782 if (chunkValid && !yaffs_SkipNANDVerification(dev)) {
783 yaffs_ExtendedTags tags;
784 yaffs_ObjectHeader *oh;
785 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
787 oh = (yaffs_ObjectHeader *)buffer;
789 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk, buffer,
792 yaffs_VerifyObjectHeader(obj, oh, &tags, 1);
794 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
797 /* Verify it has a parent */
798 if (obj && !obj->fake &&
799 (!obj->parent || obj->parent->myDev != dev)) {
800 T(YAFFS_TRACE_VERIFY,
801 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
802 obj->objectId, obj->parent));
805 /* Verify parent is a directory */
806 if (obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
807 T(YAFFS_TRACE_VERIFY,
808 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
809 obj->objectId, obj->parent->variantType));
812 switch (obj->variantType) {
813 case YAFFS_OBJECT_TYPE_FILE:
814 yaffs_VerifyFile(obj);
816 case YAFFS_OBJECT_TYPE_SYMLINK:
817 yaffs_VerifySymlink(obj);
819 case YAFFS_OBJECT_TYPE_DIRECTORY:
820 yaffs_VerifyDirectory(obj);
822 case YAFFS_OBJECT_TYPE_HARDLINK:
823 yaffs_VerifyHardLink(obj);
825 case YAFFS_OBJECT_TYPE_SPECIAL:
826 yaffs_VerifySpecial(obj);
828 case YAFFS_OBJECT_TYPE_UNKNOWN:
830 T(YAFFS_TRACE_VERIFY,
831 (TSTR("Obj %d has illegaltype %d"TENDSTR),
832 obj->objectId, obj->variantType));
837 static void yaffs_VerifyObjects(yaffs_Device *dev)
841 struct ylist_head *lh;
843 if (yaffs_SkipVerification(dev))
846 /* Iterate through the objects in each hash entry */
848 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
849 ylist_for_each(lh, &dev->objectBucket[i].list) {
851 obj = ylist_entry(lh, yaffs_Object, hashLink);
852 yaffs_VerifyObject(obj);
860 * Simple hash function. Needs to have a reasonable spread
863 static Y_INLINE int yaffs_HashFunction(int n)
866 return n % YAFFS_NOBJECT_BUCKETS;
870 * Access functions to useful fake objects.
871 * Note that root might have a presence in NAND if permissions are set.
874 yaffs_Object *yaffs_Root(yaffs_Device *dev)
879 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
881 return dev->lostNFoundDir;
886 * Erased NAND checking functions
889 int yaffs_CheckFF(__u8 *buffer, int nBytes)
891 /* Horrible, slow implementation */
900 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
903 int retval = YAFFS_OK;
904 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
905 yaffs_ExtendedTags tags;
908 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
910 if (tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
913 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
914 T(YAFFS_TRACE_NANDACCESS,
915 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
919 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
926 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
929 yaffs_ExtendedTags *tags)
931 int retval = YAFFS_OK;
932 yaffs_ExtendedTags tempTags;
933 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
936 result = yaffs_ReadChunkWithTagsFromNAND(dev,chunkInNAND,buffer,&tempTags);
937 if(memcmp(buffer,data,dev->nDataBytesPerChunk) ||
938 tempTags.objectId != tags->objectId ||
939 tempTags.chunkId != tags->chunkId ||
940 tempTags.byteCount != tags->byteCount)
943 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
948 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
950 yaffs_ExtendedTags *tags,
957 yaffs_InvalidateCheckpoint(dev);
960 yaffs_BlockInfo *bi = 0;
963 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
969 /* First check this chunk is erased, if it needs
970 * checking. The checking policy (unless forced
971 * always on) is as follows:
973 * Check the first page we try to write in a block.
974 * If the check passes then we don't need to check any
975 * more. If the check fails, we check again...
976 * If the block has been erased, we don't need to check.
978 * However, if the block has been prioritised for gc,
979 * then we think there might be something odd about
980 * this block and stop using it.
982 * Rationale: We should only ever see chunks that have
983 * not been erased if there was a partially written
984 * chunk due to power loss. This checking policy should
985 * catch that case with very few checks and thus save a
986 * lot of checks that are most likely not needed.
989 * If an erase check fails or the write fails we skip the
993 /* let's give it a try */
996 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
997 bi->skipErasedCheck = 0;
999 if (!bi->skipErasedCheck) {
1000 erasedOk = yaffs_CheckChunkErased(dev, chunk);
1001 if (erasedOk != YAFFS_OK) {
1002 T(YAFFS_TRACE_ERROR,
1003 (TSTR("**>> yaffs chunk %d was not erased"
1006 /* If not erased, delete this one,
1007 * skip rest of block and
1008 * try another chunk */
1009 yaffs_DeleteChunk(dev,chunk,1,__LINE__);
1010 yaffs_SkipRestOfBlock(dev);
1015 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
1018 if(!bi->skipErasedCheck)
1019 writeOk = yaffs_VerifyChunkWritten(dev, chunk, data, tags);
1021 if (writeOk != YAFFS_OK) {
1022 /* Clean up aborted write, skip to next block and
1023 * try another chunk */
1024 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
1028 bi->skipErasedCheck = 1;
1030 /* Copy the data into the robustification buffer */
1031 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1033 } while (writeOk != YAFFS_OK &&
1034 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1040 T(YAFFS_TRACE_ERROR,
1041 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1044 dev->nRetriedWrites += (attempts - 1);
1052 * Oldest Dirty Sequence Number handling.
1055 /* yaffs_CalcOldestDirtySequence()
1056 * yaffs_FindOldestDirtySequence()
1057 * Calculate the oldest dirty sequence number if we don't know it.
1059 static int yaffs_CalcOldestDirtySequence(yaffs_Device *dev)
1063 yaffs_BlockInfo *b = 0;
1065 if(!dev->param.isYaffs2)
1068 /* Find the oldest dirty sequence number. */
1069 seq = dev->sequenceNumber;
1070 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
1071 b = yaffs_GetBlockInfo(dev, i);
1072 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
1073 (b->pagesInUse - b->softDeletions) < dev->param.nChunksPerBlock &&
1074 b->sequenceNumber < seq)
1075 seq = b->sequenceNumber;
1081 static void yaffs_FindOldestDirtySequence(yaffs_Device *dev)
1083 if(dev->param.isYaffs2 && !dev->oldestDirtySequence)
1084 dev->oldestDirtySequence =
1085 yaffs_CalcOldestDirtySequence(dev);
1088 if(!yaffs_SkipVerification(dev) &&
1089 dev->oldestDirtySequence != yaffs_CalcOldestDirtySequence(dev))
1096 * yaffs_ClearOldestDirtySequence()
1097 * Called when a block is erased or marked bad. (ie. when its sequenceNumber
1098 * becomes invalid). If the value matches the oldest then we clear
1099 * dev->oldestDirtySequence to force its recomputation.
1101 static void yaffs_ClearOldestDirtySequence(yaffs_Device *dev, yaffs_BlockInfo *bi)
1104 if(!dev->param.isYaffs2)
1107 if(!bi || bi->sequenceNumber == dev->oldestDirtySequence)
1108 dev->oldestDirtySequence = 0;
1112 * yaffs_UpdateOldestDirtySequence()
1113 * Update the oldest dirty sequence number whenever we dirty a block.
1114 * Only do this if the oldestDirtySequence is actually being tracked.
1116 static void yaffs_UpdateOldestDirtySequence(yaffs_Device *dev, yaffs_BlockInfo *bi)
1118 if(dev->param.isYaffs2 && dev->oldestDirtySequence){
1119 if(dev->oldestDirtySequence > bi->sequenceNumber)
1120 dev->oldestDirtySequence = bi->sequenceNumber;
1125 * Block retiring for handling a broken block.
1128 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND)
1130 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1132 yaffs_InvalidateCheckpoint(dev);
1134 yaffs_ClearOldestDirtySequence(dev,bi);
1136 if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
1137 if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
1138 T(YAFFS_TRACE_ALWAYS, (TSTR(
1139 "yaffs: Failed to mark bad and erase block %d"
1140 TENDSTR), blockInNAND));
1142 yaffs_ExtendedTags tags;
1143 int chunkId = blockInNAND * dev->param.nChunksPerBlock;
1145 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
1147 memset(buffer, 0xff, dev->nDataBytesPerChunk);
1148 yaffs_InitialiseTags(&tags);
1149 tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
1150 if (dev->param.writeChunkWithTagsToNAND(dev, chunkId -
1151 dev->chunkOffset, buffer, &tags) != YAFFS_OK)
1152 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
1153 TCONT("write bad block marker to block %d")
1154 TENDSTR), blockInNAND));
1156 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
1160 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1161 bi->gcPrioritise = 0;
1162 bi->needsRetiring = 0;
1164 dev->nRetiredBlocks++;
1168 * Functions for robustisizing TODO
1172 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
1174 const yaffs_ExtendedTags *tags)
1177 chunkInNAND=chunkInNAND;
1182 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
1183 const yaffs_ExtendedTags *tags)
1186 chunkInNAND=chunkInNAND;
1190 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1192 if (!bi->gcPrioritise) {
1193 bi->gcPrioritise = 1;
1194 dev->hasPendingPrioritisedGCs = 1;
1195 bi->chunkErrorStrikes++;
1197 if (bi->chunkErrorStrikes > 3) {
1198 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1199 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1205 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
1208 int blockInNAND = chunkInNAND / dev->param.nChunksPerBlock;
1209 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1211 yaffs_HandleChunkError(dev, bi);
1214 /* Was an actual write failure, so mark the block for retirement */
1215 bi->needsRetiring = 1;
1216 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1217 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1220 /* Delete the chunk */
1221 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1222 yaffs_SkipRestOfBlock(dev);
1226 /*---------------- Name handling functions ------------*/
1228 static __u16 yaffs_CalcNameSum(const YCHAR *name)
1233 const YUCHAR *bname = (const YUCHAR *) name;
1235 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1237 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1238 sum += yaffs_toupper(*bname) * i;
1240 sum += (*bname) * i;
1249 static void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
1251 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1252 memset(obj->shortName, 0, sizeof(YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1253 if (name && yaffs_strnlen(name,YAFFS_SHORT_NAME_LENGTH+1) <= YAFFS_SHORT_NAME_LENGTH)
1254 yaffs_strcpy(obj->shortName, name);
1256 obj->shortName[0] = _Y('\0');
1258 obj->sum = yaffs_CalcNameSum(name);
1261 /*-------------------- TNODES -------------------
1263 * List of spare tnodes
1264 * The list is hooked together using the first pointer
1268 /* yaffs_CreateTnodes creates a bunch more tnodes and
1269 * adds them to the tnode free list.
1270 * Don't use this function directly
1272 static Y_INLINE int yaffs_CalcTnodeSize(yaffs_Device *dev)
1275 /* Calculate the tnode size in bytes for variable width tnode support.
1276 * Must be a multiple of 32-bits */
1277 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1279 if (tnodeSize < sizeof(yaffs_Tnode))
1280 tnodeSize = sizeof(yaffs_Tnode);
1284 static int yaffs_CreateTnodes(yaffs_Device *dev, int nTnodes)
1287 int tnodeSize = yaffs_CalcTnodeSize(dev);
1288 yaffs_Tnode *newTnodes;
1292 yaffs_TnodeList *tnl;
1298 /* make these things */
1300 newTnodes = YMALLOC(nTnodes * tnodeSize);
1301 mem = (__u8 *)newTnodes;
1304 T(YAFFS_TRACE_ERROR,
1305 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1309 /* Hook them into the free list */
1311 for (i = 0; i < nTnodes - 1; i++) {
1312 newTnodes[i].internal[0] = &newTnodes[i + 1];
1313 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1314 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1318 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1319 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1320 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1322 dev->freeTnodes = newTnodes;
1324 /* New hookup for wide tnodes */
1325 for (i = 0; i < nTnodes - 1; i++) {
1326 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1327 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1328 curr->internal[0] = next;
1331 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1332 curr->internal[0] = dev->freeTnodes;
1333 dev->freeTnodes = (yaffs_Tnode *)mem;
1338 dev->nFreeTnodes += nTnodes;
1339 dev->nTnodesCreated += nTnodes;
1341 /* Now add this bunch of tnodes to a list for freeing up.
1342 * NB If we can't add this to the management list it isn't fatal
1343 * but it just means we can't free this bunch of tnodes later.
1346 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1348 T(YAFFS_TRACE_ERROR,
1350 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1353 tnl->tnodes = newTnodes;
1354 tnl->next = dev->allocatedTnodeList;
1355 dev->allocatedTnodeList = tnl;
1358 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1363 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1365 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device *dev)
1367 yaffs_Tnode *tn = NULL;
1369 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1370 tn = YMALLOC(yaffs_CalcTnodeSize(dev));
1372 dev->nTnodesCreated++;
1374 /* If there are none left make more */
1375 if (!dev->freeTnodes)
1376 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1378 if (dev->freeTnodes) {
1379 tn = dev->freeTnodes;
1380 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1381 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1382 /* Hoosterman, this thing looks like it isn't in the list */
1383 T(YAFFS_TRACE_ALWAYS,
1384 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1387 dev->freeTnodes = dev->freeTnodes->internal[0];
1391 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1396 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
1398 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1399 int tnodeSize = yaffs_CalcTnodeSize(dev);
1402 memset(tn, 0, tnodeSize);
1407 /* FreeTnode frees up a tnode and puts it back on the free list */
1408 static void yaffs_FreeTnode(yaffs_Device *dev, yaffs_Tnode *tn)
1411 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1413 dev->nTnodesCreated--;
1415 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1416 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1417 /* Hoosterman, this thing looks like it is already in the list */
1418 T(YAFFS_TRACE_ALWAYS,
1419 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1421 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1423 tn->internal[0] = dev->freeTnodes;
1424 dev->freeTnodes = tn;
1428 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1431 static void yaffs_DeinitialiseTnodes(yaffs_Device *dev)
1433 /* Free the list of allocated tnodes */
1434 yaffs_TnodeList *tmp;
1436 while (dev->allocatedTnodeList) {
1437 tmp = dev->allocatedTnodeList->next;
1439 YFREE(dev->allocatedTnodeList->tnodes);
1440 YFREE(dev->allocatedTnodeList);
1441 dev->allocatedTnodeList = tmp;
1445 dev->freeTnodes = NULL;
1446 dev->nFreeTnodes = 0;
1447 dev->nTnodesCreated = 0;
1450 static void yaffs_InitialiseTnodes(yaffs_Device *dev)
1452 dev->allocatedTnodeList = NULL;
1453 dev->freeTnodes = NULL;
1454 dev->nFreeTnodes = 0;
1455 dev->nTnodesCreated = 0;
1459 void yaffs_LoadLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
1462 __u32 *map = (__u32 *)tn;
1468 pos &= YAFFS_TNODES_LEVEL0_MASK;
1469 val >>= dev->chunkGroupBits;
1471 bitInMap = pos * dev->tnodeWidth;
1472 wordInMap = bitInMap / 32;
1473 bitInWord = bitInMap & (32 - 1);
1475 mask = dev->tnodeMask << bitInWord;
1477 map[wordInMap] &= ~mask;
1478 map[wordInMap] |= (mask & (val << bitInWord));
1480 if (dev->tnodeWidth > (32 - bitInWord)) {
1481 bitInWord = (32 - bitInWord);
1483 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1484 map[wordInMap] &= ~mask;
1485 map[wordInMap] |= (mask & (val >> bitInWord));
1489 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
1492 __u32 *map = (__u32 *)tn;
1498 pos &= YAFFS_TNODES_LEVEL0_MASK;
1500 bitInMap = pos * dev->tnodeWidth;
1501 wordInMap = bitInMap / 32;
1502 bitInWord = bitInMap & (32 - 1);
1504 val = map[wordInMap] >> bitInWord;
1506 if (dev->tnodeWidth > (32 - bitInWord)) {
1507 bitInWord = (32 - bitInWord);
1509 val |= (map[wordInMap] << bitInWord);
1512 val &= dev->tnodeMask;
1513 val <<= dev->chunkGroupBits;
1518 /* ------------------- End of individual tnode manipulation -----------------*/
1520 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1521 * The look up tree is represented by the top tnode and the number of topLevel
1522 * in the tree. 0 means only the level 0 tnode is in the tree.
1525 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1526 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
1527 yaffs_FileStructure *fStruct,
1530 yaffs_Tnode *tn = fStruct->top;
1532 int requiredTallness;
1533 int level = fStruct->topLevel;
1537 /* Check sane level and chunk Id */
1538 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
1541 if (chunkId > YAFFS_MAX_CHUNK_ID)
1544 /* First check we're tall enough (ie enough topLevel) */
1546 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1547 requiredTallness = 0;
1549 i >>= YAFFS_TNODES_INTERNAL_BITS;
1553 if (requiredTallness > fStruct->topLevel)
1554 return NULL; /* Not tall enough, so we can't find it */
1556 /* Traverse down to level 0 */
1557 while (level > 0 && tn) {
1558 tn = tn->internal[(chunkId >>
1559 (YAFFS_TNODES_LEVEL0_BITS +
1561 YAFFS_TNODES_INTERNAL_BITS)) &
1562 YAFFS_TNODES_INTERNAL_MASK];
1569 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1570 * This happens in two steps:
1571 * 1. If the tree isn't tall enough, then make it taller.
1572 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1574 * Used when modifying the tree.
1576 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1577 * be plugged into the ttree.
1580 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
1581 yaffs_FileStructure *fStruct,
1583 yaffs_Tnode *passedTn)
1585 int requiredTallness;
1593 /* Check sane level and page Id */
1594 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
1597 if (chunkId > YAFFS_MAX_CHUNK_ID)
1600 /* First check we're tall enough (ie enough topLevel) */
1602 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1603 requiredTallness = 0;
1605 x >>= YAFFS_TNODES_INTERNAL_BITS;
1610 if (requiredTallness > fStruct->topLevel) {
1611 /* Not tall enough, gotta make the tree taller */
1612 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1614 tn = yaffs_GetTnode(dev);
1617 tn->internal[0] = fStruct->top;
1619 fStruct->topLevel++;
1621 T(YAFFS_TRACE_ERROR,
1622 (TSTR("yaffs: no more tnodes" TENDSTR)));
1628 /* Traverse down to level 0, adding anything we need */
1630 l = fStruct->topLevel;
1634 while (l > 0 && tn) {
1636 (YAFFS_TNODES_LEVEL0_BITS +
1637 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1638 YAFFS_TNODES_INTERNAL_MASK;
1641 if ((l > 1) && !tn->internal[x]) {
1642 /* Add missing non-level-zero tnode */
1643 tn->internal[x] = yaffs_GetTnode(dev);
1644 if(!tn->internal[x])
1646 } else if (l == 1) {
1647 /* Looking from level 1 at level 0 */
1649 /* If we already have one, then release it.*/
1650 if (tn->internal[x])
1651 yaffs_FreeTnode(dev, tn->internal[x]);
1652 tn->internal[x] = passedTn;
1654 } else if (!tn->internal[x]) {
1655 /* Don't have one, none passed in */
1656 tn->internal[x] = yaffs_GetTnode(dev);
1657 if(!tn->internal[x])
1662 tn = tn->internal[x];
1666 /* top is level 0 */
1668 memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1669 yaffs_FreeTnode(dev, passedTn);
1676 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
1677 yaffs_ExtendedTags *tags, int objectId,
1682 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1683 if (yaffs_CheckChunkBit(dev, theChunk / dev->param.nChunksPerBlock,
1684 theChunk % dev->param.nChunksPerBlock)) {
1686 if(dev->chunkGroupSize == 1)
1689 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1691 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1703 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1704 * chunks and tnodes in the file
1705 * Returns 1 if the tree was deleted.
1706 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1709 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
1710 int chunkOffset, int *limit)
1715 yaffs_ExtendedTags tags;
1717 yaffs_Device *dev = in->myDev;
1723 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1725 if (tn->internal[i]) {
1726 if (limit && (*limit) < 0) {
1730 yaffs_DeleteWorker(in,
1738 YAFFS_TNODES_INTERNAL_BITS)
1743 yaffs_FreeTnode(dev,
1746 tn->internal[i] = NULL;
1750 return (allDone) ? 1 : 0;
1751 } else if (level == 0) {
1754 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1756 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1759 chunkInInode = (chunkOffset <<
1760 YAFFS_TNODES_LEVEL0_BITS) + i;
1763 yaffs_FindChunkInGroup(dev,
1769 if (foundChunk > 0) {
1770 yaffs_DeleteChunk(dev,
1775 *limit = *limit - 1;
1782 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1786 return (i < 0) ? 1 : 0;
1796 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1798 yaffs_BlockInfo *theBlock;
1800 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1802 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->param.nChunksPerBlock);
1804 theBlock->softDeletions++;
1806 yaffs_UpdateOldestDirtySequence(dev,theBlock);
1810 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1811 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1813 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1816 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1817 __u32 level, int chunkOffset)
1822 yaffs_Device *dev = in->myDev;
1827 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1829 if (tn->internal[i]) {
1831 yaffs_SoftDeleteWorker(in,
1837 YAFFS_TNODES_INTERNAL_BITS)
1840 yaffs_FreeTnode(dev,
1843 tn->internal[i] = NULL;
1845 /* Hoosterman... how could this happen? */
1849 return (allDone) ? 1 : 0;
1850 } else if (level == 0) {
1852 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1853 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1855 /* Note this does not find the real chunk, only the chunk group.
1856 * We make an assumption that a chunk group is not larger than
1859 yaffs_SoftDeleteChunk(dev, theChunk);
1860 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1874 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1877 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1878 if (obj->nDataChunks <= 0) {
1879 /* Empty file with no duplicate object headers, just delete it immediately */
1880 yaffs_FreeTnode(obj->myDev,
1881 obj->variant.fileVariant.top);
1882 obj->variant.fileVariant.top = NULL;
1883 T(YAFFS_TRACE_TRACING,
1884 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1886 yaffs_DoGenericObjectDeletion(obj);
1888 yaffs_SoftDeleteWorker(obj,
1889 obj->variant.fileVariant.top,
1890 obj->variant.fileVariant.
1892 obj->softDeleted = 1;
1897 /* Pruning removes any part of the file structure tree that is beyond the
1898 * bounds of the file (ie that does not point to chunks).
1900 * A file should only get pruned when its size is reduced.
1902 * Before pruning, the chunks must be pulled from the tree and the
1903 * level 0 tnode entries must be zeroed out.
1904 * Could also use this for file deletion, but that's probably better handled
1905 * by a special case.
1907 * This function is recursive. For levels > 0 the function is called again on
1908 * any sub-tree. For level == 0 we just check if the sub-tree has data.
1909 * If there is no data in a subtree then it is pruned.
1912 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1913 __u32 level, int del0)
1922 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1923 if (tn->internal[i]) {
1925 yaffs_PruneWorker(dev, tn->internal[i],
1927 (i == 0) ? del0 : 1);
1930 if (tn->internal[i])
1934 int tnodeSize_u32 = yaffs_CalcTnodeSize(dev)/sizeof(__u32);
1935 __u32 *map = (__u32 *)tn;
1937 for(i = 0; !hasData && i < tnodeSize_u32; i++){
1943 if (hasData == 0 && del0) {
1944 /* Free and return NULL */
1946 yaffs_FreeTnode(dev, tn);
1956 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1957 yaffs_FileStructure *fStruct)
1964 if (fStruct->topLevel > 0) {
1966 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1968 /* Now we have a tree with all the non-zero branches NULL but the height
1969 * is the same as it was.
1970 * Let's see if we can trim internal tnodes to shorten the tree.
1971 * We can do this if only the 0th element in the tnode is in use
1972 * (ie all the non-zero are NULL)
1975 while (fStruct->topLevel && !done) {
1979 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1980 if (tn->internal[i])
1985 fStruct->top = tn->internal[0];
1986 fStruct->topLevel--;
1987 yaffs_FreeTnode(dev, tn);
1997 /*-------------------- End of File Structure functions.-------------------*/
1999 /* yaffs_CreateFreeObjects creates a bunch more objects and
2000 * adds them to the object free list.
2002 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
2005 yaffs_Object *newObjects;
2006 yaffs_ObjectList *list;
2011 /* make these things */
2012 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
2013 list = YMALLOC(sizeof(yaffs_ObjectList));
2015 if (!newObjects || !list) {
2024 T(YAFFS_TRACE_ALLOCATE,
2025 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
2029 /* Hook them into the free list */
2030 for (i = 0; i < nObjects - 1; i++) {
2031 newObjects[i].siblings.next =
2032 (struct ylist_head *)(&newObjects[i + 1]);
2035 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
2036 dev->freeObjects = newObjects;
2037 dev->nFreeObjects += nObjects;
2038 dev->nObjectsCreated += nObjects;
2040 /* Now add this bunch of Objects to a list for freeing up. */
2042 list->objects = newObjects;
2043 list->next = dev->allocatedObjectList;
2044 dev->allocatedObjectList = list;
2050 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
2051 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
2053 yaffs_Object *tn = NULL;
2055 #ifdef CONFIG_YAFFS_VALGRIND_TEST
2056 tn = YMALLOC(sizeof(yaffs_Object));
2058 dev->nObjectsCreated++;
2060 /* If there are none left make more */
2061 if (!dev->freeObjects)
2062 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
2064 if (dev->freeObjects) {
2065 tn = dev->freeObjects;
2067 (yaffs_Object *) (dev->freeObjects->siblings.next);
2068 dev->nFreeObjects--;
2072 /* Now sweeten it up... */
2074 memset(tn, 0, sizeof(yaffs_Object));
2075 tn->beingCreated = 1;
2079 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
2080 YINIT_LIST_HEAD(&(tn->hardLinks));
2081 YINIT_LIST_HEAD(&(tn->hashLink));
2082 YINIT_LIST_HEAD(&tn->siblings);
2085 /* Now make the directory sane */
2087 tn->parent = dev->rootDir;
2088 ylist_add(&(tn->siblings), &dev->rootDir->variant.directoryVariant.children);
2091 /* Add it to the lost and found directory.
2092 * NB Can't put root or lostNFound in lostNFound so
2093 * check if lostNFound exists first
2095 if (dev->lostNFoundDir)
2096 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
2098 tn->beingCreated = 0;
2101 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2106 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
2111 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
2113 obj->fake = 1; /* it is fake so it might have no NAND presence... */
2114 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
2115 obj->unlinkAllowed = 0; /* ... or unlink it */
2118 obj->yst_mode = mode;
2120 obj->hdrChunk = 0; /* Not a valid chunk. */
2127 static void yaffs_UnhashObject(yaffs_Object *tn)
2130 yaffs_Device *dev = tn->myDev;
2132 /* If it is still linked into the bucket list, free from the list */
2133 if (!ylist_empty(&tn->hashLink)) {
2134 ylist_del_init(&tn->hashLink);
2135 bucket = yaffs_HashFunction(tn->objectId);
2136 dev->objectBucket[bucket].count--;
2140 /* FreeObject frees up a Object and puts it back on the free list */
2141 static void yaffs_FreeObject(yaffs_Object *tn)
2143 yaffs_Device *dev = tn->myDev;
2145 T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), tn, tn->myInode));
2151 if (!ylist_empty(&tn->siblings))
2156 /* We're still hooked up to a cached inode.
2157 * Don't delete now, but mark for later deletion
2159 tn->deferedFree = 1;
2163 yaffs_UnhashObject(tn);
2165 #ifdef CONFIG_YAFFS_VALGRIND_TEST
2167 dev->nObjectsCreated--;
2170 /* Link into the free list. */
2171 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2172 dev->freeObjects = tn;
2173 dev->nFreeObjects++;
2175 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2179 void yaffs_HandleDeferedFree(yaffs_Object *obj)
2181 if (obj->deferedFree)
2182 yaffs_FreeObject(obj);
2186 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
2188 /* Free the list of allocated Objects */
2190 yaffs_ObjectList *tmp;
2192 while (dev->allocatedObjectList) {
2193 tmp = dev->allocatedObjectList->next;
2194 YFREE(dev->allocatedObjectList->objects);
2195 YFREE(dev->allocatedObjectList);
2197 dev->allocatedObjectList = tmp;
2200 dev->freeObjects = NULL;
2201 dev->nFreeObjects = 0;
2202 dev->nObjectsCreated = 0;
2205 static void yaffs_InitialiseObjects(yaffs_Device *dev)
2209 dev->allocatedObjectList = NULL;
2210 dev->freeObjects = NULL;
2211 dev->nFreeObjects = 0;
2213 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2214 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2215 dev->objectBucket[i].count = 0;
2219 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
2223 int lowest = 999999;
2226 /* Search for the shortest list or one that
2230 for (i = 0; i < 10 && lowest > 4; i++) {
2231 dev->bucketFinder++;
2232 dev->bucketFinder %= YAFFS_NOBJECT_BUCKETS;
2233 if (dev->objectBucket[dev->bucketFinder].count < lowest) {
2234 lowest = dev->objectBucket[dev->bucketFinder].count;
2235 l = dev->bucketFinder;
2243 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
2245 int bucket = yaffs_FindNiceObjectBucket(dev);
2247 /* Now find an object value that has not already been taken
2248 * by scanning the list.
2252 struct ylist_head *i;
2254 __u32 n = (__u32) bucket;
2256 /* yaffs_CheckObjectHashSanity(); */
2260 n += YAFFS_NOBJECT_BUCKETS;
2261 if (1 || dev->objectBucket[bucket].count > 0) {
2262 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2263 /* If there is already one in the list */
2264 if (i && ylist_entry(i, yaffs_Object,
2265 hashLink)->objectId == n) {
2275 static void yaffs_HashObject(yaffs_Object *in)
2277 int bucket = yaffs_HashFunction(in->objectId);
2278 yaffs_Device *dev = in->myDev;
2280 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2281 dev->objectBucket[bucket].count++;
2284 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
2286 int bucket = yaffs_HashFunction(number);
2287 struct ylist_head *i;
2290 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2291 /* Look if it is in the list */
2293 in = ylist_entry(i, yaffs_Object, hashLink);
2294 if (in->objectId == number) {
2296 /* Don't tell the VFS about this one if it is defered free */
2297 if (in->deferedFree)
2308 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
2309 yaffs_ObjectType type)
2311 yaffs_Object *theObject=NULL;
2312 yaffs_Tnode *tn = NULL;
2315 number = yaffs_CreateNewObjectNumber(dev);
2317 if (type == YAFFS_OBJECT_TYPE_FILE) {
2318 tn = yaffs_GetTnode(dev);
2323 theObject = yaffs_AllocateEmptyObject(dev);
2326 yaffs_FreeTnode(dev,tn);
2332 theObject->fake = 0;
2333 theObject->renameAllowed = 1;
2334 theObject->unlinkAllowed = 1;
2335 theObject->objectId = number;
2336 yaffs_HashObject(theObject);
2337 theObject->variantType = type;
2338 #ifdef CONFIG_YAFFS_WINCE
2339 yfsd_WinFileTimeNow(theObject->win_atime);
2340 theObject->win_ctime[0] = theObject->win_mtime[0] =
2341 theObject->win_atime[0];
2342 theObject->win_ctime[1] = theObject->win_mtime[1] =
2343 theObject->win_atime[1];
2347 theObject->yst_atime = theObject->yst_mtime =
2348 theObject->yst_ctime = Y_CURRENT_TIME;
2351 case YAFFS_OBJECT_TYPE_FILE:
2352 theObject->variant.fileVariant.fileSize = 0;
2353 theObject->variant.fileVariant.scannedFileSize = 0;
2354 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2355 theObject->variant.fileVariant.topLevel = 0;
2356 theObject->variant.fileVariant.top = tn;
2358 case YAFFS_OBJECT_TYPE_DIRECTORY:
2359 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2361 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2364 case YAFFS_OBJECT_TYPE_SYMLINK:
2365 case YAFFS_OBJECT_TYPE_HARDLINK:
2366 case YAFFS_OBJECT_TYPE_SPECIAL:
2367 /* No action required */
2369 case YAFFS_OBJECT_TYPE_UNKNOWN:
2370 /* todo this should not happen */
2378 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
2380 yaffs_ObjectType type)
2382 yaffs_Object *theObject = NULL;
2385 theObject = yaffs_FindObjectByNumber(dev, number);
2388 theObject = yaffs_CreateNewObject(dev, number, type);
2395 static YCHAR *yaffs_CloneString(const YCHAR *str)
2397 YCHAR *newStr = NULL;
2403 len = yaffs_strnlen(str,YAFFS_MAX_ALIAS_LENGTH);
2404 newStr = YMALLOC((len + 1) * sizeof(YCHAR));
2406 yaffs_strncpy(newStr, str,len);
2414 * Mknod (create) a new object.
2415 * equivalentObject only has meaning for a hard link;
2416 * aliasString only has meaning for a symlink.
2417 * rdev only has meaning for devices (a subset of special objects)
2420 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2421 yaffs_Object *parent,
2426 yaffs_Object *equivalentObject,
2427 const YCHAR *aliasString, __u32 rdev)
2432 yaffs_Device *dev = parent->myDev;
2434 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2435 if (yaffs_FindObjectByName(parent, name))
2438 if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2439 str = yaffs_CloneString(aliasString);
2444 in = yaffs_CreateNewObject(dev, -1, type);
2459 in->variantType = type;
2461 in->yst_mode = mode;
2463 #ifdef CONFIG_YAFFS_WINCE
2464 yfsd_WinFileTimeNow(in->win_atime);
2465 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2466 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2469 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2471 in->yst_rdev = rdev;
2475 in->nDataChunks = 0;
2477 yaffs_SetObjectName(in, name);
2480 yaffs_AddObjectToDirectory(parent, in);
2482 in->myDev = parent->myDev;
2485 case YAFFS_OBJECT_TYPE_SYMLINK:
2486 in->variant.symLinkVariant.alias = str;
2488 case YAFFS_OBJECT_TYPE_HARDLINK:
2489 in->variant.hardLinkVariant.equivalentObject =
2491 in->variant.hardLinkVariant.equivalentObjectId =
2492 equivalentObject->objectId;
2493 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2495 case YAFFS_OBJECT_TYPE_FILE:
2496 case YAFFS_OBJECT_TYPE_DIRECTORY:
2497 case YAFFS_OBJECT_TYPE_SPECIAL:
2498 case YAFFS_OBJECT_TYPE_UNKNOWN:
2503 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2504 /* Could not create the object header, fail the creation */
2505 yaffs_DeleteObject(in);
2509 yaffs_UpdateParent(parent);
2515 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
2516 __u32 mode, __u32 uid, __u32 gid)
2518 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2519 uid, gid, NULL, NULL, 0);
2522 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
2523 __u32 mode, __u32 uid, __u32 gid)
2525 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2526 mode, uid, gid, NULL, NULL, 0);
2529 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
2530 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2532 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2533 uid, gid, NULL, NULL, rdev);
2536 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
2537 __u32 mode, __u32 uid, __u32 gid,
2540 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2541 uid, gid, NULL, alias, 0);
2544 /* yaffs_Link returns the object id of the equivalent object.*/
2545 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
2546 yaffs_Object *equivalentObject)
2548 /* Get the real object in case we were fed a hard link as an equivalent object */
2549 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2551 if (yaffs_MknodObject
2552 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2553 equivalentObject, NULL, 0)) {
2554 return equivalentObject;
2561 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
2562 const YCHAR *newName, int force, int shadows)
2567 yaffs_Object *existingTarget;
2570 newDir = obj->parent; /* use the old directory */
2572 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2573 T(YAFFS_TRACE_ALWAYS,
2575 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2580 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2581 if (obj->myDev->param.isYaffs2)
2582 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2584 unlinkOp = (newDir == obj->myDev->unlinkedDir
2585 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2587 deleteOp = (newDir == obj->myDev->deletedDir);
2589 existingTarget = yaffs_FindObjectByName(newDir, newName);
2591 /* If the object is a file going into the unlinked directory,
2592 * then it is OK to just stuff it in since duplicate names are allowed.
2593 * else only proceed if the new name does not exist and if we're putting
2594 * it into a directory.
2601 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2602 yaffs_SetObjectName(obj, newName);
2605 yaffs_AddObjectToDirectory(newDir, obj);
2610 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2611 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows) >= 0)
2618 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
2619 yaffs_Object *newDir, const YCHAR *newName)
2621 yaffs_Object *obj = NULL;
2622 yaffs_Object *existingTarget = NULL;
2628 if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2630 if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2633 dev = oldDir->myDev;
2635 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2636 /* Special case for case insemsitive systems (eg. WinCE).
2637 * While look-up is case insensitive, the name isn't.
2638 * Therefore we might want to change x.txt to X.txt
2640 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
2644 if(yaffs_strnlen(newName,YAFFS_MAX_NAME_LENGTH+1) > YAFFS_MAX_NAME_LENGTH)
2648 obj = yaffs_FindObjectByName(oldDir, oldName);
2650 if (obj && obj->renameAllowed) {
2652 /* Now do the handling for an existing target, if there is one */
2654 existingTarget = yaffs_FindObjectByName(newDir, newName);
2655 if (existingTarget &&
2656 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2657 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2658 /* There is a target that is a non-empty directory, so we fail */
2659 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2660 } else if (existingTarget && existingTarget != obj) {
2661 /* Nuke the target first, using shadowing,
2662 * but only if it isn't the same object.
2664 * Note we must disable gc otherwise it can mess up the shadowing.
2668 yaffs_ChangeObjectName(obj, newDir, newName, force,
2669 existingTarget->objectId);
2670 existingTarget->isShadowed = 1;
2671 yaffs_UnlinkObject(existingTarget);
2675 result = yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2677 yaffs_UpdateParent(oldDir);
2678 if(newDir != oldDir)
2679 yaffs_UpdateParent(newDir);
2686 /*------------------------- Block Management and Page Allocation ----------------*/
2688 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
2690 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2692 dev->blockInfo = NULL;
2693 dev->chunkBits = NULL;
2695 dev->allocationBlock = -1; /* force it to get a new one */
2697 /* If the first allocation strategy fails, thry the alternate one */
2698 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2699 if (!dev->blockInfo) {
2700 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2701 dev->blockInfoAlt = 1;
2703 dev->blockInfoAlt = 0;
2705 if (dev->blockInfo) {
2706 /* Set up dynamic blockinfo stuff. */
2707 dev->chunkBitmapStride = (dev->param.nChunksPerBlock + 7) / 8; /* round up bytes */
2708 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2709 if (!dev->chunkBits) {
2710 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2711 dev->chunkBitsAlt = 1;
2713 dev->chunkBitsAlt = 0;
2716 if (dev->blockInfo && dev->chunkBits) {
2717 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2718 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2725 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2727 if (dev->blockInfoAlt && dev->blockInfo)
2728 YFREE_ALT(dev->blockInfo);
2729 else if (dev->blockInfo)
2730 YFREE(dev->blockInfo);
2732 dev->blockInfoAlt = 0;
2734 dev->blockInfo = NULL;
2736 if (dev->chunkBitsAlt && dev->chunkBits)
2737 YFREE_ALT(dev->chunkBits);
2738 else if (dev->chunkBits)
2739 YFREE(dev->chunkBits);
2740 dev->chunkBitsAlt = 0;
2741 dev->chunkBits = NULL;
2744 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
2745 yaffs_BlockInfo *bi)
2748 if (!dev->param.isYaffs2)
2749 return 1; /* disqualification only applies to yaffs2. */
2751 if (!bi->hasShrinkHeader)
2752 return 1; /* can gc */
2754 yaffs_FindOldestDirtySequence(dev);
2756 /* Can't do gc of this block if there are any blocks older than this one that have
2759 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2763 * yaffs_FindRefreshBlock()
2764 * periodically finds the oldest full block by sequence number for refreshing.
2767 static __u32 yaffs_FindRefreshBlock(yaffs_Device *dev)
2772 __u32 oldestSequence = 0;
2774 yaffs_BlockInfo *bi;
2777 * If refresh period < 10 then refreshing is disabled.
2779 if(dev->param.refreshPeriod < 10 ||
2780 !dev->param.isYaffs2)
2784 * Fix broken values.
2786 if(dev->refreshSkip > dev->param.refreshPeriod)
2787 dev->refreshSkip = dev->param.refreshPeriod;
2789 if(dev->refreshSkip > 0){
2795 * Refresh skip is now zero.
2796 * We'll do a refresh this time around....
2797 * Update the refresh skip and find the oldest block.
2799 dev->refreshSkip = dev->param.refreshPeriod;
2800 dev->refreshCount++;
2802 for (b = dev->internalStartBlock; b <=dev->internalEndBlock; b++){
2804 bi = yaffs_GetBlockInfo(dev, b);
2807 if (bi->blockState == YAFFS_BLOCK_STATE_FULL){
2810 bi->sequenceNumber < oldestSequence){
2812 oldestSequence = bi->sequenceNumber;
2819 (TSTR("GC refresh count %d selected block %d with sequenceNumber %d" TENDSTR),
2820 dev->refreshCount, oldest, oldestSequence));
2827 * FindDiretiestBlock is used to select the dirtiest block (or close enough)
2828 * for garbage collection.
2831 static int yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
2834 int b = dev->currentDirtyChecker;
2840 int prioritised = 0;
2841 yaffs_BlockInfo *bi;
2842 int pendingPrioritisedExist = 0;
2844 /* First let's see if we need to grab a prioritised block */
2845 if (dev->hasPendingPrioritisedGCs) {
2846 for (i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++) {
2848 bi = yaffs_GetBlockInfo(dev, i);
2849 /* yaffs_VerifyBlock(dev,bi,i); */
2851 if (bi->gcPrioritise) {
2852 pendingPrioritisedExist = 1;
2853 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2854 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2855 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2858 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 (!bi->needsRetiring) {
2947 yaffs_InvalidateCheckpoint(dev);
2948 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2950 dev->nErasureFailures++;
2951 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2952 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2957 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2959 for (i = 0; i < dev->param.nChunksPerBlock; i++) {
2960 if (!yaffs_CheckChunkErased
2961 (dev, blockNo * dev->param.nChunksPerBlock + i)) {
2962 T(YAFFS_TRACE_ERROR,
2964 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2965 TENDSTR), blockNo, i));
2971 /* Clean it up... */
2972 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2973 bi->sequenceNumber = 0;
2974 dev->nErasedBlocks++;
2976 bi->softDeletions = 0;
2977 bi->hasShrinkHeader = 0;
2978 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2979 bi->gcPrioritise = 0;
2980 yaffs_ClearChunkBits(dev, blockNo);
2982 T(YAFFS_TRACE_ERASE,
2983 (TSTR("Erased block %d" TENDSTR), blockNo));
2985 dev->nFreeChunks -= dev->param.nChunksPerBlock; /* We lost a block of free space */
2987 yaffs_RetireBlock(dev, blockNo);
2988 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2989 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2993 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2997 yaffs_BlockInfo *bi;
2999 if (dev->nErasedBlocks < 1) {
3000 /* Hoosterman we've got a problem.
3001 * Can't get space to gc
3003 T(YAFFS_TRACE_ERROR,
3004 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
3009 /* Find an empty block. */
3011 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
3012 dev->allocationBlockFinder++;
3013 if (dev->allocationBlockFinder < dev->internalStartBlock
3014 || dev->allocationBlockFinder > dev->internalEndBlock) {
3015 dev->allocationBlockFinder = dev->internalStartBlock;
3018 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
3020 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
3021 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
3022 dev->sequenceNumber++;
3023 bi->sequenceNumber = dev->sequenceNumber;
3024 dev->nErasedBlocks--;
3025 T(YAFFS_TRACE_ALLOCATE,
3026 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
3027 dev->allocationBlockFinder, dev->sequenceNumber,
3028 dev->nErasedBlocks));
3029 return dev->allocationBlockFinder;
3033 T(YAFFS_TRACE_ALWAYS,
3035 ("yaffs tragedy: no more erased blocks, but there should have been %d"
3036 TENDSTR), dev->nErasedBlocks));
3043 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
3045 if (!dev->nCheckpointBlocksRequired &&
3046 dev->param.isYaffs2) {
3047 /* Not a valid value so recalculate */
3050 int devBlocks = (dev->param.endBlock - dev->param.startBlock + 1);
3051 int tnodeSize = yaffs_CalcTnodeSize(dev);
3053 nBytes += sizeof(yaffs_CheckpointValidity);
3054 nBytes += sizeof(yaffs_CheckpointDevice);
3055 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
3056 nBytes += devBlocks * dev->chunkBitmapStride;
3057 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
3058 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
3059 nBytes += sizeof(yaffs_CheckpointValidity);
3060 nBytes += sizeof(__u32); /* checksum*/
3062 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
3064 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->param.nChunksPerBlock)) + 3;
3066 dev->nCheckpointBlocksRequired = nBlocks;
3069 return dev->nCheckpointBlocksRequired;
3073 * Check if there's space to allocate...
3074 * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
3076 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev)
3079 int reservedBlocks = dev->param.nReservedBlocks;
3080 int checkpointBlocks;
3082 if (dev->param.isYaffs2) {
3083 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
3084 dev->blocksInCheckpoint;
3085 if (checkpointBlocks < 0)
3086 checkpointBlocks = 0;
3088 checkpointBlocks = 0;
3091 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->param.nChunksPerBlock);
3093 return (dev->nFreeChunks > reservedChunks);
3096 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
3097 yaffs_BlockInfo **blockUsedPtr)
3100 yaffs_BlockInfo *bi;
3102 if (dev->allocationBlock < 0) {
3103 /* Get next block to allocate off */
3104 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
3105 dev->allocationPage = 0;
3108 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
3109 /* Not enough space to allocate unless we're allowed to use the reserve. */
3113 if (dev->nErasedBlocks < dev->param.nReservedBlocks
3114 && dev->allocationPage == 0) {
3115 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
3118 /* Next page please.... */
3119 if (dev->allocationBlock >= 0) {
3120 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3122 retVal = (dev->allocationBlock * dev->param.nChunksPerBlock) +
3123 dev->allocationPage;
3125 yaffs_SetChunkBit(dev, dev->allocationBlock,
3126 dev->allocationPage);
3128 dev->allocationPage++;
3132 /* If the block is full set the state to full */
3133 if (dev->allocationPage >= dev->param.nChunksPerBlock) {
3134 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3135 dev->allocationBlock = -1;
3144 T(YAFFS_TRACE_ERROR,
3145 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
3150 static int yaffs_GetErasedChunks(yaffs_Device *dev)
3154 n = dev->nErasedBlocks * dev->param.nChunksPerBlock;
3156 if (dev->allocationBlock > 0)
3157 n += (dev->param.nChunksPerBlock - dev->allocationPage);
3164 * yaffs_SkipRestOfBlock() skips over the rest of the allocation block
3165 * if we don't want to write to it.
3167 static void yaffs_SkipRestOfBlock(yaffs_Device *dev)
3169 if(dev->allocationBlock > 0){
3170 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3171 if(bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING){
3172 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3173 dev->allocationBlock = -1;
3179 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
3185 int retVal = YAFFS_OK;
3188 int isCheckpointBlock;
3192 int chunksBefore = yaffs_GetErasedChunks(dev);
3195 yaffs_ExtendedTags tags;
3197 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3199 yaffs_Object *object;
3201 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3204 T(YAFFS_TRACE_TRACING,
3205 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3208 bi->hasShrinkHeader,
3211 /*yaffs_VerifyFreeChunks(dev); */
3213 if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
3214 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3216 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
3218 /* Take off the number of soft deleted entries because
3219 * they're going to get really deleted during GC.
3221 if(dev->gcChunk == 0) /* first time through for this block */
3222 dev->nFreeChunks -= bi->softDeletions;
3226 if (isCheckpointBlock ||
3227 !yaffs_StillSomeChunkBits(dev, block)) {
3228 T(YAFFS_TRACE_TRACING,
3230 ("Collecting block %d that has no chunks in use" TENDSTR),
3232 yaffs_BlockBecameDirty(dev, block);
3235 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3237 yaffs_VerifyBlock(dev, bi, block);
3239 maxCopies = (wholeBlock) ? dev->param.nChunksPerBlock : 10;
3240 oldChunk = block * dev->param.nChunksPerBlock + dev->gcChunk;
3242 for (/* init already done */;
3243 retVal == YAFFS_OK &&
3244 dev->gcChunk < dev->param.nChunksPerBlock &&
3245 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
3247 dev->gcChunk++, oldChunk++) {
3248 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3250 /* This page is in use and might need to be copied off */
3256 yaffs_InitialiseTags(&tags);
3258 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3262 yaffs_FindObjectByNumber(dev,
3265 T(YAFFS_TRACE_GC_DETAIL,
3267 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3268 dev->gcChunk, tags.objectId, tags.chunkId,
3271 if (object && !yaffs_SkipVerification(dev)) {
3272 if (tags.chunkId == 0)
3273 matchingChunk = object->hdrChunk;
3274 else if (object->softDeleted)
3275 matchingChunk = oldChunk; /* Defeat the test */
3277 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
3279 if (oldChunk != matchingChunk)
3280 T(YAFFS_TRACE_ERROR,
3281 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3282 oldChunk, matchingChunk, tags.objectId, tags.chunkId));
3287 T(YAFFS_TRACE_ERROR,
3289 ("page %d in gc has no object: %d %d %d "
3291 tags.objectId, tags.chunkId, tags.byteCount));
3296 object->softDeleted &&
3297 tags.chunkId != 0) {
3298 /* Data chunk in a soft deleted file, throw it away
3299 * It's a soft deleted data chunk,
3300 * No need to copy this, just forget about it and
3301 * fix up the object.
3304 object->nDataChunks--;
3306 if (object->nDataChunks <= 0) {
3307 /* remeber to clean up the object */
3308 dev->gcCleanupList[cleanups] =
3314 /* Todo object && object->deleted && object->nDataChunks == 0 */
3315 /* Deleted object header with no data chunks.
3316 * Can be discarded and the file deleted.
3318 object->hdrChunk = 0;
3319 yaffs_FreeTnode(object->myDev,
3322 object->variant.fileVariant.top = NULL;
3323 yaffs_DoGenericObjectDeletion(object);
3325 } else if (object) {
3326 /* It's either a data chunk in a live file or
3327 * an ObjectHeader, so we're interested in it.
3328 * NB Need to keep the ObjectHeaders of deleted files
3329 * until the whole file has been deleted off
3331 tags.serialNumber++;
3335 if (tags.chunkId == 0) {
3336 /* It is an object Id,
3337 * We need to nuke the shrinkheader flags first
3338 * Also need to clean up shadowing.
3339 * We no longer want the shrinkHeader flag since its work is done
3340 * and if it is left in place it will mess up scanning.
3343 yaffs_ObjectHeader *oh;
3344 oh = (yaffs_ObjectHeader *)buffer;
3347 tags.extraIsShrinkHeader = 0;
3349 oh->shadowsObject = 0;
3350 oh->inbandShadowsObject = 0;
3351 tags.extraShadows = 0;
3353 /* Update file size */
3354 if(object->variantType == YAFFS_OBJECT_TYPE_FILE){
3355 oh->fileSize = object->variant.fileVariant.fileSize;
3356 tags.extraFileLength = oh->fileSize;
3359 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
3361 yaffs_WriteNewChunkWithTagsToNAND(dev,(__u8 *) oh, &tags, 1);
3364 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3367 retVal = YAFFS_FAIL;
3370 /* Ok, now fix up the Tnodes etc. */
3372 if (tags.chunkId == 0) {
3374 object->hdrChunk = newChunk;
3375 object->serial = tags.serialNumber;
3377 /* It's a data chunk */
3379 ok = yaffs_PutChunkIntoFile
3387 if (retVal == YAFFS_OK)
3388 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3393 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3396 /* Do any required cleanups */
3397 for (i = 0; i < cleanups; i++) {
3398 /* Time to delete the file too */
3400 yaffs_FindObjectByNumber(dev,
3401 dev->gcCleanupList[i]);
3403 yaffs_FreeTnode(dev,
3404 object->variant.fileVariant.
3406 object->variant.fileVariant.top = NULL;
3409 ("yaffs: About to finally delete object %d"
3410 TENDSTR), object->objectId));
3411 yaffs_DoGenericObjectDeletion(object);
3412 object->myDev->nDeletedFiles--;
3419 yaffs_VerifyCollectedBlock(dev, bi, block);
3423 /* If the gc completed then clear the current gcBlock so that we find another. */
3424 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING) {
3425 chunksAfter = yaffs_GetErasedChunks(dev);
3426 if (chunksBefore >= chunksAfter) {
3429 ("gc did not increase free chunks before %d after %d"
3430 TENDSTR), chunksBefore, chunksAfter));
3441 /* New garbage collector
3442 * If we're very low on erased blocks then we do aggressive garbage collection
3443 * otherwise we do "leasurely" garbage collection.
3444 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3445 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3447 * The idea is to help clear out space in a more spread-out manner.
3448 * Dunno if it really does anything useful.
3450 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
3454 int gcOk = YAFFS_OK;
3457 int checkpointBlockAdjust;
3459 if (dev->isDoingGC) {
3460 /* Bail out so we don't get recursive gc */
3464 /* This loop should pass the first time.
3465 * We'll only see looping here if the erase of the collected block fails.
3471 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3472 if (checkpointBlockAdjust < 0)
3473 checkpointBlockAdjust = 0;
3475 /* If we need a block soon then do aggressive gc.*/
3476 if (dev->nErasedBlocks < (dev->param.nReservedBlocks + checkpointBlockAdjust + 2))
3481 /* If we don't already have a block being gc'd then see if we should start another */
3483 if (dev->gcBlock < 1 && !aggressive) {
3484 dev->gcBlock = yaffs_FindRefreshBlock(dev);
3487 if (dev->gcBlock < 1) {
3488 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3492 block = dev->gcBlock;
3495 dev->garbageCollections++;
3497 dev->passiveGarbageCollections++;
3501 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3502 dev->nErasedBlocks, aggressive));
3504 gcOk = yaffs_GarbageCollectBlock(dev, block, aggressive);
3507 if (dev->nErasedBlocks < (dev->param.nReservedBlocks) && block > 0) {
3510 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3511 TENDSTR), dev->nErasedBlocks, maxTries, block));
3513 } while ((dev->nErasedBlocks < dev->param.nReservedBlocks) &&
3517 return aggressive ? gcOk : YAFFS_OK;
3520 /*------------------------- TAGS --------------------------------*/
3522 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
3525 return (tags->chunkId == chunkInObject &&
3526 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3531 /*-------------------- Data file manipulation -----------------*/
3533 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
3534 yaffs_ExtendedTags *tags)
3536 /*Get the Tnode, then get the level 0 offset chunk offset */
3539 yaffs_ExtendedTags localTags;
3542 yaffs_Device *dev = in->myDev;
3545 /* Passed a NULL, so use our own tags space */
3549 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3552 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3555 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3561 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
3562 yaffs_ExtendedTags *tags)
3564 /* Get the Tnode, then get the level 0 offset chunk offset */
3567 yaffs_ExtendedTags localTags;
3569 yaffs_Device *dev = in->myDev;
3573 /* Passed a NULL, so use our own tags space */
3577 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3581 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3584 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3587 /* Delete the entry in the filestructure (if found) */
3589 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, 0);
3595 #ifdef YAFFS_PARANOID
3597 static int yaffs_CheckFileSanity(yaffs_Object *in)
3605 yaffs_Tags localTags;
3606 yaffs_Tags *tags = &localTags;
3610 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3613 objId = in->objectId;
3614 fSize = in->variant.fileVariant.fileSize;
3616 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3618 for (chunk = 1; chunk <= nChunks; chunk++) {
3619 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3624 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunk);
3626 if (yaffs_CheckChunkBits
3627 (dev, theChunk / dev->param.nChunksPerBlock,
3628 theChunk % dev->param.nChunksPerBlock)) {
3630 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3634 (tags, in->objectId, chunk, chunkDeleted)) {
3644 /* T(("No level 0 found for %d\n", chunk)); */
3648 return failed ? YAFFS_FAIL : YAFFS_OK;
3653 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
3654 int chunkInNAND, int inScan)
3656 /* NB inScan is zero unless scanning.
3657 * For forward scanning, inScan is > 0;
3658 * for backward scanning inScan is < 0
3660 * chunkInNAND = 0 is a dummy insert to make sure the tnodes are there.
3664 yaffs_Device *dev = in->myDev;
3666 yaffs_ExtendedTags existingTags;
3667 yaffs_ExtendedTags newTags;
3668 unsigned existingSerial, newSerial;
3670 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3671 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3672 * If it is not during Scanning then something went wrong!
3675 T(YAFFS_TRACE_ERROR,
3677 ("yaffs tragedy:attempt to put data chunk into a non-file"
3682 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3686 tn = yaffs_AddOrFindLevel0Tnode(dev,
3687 &in->variant.fileVariant,
3694 /* Dummy insert, bail now */
3697 existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3700 /* If we're scanning then we need to test for duplicates
3701 * NB This does not need to be efficient since it should only ever
3702 * happen when the power fails during a write, then only one
3703 * chunk should ever be affected.
3705 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3706 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3709 if (existingChunk > 0) {
3710 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3711 * thus we have to do a FindChunkInFile to get the real chunk id.
3713 * We have a duplicate now we need to decide which one to use:
3715 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3716 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3717 * YAFFS1: Get both sets of tags and compare serial numbers.
3721 /* Only do this for forward scanning */
3722 yaffs_ReadChunkWithTagsFromNAND(dev,
3726 /* Do a proper find */
3728 yaffs_FindChunkInFile(in, chunkInInode,
3732 if (existingChunk <= 0) {
3733 /*Hoosterman - how did this happen? */
3735 T(YAFFS_TRACE_ERROR,
3737 ("yaffs tragedy: existing chunk < 0 in scan"
3742 /* NB The deleted flags should be false, otherwise the chunks will
3743 * not be loaded during a scan
3747 newSerial = newTags.serialNumber;
3748 existingSerial = existingTags.serialNumber;
3752 (in->myDev->param.isYaffs2 ||
3753 existingChunk <= 0 ||
3754 ((existingSerial + 1) & 3) == newSerial)) {
3755 /* Forward scanning.
3757 * Delete the old one and drop through to update the tnode
3759 yaffs_DeleteChunk(dev, existingChunk, 1,
3762 /* Backward scanning or we want to use the existing one
3764 * Delete the new one and return early so that the tnode isn't changed
3766 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3774 if (existingChunk == 0)
3777 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
3782 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
3785 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3787 if (chunkInNAND >= 0)
3788 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3791 T(YAFFS_TRACE_NANDACCESS,
3792 (TSTR("Chunk %d not found zero instead" TENDSTR),
3794 /* get sane (zero) data if you read a hole */
3795 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3801 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
3805 yaffs_ExtendedTags tags;
3806 yaffs_BlockInfo *bi;
3812 block = chunkId / dev->param.nChunksPerBlock;
3813 page = chunkId % dev->param.nChunksPerBlock;
3816 if (!yaffs_CheckChunkBit(dev, block, page))
3817 T(YAFFS_TRACE_VERIFY,
3818 (TSTR("Deleting invalid chunk %d"TENDSTR),
3821 bi = yaffs_GetBlockInfo(dev, block);
3823 yaffs_UpdateOldestDirtySequence(dev,bi);
3825 T(YAFFS_TRACE_DELETION,
3826 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3829 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->param.isYaffs2) {
3831 yaffs_InitialiseTags(&tags);
3833 tags.chunkDeleted = 1;
3835 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3836 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3838 dev->nUnmarkedDeletions++;
3841 /* Pull out of the management area.
3842 * If the whole block became dirty, this will kick off an erasure.
3844 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3845 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3846 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3847 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3850 yaffs_ClearChunkBit(dev, block, page);
3854 if (bi->pagesInUse == 0 &&
3855 !bi->hasShrinkHeader &&
3856 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3857 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3858 yaffs_BlockBecameDirty(dev, block);
3865 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
3866 const __u8 *buffer, int nBytes,
3869 /* Find old chunk Need to do this to get serial number
3870 * Write new one and patch into tree.
3871 * Invalidate old tags.
3875 yaffs_ExtendedTags prevTags;
3878 yaffs_ExtendedTags newTags;
3880 yaffs_Device *dev = in->myDev;
3882 yaffs_CheckGarbageCollection(dev);
3884 /* Get the previous chunk at this location in the file if it exists.
3885 * If it does not exist then put a zero into the tree. This creates
3886 * the tnode now, rather than later when it is harder to clean up.
3888 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3889 if(prevChunkId < 1 &&
3890 !yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0))
3893 /* Set up new tags */
3894 yaffs_InitialiseTags(&newTags);
3896 newTags.chunkId = chunkInInode;
3897 newTags.objectId = in->objectId;
3898 newTags.serialNumber =
3899 (prevChunkId > 0) ? prevTags.serialNumber + 1 : 1;
3900 newTags.byteCount = nBytes;
3902 if (nBytes < 1 || nBytes > dev->param.totalBytesPerChunk) {
3903 T(YAFFS_TRACE_ERROR,
3904 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3910 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3913 if (newChunkId > 0) {
3914 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3916 if (prevChunkId > 0)
3917 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3919 yaffs_CheckFileSanity(in);
3925 /* UpdateObjectHeader updates the header on NAND for an object.
3926 * If name is not NULL, then that new name is used.
3928 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
3929 int isShrink, int shadows)
3932 yaffs_BlockInfo *bi;
3934 yaffs_Device *dev = in->myDev;
3941 yaffs_ExtendedTags newTags;
3942 yaffs_ExtendedTags oldTags;
3943 YCHAR *alias = NULL;
3945 __u8 *buffer = NULL;
3946 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3948 yaffs_ObjectHeader *oh = NULL;
3950 yaffs_strcpy(oldName, _Y("silly old name"));
3954 in == dev->rootDir || /* The rootDir should also be saved */
3957 yaffs_CheckGarbageCollection(dev);
3958 yaffs_CheckObjectDetailsLoaded(in);
3960 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3961 oh = (yaffs_ObjectHeader *) buffer;
3963 prevChunkId = in->hdrChunk;
3965 if (prevChunkId > 0) {
3966 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3969 yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
3971 memcpy(oldName, oh->name, sizeof(oh->name));
3974 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3976 oh->type = in->variantType;
3977 oh->yst_mode = in->yst_mode;
3978 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3980 #ifdef CONFIG_YAFFS_WINCE
3981 oh->win_atime[0] = in->win_atime[0];
3982 oh->win_ctime[0] = in->win_ctime[0];
3983 oh->win_mtime[0] = in->win_mtime[0];
3984 oh->win_atime[1] = in->win_atime[1];
3985 oh->win_ctime[1] = in->win_ctime[1];
3986 oh->win_mtime[1] = in->win_mtime[1];
3988 oh->yst_uid = in->yst_uid;
3989 oh->yst_gid = in->yst_gid;
3990 oh->yst_atime = in->yst_atime;
3991 oh->yst_mtime = in->yst_mtime;
3992 oh->yst_ctime = in->yst_ctime;
3993 oh->yst_rdev = in->yst_rdev;
3996 oh->parentObjectId = in->parent->objectId;
3998 oh->parentObjectId = 0;
4000 if (name && *name) {
4001 memset(oh->name, 0, sizeof(oh->name));
4002 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
4003 } else if (prevChunkId > 0)
4004 memcpy(oh->name, oldName, sizeof(oh->name));
4006 memset(oh->name, 0, sizeof(oh->name));
4008 oh->isShrink = isShrink;
4010 switch (in->variantType) {
4011 case YAFFS_OBJECT_TYPE_UNKNOWN:
4012 /* Should not happen */
4014 case YAFFS_OBJECT_TYPE_FILE:
4016 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
4017 || oh->parentObjectId ==
4018 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
4019 fileVariant.fileSize;
4021 case YAFFS_OBJECT_TYPE_HARDLINK:
4022 oh->equivalentObjectId =
4023 in->variant.hardLinkVariant.equivalentObjectId;
4025 case YAFFS_OBJECT_TYPE_SPECIAL:
4028 case YAFFS_OBJECT_TYPE_DIRECTORY:
4031 case YAFFS_OBJECT_TYPE_SYMLINK:
4032 alias = in->variant.symLinkVariant.alias;
4034 alias = _Y("no alias");
4035 yaffs_strncpy(oh->alias,
4037 YAFFS_MAX_ALIAS_LENGTH);
4038 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
4043 yaffs_InitialiseTags(&newTags);
4045 newTags.chunkId = 0;
4046 newTags.objectId = in->objectId;
4047 newTags.serialNumber = in->serial;
4049 /* Add extra info for file header */
4051 newTags.extraHeaderInfoAvailable = 1;
4052 newTags.extraParentObjectId = oh->parentObjectId;
4053 newTags.extraFileLength = oh->fileSize;
4054 newTags.extraIsShrinkHeader = oh->isShrink;
4055 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
4056 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
4057 newTags.extraObjectType = in->variantType;
4059 yaffs_VerifyObjectHeader(in, oh, &newTags, 1);
4061 /* Create new chunk in NAND */
4063 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
4064 (prevChunkId > 0) ? 1 : 0);
4066 if (newChunkId >= 0) {
4068 in->hdrChunk = newChunkId;
4070 if (prevChunkId > 0) {
4071 yaffs_DeleteChunk(dev, prevChunkId, 1,
4075 if (!yaffs_ObjectHasCachedWriteData(in))
4078 /* If this was a shrink, then mark the block that the chunk lives on */
4080 bi = yaffs_GetBlockInfo(in->myDev,
4081 newChunkId / in->myDev->param.nChunksPerBlock);
4082 bi->hasShrinkHeader = 1;
4087 retVal = newChunkId;
4092 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
4097 /*------------------------ Short Operations Cache ----------------------------------------
4098 * In many situations where there is no high level buffering (eg WinCE) a lot of
4099 * reads might be short sequential reads, and a lot of writes may be short
4100 * sequential writes. eg. scanning/writing a jpeg file.
4101 * In these cases, a short read/write cache can provide a huge perfomance benefit
4102 * with dumb-as-a-rock code.
4103 * In Linux, the page cache provides read buffering aand the short op cache provides write
4106 * There are a limited number (~10) of cache chunks per device so that we don't
4107 * need a very intelligent search.
4110 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
4112 yaffs_Device *dev = obj->myDev;
4114 yaffs_ChunkCache *cache;
4115 int nCaches = obj->myDev->param.nShortOpCaches;
4117 for (i = 0; i < nCaches; i++) {
4118 cache = &dev->srCache[i];
4119 if (cache->object == obj &&
4128 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
4130 yaffs_Device *dev = obj->myDev;
4131 int lowest = -99; /* Stop compiler whining. */
4133 yaffs_ChunkCache *cache;
4134 int chunkWritten = 0;
4135 int nCaches = obj->myDev->param.nShortOpCaches;
4141 /* Find the dirty cache for this object with the lowest chunk id. */
4142 for (i = 0; i < nCaches; i++) {
4143 if (dev->srCache[i].object == obj &&
4144 dev->srCache[i].dirty) {
4146 || dev->srCache[i].chunkId <
4148 cache = &dev->srCache[i];
4149 lowest = cache->chunkId;
4154 if (cache && !cache->locked) {
4155 /* Write it out and free it up */
4158 yaffs_WriteChunkDataToObject(cache->object,
4164 cache->object = NULL;
4167 } while (cache && chunkWritten > 0);
4170 /* Hoosterman, disk full while writing cache out. */
4171 T(YAFFS_TRACE_ERROR,
4172 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
4179 /*yaffs_FlushEntireDeviceCache(dev)
4184 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
4187 int nCaches = dev->param.nShortOpCaches;
4190 /* Find a dirty object in the cache and flush it...
4191 * until there are no further dirty objects.
4195 for (i = 0; i < nCaches && !obj; i++) {
4196 if (dev->srCache[i].object &&
4197 dev->srCache[i].dirty)
4198 obj = dev->srCache[i].object;
4202 yaffs_FlushFilesChunkCache(obj);
4209 /* Grab us a cache chunk for use.
4210 * First look for an empty one.
4211 * Then look for the least recently used non-dirty one.
4212 * Then look for the least recently used dirty one...., flush and look again.
4214 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
4218 if (dev->param.nShortOpCaches > 0) {
4219 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4220 if (!dev->srCache[i].object)
4221 return &dev->srCache[i];
4228 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
4230 yaffs_ChunkCache *cache;
4231 yaffs_Object *theObj;
4236 if (dev->param.nShortOpCaches > 0) {
4237 /* Try find a non-dirty one... */
4239 cache = yaffs_GrabChunkCacheWorker(dev);
4242 /* They were all dirty, find the last recently used object and flush
4243 * its cache, then find again.
4244 * NB what's here is not very accurate, we actually flush the object
4245 * the last recently used page.
4248 /* With locking we can't assume we can use entry zero */
4255 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4256 if (dev->srCache[i].object &&
4257 !dev->srCache[i].locked &&
4258 (dev->srCache[i].lastUse < usage || !cache)) {
4259 usage = dev->srCache[i].lastUse;
4260 theObj = dev->srCache[i].object;
4261 cache = &dev->srCache[i];
4266 if (!cache || cache->dirty) {
4267 /* Flush and try again */
4268 yaffs_FlushFilesChunkCache(theObj);
4269 cache = yaffs_GrabChunkCacheWorker(dev);
4279 /* Find a cached chunk */
4280 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj,
4283 yaffs_Device *dev = obj->myDev;
4285 if (dev->param.nShortOpCaches > 0) {
4286 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4287 if (dev->srCache[i].object == obj &&
4288 dev->srCache[i].chunkId == chunkId) {
4291 return &dev->srCache[i];
4298 /* Mark the chunk for the least recently used algorithym */
4299 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache,
4303 if (dev->param.nShortOpCaches > 0) {
4304 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4305 /* Reset the cache usages */
4307 for (i = 1; i < dev->param.nShortOpCaches; i++)
4308 dev->srCache[i].lastUse = 0;
4315 cache->lastUse = dev->srLastUse;
4322 /* Invalidate a single cache page.
4323 * Do this when a whole page gets written,
4324 * ie the short cache for this page is no longer valid.
4326 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
4328 if (object->myDev->param.nShortOpCaches > 0) {
4329 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4332 cache->object = NULL;
4336 /* Invalidate all the cache pages associated with this object
4337 * Do this whenever ther file is deleted or resized.
4339 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
4342 yaffs_Device *dev = in->myDev;
4344 if (dev->param.nShortOpCaches > 0) {
4345 /* Invalidate it. */
4346 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4347 if (dev->srCache[i].object == in)
4348 dev->srCache[i].object = NULL;
4353 /*--------------------- Checkpointing --------------------*/
4356 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev, int head)
4358 yaffs_CheckpointValidity cp;
4360 memset(&cp, 0, sizeof(cp));
4362 cp.structType = sizeof(cp);
4363 cp.magic = YAFFS_MAGIC;
4364 cp.version = YAFFS_CHECKPOINT_VERSION;
4365 cp.head = (head) ? 1 : 0;
4367 return (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp)) ?
4371 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4373 yaffs_CheckpointValidity cp;
4376 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4379 ok = (cp.structType == sizeof(cp)) &&
4380 (cp.magic == YAFFS_MAGIC) &&
4381 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4382 (cp.head == ((head) ? 1 : 0));
4386 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4389 cp->nErasedBlocks = dev->nErasedBlocks;
4390 cp->allocationBlock = dev->allocationBlock;
4391 cp->allocationPage = dev->allocationPage;
4392 cp->nFreeChunks = dev->nFreeChunks;
4394 cp->nDeletedFiles = dev->nDeletedFiles;
4395 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4396 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4397 cp->sequenceNumber = dev->sequenceNumber;
4401 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4402 yaffs_CheckpointDevice *cp)
4404 dev->nErasedBlocks = cp->nErasedBlocks;
4405 dev->allocationBlock = cp->allocationBlock;
4406 dev->allocationPage = cp->allocationPage;
4407 dev->nFreeChunks = cp->nFreeChunks;
4409 dev->nDeletedFiles = cp->nDeletedFiles;
4410 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4411 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4412 dev->sequenceNumber = cp->sequenceNumber;
4416 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4418 yaffs_CheckpointDevice cp;
4420 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4424 /* Write device runtime values*/
4425 yaffs_DeviceToCheckpointDevice(&cp, dev);
4426 cp.structType = sizeof(cp);
4428 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4430 /* Write block info */
4432 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4433 ok = (yaffs_CheckpointWrite(dev, dev->blockInfo, nBytes) == nBytes);
4436 /* Write chunk bits */
4438 nBytes = nBlocks * dev->chunkBitmapStride;
4439 ok = (yaffs_CheckpointWrite(dev, dev->chunkBits, nBytes) == nBytes);
4445 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4447 yaffs_CheckpointDevice cp;
4449 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4453 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4457 if (cp.structType != sizeof(cp))
4461 yaffs_CheckpointDeviceToDevice(dev, &cp);
4463 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4465 ok = (yaffs_CheckpointRead(dev, dev->blockInfo, nBytes) == nBytes);
4469 nBytes = nBlocks * dev->chunkBitmapStride;
4471 ok = (yaffs_CheckpointRead(dev, dev->chunkBits, nBytes) == nBytes);
4476 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4480 cp->objectId = obj->objectId;
4481 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4482 cp->hdrChunk = obj->hdrChunk;
4483 cp->variantType = obj->variantType;
4484 cp->deleted = obj->deleted;
4485 cp->softDeleted = obj->softDeleted;
4486 cp->unlinked = obj->unlinked;
4487 cp->fake = obj->fake;
4488 cp->renameAllowed = obj->renameAllowed;
4489 cp->unlinkAllowed = obj->unlinkAllowed;
4490 cp->serial = obj->serial;
4491 cp->nDataChunks = obj->nDataChunks;
4493 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4494 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4495 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4496 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4499 static int yaffs_CheckpointObjectToObject(yaffs_Object *obj, yaffs_CheckpointObject *cp)
4502 yaffs_Object *parent;
4504 if (obj->variantType != cp->variantType) {
4505 T(YAFFS_TRACE_ERROR, (TSTR("Checkpoint read object %d type %d "
4506 TCONT("chunk %d does not match existing object type %d")
4507 TENDSTR), cp->objectId, cp->variantType, cp->hdrChunk,
4512 obj->objectId = cp->objectId;
4515 parent = yaffs_FindOrCreateObjectByNumber(
4518 YAFFS_OBJECT_TYPE_DIRECTORY);
4523 if (parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4524 T(YAFFS_TRACE_ALWAYS, (TSTR("Checkpoint read object %d parent %d type %d"
4525 TCONT(" chunk %d Parent type, %d, not directory")
4527 cp->objectId, cp->parentId, cp->variantType,
4528 cp->hdrChunk, parent->variantType));
4531 yaffs_AddObjectToDirectory(parent, obj);
4534 obj->hdrChunk = cp->hdrChunk;
4535 obj->variantType = cp->variantType;
4536 obj->deleted = cp->deleted;
4537 obj->softDeleted = cp->softDeleted;
4538 obj->unlinked = cp->unlinked;
4539 obj->fake = cp->fake;
4540 obj->renameAllowed = cp->renameAllowed;
4541 obj->unlinkAllowed = cp->unlinkAllowed;
4542 obj->serial = cp->serial;
4543 obj->nDataChunks = cp->nDataChunks;
4545 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4546 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4547 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4548 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4550 if (obj->hdrChunk > 0)
4551 obj->lazyLoaded = 1;
4557 static int yaffs_CheckpointTnodeWorker(yaffs_Object *in, yaffs_Tnode *tn,
4558 __u32 level, int chunkOffset)
4561 yaffs_Device *dev = in->myDev;
4563 int tnodeSize = yaffs_CalcTnodeSize(dev);
4568 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
4569 if (tn->internal[i]) {
4570 ok = yaffs_CheckpointTnodeWorker(in,
4573 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4576 } else if (level == 0) {
4577 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4578 ok = (yaffs_CheckpointWrite(dev, &baseOffset, sizeof(baseOffset)) == sizeof(baseOffset));
4580 ok = (yaffs_CheckpointWrite(dev, tn, tnodeSize) == tnodeSize);
4588 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4590 __u32 endMarker = ~0;
4593 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4594 ok = yaffs_CheckpointTnodeWorker(obj,
4595 obj->variant.fileVariant.top,
4596 obj->variant.fileVariant.topLevel,
4599 ok = (yaffs_CheckpointWrite(obj->myDev, &endMarker, sizeof(endMarker)) ==
4606 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4610 yaffs_Device *dev = obj->myDev;
4611 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4614 int tnodeSize = yaffs_CalcTnodeSize(dev);
4616 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4618 while (ok && (~baseChunk)) {
4620 /* Read level 0 tnode */
4623 tn = yaffs_GetTnodeRaw(dev);
4625 ok = (yaffs_CheckpointRead(dev, tn, tnodeSize) == tnodeSize);
4630 ok = yaffs_AddOrFindLevel0Tnode(dev,
4636 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4640 T(YAFFS_TRACE_CHECKPOINT, (
4641 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4642 nread, baseChunk, ok));
4648 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4651 yaffs_CheckpointObject cp;
4654 struct ylist_head *lh;
4657 /* Iterate through the objects in each hash entry,
4658 * dumping them to the checkpointing stream.
4661 for (i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++) {
4662 ylist_for_each(lh, &dev->objectBucket[i].list) {
4664 obj = ylist_entry(lh, yaffs_Object, hashLink);
4665 if (!obj->deferedFree) {
4666 yaffs_ObjectToCheckpointObject(&cp, obj);
4667 cp.structType = sizeof(cp);
4669 T(YAFFS_TRACE_CHECKPOINT, (
4670 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %p" TENDSTR),
4671 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk, obj));
4673 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4675 if (ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4676 ok = yaffs_WriteCheckpointTnodes(obj);
4682 /* Dump end of list */
4683 memset(&cp, 0xFF, sizeof(yaffs_CheckpointObject));
4684 cp.structType = sizeof(cp);
4687 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4692 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4695 yaffs_CheckpointObject cp;
4698 yaffs_Object *hardList = NULL;
4700 while (ok && !done) {
4701 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4702 if (cp.structType != sizeof(cp)) {
4703 T(YAFFS_TRACE_CHECKPOINT, (TSTR("struct size %d instead of %d ok %d"TENDSTR),
4704 cp.structType, (int)sizeof(cp), ok));
4708 T(YAFFS_TRACE_CHECKPOINT, (TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4709 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk));
4711 if (ok && cp.objectId == ~0)
4714 obj = yaffs_FindOrCreateObjectByNumber(dev, cp.objectId, cp.variantType);
4716 ok = yaffs_CheckpointObjectToObject(obj, &cp);
4719 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4720 ok = yaffs_ReadCheckpointTnodes(obj);
4721 } else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4722 obj->hardLinks.next =
4723 (struct ylist_head *) hardList;
4732 yaffs_HardlinkFixup(dev, hardList);
4737 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4739 __u32 checkpointSum;
4742 yaffs_GetCheckpointSum(dev, &checkpointSum);
4744 ok = (yaffs_CheckpointWrite(dev, &checkpointSum, sizeof(checkpointSum)) == sizeof(checkpointSum));
4752 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4754 __u32 checkpointSum0;
4755 __u32 checkpointSum1;
4758 yaffs_GetCheckpointSum(dev, &checkpointSum0);
4760 ok = (yaffs_CheckpointRead(dev, &checkpointSum1, sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4765 if (checkpointSum0 != checkpointSum1)
4772 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4776 if (dev->param.skipCheckpointWrite || !dev->param.isYaffs2) {
4777 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint write" TENDSTR)));
4782 ok = yaffs_CheckpointOpen(dev, 1);
4785 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4786 ok = yaffs_WriteCheckpointValidityMarker(dev, 1);
4789 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint device" TENDSTR)));
4790 ok = yaffs_WriteCheckpointDevice(dev);
4793 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint objects" TENDSTR)));
4794 ok = yaffs_WriteCheckpointObjects(dev);
4797 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4798 ok = yaffs_WriteCheckpointValidityMarker(dev, 0);
4802 ok = yaffs_WriteCheckpointSum(dev);
4804 if (!yaffs_CheckpointClose(dev))
4808 dev->isCheckpointed = 1;
4810 dev->isCheckpointed = 0;
4812 return dev->isCheckpointed;
4815 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4819 if (dev->param.skipCheckpointRead || !dev->param.isYaffs2) {
4820 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint read" TENDSTR)));
4825 ok = yaffs_CheckpointOpen(dev, 0); /* open for read */
4828 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4829 ok = yaffs_ReadCheckpointValidityMarker(dev, 1);
4832 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint device" TENDSTR)));
4833 ok = yaffs_ReadCheckpointDevice(dev);
4836 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint objects" TENDSTR)));
4837 ok = yaffs_ReadCheckpointObjects(dev);
4840 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4841 ok = yaffs_ReadCheckpointValidityMarker(dev, 0);
4845 ok = yaffs_ReadCheckpointSum(dev);
4846 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint checksum %d" TENDSTR), ok));
4849 if (!yaffs_CheckpointClose(dev))
4853 dev->isCheckpointed = 1;
4855 dev->isCheckpointed = 0;
4861 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4863 if (dev->isCheckpointed ||
4864 dev->blocksInCheckpoint > 0) {
4865 dev->isCheckpointed = 0;
4866 yaffs_CheckpointInvalidateStream(dev);
4868 if (dev->param.markSuperBlockDirty)
4869 dev->param.markSuperBlockDirty(dev);
4873 int yaffs_CheckpointSave(yaffs_Device *dev)
4876 T(YAFFS_TRACE_CHECKPOINT, (TSTR("save entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4878 yaffs_VerifyObjects(dev);
4879 yaffs_VerifyBlocks(dev);
4880 yaffs_VerifyFreeChunks(dev);
4882 if (!dev->isCheckpointed) {
4883 yaffs_InvalidateCheckpoint(dev);
4884 yaffs_WriteCheckpointData(dev);
4887 T(YAFFS_TRACE_ALWAYS, (TSTR("save exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4889 return dev->isCheckpointed;
4892 int yaffs_CheckpointRestore(yaffs_Device *dev)
4895 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4897 retval = yaffs_ReadCheckpointData(dev);
4899 if (dev->isCheckpointed) {
4900 yaffs_VerifyObjects(dev);
4901 yaffs_VerifyBlocks(dev);
4902 yaffs_VerifyFreeChunks(dev);
4905 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4910 /*--------------------- File read/write ------------------------
4911 * Read and write have very similar structures.
4912 * In general the read/write has three parts to it
4913 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4914 * Some complete chunks
4915 * An incomplete chunk to end off with
4917 * Curve-balls: the first chunk might also be the last chunk.
4920 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 *buffer, loff_t offset,
4929 yaffs_ChunkCache *cache;
4936 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4937 /* start = offset % dev->nDataBytesPerChunk; */
4938 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4941 /* OK now check for the curveball where the start and end are in
4944 if ((start + n) < dev->nDataBytesPerChunk)
4947 nToCopy = dev->nDataBytesPerChunk - start;
4949 cache = yaffs_FindChunkCache(in, chunk);
4951 /* If the chunk is already in the cache or it is less than a whole chunk
4952 * or we're using inband tags then use the cache (if there is caching)
4953 * else bypass the cache.
4955 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
4956 if (dev->param.nShortOpCaches > 0) {
4958 /* If we can't find the data in the cache, then load it up. */
4961 cache = yaffs_GrabChunkCache(in->myDev);
4963 cache->chunkId = chunk;
4966 yaffs_ReadChunkDataFromObject(in, chunk,
4972 yaffs_UseChunkCache(dev, cache, 0);
4977 memcpy(buffer, &cache->data[start], nToCopy);
4981 /* Read into the local buffer then copy..*/
4984 yaffs_GetTempBuffer(dev, __LINE__);
4985 yaffs_ReadChunkDataFromObject(in, chunk,
4988 memcpy(buffer, &localBuffer[start], nToCopy);
4991 yaffs_ReleaseTempBuffer(dev, localBuffer,
4997 /* A full chunk. Read directly into the supplied buffer. */
4998 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
5012 int yaffs_WriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
5013 int nBytes, int writeThrough)
5022 int startOfWrite = offset;
5023 int chunkWritten = 0;
5031 while (n > 0 && chunkWritten >= 0) {
5032 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
5033 /* start = offset % dev->nDataBytesPerChunk; */
5034 yaffs_AddrToChunk(dev, offset, &chunk, &start);
5036 if (chunk * dev->nDataBytesPerChunk + start != offset ||
5037 start >= dev->nDataBytesPerChunk) {
5038 T(YAFFS_TRACE_ERROR, (
5039 TSTR("AddrToChunk of offset %d gives chunk %d start %d"
5041 (int)offset, chunk, start));
5045 /* OK now check for the curveball where the start and end are in
5049 if ((start + n) < dev->nDataBytesPerChunk) {
5052 /* Now folks, to calculate how many bytes to write back....
5053 * If we're overwriting and not writing to then end of file then
5054 * we need to write back as much as was there before.
5057 chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
5059 if (chunkStart > in->variant.fileVariant.fileSize)
5060 nBytesRead = 0; /* Past end of file */
5062 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
5064 if (nBytesRead > dev->nDataBytesPerChunk)
5065 nBytesRead = dev->nDataBytesPerChunk;
5069 (start + n)) ? nBytesRead : (start + n);
5071 if (nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
5075 nToCopy = dev->nDataBytesPerChunk - start;
5076 nToWriteBack = dev->nDataBytesPerChunk;
5079 if (nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
5080 /* An incomplete start or end chunk (or maybe both start and end chunk),
5081 * or we're using inband tags, so we want to use the cache buffers.
5083 if (dev->param.nShortOpCaches > 0) {
5084 yaffs_ChunkCache *cache;
5085 /* If we can't find the data in the cache, then load the cache */
5086 cache = yaffs_FindChunkCache(in, chunk);
5089 && yaffs_CheckSpaceForAllocation(in->
5091 cache = yaffs_GrabChunkCache(in->myDev);
5093 cache->chunkId = chunk;
5096 yaffs_ReadChunkDataFromObject(in, chunk,
5101 !yaffs_CheckSpaceForAllocation(in->myDev)) {
5102 /* Drop the cache if it was a read cache item and
5103 * no space check has been made for it.
5109 yaffs_UseChunkCache(dev, cache, 1);
5113 memcpy(&cache->data[start], buffer,
5118 cache->nBytes = nToWriteBack;
5122 yaffs_WriteChunkDataToObject
5125 cache->data, cache->nBytes,
5131 chunkWritten = -1; /* fail the write */
5134 /* An incomplete start or end chunk (or maybe both start and end chunk)
5135 * Read into the local buffer then copy, then copy over and write back.
5139 yaffs_GetTempBuffer(dev, __LINE__);
5141 yaffs_ReadChunkDataFromObject(in, chunk,
5146 memcpy(&localBuffer[start], buffer, nToCopy);
5149 yaffs_WriteChunkDataToObject(in, chunk,
5154 yaffs_ReleaseTempBuffer(dev, localBuffer,
5160 /* A full chunk. Write directly from the supplied buffer. */
5165 yaffs_WriteChunkDataToObject(in, chunk, buffer,
5166 dev->nDataBytesPerChunk,
5169 /* Since we've overwritten the cached data, we better invalidate it. */
5170 yaffs_InvalidateChunkCache(in, chunk);
5173 if (chunkWritten >= 0) {
5182 /* Update file object */
5184 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
5185 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
5193 /* ---------------------- File resizing stuff ------------------ */
5195 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
5198 yaffs_Device *dev = in->myDev;
5199 int oldFileSize = in->variant.fileVariant.fileSize;
5201 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
5203 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
5204 dev->nDataBytesPerChunk;
5208 /* Delete backwards so that we don't end up with holes if
5209 * power is lost part-way through the operation.
5211 for (i = lastDel; i >= startDel; i--) {
5212 /* NB this could be optimised somewhat,
5213 * eg. could retrieve the tags and write them without
5214 * using yaffs_DeleteChunk
5217 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5220 (dev->internalStartBlock * dev->param.nChunksPerBlock)
5222 ((dev->internalEndBlock +
5223 1) * dev->param.nChunksPerBlock)) {
5224 T(YAFFS_TRACE_ALWAYS,
5225 (TSTR("Found daft chunkId %d for %d" TENDSTR),
5229 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5236 int yaffs_ResizeFile(yaffs_Object *in, loff_t newSize)
5239 int oldFileSize = in->variant.fileVariant.fileSize;
5240 __u32 newSizeOfPartialChunk;
5243 yaffs_Device *dev = in->myDev;
5245 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5247 yaffs_FlushFilesChunkCache(in);
5248 yaffs_InvalidateWholeChunkCache(in);
5250 yaffs_CheckGarbageCollection(dev);
5252 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
5255 if (newSize == oldFileSize)
5258 if (newSize < oldFileSize) {
5260 yaffs_PruneResizedChunks(in, newSize);
5262 if (newSizeOfPartialChunk != 0) {
5263 int lastChunk = 1 + newFullChunks;
5265 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5267 /* Got to read and rewrite the last chunk with its new size and zero pad */
5268 yaffs_ReadChunkDataFromObject(in, lastChunk,
5271 memset(localBuffer + newSizeOfPartialChunk, 0,
5272 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5274 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5275 newSizeOfPartialChunk, 1);
5277 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5280 in->variant.fileVariant.fileSize = newSize;
5282 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5284 /* newsSize > oldFileSize */
5285 in->variant.fileVariant.fileSize = newSize;
5288 /* Write a new object header to reflect the resize.
5289 * show we've shrunk the file, if need be
5290 * Do this only if the file is not in the deleted directories
5291 * and is not shadowed.
5295 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5296 in->parent->objectId != YAFFS_OBJECTID_DELETED)
5297 yaffs_UpdateObjectHeader(in, NULL, 0,
5298 (newSize < oldFileSize) ? 1 : 0, 0);
5303 loff_t yaffs_GetFileSize(yaffs_Object *obj)
5305 YCHAR *alias = NULL;
5306 obj = yaffs_GetEquivalentObject(obj);
5308 switch (obj->variantType) {
5309 case YAFFS_OBJECT_TYPE_FILE:
5310 return obj->variant.fileVariant.fileSize;
5311 case YAFFS_OBJECT_TYPE_SYMLINK:
5312 alias = obj->variant.symLinkVariant.alias;
5315 return yaffs_strnlen(alias,YAFFS_MAX_ALIAS_LENGTH);
5323 int yaffs_FlushFile(yaffs_Object *in, int updateTime, int dataSync)
5327 yaffs_FlushFilesChunkCache(in);
5328 if(dataSync) /* Only sync data */
5332 #ifdef CONFIG_YAFFS_WINCE
5333 yfsd_WinFileTimeNow(in->win_mtime);
5336 in->yst_mtime = Y_CURRENT_TIME;
5341 retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5342 0) ? YAFFS_OK : YAFFS_FAIL;
5352 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
5355 /* First off, invalidate the file's data in the cache, without flushing. */
5356 yaffs_InvalidateWholeChunkCache(in);
5358 if (in->myDev->param.isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5359 /* Move to the unlinked directory so we have a record that it was deleted. */
5360 yaffs_ChangeObjectName(in, in->myDev->deletedDir, _Y("deleted"), 0, 0);
5364 yaffs_RemoveObjectFromDirectory(in);
5365 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5368 yaffs_FreeObject(in);
5373 /* yaffs_DeleteFile deletes the whole file data
5374 * and the inode associated with the file.
5375 * It does not delete the links associated with the file.
5377 static int yaffs_UnlinkFileIfNeeded(yaffs_Object *in)
5381 int immediateDeletion = 0;
5384 immediateDeletion = 1;
5386 if (immediateDeletion) {
5388 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5389 _Y("deleted"), 0, 0);
5390 T(YAFFS_TRACE_TRACING,
5391 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5394 in->myDev->nDeletedFiles++;
5395 if (1 || in->myDev->param.isYaffs2)
5396 yaffs_ResizeFile(in, 0);
5397 yaffs_SoftDeleteFile(in);
5400 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5401 _Y("unlinked"), 0, 0);
5408 int yaffs_DeleteFile(yaffs_Object *in)
5410 int retVal = YAFFS_OK;
5411 int deleted = in->deleted;
5413 yaffs_ResizeFile(in, 0);
5415 if (in->nDataChunks > 0) {
5416 /* Use soft deletion if there is data in the file.
5417 * That won't be the case if it has been resized to zero.
5420 retVal = yaffs_UnlinkFileIfNeeded(in);
5422 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5425 in->myDev->nDeletedFiles++;
5426 yaffs_SoftDeleteFile(in);
5428 return deleted ? YAFFS_OK : YAFFS_FAIL;
5430 /* The file has no data chunks so we toss it immediately */
5431 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5432 in->variant.fileVariant.top = NULL;
5433 yaffs_DoGenericObjectDeletion(in);
5439 static int yaffs_IsNonEmptyDirectory(yaffs_Object *obj)
5441 return (obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) &&
5442 !(ylist_empty(&obj->variant.directoryVariant.children));
5445 static int yaffs_DeleteDirectory(yaffs_Object *obj)
5447 /* First check that the directory is empty. */
5448 if (yaffs_IsNonEmptyDirectory(obj))
5451 return yaffs_DoGenericObjectDeletion(obj);
5454 static int yaffs_DeleteSymLink(yaffs_Object *in)
5456 if(in->variant.symLinkVariant.alias)
5457 YFREE(in->variant.symLinkVariant.alias);
5458 in->variant.symLinkVariant.alias=NULL;
5460 return yaffs_DoGenericObjectDeletion(in);
5463 static int yaffs_DeleteHardLink(yaffs_Object *in)
5465 /* remove this hardlink from the list assocaited with the equivalent
5468 ylist_del_init(&in->hardLinks);
5469 return yaffs_DoGenericObjectDeletion(in);
5472 int yaffs_DeleteObject(yaffs_Object *obj)
5475 switch (obj->variantType) {
5476 case YAFFS_OBJECT_TYPE_FILE:
5477 retVal = yaffs_DeleteFile(obj);
5479 case YAFFS_OBJECT_TYPE_DIRECTORY:
5480 if(!ylist_empty(&obj->variant.directoryVariant.dirty)){
5481 T(YAFFS_TRACE_BACKGROUND, (TSTR("Remove object %d from dirty directories" TENDSTR),obj->objectId));
5482 ylist_del_init(&obj->variant.directoryVariant.dirty);
5484 return yaffs_DeleteDirectory(obj);
5486 case YAFFS_OBJECT_TYPE_SYMLINK:
5487 retVal = yaffs_DeleteSymLink(obj);
5489 case YAFFS_OBJECT_TYPE_HARDLINK:
5490 retVal = yaffs_DeleteHardLink(obj);
5492 case YAFFS_OBJECT_TYPE_SPECIAL:
5493 retVal = yaffs_DoGenericObjectDeletion(obj);
5495 case YAFFS_OBJECT_TYPE_UNKNOWN:
5497 break; /* should not happen. */
5503 static int yaffs_UnlinkWorker(yaffs_Object *obj)
5506 int immediateDeletion = 0;
5509 immediateDeletion = 1;
5512 yaffs_UpdateParent(obj->parent);
5514 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5515 return yaffs_DeleteHardLink(obj);
5516 } else if (!ylist_empty(&obj->hardLinks)) {
5517 /* Curve ball: We're unlinking an object that has a hardlink.
5519 * This problem arises because we are not strictly following
5520 * The Linux link/inode model.
5522 * We can't really delete the object.
5523 * Instead, we do the following:
5524 * - Select a hardlink.
5525 * - Unhook it from the hard links
5526 * - Move it from its parent directory (so that the rename can work)
5527 * - Rename the object to the hardlink's name.
5528 * - Delete the hardlink
5532 yaffs_Object *parent;
5534 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5536 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5538 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5539 parent = hl->parent;
5541 ylist_del_init(&hl->hardLinks);
5543 yaffs_AddObjectToDirectory(obj->myDev->unlinkedDir, hl);
5545 retVal = yaffs_ChangeObjectName(obj,parent, name, 0, 0);
5547 if (retVal == YAFFS_OK)
5548 retVal = yaffs_DoGenericObjectDeletion(hl);
5552 } else if (immediateDeletion) {
5553 switch (obj->variantType) {
5554 case YAFFS_OBJECT_TYPE_FILE:
5555 return yaffs_DeleteFile(obj);
5557 case YAFFS_OBJECT_TYPE_DIRECTORY:
5558 ylist_del_init(&obj->variant.directoryVariant.dirty);
5559 return yaffs_DeleteDirectory(obj);
5561 case YAFFS_OBJECT_TYPE_SYMLINK:
5562 return yaffs_DeleteSymLink(obj);
5564 case YAFFS_OBJECT_TYPE_SPECIAL:
5565 return yaffs_DoGenericObjectDeletion(obj);
5567 case YAFFS_OBJECT_TYPE_HARDLINK:
5568 case YAFFS_OBJECT_TYPE_UNKNOWN:
5572 } else if(yaffs_IsNonEmptyDirectory(obj))
5575 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
5576 _Y("unlinked"), 0, 0);
5580 static int yaffs_UnlinkObject(yaffs_Object *obj)
5583 if (obj && obj->unlinkAllowed)
5584 return yaffs_UnlinkWorker(obj);
5589 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
5593 obj = yaffs_FindObjectByName(dir, name);
5594 return yaffs_UnlinkObject(obj);
5597 /*----------------------- Initialisation Scanning ---------------------- */
5599 static void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
5600 int backwardScanning)
5604 if (!backwardScanning) {
5605 /* Handle YAFFS1 forward scanning case
5606 * For YAFFS1 we always do the deletion
5610 /* Handle YAFFS2 case (backward scanning)
5611 * If the shadowed object exists then ignore.
5613 obj = yaffs_FindObjectByNumber(dev, objId);
5618 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5619 * We put it in unlinked dir to be cleaned up after the scanning
5622 yaffs_FindOrCreateObjectByNumber(dev, objId,
5623 YAFFS_OBJECT_TYPE_FILE);
5626 obj->isShadowed = 1;
5627 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5628 obj->variant.fileVariant.shrinkSize = 0;
5629 obj->valid = 1; /* So that we don't read any other info for this file */
5639 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5646 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5648 in = yaffs_FindObjectByNumber(dev,
5649 hl->variant.hardLinkVariant.
5650 equivalentObjectId);
5653 /* Add the hardlink pointers */
5654 hl->variant.hardLinkVariant.equivalentObject = in;
5655 ylist_add(&hl->hardLinks, &in->hardLinks);
5657 /* Todo Need to report/handle this better.
5658 * Got a problem... hardlink to a non-existant object
5660 hl->variant.hardLinkVariant.equivalentObject = NULL;
5661 YINIT_LIST_HEAD(&hl->hardLinks);
5671 static int ybicmp(const void *a, const void *b)
5673 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5674 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5675 register int ablock = ((yaffs_BlockIndex *)a)->block;
5676 register int bblock = ((yaffs_BlockIndex *)b)->block;
5678 return ablock - bblock;
5684 struct yaffs_ShadowFixerStruct {
5687 struct yaffs_ShadowFixerStruct *next;
5691 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5694 * Sort out state of unlinked and deleted objects after scanning.
5696 struct ylist_head *i;
5697 struct ylist_head *n;
5700 /* Soft delete all the unlinked files */
5701 ylist_for_each_safe(i, n,
5702 &dev->unlinkedDir->variant.directoryVariant.children) {
5704 l = ylist_entry(i, yaffs_Object, siblings);
5705 yaffs_DeleteObject(l);
5709 ylist_for_each_safe(i, n,
5710 &dev->deletedDir->variant.directoryVariant.children) {
5712 l = ylist_entry(i, yaffs_Object, siblings);
5713 yaffs_DeleteObject(l);
5720 * This code iterates through all the objects making sure that they are rooted.
5721 * Any unrooted objects are re-rooted in lost+found.
5722 * An object needs to be in one of:
5723 * - Directly under deleted, unlinked
5724 * - Directly or indirectly under root.
5727 * This code assumes that we don't ever change the current relationships between
5729 * rootDir->parent == unlinkedDir->parent == deletedDir->parent == NULL
5730 * lostNfound->parent == rootDir
5732 * This fixes the problem where directories might have inadvertently been deleted
5733 * leaving the object "hanging" without being rooted in the directory tree.
5736 static int yaffs_HasNULLParent(yaffs_Device *dev, yaffs_Object *obj)
5738 return (obj == dev->deletedDir ||
5739 obj == dev->unlinkedDir||
5740 obj == dev->rootDir);
5743 static void yaffs_FixHangingObjects(yaffs_Device *dev)
5746 yaffs_Object *parent;
5748 struct ylist_head *lh;
5749 struct ylist_head *n;
5754 /* Iterate through the objects in each hash entry,
5755 * looking at each object.
5756 * Make sure it is rooted.
5759 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
5760 ylist_for_each_safe(lh, n, &dev->objectBucket[i].list) {
5762 obj = ylist_entry(lh, yaffs_Object, hashLink);
5763 parent= obj->parent;
5765 if(yaffs_HasNULLParent(dev,obj)){
5766 /* These directories are not hanging */
5769 else if(!parent || parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5771 else if(yaffs_HasNULLParent(dev,parent))
5775 * Need to follow the parent chain to see if it is hanging.
5780 while(parent != dev->rootDir &&
5782 parent->parent->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
5784 parent = parent->parent;
5787 if(parent != dev->rootDir)
5792 (TSTR("Hanging object %d moved to lost and found" TENDSTR),
5794 yaffs_AddObjectToDirectory(dev->lostNFoundDir,obj);
5803 * Delete directory contents for cleaning up lost and found.
5805 static void yaffs_DeleteDirectoryContents(yaffs_Object *dir)
5808 struct ylist_head *lh;
5809 struct ylist_head *n;
5811 if(dir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5814 ylist_for_each_safe(lh, n, &dir->variant.directoryVariant.children) {
5816 obj = ylist_entry(lh, yaffs_Object, siblings);
5817 if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
5818 yaffs_DeleteDirectoryContents(obj);
5821 (TSTR("Deleting lost_found object %d" TENDSTR),
5824 /* Need to use UnlinkObject since Delete would not handle
5825 * hardlinked objects correctly.
5827 yaffs_UnlinkObject(obj);
5833 static void yaffs_EmptyLostAndFound(yaffs_Device *dev)
5835 yaffs_DeleteDirectoryContents(dev->lostNFoundDir);
5838 static int yaffs_Scan(yaffs_Device *dev)
5840 yaffs_ExtendedTags tags;
5850 yaffs_BlockState state;
5851 yaffs_Object *hardList = NULL;
5852 yaffs_BlockInfo *bi;
5853 __u32 sequenceNumber;
5854 yaffs_ObjectHeader *oh;
5856 yaffs_Object *parent;
5858 int alloc_failed = 0;
5860 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5868 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5869 dev->internalStartBlock, dev->internalEndBlock));
5871 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5873 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5875 /* Scan all the blocks to determine their state */
5876 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5877 bi = yaffs_GetBlockInfo(dev, blk);
5878 yaffs_ClearChunkBits(dev, blk);
5880 bi->softDeletions = 0;
5882 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5884 bi->blockState = state;
5885 bi->sequenceNumber = sequenceNumber;
5887 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
5888 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
5890 T(YAFFS_TRACE_SCAN_DEBUG,
5891 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5892 state, sequenceNumber));
5894 if (state == YAFFS_BLOCK_STATE_DEAD) {
5895 T(YAFFS_TRACE_BAD_BLOCKS,
5896 (TSTR("block %d is bad" TENDSTR), blk));
5897 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5898 T(YAFFS_TRACE_SCAN_DEBUG,
5899 (TSTR("Block empty " TENDSTR)));
5900 dev->nErasedBlocks++;
5901 dev->nFreeChunks += dev->param.nChunksPerBlock;
5905 startIterator = dev->internalStartBlock;
5906 endIterator = dev->internalEndBlock;
5908 /* For each block.... */
5909 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5916 blk = blockIterator;
5918 bi = yaffs_GetBlockInfo(dev, blk);
5919 state = bi->blockState;
5923 /* For each chunk in each block that needs scanning....*/
5924 for (c = 0; !alloc_failed && c < dev->param.nChunksPerBlock &&
5925 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5926 /* Read the tags and decide what to do */
5927 chunk = blk * dev->param.nChunksPerBlock + c;
5929 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5932 /* Let's have a good look at this chunk... */
5934 if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
5940 /*T((" %d %d deleted\n",blk,c)); */
5941 } else if (!tags.chunkUsed) {
5942 /* An unassigned chunk in the block
5943 * This means that either the block is empty or
5944 * this is the one being allocated from
5948 /* We're looking at the first chunk in the block so the block is unused */
5949 state = YAFFS_BLOCK_STATE_EMPTY;
5950 dev->nErasedBlocks++;
5952 /* this is the block being allocated from */
5955 (" Allocating from %d %d" TENDSTR),
5957 state = YAFFS_BLOCK_STATE_ALLOCATING;
5958 dev->allocationBlock = blk;
5959 dev->allocationPage = c;
5960 dev->allocationBlockFinder = blk;
5961 /* Set block finder here to encourage the allocator to go forth from here. */
5965 dev->nFreeChunks += (dev->param.nChunksPerBlock - c);
5966 } else if (tags.chunkId > 0) {
5967 /* chunkId > 0 so it is a data chunk... */
5968 unsigned int endpos;
5970 yaffs_SetChunkBit(dev, blk, c);
5973 in = yaffs_FindOrCreateObjectByNumber(dev,
5976 YAFFS_OBJECT_TYPE_FILE);
5977 /* PutChunkIntoFile checks for a clash (two data chunks with
5978 * the same chunkId).
5985 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, 1))
5990 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5993 in->variantType == YAFFS_OBJECT_TYPE_FILE
5994 && in->variant.fileVariant.scannedFileSize <
5996 in->variant.fileVariant.
5997 scannedFileSize = endpos;
5998 if (!dev->param.useHeaderFileSize) {
5999 in->variant.fileVariant.
6001 in->variant.fileVariant.
6006 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
6008 /* chunkId == 0, so it is an ObjectHeader.
6009 * Thus, we read in the object header and make the object
6011 yaffs_SetChunkBit(dev, blk, c);
6014 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
6018 oh = (yaffs_ObjectHeader *) chunkData;
6020 in = yaffs_FindObjectByNumber(dev,
6022 if (in && in->variantType != oh->type) {
6023 /* This should not happen, but somehow
6024 * Wev'e ended up with an objectId that has been reused but not yet
6025 * deleted, and worse still it has changed type. Delete the old object.
6028 yaffs_DeleteObject(in);
6033 in = yaffs_FindOrCreateObjectByNumber(dev,
6041 if (in && oh->shadowsObject > 0) {
6043 struct yaffs_ShadowFixerStruct *fixer;
6044 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
6046 fixer->next = shadowFixerList;
6047 shadowFixerList = fixer;
6048 fixer->objectId = tags.objectId;
6049 fixer->shadowedId = oh->shadowsObject;
6054 if (in && in->valid) {
6055 /* We have already filled this one. We have a duplicate and need to resolve it. */
6057 unsigned existingSerial = in->serial;
6058 unsigned newSerial = tags.serialNumber;
6060 if (((existingSerial + 1) & 3) == newSerial) {
6061 /* Use new one - destroy the exisiting one */
6062 yaffs_DeleteChunk(dev,
6067 /* Use existing - destroy this one. */
6068 yaffs_DeleteChunk(dev, chunk, 1,
6073 if (in && !in->valid &&
6074 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6075 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
6076 /* We only load some info, don't fiddle with directory structure */
6078 in->variantType = oh->type;
6080 in->yst_mode = oh->yst_mode;
6081 #ifdef CONFIG_YAFFS_WINCE
6082 in->win_atime[0] = oh->win_atime[0];
6083 in->win_ctime[0] = oh->win_ctime[0];
6084 in->win_mtime[0] = oh->win_mtime[0];
6085 in->win_atime[1] = oh->win_atime[1];
6086 in->win_ctime[1] = oh->win_ctime[1];
6087 in->win_mtime[1] = oh->win_mtime[1];
6089 in->yst_uid = oh->yst_uid;
6090 in->yst_gid = oh->yst_gid;
6091 in->yst_atime = oh->yst_atime;
6092 in->yst_mtime = oh->yst_mtime;
6093 in->yst_ctime = oh->yst_ctime;
6094 in->yst_rdev = oh->yst_rdev;
6096 in->hdrChunk = chunk;
6097 in->serial = tags.serialNumber;
6099 } else if (in && !in->valid) {
6100 /* we need to load this info */
6103 in->variantType = oh->type;
6105 in->yst_mode = oh->yst_mode;
6106 #ifdef CONFIG_YAFFS_WINCE
6107 in->win_atime[0] = oh->win_atime[0];
6108 in->win_ctime[0] = oh->win_ctime[0];
6109 in->win_mtime[0] = oh->win_mtime[0];
6110 in->win_atime[1] = oh->win_atime[1];
6111 in->win_ctime[1] = oh->win_ctime[1];
6112 in->win_mtime[1] = oh->win_mtime[1];
6114 in->yst_uid = oh->yst_uid;
6115 in->yst_gid = oh->yst_gid;
6116 in->yst_atime = oh->yst_atime;
6117 in->yst_mtime = oh->yst_mtime;
6118 in->yst_ctime = oh->yst_ctime;
6119 in->yst_rdev = oh->yst_rdev;
6121 in->hdrChunk = chunk;
6122 in->serial = tags.serialNumber;
6124 yaffs_SetObjectName(in, oh->name);
6127 /* directory stuff...
6132 yaffs_FindOrCreateObjectByNumber
6133 (dev, oh->parentObjectId,
6134 YAFFS_OBJECT_TYPE_DIRECTORY);
6137 if (parent && parent->variantType ==
6138 YAFFS_OBJECT_TYPE_UNKNOWN) {
6139 /* Set up as a directory */
6140 parent->variantType =
6141 YAFFS_OBJECT_TYPE_DIRECTORY;
6142 YINIT_LIST_HEAD(&parent->variant.
6145 } else if (!parent || parent->variantType !=
6146 YAFFS_OBJECT_TYPE_DIRECTORY) {
6147 /* Hoosterman, another problem....
6148 * We're trying to use a non-directory as a directory
6151 T(YAFFS_TRACE_ERROR,
6153 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6155 parent = dev->lostNFoundDir;
6158 yaffs_AddObjectToDirectory(parent, in);
6160 if (0 && (parent == dev->deletedDir ||
6161 parent == dev->unlinkedDir)) {
6162 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
6163 dev->nDeletedFiles++;
6165 /* Note re hardlinks.
6166 * Since we might scan a hardlink before its equivalent object is scanned
6167 * we put them all in a list.
6168 * After scanning is complete, we should have all the objects, so we run through this
6169 * list and fix up all the chains.
6172 switch (in->variantType) {
6173 case YAFFS_OBJECT_TYPE_UNKNOWN:
6174 /* Todo got a problem */
6176 case YAFFS_OBJECT_TYPE_FILE:
6177 if (dev->param.useHeaderFileSize)
6179 in->variant.fileVariant.
6184 case YAFFS_OBJECT_TYPE_HARDLINK:
6185 in->variant.hardLinkVariant.
6186 equivalentObjectId =
6187 oh->equivalentObjectId;
6188 in->hardLinks.next =
6189 (struct ylist_head *)
6193 case YAFFS_OBJECT_TYPE_DIRECTORY:
6196 case YAFFS_OBJECT_TYPE_SPECIAL:
6199 case YAFFS_OBJECT_TYPE_SYMLINK:
6200 in->variant.symLinkVariant.alias =
6201 yaffs_CloneString(oh->alias);
6202 if (!in->variant.symLinkVariant.alias)
6211 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6212 /* If we got this far while scanning, then the block is fully allocated.*/
6213 state = YAFFS_BLOCK_STATE_FULL;
6216 if (state == YAFFS_BLOCK_STATE_ALLOCATING) {
6217 /* If the block was partially allocated then treat it as fully allocated.*/
6218 state = YAFFS_BLOCK_STATE_FULL;
6219 dev->allocationBlock = -1;
6222 bi->blockState = state;
6224 /* Now let's see if it was dirty */
6225 if (bi->pagesInUse == 0 &&
6226 !bi->hasShrinkHeader &&
6227 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6228 yaffs_BlockBecameDirty(dev, blk);
6234 /* Ok, we've done all the scanning.
6235 * Fix up the hard link chains.
6236 * We should now have scanned all the objects, now it's time to add these
6240 yaffs_HardlinkFixup(dev, hardList);
6242 /* Fix up any shadowed objects */
6244 struct yaffs_ShadowFixerStruct *fixer;
6247 while (shadowFixerList) {
6248 fixer = shadowFixerList;
6249 shadowFixerList = fixer->next;
6250 /* Complete the rename transaction by deleting the shadowed object
6251 * then setting the object header to unshadowed.
6253 obj = yaffs_FindObjectByNumber(dev, fixer->shadowedId);
6255 yaffs_DeleteObject(obj);
6257 obj = yaffs_FindObjectByNumber(dev, fixer->objectId);
6260 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6266 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6271 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
6277 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
6280 yaffs_ObjectHeader *oh;
6282 yaffs_ExtendedTags tags;
6284 int alloc_failed = 0;
6292 T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
6294 in->lazyLoaded ? "not yet" : "already"));
6297 if (in->lazyLoaded && in->hdrChunk > 0) {
6299 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6301 result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
6302 oh = (yaffs_ObjectHeader *) chunkData;
6304 in->yst_mode = oh->yst_mode;
6305 #ifdef CONFIG_YAFFS_WINCE
6306 in->win_atime[0] = oh->win_atime[0];
6307 in->win_ctime[0] = oh->win_ctime[0];
6308 in->win_mtime[0] = oh->win_mtime[0];
6309 in->win_atime[1] = oh->win_atime[1];
6310 in->win_ctime[1] = oh->win_ctime[1];
6311 in->win_mtime[1] = oh->win_mtime[1];
6313 in->yst_uid = oh->yst_uid;
6314 in->yst_gid = oh->yst_gid;
6315 in->yst_atime = oh->yst_atime;
6316 in->yst_mtime = oh->yst_mtime;
6317 in->yst_ctime = oh->yst_ctime;
6318 in->yst_rdev = oh->yst_rdev;
6321 yaffs_SetObjectName(in, oh->name);
6323 if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6324 in->variant.symLinkVariant.alias =
6325 yaffs_CloneString(oh->alias);
6326 if (!in->variant.symLinkVariant.alias)
6327 alloc_failed = 1; /* Not returned to caller */
6330 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6334 static int yaffs_ScanBackwards(yaffs_Device *dev)
6336 yaffs_ExtendedTags tags;
6341 int nBlocksToScan = 0;
6347 yaffs_BlockState state;
6348 yaffs_Object *hardList = NULL;
6349 yaffs_BlockInfo *bi;
6350 __u32 sequenceNumber;
6351 yaffs_ObjectHeader *oh;
6353 yaffs_Object *parent;
6354 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6360 int foundChunksInBlock;
6361 int equivalentObjectId;
6362 int alloc_failed = 0;
6365 yaffs_BlockIndex *blockIndex = NULL;
6366 int altBlockIndex = 0;
6368 if (!dev->param.isYaffs2) {
6370 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6376 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
6377 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6380 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6382 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6385 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6391 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6395 dev->blocksInCheckpoint = 0;
6397 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6399 /* Scan all the blocks to determine their state */
6400 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6401 bi = yaffs_GetBlockInfo(dev, blk);
6402 yaffs_ClearChunkBits(dev, blk);
6404 bi->softDeletions = 0;
6406 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6408 bi->blockState = state;
6409 bi->sequenceNumber = sequenceNumber;
6411 if (bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6412 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6413 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6414 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6416 T(YAFFS_TRACE_SCAN_DEBUG,
6417 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6418 state, sequenceNumber));
6421 if (state == YAFFS_BLOCK_STATE_CHECKPOINT) {
6422 dev->blocksInCheckpoint++;
6424 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6425 T(YAFFS_TRACE_BAD_BLOCKS,
6426 (TSTR("block %d is bad" TENDSTR), blk));
6427 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6428 T(YAFFS_TRACE_SCAN_DEBUG,
6429 (TSTR("Block empty " TENDSTR)));
6430 dev->nErasedBlocks++;
6431 dev->nFreeChunks += dev->param.nChunksPerBlock;
6432 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6434 /* Determine the highest sequence number */
6435 if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6436 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6438 blockIndex[nBlocksToScan].seq = sequenceNumber;
6439 blockIndex[nBlocksToScan].block = blk;
6443 if (sequenceNumber >= dev->sequenceNumber)
6444 dev->sequenceNumber = sequenceNumber;
6446 /* TODO: Nasty sequence number! */
6449 ("Block scanning block %d has bad sequence number %d"
6450 TENDSTR), blk, sequenceNumber));
6457 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6463 /* Sort the blocks */
6464 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6466 /* Use qsort now. */
6467 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6471 /* Dungy old bubble sort... */
6473 yaffs_BlockIndex temp;
6477 for (i = 0; i < nBlocksToScan; i++)
6478 for (j = i + 1; j < nBlocksToScan; j++)
6479 if (blockIndex[i].seq > blockIndex[j].seq) {
6480 temp = blockIndex[j];
6481 blockIndex[j] = blockIndex[i];
6482 blockIndex[i] = temp;
6489 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6491 /* Now scan the blocks looking at the data. */
6493 endIterator = nBlocksToScan - 1;
6494 T(YAFFS_TRACE_SCAN_DEBUG,
6495 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6497 /* For each block.... backwards */
6498 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6500 /* Cooperative multitasking! This loop can run for so
6501 long that watchdog timers expire. */
6504 /* get the block to scan in the correct order */
6505 blk = blockIndex[blockIterator].block;
6507 bi = yaffs_GetBlockInfo(dev, blk);
6510 state = bi->blockState;
6514 /* For each chunk in each block that needs scanning.... */
6515 foundChunksInBlock = 0;
6516 for (c = dev->param.nChunksPerBlock - 1;
6517 !alloc_failed && c >= 0 &&
6518 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6519 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6520 /* Scan backwards...
6521 * Read the tags and decide what to do
6524 chunk = blk * dev->param.nChunksPerBlock + c;
6526 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6529 /* Let's have a good look at this chunk... */
6531 if (!tags.chunkUsed) {
6532 /* An unassigned chunk in the block.
6533 * If there are used chunks after this one, then
6534 * it is a chunk that was skipped due to failing the erased
6535 * check. Just skip it so that it can be deleted.
6536 * But, more typically, We get here when this is an unallocated
6537 * chunk and his means that either the block is empty or
6538 * this is the one being allocated from
6541 if (foundChunksInBlock) {
6542 /* This is a chunk that was skipped due to failing the erased check */
6543 } else if (c == 0) {
6544 /* We're looking at the first chunk in the block so the block is unused */
6545 state = YAFFS_BLOCK_STATE_EMPTY;
6546 dev->nErasedBlocks++;
6548 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6549 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6550 if (dev->sequenceNumber == bi->sequenceNumber) {
6551 /* this is the block being allocated from */
6555 (" Allocating from %d %d"
6558 state = YAFFS_BLOCK_STATE_ALLOCATING;
6559 dev->allocationBlock = blk;
6560 dev->allocationPage = c;
6561 dev->allocationBlockFinder = blk;
6563 /* This is a partially written block that is not
6564 * the current allocation block.
6567 T(YAFFS_TRACE_ALWAYS,
6568 (TSTR("Partially written block %d detected" TENDSTR),
6576 } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED) {
6578 (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
6583 } else if (tags.chunkId > 0) {
6584 /* chunkId > 0 so it is a data chunk... */
6585 unsigned int endpos;
6587 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6589 foundChunksInBlock = 1;
6592 yaffs_SetChunkBit(dev, blk, c);
6595 in = yaffs_FindOrCreateObjectByNumber(dev,
6598 YAFFS_OBJECT_TYPE_FILE);
6605 in->variantType == YAFFS_OBJECT_TYPE_FILE
6606 && chunkBase < in->variant.fileVariant.shrinkSize) {
6607 /* This has not been invalidated by a resize */
6608 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, -1)) {
6612 /* File size is calculated by looking at the data chunks if we have not
6613 * seen an object header yet. Stop this practice once we find an object header.
6615 endpos = chunkBase + tags.byteCount;
6617 if (!in->valid && /* have not got an object header yet */
6618 in->variant.fileVariant.scannedFileSize < endpos) {
6619 in->variant.fileVariant.scannedFileSize = endpos;
6620 in->variant.fileVariant.fileSize = endpos;
6624 /* This chunk has been invalidated by a resize, or a past file deletion
6625 * so delete the chunk*/
6626 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6630 /* chunkId == 0, so it is an ObjectHeader.
6631 * Thus, we read in the object header and make the object
6633 foundChunksInBlock = 1;
6635 yaffs_SetChunkBit(dev, blk, c);
6641 if (tags.extraHeaderInfoAvailable) {
6642 in = yaffs_FindOrCreateObjectByNumber(dev,
6644 tags.extraObjectType);
6650 (!in->valid && dev->param.disableLazyLoad) ||
6651 tags.extraShadows ||
6653 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6654 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))) {
6656 /* If we don't have valid info then we need to read the chunk
6657 * TODO In future we can probably defer reading the chunk and
6658 * living with invalid data until needed.
6661 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6666 oh = (yaffs_ObjectHeader *) chunkData;
6668 if (dev->param.inbandTags) {
6669 /* Fix up the header if they got corrupted by inband tags */
6670 oh->shadowsObject = oh->inbandShadowsObject;
6671 oh->isShrink = oh->inbandIsShrink;
6675 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6683 /* TODO Hoosterman we have a problem! */
6684 T(YAFFS_TRACE_ERROR,
6686 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6687 TENDSTR), tags.objectId, chunk));
6692 /* We have already filled this one.
6693 * We have a duplicate that will be discarded, but
6694 * we first have to suck out resize info if it is a file.
6697 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6699 oh->type == YAFFS_OBJECT_TYPE_FILE) ||
6700 (tags.extraHeaderInfoAvailable &&
6701 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))) {
6703 (oh) ? oh->fileSize : tags.
6705 __u32 parentObjectId =
6707 parentObjectId : tags.
6708 extraParentObjectId;
6712 (oh) ? oh->isShrink : tags.
6713 extraIsShrinkHeader;
6715 /* If it is deleted (unlinked at start also means deleted)
6716 * we treat the file size as being zeroed at this point.
6718 if (parentObjectId ==
6719 YAFFS_OBJECTID_DELETED
6720 || parentObjectId ==
6721 YAFFS_OBJECTID_UNLINKED) {
6726 if (isShrink && in->variant.fileVariant.shrinkSize > thisSize)
6727 in->variant.fileVariant.shrinkSize = thisSize;
6730 bi->hasShrinkHeader = 1;
6733 /* Use existing - destroy this one. */
6734 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6738 if (!in->valid && in->variantType !=
6739 (oh ? oh->type : tags.extraObjectType))
6740 T(YAFFS_TRACE_ERROR, (
6741 TSTR("yaffs tragedy: Bad object type, "
6742 TCONT("%d != %d, for object %d at chunk ")
6743 TCONT("%d during scan")
6745 oh->type : tags.extraObjectType,
6746 in->variantType, tags.objectId,
6750 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6752 YAFFS_OBJECTID_LOSTNFOUND)) {
6753 /* We only load some info, don't fiddle with directory structure */
6757 in->variantType = oh->type;
6759 in->yst_mode = oh->yst_mode;
6760 #ifdef CONFIG_YAFFS_WINCE
6761 in->win_atime[0] = oh->win_atime[0];
6762 in->win_ctime[0] = oh->win_ctime[0];
6763 in->win_mtime[0] = oh->win_mtime[0];
6764 in->win_atime[1] = oh->win_atime[1];
6765 in->win_ctime[1] = oh->win_ctime[1];
6766 in->win_mtime[1] = oh->win_mtime[1];
6768 in->yst_uid = oh->yst_uid;
6769 in->yst_gid = oh->yst_gid;
6770 in->yst_atime = oh->yst_atime;
6771 in->yst_mtime = oh->yst_mtime;
6772 in->yst_ctime = oh->yst_ctime;
6773 in->yst_rdev = oh->yst_rdev;
6777 in->variantType = tags.extraObjectType;
6781 in->hdrChunk = chunk;
6783 } else if (!in->valid) {
6784 /* we need to load this info */
6787 in->hdrChunk = chunk;
6790 in->variantType = oh->type;
6792 in->yst_mode = oh->yst_mode;
6793 #ifdef CONFIG_YAFFS_WINCE
6794 in->win_atime[0] = oh->win_atime[0];
6795 in->win_ctime[0] = oh->win_ctime[0];
6796 in->win_mtime[0] = oh->win_mtime[0];
6797 in->win_atime[1] = oh->win_atime[1];
6798 in->win_ctime[1] = oh->win_ctime[1];
6799 in->win_mtime[1] = oh->win_mtime[1];
6801 in->yst_uid = oh->yst_uid;
6802 in->yst_gid = oh->yst_gid;
6803 in->yst_atime = oh->yst_atime;
6804 in->yst_mtime = oh->yst_mtime;
6805 in->yst_ctime = oh->yst_ctime;
6806 in->yst_rdev = oh->yst_rdev;
6809 if (oh->shadowsObject > 0)
6810 yaffs_HandleShadowedObject(dev,
6817 yaffs_SetObjectName(in, oh->name);
6819 yaffs_FindOrCreateObjectByNumber
6820 (dev, oh->parentObjectId,
6821 YAFFS_OBJECT_TYPE_DIRECTORY);
6823 fileSize = oh->fileSize;
6824 isShrink = oh->isShrink;
6825 equivalentObjectId = oh->equivalentObjectId;
6828 in->variantType = tags.extraObjectType;
6830 yaffs_FindOrCreateObjectByNumber
6831 (dev, tags.extraParentObjectId,
6832 YAFFS_OBJECT_TYPE_DIRECTORY);
6833 fileSize = tags.extraFileLength;
6834 isShrink = tags.extraIsShrinkHeader;
6835 equivalentObjectId = tags.extraEquivalentObjectId;
6844 /* directory stuff...
6848 if (parent && parent->variantType ==
6849 YAFFS_OBJECT_TYPE_UNKNOWN) {
6850 /* Set up as a directory */
6851 parent->variantType =
6852 YAFFS_OBJECT_TYPE_DIRECTORY;
6853 YINIT_LIST_HEAD(&parent->variant.
6856 } else if (!parent || parent->variantType !=
6857 YAFFS_OBJECT_TYPE_DIRECTORY) {
6858 /* Hoosterman, another problem....
6859 * We're trying to use a non-directory as a directory
6862 T(YAFFS_TRACE_ERROR,
6864 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6866 parent = dev->lostNFoundDir;
6869 yaffs_AddObjectToDirectory(parent, in);
6871 itsUnlinked = (parent == dev->deletedDir) ||
6872 (parent == dev->unlinkedDir);
6875 /* Mark the block as having a shrinkHeader */
6876 bi->hasShrinkHeader = 1;
6879 /* Note re hardlinks.
6880 * Since we might scan a hardlink before its equivalent object is scanned
6881 * we put them all in a list.
6882 * After scanning is complete, we should have all the objects, so we run
6883 * through this list and fix up all the chains.
6886 switch (in->variantType) {
6887 case YAFFS_OBJECT_TYPE_UNKNOWN:
6888 /* Todo got a problem */
6890 case YAFFS_OBJECT_TYPE_FILE:
6892 if (in->variant.fileVariant.
6893 scannedFileSize < fileSize) {
6894 /* This covers the case where the file size is greater
6895 * than where the data is
6896 * This will happen if the file is resized to be larger
6897 * than its current data extents.
6899 in->variant.fileVariant.fileSize = fileSize;
6900 in->variant.fileVariant.scannedFileSize = fileSize;
6903 if (in->variant.fileVariant.shrinkSize > fileSize)
6904 in->variant.fileVariant.shrinkSize = fileSize;
6908 case YAFFS_OBJECT_TYPE_HARDLINK:
6910 in->variant.hardLinkVariant.equivalentObjectId =
6912 in->hardLinks.next =
6913 (struct ylist_head *) hardList;
6917 case YAFFS_OBJECT_TYPE_DIRECTORY:
6920 case YAFFS_OBJECT_TYPE_SPECIAL:
6923 case YAFFS_OBJECT_TYPE_SYMLINK:
6925 in->variant.symLinkVariant.alias =
6926 yaffs_CloneString(oh->alias);
6927 if (!in->variant.symLinkVariant.alias)
6937 } /* End of scanning for each chunk */
6939 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6940 /* If we got this far while scanning, then the block is fully allocated. */
6941 state = YAFFS_BLOCK_STATE_FULL;
6945 bi->blockState = state;
6947 /* Now let's see if it was dirty */
6948 if (bi->pagesInUse == 0 &&
6949 !bi->hasShrinkHeader &&
6950 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6951 yaffs_BlockBecameDirty(dev, blk);
6956 yaffs_SkipRestOfBlock(dev);
6959 YFREE_ALT(blockIndex);
6963 /* Ok, we've done all the scanning.
6964 * Fix up the hard link chains.
6965 * We should now have scanned all the objects, now it's time to add these
6968 yaffs_HardlinkFixup(dev, hardList);
6971 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6976 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6981 /*------------------------------ Directory Functions ----------------------------- */
6983 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
6985 struct ylist_head *lh;
6986 yaffs_Object *listObj;
6991 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
6996 if (yaffs_SkipVerification(obj->myDev))
7000 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
7005 if (obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7006 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
7010 /* Iterate through the objects in each hash entry */
7012 ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
7014 listObj = ylist_entry(lh, yaffs_Object, siblings);
7015 yaffs_VerifyObject(listObj);
7022 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR), count));
7027 static void yaffs_VerifyDirectory(yaffs_Object *directory)
7029 struct ylist_head *lh;
7030 yaffs_Object *listObj;
7037 if (yaffs_SkipFullVerification(directory->myDev))
7040 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7041 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR), directory->variantType));
7045 /* Iterate through the objects in each hash entry */
7047 ylist_for_each(lh, &directory->variant.directoryVariant.children) {
7049 listObj = ylist_entry(lh, yaffs_Object, siblings);
7050 if (listObj->parent != directory) {
7051 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR), listObj->parent));
7054 yaffs_VerifyObjectInDirectory(listObj);
7060 *yaffs_UpdateParent() handles fixing a directories mtime and ctime when a new
7061 * link (ie. name) is created or deleted in the directory.
7064 * create dir/a : update dir's mtime/ctime
7065 * rm dir/a: update dir's mtime/ctime
7066 * modify dir/a: don't update dir's mtimme/ctime
7068 * This can be handled immediately or defered. Defering helps reduce the number
7069 * of updates when many files in a directory are changed within a brief period.
7071 * If the directory updating is defered then yaffs_UpdateDirtyDirecories must be
7072 * called periodically.
7075 static void yaffs_UpdateParent(yaffs_Object *obj)
7083 obj->yst_mtime = obj->yst_ctime = Y_CURRENT_TIME;
7084 if(dev->param.deferDirectoryUpdate){
7085 struct ylist_head *link = &obj->variant.directoryVariant.dirty;
7087 if(ylist_empty(link)){
7088 ylist_add(link,&dev->dirtyDirectories);
7089 T(YAFFS_TRACE_BACKGROUND, (TSTR("Added object %d to dirty directories" TENDSTR),obj->objectId));
7093 yaffs_UpdateObjectHeader(obj,NULL,0,0,0);
7096 void yaffs_UpdateDirtyDirectories(yaffs_Device *dev)
7098 struct ylist_head *link;
7100 yaffs_DirectoryStructure *dS;
7101 yaffs_ObjectVariant *oV;
7103 T(YAFFS_TRACE_BACKGROUND, (TSTR("Update dirty directories" TENDSTR)));
7105 while(!ylist_empty(&dev->dirtyDirectories)){
7106 link = dev->dirtyDirectories.next;
7107 ylist_del_init(link);
7109 dS=ylist_entry(link,yaffs_DirectoryStructure,dirty);
7110 oV = ylist_entry(dS,yaffs_ObjectVariant,directoryVariant);
7111 obj = ylist_entry(oV,yaffs_Object,variant);
7113 T(YAFFS_TRACE_BACKGROUND, (TSTR("Update directory %d" TENDSTR), obj->objectId));
7116 yaffs_UpdateObjectHeader(obj,NULL,0,0,0);
7120 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
7122 yaffs_Device *dev = obj->myDev;
7123 yaffs_Object *parent;
7125 yaffs_VerifyObjectInDirectory(obj);
7126 parent = obj->parent;
7128 yaffs_VerifyDirectory(parent);
7130 if (dev && dev->param.removeObjectCallback)
7131 dev->param.removeObjectCallback(obj);
7134 ylist_del_init(&obj->siblings);
7137 yaffs_VerifyDirectory(parent);
7140 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
7144 T(YAFFS_TRACE_ALWAYS,
7146 ("tragedy: Trying to add an object to a null pointer directory"
7151 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7152 T(YAFFS_TRACE_ALWAYS,
7154 ("tragedy: Trying to add an object to a non-directory"
7159 if (obj->siblings.prev == NULL) {
7160 /* Not initialised */
7165 yaffs_VerifyDirectory(directory);
7167 yaffs_RemoveObjectFromDirectory(obj);
7171 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
7172 obj->parent = directory;
7174 if (directory == obj->myDev->unlinkedDir
7175 || directory == obj->myDev->deletedDir) {
7177 obj->myDev->nUnlinkedFiles++;
7178 obj->renameAllowed = 0;
7181 yaffs_VerifyDirectory(directory);
7182 yaffs_VerifyObjectInDirectory(obj);
7185 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
7190 struct ylist_head *i;
7191 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
7199 T(YAFFS_TRACE_ALWAYS,
7201 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7206 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7207 T(YAFFS_TRACE_ALWAYS,
7209 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7213 sum = yaffs_CalcNameSum(name);
7215 ylist_for_each(i, &directory->variant.directoryVariant.children) {
7217 l = ylist_entry(i, yaffs_Object, siblings);
7219 if (l->parent != directory)
7222 yaffs_CheckObjectDetailsLoaded(l);
7224 /* Special case for lost-n-found */
7225 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7226 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
7228 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
7229 /* LostnFound chunk called Objxxx
7232 yaffs_GetObjectName(l, buffer,
7233 YAFFS_MAX_NAME_LENGTH + 1);
7234 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
7245 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
7246 int (*fn) (yaffs_Object *))
7248 struct ylist_head *i;
7252 T(YAFFS_TRACE_ALWAYS,
7254 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7259 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7260 T(YAFFS_TRACE_ALWAYS,
7262 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7267 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
7269 l = ylist_entry(i, yaffs_Object, siblings);
7280 /* GetEquivalentObject dereferences any hard links to get to the
7284 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
7286 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
7287 /* We want the object id of the equivalent object, not this one */
7288 obj = obj->variant.hardLinkVariant.equivalentObject;
7289 yaffs_CheckObjectDetailsLoaded(obj);
7294 int yaffs_GetObjectName(yaffs_Object *obj, YCHAR *name, int buffSize)
7296 memset(name, 0, buffSize * sizeof(YCHAR));
7298 yaffs_CheckObjectDetailsLoaded(obj);
7300 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7301 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
7302 } else if (obj->hdrChunk <= 0) {
7304 YCHAR numString[20];
7305 YCHAR *x = &numString[19];
7306 unsigned v = obj->objectId;
7310 *x = '0' + (v % 10);
7313 /* make up a name */
7314 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
7315 yaffs_strcat(locName, x);
7316 yaffs_strncpy(name, locName, buffSize - 1);
7319 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
7320 else if (obj->shortName[0])
7321 yaffs_strncpy(name, obj->shortName,YAFFS_SHORT_NAME_LENGTH+1);
7325 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
7327 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
7329 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
7331 if (obj->hdrChunk > 0) {
7332 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
7333 obj->hdrChunk, buffer,
7336 yaffs_strncpy(name, oh->name, buffSize - 1);
7339 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
7342 return yaffs_strnlen(name,buffSize-1);
7345 int yaffs_GetObjectFileLength(yaffs_Object *obj)
7347 /* Dereference any hard linking */
7348 obj = yaffs_GetEquivalentObject(obj);
7350 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
7351 return obj->variant.fileVariant.fileSize;
7352 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
7353 if(!obj->variant.symLinkVariant.alias)
7355 return yaffs_strnlen(obj->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
7357 /* Only a directory should drop through to here */
7358 return obj->myDev->nDataBytesPerChunk;
7362 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
7365 struct ylist_head *i;
7368 count++; /* the object itself */
7370 ylist_for_each(i, &obj->hardLinks)
7371 count++; /* add the hard links; */
7376 int yaffs_GetObjectInode(yaffs_Object *obj)
7378 obj = yaffs_GetEquivalentObject(obj);
7380 return obj->objectId;
7383 unsigned yaffs_GetObjectType(yaffs_Object *obj)
7385 obj = yaffs_GetEquivalentObject(obj);
7387 switch (obj->variantType) {
7388 case YAFFS_OBJECT_TYPE_FILE:
7391 case YAFFS_OBJECT_TYPE_DIRECTORY:
7394 case YAFFS_OBJECT_TYPE_SYMLINK:
7397 case YAFFS_OBJECT_TYPE_HARDLINK:
7400 case YAFFS_OBJECT_TYPE_SPECIAL:
7401 if (S_ISFIFO(obj->yst_mode))
7403 if (S_ISCHR(obj->yst_mode))
7405 if (S_ISBLK(obj->yst_mode))
7407 if (S_ISSOCK(obj->yst_mode))
7415 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
7417 obj = yaffs_GetEquivalentObject(obj);
7418 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
7419 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7421 return yaffs_CloneString(_Y(""));
7424 #ifndef CONFIG_YAFFS_WINCE
7426 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
7428 unsigned int valid = attr->ia_valid;
7430 if (valid & ATTR_MODE)
7431 obj->yst_mode = attr->ia_mode;
7432 if (valid & ATTR_UID)
7433 obj->yst_uid = attr->ia_uid;
7434 if (valid & ATTR_GID)
7435 obj->yst_gid = attr->ia_gid;
7437 if (valid & ATTR_ATIME)
7438 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7439 if (valid & ATTR_CTIME)
7440 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7441 if (valid & ATTR_MTIME)
7442 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7444 if (valid & ATTR_SIZE)
7445 yaffs_ResizeFile(obj, attr->ia_size);
7447 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7452 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
7454 unsigned int valid = 0;
7456 attr->ia_mode = obj->yst_mode;
7458 attr->ia_uid = obj->yst_uid;
7460 attr->ia_gid = obj->yst_gid;
7463 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7464 valid |= ATTR_ATIME;
7465 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7466 valid |= ATTR_CTIME;
7467 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7468 valid |= ATTR_MTIME;
7470 attr->ia_size = yaffs_GetFileSize(obj);
7473 attr->ia_valid = valid;
7481 int yaffs_DumpObject(yaffs_Object *obj)
7485 yaffs_GetObjectName(obj, name, YAFFS_MAX_NAME_LENGTH + 1);
7487 T(YAFFS_TRACE_ALWAYS,
7489 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7490 " chunk %d type %d size %d\n"
7491 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7492 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7493 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7499 /*---------------------------- Initialisation code -------------------------------------- */
7501 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
7504 /* Common functions, gotta have */
7505 if (!dev->param.eraseBlockInNAND || !dev->param.initialiseNAND)
7508 #ifdef CONFIG_YAFFS_YAFFS2
7510 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7511 if (dev->param.writeChunkWithTagsToNAND &&
7512 dev->param.readChunkWithTagsFromNAND &&
7513 !dev->param.writeChunkToNAND &&
7514 !dev->param.readChunkFromNAND &&
7515 dev->param.markNANDBlockBad &&
7516 dev->param.queryNANDBlock)
7520 /* Can use the "spare" style interface for yaffs1 */
7521 if (!dev->param.isYaffs2 &&
7522 !dev->param.writeChunkWithTagsToNAND &&
7523 !dev->param.readChunkWithTagsFromNAND &&
7524 dev->param.writeChunkToNAND &&
7525 dev->param.readChunkFromNAND &&
7526 !dev->param.markNANDBlockBad &&
7527 !dev->param.queryNANDBlock)
7534 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7536 /* Initialise the unlinked, deleted, root and lost and found directories */
7538 dev->lostNFoundDir = dev->rootDir = NULL;
7539 dev->unlinkedDir = dev->deletedDir = NULL;
7542 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7545 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7548 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7549 YAFFS_ROOT_MODE | S_IFDIR);
7550 dev->lostNFoundDir =
7551 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7552 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7554 if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
7555 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7562 int yaffs_GutsInitialise(yaffs_Device *dev)
7564 int init_failed = 0;
7568 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7570 /* Check stuff that must be set */
7573 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7577 dev->internalStartBlock = dev->param.startBlock;
7578 dev->internalEndBlock = dev->param.endBlock;
7579 dev->blockOffset = 0;
7580 dev->chunkOffset = 0;
7581 dev->nFreeChunks = 0;
7585 if (dev->param.startBlock == 0) {
7586 dev->internalStartBlock = dev->param.startBlock + 1;
7587 dev->internalEndBlock = dev->param.endBlock + 1;
7588 dev->blockOffset = 1;
7589 dev->chunkOffset = dev->param.nChunksPerBlock;
7592 /* Check geometry parameters. */
7594 if ((!dev->param.inbandTags && dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 1024) ||
7595 (!dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 512) ||
7596 (dev->param.inbandTags && !dev->param.isYaffs2) ||
7597 dev->param.nChunksPerBlock < 2 ||
7598 dev->param.nReservedBlocks < 2 ||
7599 dev->internalStartBlock <= 0 ||
7600 dev->internalEndBlock <= 0 ||
7601 dev->internalEndBlock <= (dev->internalStartBlock + dev->param.nReservedBlocks + 2)) { /* otherwise it is too small */
7602 T(YAFFS_TRACE_ALWAYS,
7604 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7605 TENDSTR), dev->param.totalBytesPerChunk, dev->param.isYaffs2 ? "2" : "", dev->param.inbandTags));
7609 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7610 T(YAFFS_TRACE_ALWAYS,
7611 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7615 /* Sort out space for inband tags, if required */
7616 if (dev->param.inbandTags)
7617 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7619 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk;
7621 /* Got the right mix of functions? */
7622 if (!yaffs_CheckDevFunctions(dev)) {
7623 /* Function missing */
7624 T(YAFFS_TRACE_ALWAYS,
7626 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7631 /* This is really a compilation check. */
7632 if (!yaffs_CheckStructures()) {
7633 T(YAFFS_TRACE_ALWAYS,
7634 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7638 if (dev->isMounted) {
7639 T(YAFFS_TRACE_ALWAYS,
7640 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7644 /* Finished with most checks. One or two more checks happen later on too. */
7648 /* OK now calculate a few things for the device */
7651 * Calculate all the chunk size manipulation numbers:
7653 x = dev->nDataBytesPerChunk;
7654 /* We always use dev->chunkShift and dev->chunkDiv */
7655 dev->chunkShift = Shifts(x);
7656 x >>= dev->chunkShift;
7658 /* We only use chunk mask if chunkDiv is 1 */
7659 dev->chunkMask = (1<<dev->chunkShift) - 1;
7662 * Calculate chunkGroupBits.
7663 * We need to find the next power of 2 > than internalEndBlock
7666 x = dev->param.nChunksPerBlock * (dev->internalEndBlock + 1);
7670 /* Set up tnode width if wide tnodes are enabled. */
7671 if (!dev->param.wideTnodesDisabled) {
7672 /* bits must be even so that we end up with 32-bit words */
7676 dev->tnodeWidth = 16;
7678 dev->tnodeWidth = bits;
7680 dev->tnodeWidth = 16;
7682 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7684 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7685 * so if the bitwidth of the
7686 * chunk range we're using is greater than 16 we need
7687 * to figure out chunk shift and chunkGroupSize
7690 if (bits <= dev->tnodeWidth)
7691 dev->chunkGroupBits = 0;
7693 dev->chunkGroupBits = bits - dev->tnodeWidth;
7696 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7698 if (dev->param.nChunksPerBlock < dev->chunkGroupSize) {
7699 /* We have a problem because the soft delete won't work if
7700 * the chunk group size > chunks per block.
7701 * This can be remedied by using larger "virtual blocks".
7703 T(YAFFS_TRACE_ALWAYS,
7704 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7709 /* OK, we've finished verifying the device, lets continue with initialisation */
7711 /* More device initialisation */
7712 dev->garbageCollections = 0;
7713 dev->passiveGarbageCollections = 0;
7714 dev->currentDirtyChecker = 0;
7715 dev->bufferedBlock = -1;
7716 dev->doingBufferedBlockRewrite = 0;
7717 dev->nDeletedFiles = 0;
7718 dev->nBackgroundDeletions = 0;
7719 dev->nUnlinkedFiles = 0;
7721 dev->eccUnfixed = 0;
7722 dev->tagsEccFixed = 0;
7723 dev->tagsEccUnfixed = 0;
7724 dev->nErasureFailures = 0;
7725 dev->nErasedBlocks = 0;
7727 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7728 YINIT_LIST_HEAD(&dev->dirtyDirectories);
7729 dev->oldestDirtySequence = 0;
7731 /* Initialise temporary buffers and caches. */
7732 if (!yaffs_InitialiseTempBuffers(dev))
7735 dev->srCache = NULL;
7736 dev->gcCleanupList = NULL;
7740 dev->param.nShortOpCaches > 0) {
7743 int srCacheBytes = dev->param.nShortOpCaches * sizeof(yaffs_ChunkCache);
7745 if (dev->param.nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
7746 dev->param.nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7748 dev->srCache = YMALLOC(srCacheBytes);
7750 buf = (__u8 *) dev->srCache;
7753 memset(dev->srCache, 0, srCacheBytes);
7755 for (i = 0; i < dev->param.nShortOpCaches && buf; i++) {
7756 dev->srCache[i].object = NULL;
7757 dev->srCache[i].lastUse = 0;
7758 dev->srCache[i].dirty = 0;
7759 dev->srCache[i].data = buf = YMALLOC_DMA(dev->param.totalBytesPerChunk);
7770 dev->gcCleanupList = YMALLOC(dev->param.nChunksPerBlock * sizeof(__u32));
7771 if (!dev->gcCleanupList)
7775 if (dev->param.isYaffs2)
7776 dev->param.useHeaderFileSize = 1;
7778 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7781 yaffs_InitialiseTnodes(dev);
7782 yaffs_InitialiseObjects(dev);
7784 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7789 /* Now scan the flash. */
7790 if (dev->param.isYaffs2) {
7791 if (yaffs_CheckpointRestore(dev)) {
7792 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7793 T(YAFFS_TRACE_ALWAYS,
7794 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7797 /* Clean up the mess caused by an aborted checkpoint load
7798 * and scan backwards.
7800 yaffs_DeinitialiseBlocks(dev);
7801 yaffs_DeinitialiseTnodes(dev);
7802 yaffs_DeinitialiseObjects(dev);
7805 dev->nErasedBlocks = 0;
7806 dev->nFreeChunks = 0;
7807 dev->allocationBlock = -1;
7808 dev->allocationPage = -1;
7809 dev->nDeletedFiles = 0;
7810 dev->nUnlinkedFiles = 0;
7811 dev->nBackgroundDeletions = 0;
7813 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7816 yaffs_InitialiseTnodes(dev);
7817 yaffs_InitialiseObjects(dev);
7819 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7822 if (!init_failed && !yaffs_ScanBackwards(dev))
7825 } else if (!yaffs_Scan(dev))
7828 yaffs_StripDeletedObjects(dev);
7829 yaffs_FixHangingObjects(dev);
7830 if(dev->param.emptyLostAndFound)
7831 yaffs_EmptyLostAndFound(dev);
7835 /* Clean up the mess */
7836 T(YAFFS_TRACE_TRACING,
7837 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7839 yaffs_Deinitialise(dev);
7843 /* Zero out stats */
7844 dev->nPageReads = 0;
7845 dev->nPageWrites = 0;
7846 dev->nBlockErasures = 0;
7848 dev->nRetriedWrites = 0;
7850 dev->nRetiredBlocks = 0;
7852 yaffs_VerifyFreeChunks(dev);
7853 yaffs_VerifyBlocks(dev);
7855 /* Clean up any aborted checkpoint data */
7856 if(!dev->isCheckpointed && dev->blocksInCheckpoint > 0)
7857 yaffs_InvalidateCheckpoint(dev);
7859 T(YAFFS_TRACE_TRACING,
7860 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7865 void yaffs_Deinitialise(yaffs_Device *dev)
7867 if (dev->isMounted) {
7870 yaffs_DeinitialiseBlocks(dev);
7871 yaffs_DeinitialiseTnodes(dev);
7872 yaffs_DeinitialiseObjects(dev);
7873 if (dev->param.nShortOpCaches > 0 &&
7876 for (i = 0; i < dev->param.nShortOpCaches; i++) {
7877 if (dev->srCache[i].data)
7878 YFREE(dev->srCache[i].data);
7879 dev->srCache[i].data = NULL;
7882 YFREE(dev->srCache);
7883 dev->srCache = NULL;
7886 YFREE(dev->gcCleanupList);
7888 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
7889 YFREE(dev->tempBuffer[i].buffer);
7893 if (dev->param.deinitialiseNAND)
7894 dev->param.deinitialiseNAND(dev);
7898 static int yaffs_CountFreeChunks(yaffs_Device *dev)
7903 yaffs_BlockInfo *blk;
7905 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7907 blk = yaffs_GetBlockInfo(dev, b);
7909 switch (blk->blockState) {
7910 case YAFFS_BLOCK_STATE_EMPTY:
7911 case YAFFS_BLOCK_STATE_ALLOCATING:
7912 case YAFFS_BLOCK_STATE_COLLECTING:
7913 case YAFFS_BLOCK_STATE_FULL:
7915 (dev->param.nChunksPerBlock - blk->pagesInUse +
7916 blk->softDeletions);
7926 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
7928 /* This is what we report to the outside world */
7931 int nDirtyCacheChunks;
7932 int blocksForCheckpoint;
7936 nFree = dev->nFreeChunks;
7938 nFree = yaffs_CountFreeChunks(dev);
7941 nFree += dev->nDeletedFiles;
7943 /* Now count the number of dirty chunks in the cache and subtract those */
7945 for (nDirtyCacheChunks = 0, i = 0; i < dev->param.nShortOpCaches; i++) {
7946 if (dev->srCache[i].dirty)
7947 nDirtyCacheChunks++;
7950 nFree -= nDirtyCacheChunks;
7952 nFree -= ((dev->param.nReservedBlocks + 1) * dev->param.nChunksPerBlock);
7954 /* Now we figure out how much to reserve for the checkpoint and report that... */
7955 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7956 if (blocksForCheckpoint < 0)
7957 blocksForCheckpoint = 0;
7959 nFree -= (blocksForCheckpoint * dev->param.nChunksPerBlock);
7968 static int yaffs_freeVerificationFailures;
7970 static void yaffs_VerifyFreeChunks(yaffs_Device *dev)
7975 if (yaffs_SkipVerification(dev))
7978 counted = yaffs_CountFreeChunks(dev);
7980 difference = dev->nFreeChunks - counted;
7983 T(YAFFS_TRACE_ALWAYS,
7984 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7985 dev->nFreeChunks, counted, difference));
7986 yaffs_freeVerificationFailures++;
7990 /*---------------------------------------- YAFFS test code ----------------------*/
7992 #define yaffs_CheckStruct(structure, syze, name) \
7994 if (sizeof(structure) != syze) { \
7995 T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
7996 name, syze, (int) sizeof(structure))); \
7997 return YAFFS_FAIL; \
8001 static int yaffs_CheckStructures(void)
8003 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
8004 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
8005 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
8006 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
8007 /* yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode"); */
8009 #ifndef CONFIG_YAFFS_WINCE
8010 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");