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.114 2010-03-07 22:07:03 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;
1066 /* Find the oldest dirty sequence number. */
1067 seq = dev->sequenceNumber;
1068 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
1069 b = yaffs_GetBlockInfo(dev, i);
1070 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
1071 (b->pagesInUse - b->softDeletions) < dev->param.nChunksPerBlock &&
1072 b->sequenceNumber < seq)
1073 seq = b->sequenceNumber;
1079 static void yaffs_FindOldestDirtySequence(yaffs_Device *dev)
1081 if(!dev->oldestDirtySequence)
1082 dev->oldestDirtySequence =
1083 yaffs_CalcOldestDirtySequence(dev);
1086 if(!yaffs_SkipVerification(dev) &&
1087 dev->oldestDirtySequence != yaffs_CalcOldestDirtySequence(dev))
1094 * yaffs_ClearOldestDirtySequence()
1095 * Called when a block is erased or marked bad. (ie. when its sequenceNumber
1096 * becomes invalid). If the value matches the oldest then we clear
1097 * dev->oldestDirtySequence to force its recomputation.
1099 static void yaffs_ClearOldestDirtySequence(yaffs_Device *dev, yaffs_BlockInfo *bi)
1102 if(!bi || bi->sequenceNumber == dev->oldestDirtySequence)
1103 dev->oldestDirtySequence = 0;
1107 * yaffs_UpdateOldestDirtySequence()
1108 * Update the oldest dirty sequence number whenever we dirty a block.
1109 * Only do this if the oldestDirtySequence is actually being tracked.
1111 static void yaffs_UpdateOldestDirtySequence(yaffs_Device *dev, yaffs_BlockInfo *bi)
1113 if(dev->oldestDirtySequence){
1114 if(dev->oldestDirtySequence > bi->sequenceNumber)
1115 dev->oldestDirtySequence = bi->sequenceNumber;
1120 * Block retiring for handling a broken block.
1123 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND)
1125 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1127 yaffs_InvalidateCheckpoint(dev);
1129 yaffs_ClearOldestDirtySequence(dev,bi);
1131 if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
1132 if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
1133 T(YAFFS_TRACE_ALWAYS, (TSTR(
1134 "yaffs: Failed to mark bad and erase block %d"
1135 TENDSTR), blockInNAND));
1137 yaffs_ExtendedTags tags;
1138 int chunkId = blockInNAND * dev->param.nChunksPerBlock;
1140 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
1142 memset(buffer, 0xff, dev->nDataBytesPerChunk);
1143 yaffs_InitialiseTags(&tags);
1144 tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
1145 if (dev->param.writeChunkWithTagsToNAND(dev, chunkId -
1146 dev->chunkOffset, buffer, &tags) != YAFFS_OK)
1147 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
1148 TCONT("write bad block marker to block %d")
1149 TENDSTR), blockInNAND));
1151 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
1155 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1156 bi->gcPrioritise = 0;
1157 bi->needsRetiring = 0;
1159 dev->nRetiredBlocks++;
1163 * Functions for robustisizing TODO
1167 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
1169 const yaffs_ExtendedTags *tags)
1172 chunkInNAND=chunkInNAND;
1177 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
1178 const yaffs_ExtendedTags *tags)
1181 chunkInNAND=chunkInNAND;
1185 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1187 if (!bi->gcPrioritise) {
1188 bi->gcPrioritise = 1;
1189 dev->hasPendingPrioritisedGCs = 1;
1190 bi->chunkErrorStrikes++;
1192 if (bi->chunkErrorStrikes > 3) {
1193 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1194 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1200 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
1203 int blockInNAND = chunkInNAND / dev->param.nChunksPerBlock;
1204 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1206 yaffs_HandleChunkError(dev, bi);
1209 /* Was an actual write failure, so mark the block for retirement */
1210 bi->needsRetiring = 1;
1211 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1212 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1215 /* Delete the chunk */
1216 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1217 yaffs_SkipRestOfBlock(dev);
1221 /*---------------- Name handling functions ------------*/
1223 static __u16 yaffs_CalcNameSum(const YCHAR *name)
1228 const YUCHAR *bname = (const YUCHAR *) name;
1230 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1232 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1233 sum += yaffs_toupper(*bname) * i;
1235 sum += (*bname) * i;
1244 static void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
1246 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1247 memset(obj->shortName, 0, sizeof(YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1248 if (name && yaffs_strnlen(name,YAFFS_SHORT_NAME_LENGTH+1) <= YAFFS_SHORT_NAME_LENGTH)
1249 yaffs_strcpy(obj->shortName, name);
1251 obj->shortName[0] = _Y('\0');
1253 obj->sum = yaffs_CalcNameSum(name);
1256 /*-------------------- TNODES -------------------
1258 * List of spare tnodes
1259 * The list is hooked together using the first pointer
1263 /* yaffs_CreateTnodes creates a bunch more tnodes and
1264 * adds them to the tnode free list.
1265 * Don't use this function directly
1267 static Y_INLINE int yaffs_CalcTnodeSize(yaffs_Device *dev)
1270 /* Calculate the tnode size in bytes for variable width tnode support.
1271 * Must be a multiple of 32-bits */
1272 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1274 if (tnodeSize < sizeof(yaffs_Tnode))
1275 tnodeSize = sizeof(yaffs_Tnode);
1279 static int yaffs_CreateTnodes(yaffs_Device *dev, int nTnodes)
1282 int tnodeSize = yaffs_CalcTnodeSize(dev);
1283 yaffs_Tnode *newTnodes;
1287 yaffs_TnodeList *tnl;
1293 /* make these things */
1295 newTnodes = YMALLOC(nTnodes * tnodeSize);
1296 mem = (__u8 *)newTnodes;
1299 T(YAFFS_TRACE_ERROR,
1300 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1304 /* Hook them into the free list */
1306 for (i = 0; i < nTnodes - 1; i++) {
1307 newTnodes[i].internal[0] = &newTnodes[i + 1];
1308 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1309 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1313 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1314 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1315 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1317 dev->freeTnodes = newTnodes;
1319 /* New hookup for wide tnodes */
1320 for (i = 0; i < nTnodes - 1; i++) {
1321 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1322 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1323 curr->internal[0] = next;
1326 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1327 curr->internal[0] = dev->freeTnodes;
1328 dev->freeTnodes = (yaffs_Tnode *)mem;
1333 dev->nFreeTnodes += nTnodes;
1334 dev->nTnodesCreated += nTnodes;
1336 /* Now add this bunch of tnodes to a list for freeing up.
1337 * NB If we can't add this to the management list it isn't fatal
1338 * but it just means we can't free this bunch of tnodes later.
1341 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1343 T(YAFFS_TRACE_ERROR,
1345 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1348 tnl->tnodes = newTnodes;
1349 tnl->next = dev->allocatedTnodeList;
1350 dev->allocatedTnodeList = tnl;
1353 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1358 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1360 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device *dev)
1362 yaffs_Tnode *tn = NULL;
1364 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1365 tn = YMALLOC(yaffs_CalcTnodeSize(dev));
1367 dev->nTnodesCreated++;
1369 /* If there are none left make more */
1370 if (!dev->freeTnodes)
1371 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1373 if (dev->freeTnodes) {
1374 tn = dev->freeTnodes;
1375 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1376 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1377 /* Hoosterman, this thing looks like it isn't in the list */
1378 T(YAFFS_TRACE_ALWAYS,
1379 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1382 dev->freeTnodes = dev->freeTnodes->internal[0];
1386 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1391 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
1393 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1394 int tnodeSize = yaffs_CalcTnodeSize(dev);
1397 memset(tn, 0, tnodeSize);
1402 /* FreeTnode frees up a tnode and puts it back on the free list */
1403 static void yaffs_FreeTnode(yaffs_Device *dev, yaffs_Tnode *tn)
1406 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1408 dev->nTnodesCreated--;
1410 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1411 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1412 /* Hoosterman, this thing looks like it is already in the list */
1413 T(YAFFS_TRACE_ALWAYS,
1414 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1416 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1418 tn->internal[0] = dev->freeTnodes;
1419 dev->freeTnodes = tn;
1423 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1426 static void yaffs_DeinitialiseTnodes(yaffs_Device *dev)
1428 /* Free the list of allocated tnodes */
1429 yaffs_TnodeList *tmp;
1431 while (dev->allocatedTnodeList) {
1432 tmp = dev->allocatedTnodeList->next;
1434 YFREE(dev->allocatedTnodeList->tnodes);
1435 YFREE(dev->allocatedTnodeList);
1436 dev->allocatedTnodeList = tmp;
1440 dev->freeTnodes = NULL;
1441 dev->nFreeTnodes = 0;
1442 dev->nTnodesCreated = 0;
1445 static void yaffs_InitialiseTnodes(yaffs_Device *dev)
1447 dev->allocatedTnodeList = NULL;
1448 dev->freeTnodes = NULL;
1449 dev->nFreeTnodes = 0;
1450 dev->nTnodesCreated = 0;
1454 void yaffs_LoadLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
1457 __u32 *map = (__u32 *)tn;
1463 pos &= YAFFS_TNODES_LEVEL0_MASK;
1464 val >>= dev->chunkGroupBits;
1466 bitInMap = pos * dev->tnodeWidth;
1467 wordInMap = bitInMap / 32;
1468 bitInWord = bitInMap & (32 - 1);
1470 mask = dev->tnodeMask << bitInWord;
1472 map[wordInMap] &= ~mask;
1473 map[wordInMap] |= (mask & (val << bitInWord));
1475 if (dev->tnodeWidth > (32 - bitInWord)) {
1476 bitInWord = (32 - bitInWord);
1478 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1479 map[wordInMap] &= ~mask;
1480 map[wordInMap] |= (mask & (val >> bitInWord));
1484 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
1487 __u32 *map = (__u32 *)tn;
1493 pos &= YAFFS_TNODES_LEVEL0_MASK;
1495 bitInMap = pos * dev->tnodeWidth;
1496 wordInMap = bitInMap / 32;
1497 bitInWord = bitInMap & (32 - 1);
1499 val = map[wordInMap] >> bitInWord;
1501 if (dev->tnodeWidth > (32 - bitInWord)) {
1502 bitInWord = (32 - bitInWord);
1504 val |= (map[wordInMap] << bitInWord);
1507 val &= dev->tnodeMask;
1508 val <<= dev->chunkGroupBits;
1513 /* ------------------- End of individual tnode manipulation -----------------*/
1515 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1516 * The look up tree is represented by the top tnode and the number of topLevel
1517 * in the tree. 0 means only the level 0 tnode is in the tree.
1520 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1521 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
1522 yaffs_FileStructure *fStruct,
1525 yaffs_Tnode *tn = fStruct->top;
1527 int requiredTallness;
1528 int level = fStruct->topLevel;
1532 /* Check sane level and chunk Id */
1533 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
1536 if (chunkId > YAFFS_MAX_CHUNK_ID)
1539 /* First check we're tall enough (ie enough topLevel) */
1541 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1542 requiredTallness = 0;
1544 i >>= YAFFS_TNODES_INTERNAL_BITS;
1548 if (requiredTallness > fStruct->topLevel)
1549 return NULL; /* Not tall enough, so we can't find it */
1551 /* Traverse down to level 0 */
1552 while (level > 0 && tn) {
1553 tn = tn->internal[(chunkId >>
1554 (YAFFS_TNODES_LEVEL0_BITS +
1556 YAFFS_TNODES_INTERNAL_BITS)) &
1557 YAFFS_TNODES_INTERNAL_MASK];
1564 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1565 * This happens in two steps:
1566 * 1. If the tree isn't tall enough, then make it taller.
1567 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1569 * Used when modifying the tree.
1571 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1572 * be plugged into the ttree.
1575 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
1576 yaffs_FileStructure *fStruct,
1578 yaffs_Tnode *passedTn)
1580 int requiredTallness;
1588 /* Check sane level and page Id */
1589 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
1592 if (chunkId > YAFFS_MAX_CHUNK_ID)
1595 /* First check we're tall enough (ie enough topLevel) */
1597 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1598 requiredTallness = 0;
1600 x >>= YAFFS_TNODES_INTERNAL_BITS;
1605 if (requiredTallness > fStruct->topLevel) {
1606 /* Not tall enough, gotta make the tree taller */
1607 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1609 tn = yaffs_GetTnode(dev);
1612 tn->internal[0] = fStruct->top;
1614 fStruct->topLevel++;
1616 T(YAFFS_TRACE_ERROR,
1617 (TSTR("yaffs: no more tnodes" TENDSTR)));
1623 /* Traverse down to level 0, adding anything we need */
1625 l = fStruct->topLevel;
1629 while (l > 0 && tn) {
1631 (YAFFS_TNODES_LEVEL0_BITS +
1632 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1633 YAFFS_TNODES_INTERNAL_MASK;
1636 if ((l > 1) && !tn->internal[x]) {
1637 /* Add missing non-level-zero tnode */
1638 tn->internal[x] = yaffs_GetTnode(dev);
1639 if(!tn->internal[x])
1641 } else if (l == 1) {
1642 /* Looking from level 1 at level 0 */
1644 /* If we already have one, then release it.*/
1645 if (tn->internal[x])
1646 yaffs_FreeTnode(dev, tn->internal[x]);
1647 tn->internal[x] = passedTn;
1649 } else if (!tn->internal[x]) {
1650 /* Don't have one, none passed in */
1651 tn->internal[x] = yaffs_GetTnode(dev);
1652 if(!tn->internal[x])
1657 tn = tn->internal[x];
1661 /* top is level 0 */
1663 memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1664 yaffs_FreeTnode(dev, passedTn);
1671 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
1672 yaffs_ExtendedTags *tags, int objectId,
1677 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1678 if (yaffs_CheckChunkBit(dev, theChunk / dev->param.nChunksPerBlock,
1679 theChunk % dev->param.nChunksPerBlock)) {
1681 if(dev->chunkGroupSize == 1)
1684 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1686 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1698 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1699 * chunks and tnodes in the file
1700 * Returns 1 if the tree was deleted.
1701 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1704 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
1705 int chunkOffset, int *limit)
1710 yaffs_ExtendedTags tags;
1712 yaffs_Device *dev = in->myDev;
1718 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1720 if (tn->internal[i]) {
1721 if (limit && (*limit) < 0) {
1725 yaffs_DeleteWorker(in,
1733 YAFFS_TNODES_INTERNAL_BITS)
1738 yaffs_FreeTnode(dev,
1741 tn->internal[i] = NULL;
1745 return (allDone) ? 1 : 0;
1746 } else if (level == 0) {
1749 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1751 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1754 chunkInInode = (chunkOffset <<
1755 YAFFS_TNODES_LEVEL0_BITS) + i;
1758 yaffs_FindChunkInGroup(dev,
1764 if (foundChunk > 0) {
1765 yaffs_DeleteChunk(dev,
1770 *limit = *limit - 1;
1777 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1781 return (i < 0) ? 1 : 0;
1791 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1793 yaffs_BlockInfo *theBlock;
1795 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1797 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->param.nChunksPerBlock);
1799 theBlock->softDeletions++;
1804 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1805 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1807 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1810 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1811 __u32 level, int chunkOffset)
1816 yaffs_Device *dev = in->myDev;
1821 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1823 if (tn->internal[i]) {
1825 yaffs_SoftDeleteWorker(in,
1831 YAFFS_TNODES_INTERNAL_BITS)
1834 yaffs_FreeTnode(dev,
1837 tn->internal[i] = NULL;
1839 /* Hoosterman... how could this happen? */
1843 return (allDone) ? 1 : 0;
1844 } else if (level == 0) {
1846 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1847 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1849 /* Note this does not find the real chunk, only the chunk group.
1850 * We make an assumption that a chunk group is not larger than
1853 yaffs_SoftDeleteChunk(dev, theChunk);
1854 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1868 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1871 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1872 if (obj->nDataChunks <= 0) {
1873 /* Empty file with no duplicate object headers, just delete it immediately */
1874 yaffs_FreeTnode(obj->myDev,
1875 obj->variant.fileVariant.top);
1876 obj->variant.fileVariant.top = NULL;
1877 T(YAFFS_TRACE_TRACING,
1878 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1880 yaffs_DoGenericObjectDeletion(obj);
1882 yaffs_SoftDeleteWorker(obj,
1883 obj->variant.fileVariant.top,
1884 obj->variant.fileVariant.
1886 obj->softDeleted = 1;
1891 /* Pruning removes any part of the file structure tree that is beyond the
1892 * bounds of the file (ie that does not point to chunks).
1894 * A file should only get pruned when its size is reduced.
1896 * Before pruning, the chunks must be pulled from the tree and the
1897 * level 0 tnode entries must be zeroed out.
1898 * Could also use this for file deletion, but that's probably better handled
1899 * by a special case.
1901 * This function is recursive. For levels > 0 the function is called again on
1902 * any sub-tree. For level == 0 we just check if the sub-tree has data.
1903 * If there is no data in a subtree then it is pruned.
1906 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1907 __u32 level, int del0)
1916 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1917 if (tn->internal[i]) {
1919 yaffs_PruneWorker(dev, tn->internal[i],
1921 (i == 0) ? del0 : 1);
1924 if (tn->internal[i])
1928 int tnodeSize_u32 = yaffs_CalcTnodeSize(dev)/sizeof(__u32);
1929 __u32 *map = (__u32 *)tn;
1931 for(i = 0; !hasData && i < tnodeSize_u32; i++){
1937 if (hasData == 0 && del0) {
1938 /* Free and return NULL */
1940 yaffs_FreeTnode(dev, tn);
1950 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1951 yaffs_FileStructure *fStruct)
1958 if (fStruct->topLevel > 0) {
1960 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1962 /* Now we have a tree with all the non-zero branches NULL but the height
1963 * is the same as it was.
1964 * Let's see if we can trim internal tnodes to shorten the tree.
1965 * We can do this if only the 0th element in the tnode is in use
1966 * (ie all the non-zero are NULL)
1969 while (fStruct->topLevel && !done) {
1973 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1974 if (tn->internal[i])
1979 fStruct->top = tn->internal[0];
1980 fStruct->topLevel--;
1981 yaffs_FreeTnode(dev, tn);
1991 /*-------------------- End of File Structure functions.-------------------*/
1993 /* yaffs_CreateFreeObjects creates a bunch more objects and
1994 * adds them to the object free list.
1996 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1999 yaffs_Object *newObjects;
2000 yaffs_ObjectList *list;
2005 /* make these things */
2006 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
2007 list = YMALLOC(sizeof(yaffs_ObjectList));
2009 if (!newObjects || !list) {
2018 T(YAFFS_TRACE_ALLOCATE,
2019 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
2023 /* Hook them into the free list */
2024 for (i = 0; i < nObjects - 1; i++) {
2025 newObjects[i].siblings.next =
2026 (struct ylist_head *)(&newObjects[i + 1]);
2029 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
2030 dev->freeObjects = newObjects;
2031 dev->nFreeObjects += nObjects;
2032 dev->nObjectsCreated += nObjects;
2034 /* Now add this bunch of Objects to a list for freeing up. */
2036 list->objects = newObjects;
2037 list->next = dev->allocatedObjectList;
2038 dev->allocatedObjectList = list;
2044 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
2045 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
2047 yaffs_Object *tn = NULL;
2049 #ifdef CONFIG_YAFFS_VALGRIND_TEST
2050 tn = YMALLOC(sizeof(yaffs_Object));
2052 dev->nObjectsCreated++;
2054 /* If there are none left make more */
2055 if (!dev->freeObjects)
2056 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
2058 if (dev->freeObjects) {
2059 tn = dev->freeObjects;
2061 (yaffs_Object *) (dev->freeObjects->siblings.next);
2062 dev->nFreeObjects--;
2066 /* Now sweeten it up... */
2068 memset(tn, 0, sizeof(yaffs_Object));
2069 tn->beingCreated = 1;
2073 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
2074 YINIT_LIST_HEAD(&(tn->hardLinks));
2075 YINIT_LIST_HEAD(&(tn->hashLink));
2076 YINIT_LIST_HEAD(&tn->siblings);
2079 /* Now make the directory sane */
2081 tn->parent = dev->rootDir;
2082 ylist_add(&(tn->siblings), &dev->rootDir->variant.directoryVariant.children);
2085 /* Add it to the lost and found directory.
2086 * NB Can't put root or lostNFound in lostNFound so
2087 * check if lostNFound exists first
2089 if (dev->lostNFoundDir)
2090 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
2092 tn->beingCreated = 0;
2095 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2100 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
2105 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
2107 obj->fake = 1; /* it is fake so it might have no NAND presence... */
2108 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
2109 obj->unlinkAllowed = 0; /* ... or unlink it */
2112 obj->yst_mode = mode;
2114 obj->hdrChunk = 0; /* Not a valid chunk. */
2121 static void yaffs_UnhashObject(yaffs_Object *tn)
2124 yaffs_Device *dev = tn->myDev;
2126 /* If it is still linked into the bucket list, free from the list */
2127 if (!ylist_empty(&tn->hashLink)) {
2128 ylist_del_init(&tn->hashLink);
2129 bucket = yaffs_HashFunction(tn->objectId);
2130 dev->objectBucket[bucket].count--;
2134 /* FreeObject frees up a Object and puts it back on the free list */
2135 static void yaffs_FreeObject(yaffs_Object *tn)
2137 yaffs_Device *dev = tn->myDev;
2139 T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), tn, tn->myInode));
2145 if (!ylist_empty(&tn->siblings))
2150 /* We're still hooked up to a cached inode.
2151 * Don't delete now, but mark for later deletion
2153 tn->deferedFree = 1;
2157 yaffs_UnhashObject(tn);
2159 #ifdef CONFIG_YAFFS_VALGRIND_TEST
2161 dev->nObjectsCreated--;
2164 /* Link into the free list. */
2165 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2166 dev->freeObjects = tn;
2167 dev->nFreeObjects++;
2169 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2173 void yaffs_HandleDeferedFree(yaffs_Object *obj)
2175 if (obj->deferedFree)
2176 yaffs_FreeObject(obj);
2180 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
2182 /* Free the list of allocated Objects */
2184 yaffs_ObjectList *tmp;
2186 while (dev->allocatedObjectList) {
2187 tmp = dev->allocatedObjectList->next;
2188 YFREE(dev->allocatedObjectList->objects);
2189 YFREE(dev->allocatedObjectList);
2191 dev->allocatedObjectList = tmp;
2194 dev->freeObjects = NULL;
2195 dev->nFreeObjects = 0;
2196 dev->nObjectsCreated = 0;
2199 static void yaffs_InitialiseObjects(yaffs_Device *dev)
2203 dev->allocatedObjectList = NULL;
2204 dev->freeObjects = NULL;
2205 dev->nFreeObjects = 0;
2207 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2208 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2209 dev->objectBucket[i].count = 0;
2213 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
2217 int lowest = 999999;
2220 /* Search for the shortest list or one that
2224 for (i = 0; i < 10 && lowest > 4; i++) {
2225 dev->bucketFinder++;
2226 dev->bucketFinder %= YAFFS_NOBJECT_BUCKETS;
2227 if (dev->objectBucket[dev->bucketFinder].count < lowest) {
2228 lowest = dev->objectBucket[dev->bucketFinder].count;
2229 l = dev->bucketFinder;
2237 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
2239 int bucket = yaffs_FindNiceObjectBucket(dev);
2241 /* Now find an object value that has not already been taken
2242 * by scanning the list.
2246 struct ylist_head *i;
2248 __u32 n = (__u32) bucket;
2250 /* yaffs_CheckObjectHashSanity(); */
2254 n += YAFFS_NOBJECT_BUCKETS;
2255 if (1 || dev->objectBucket[bucket].count > 0) {
2256 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2257 /* If there is already one in the list */
2258 if (i && ylist_entry(i, yaffs_Object,
2259 hashLink)->objectId == n) {
2269 static void yaffs_HashObject(yaffs_Object *in)
2271 int bucket = yaffs_HashFunction(in->objectId);
2272 yaffs_Device *dev = in->myDev;
2274 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2275 dev->objectBucket[bucket].count++;
2278 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
2280 int bucket = yaffs_HashFunction(number);
2281 struct ylist_head *i;
2284 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2285 /* Look if it is in the list */
2287 in = ylist_entry(i, yaffs_Object, hashLink);
2288 if (in->objectId == number) {
2290 /* Don't tell the VFS about this one if it is defered free */
2291 if (in->deferedFree)
2302 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
2303 yaffs_ObjectType type)
2305 yaffs_Object *theObject=NULL;
2306 yaffs_Tnode *tn = NULL;
2309 number = yaffs_CreateNewObjectNumber(dev);
2311 if (type == YAFFS_OBJECT_TYPE_FILE) {
2312 tn = yaffs_GetTnode(dev);
2317 theObject = yaffs_AllocateEmptyObject(dev);
2320 yaffs_FreeTnode(dev,tn);
2326 theObject->fake = 0;
2327 theObject->renameAllowed = 1;
2328 theObject->unlinkAllowed = 1;
2329 theObject->objectId = number;
2330 yaffs_HashObject(theObject);
2331 theObject->variantType = type;
2332 #ifdef CONFIG_YAFFS_WINCE
2333 yfsd_WinFileTimeNow(theObject->win_atime);
2334 theObject->win_ctime[0] = theObject->win_mtime[0] =
2335 theObject->win_atime[0];
2336 theObject->win_ctime[1] = theObject->win_mtime[1] =
2337 theObject->win_atime[1];
2341 theObject->yst_atime = theObject->yst_mtime =
2342 theObject->yst_ctime = Y_CURRENT_TIME;
2345 case YAFFS_OBJECT_TYPE_FILE:
2346 theObject->variant.fileVariant.fileSize = 0;
2347 theObject->variant.fileVariant.scannedFileSize = 0;
2348 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2349 theObject->variant.fileVariant.topLevel = 0;
2350 theObject->variant.fileVariant.top = tn;
2352 case YAFFS_OBJECT_TYPE_DIRECTORY:
2353 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2356 case YAFFS_OBJECT_TYPE_SYMLINK:
2357 case YAFFS_OBJECT_TYPE_HARDLINK:
2358 case YAFFS_OBJECT_TYPE_SPECIAL:
2359 /* No action required */
2361 case YAFFS_OBJECT_TYPE_UNKNOWN:
2362 /* todo this should not happen */
2370 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
2372 yaffs_ObjectType type)
2374 yaffs_Object *theObject = NULL;
2377 theObject = yaffs_FindObjectByNumber(dev, number);
2380 theObject = yaffs_CreateNewObject(dev, number, type);
2387 static YCHAR *yaffs_CloneString(const YCHAR *str)
2389 YCHAR *newStr = NULL;
2395 len = yaffs_strnlen(str,YAFFS_MAX_ALIAS_LENGTH);
2396 newStr = YMALLOC((len + 1) * sizeof(YCHAR));
2398 yaffs_strncpy(newStr, str,len);
2406 * Mknod (create) a new object.
2407 * equivalentObject only has meaning for a hard link;
2408 * aliasString only has meaning for a symlink.
2409 * rdev only has meaning for devices (a subset of special objects)
2412 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2413 yaffs_Object *parent,
2418 yaffs_Object *equivalentObject,
2419 const YCHAR *aliasString, __u32 rdev)
2424 yaffs_Device *dev = parent->myDev;
2426 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2427 if (yaffs_FindObjectByName(parent, name))
2430 if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2431 str = yaffs_CloneString(aliasString);
2436 in = yaffs_CreateNewObject(dev, -1, type);
2451 in->variantType = type;
2453 in->yst_mode = mode;
2455 #ifdef CONFIG_YAFFS_WINCE
2456 yfsd_WinFileTimeNow(in->win_atime);
2457 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2458 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2461 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2463 in->yst_rdev = rdev;
2467 in->nDataChunks = 0;
2469 yaffs_SetObjectName(in, name);
2472 yaffs_AddObjectToDirectory(parent, in);
2474 in->myDev = parent->myDev;
2477 case YAFFS_OBJECT_TYPE_SYMLINK:
2478 in->variant.symLinkVariant.alias = str;
2480 case YAFFS_OBJECT_TYPE_HARDLINK:
2481 in->variant.hardLinkVariant.equivalentObject =
2483 in->variant.hardLinkVariant.equivalentObjectId =
2484 equivalentObject->objectId;
2485 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2487 case YAFFS_OBJECT_TYPE_FILE:
2488 case YAFFS_OBJECT_TYPE_DIRECTORY:
2489 case YAFFS_OBJECT_TYPE_SPECIAL:
2490 case YAFFS_OBJECT_TYPE_UNKNOWN:
2495 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2496 /* Could not create the object header, fail the creation */
2497 yaffs_DeleteObject(in);
2501 yaffs_UpdateParent(parent);
2507 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
2508 __u32 mode, __u32 uid, __u32 gid)
2510 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2511 uid, gid, NULL, NULL, 0);
2514 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
2515 __u32 mode, __u32 uid, __u32 gid)
2517 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2518 mode, uid, gid, NULL, NULL, 0);
2521 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
2522 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2524 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2525 uid, gid, NULL, NULL, rdev);
2528 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
2529 __u32 mode, __u32 uid, __u32 gid,
2532 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2533 uid, gid, NULL, alias, 0);
2536 /* yaffs_Link returns the object id of the equivalent object.*/
2537 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
2538 yaffs_Object *equivalentObject)
2540 /* Get the real object in case we were fed a hard link as an equivalent object */
2541 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2543 if (yaffs_MknodObject
2544 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2545 equivalentObject, NULL, 0)) {
2546 return equivalentObject;
2553 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
2554 const YCHAR *newName, int force, int shadows)
2559 yaffs_Object *existingTarget;
2562 newDir = obj->parent; /* use the old directory */
2564 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2565 T(YAFFS_TRACE_ALWAYS,
2567 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2572 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2573 if (obj->myDev->param.isYaffs2)
2574 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2576 unlinkOp = (newDir == obj->myDev->unlinkedDir
2577 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2579 deleteOp = (newDir == obj->myDev->deletedDir);
2581 existingTarget = yaffs_FindObjectByName(newDir, newName);
2583 /* If the object is a file going into the unlinked directory,
2584 * then it is OK to just stuff it in since duplicate names are allowed.
2585 * else only proceed if the new name does not exist and if we're putting
2586 * it into a directory.
2593 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2594 yaffs_SetObjectName(obj, newName);
2597 yaffs_AddObjectToDirectory(newDir, obj);
2602 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2603 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows) >= 0)
2610 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
2611 yaffs_Object *newDir, const YCHAR *newName)
2613 yaffs_Object *obj = NULL;
2614 yaffs_Object *existingTarget = NULL;
2620 if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2622 if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2625 dev = oldDir->myDev;
2627 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2628 /* Special case for case insemsitive systems (eg. WinCE).
2629 * While look-up is case insensitive, the name isn't.
2630 * Therefore we might want to change x.txt to X.txt
2632 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
2636 if(yaffs_strnlen(newName,YAFFS_MAX_NAME_LENGTH+1) > YAFFS_MAX_NAME_LENGTH)
2640 obj = yaffs_FindObjectByName(oldDir, oldName);
2642 if (obj && obj->renameAllowed) {
2644 /* Now do the handling for an existing target, if there is one */
2646 existingTarget = yaffs_FindObjectByName(newDir, newName);
2647 if (existingTarget &&
2648 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2649 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2650 /* There is a target that is a non-empty directory, so we fail */
2651 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2652 } else if (existingTarget && existingTarget != obj) {
2653 /* Nuke the target first, using shadowing,
2654 * but only if it isn't the same object.
2656 * Note we must disable gc otherwise it can mess up the shadowing.
2660 yaffs_ChangeObjectName(obj, newDir, newName, force,
2661 existingTarget->objectId);
2662 existingTarget->isShadowed = 1;
2663 yaffs_UnlinkObject(existingTarget);
2667 result = yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2669 yaffs_UpdateParent(oldDir);
2670 if(newDir != oldDir)
2671 yaffs_UpdateParent(newDir);
2678 /*------------------------- Block Management and Page Allocation ----------------*/
2680 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
2682 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2684 dev->blockInfo = NULL;
2685 dev->chunkBits = NULL;
2687 dev->allocationBlock = -1; /* force it to get a new one */
2689 /* If the first allocation strategy fails, thry the alternate one */
2690 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2691 if (!dev->blockInfo) {
2692 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2693 dev->blockInfoAlt = 1;
2695 dev->blockInfoAlt = 0;
2697 if (dev->blockInfo) {
2698 /* Set up dynamic blockinfo stuff. */
2699 dev->chunkBitmapStride = (dev->param.nChunksPerBlock + 7) / 8; /* round up bytes */
2700 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2701 if (!dev->chunkBits) {
2702 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2703 dev->chunkBitsAlt = 1;
2705 dev->chunkBitsAlt = 0;
2708 if (dev->blockInfo && dev->chunkBits) {
2709 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2710 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2717 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2719 if (dev->blockInfoAlt && dev->blockInfo)
2720 YFREE_ALT(dev->blockInfo);
2721 else if (dev->blockInfo)
2722 YFREE(dev->blockInfo);
2724 dev->blockInfoAlt = 0;
2726 dev->blockInfo = NULL;
2728 if (dev->chunkBitsAlt && dev->chunkBits)
2729 YFREE_ALT(dev->chunkBits);
2730 else if (dev->chunkBits)
2731 YFREE(dev->chunkBits);
2732 dev->chunkBitsAlt = 0;
2733 dev->chunkBits = NULL;
2736 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
2737 yaffs_BlockInfo *bi)
2740 if (!dev->param.isYaffs2)
2741 return 1; /* disqualification only applies to yaffs2. */
2743 if (!bi->hasShrinkHeader)
2744 return 1; /* can gc */
2746 yaffs_FindOldestDirtySequence(dev);
2748 /* Can't do gc of this block if there are any blocks older than this one that have
2751 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2755 * yaffs_FindRefreshBlock()
2756 * periodically finds the oldest full block by sequence number for refreshing.
2759 static __u32 yaffs_FindRefreshBlock(yaffs_Device *dev)
2764 __u32 oldestSequence = 0;
2766 yaffs_BlockInfo *bi;
2769 * If refresh period < 10 then refreshing is disabled.
2771 if(dev->param.refreshPeriod < 10 ||
2772 !dev->param.isYaffs2)
2776 * Fix broken values.
2778 if(dev->refreshSkip > dev->param.refreshPeriod)
2779 dev->refreshSkip = dev->param.refreshPeriod;
2781 if(dev->refreshSkip > 0){
2787 * Refresh skip is now zero.
2788 * We'll do a refresh this time around....
2789 * Update the refresh skip and find the oldest block.
2791 dev->refreshSkip = dev->param.refreshPeriod;
2792 dev->refreshCount++;
2794 for (b = dev->internalStartBlock; b <=dev->internalEndBlock; b++){
2796 bi = yaffs_GetBlockInfo(dev, b);
2799 if (bi->blockState == YAFFS_BLOCK_STATE_FULL){
2802 bi->sequenceNumber < oldestSequence){
2804 oldestSequence = bi->sequenceNumber;
2811 (TSTR("GC refresh count %d selected block %d with sequenceNumber %d" TENDSTR),
2812 dev->refreshCount, oldest, oldestSequence));
2819 * FindDiretiestBlock is used to select the dirtiest block (or close enough)
2820 * for garbage collection.
2823 static int yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
2826 int b = dev->currentDirtyChecker;
2832 int prioritised = 0;
2833 yaffs_BlockInfo *bi;
2834 int pendingPrioritisedExist = 0;
2836 /* First let's see if we need to grab a prioritised block */
2837 if (dev->hasPendingPrioritisedGCs) {
2838 for (i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++) {
2840 bi = yaffs_GetBlockInfo(dev, i);
2841 /* yaffs_VerifyBlock(dev,bi,i); */
2843 if (bi->gcPrioritise) {
2844 pendingPrioritisedExist = 1;
2845 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2846 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2847 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2850 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2855 if (!pendingPrioritisedExist) /* None found, so we can clear this */
2856 dev->hasPendingPrioritisedGCs = 0;
2859 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2861 * else (we're doing a leasurely gc), then we only bother to do this if the
2862 * block has only a few pages in use.
2865 dev->nonAggressiveSkip--;
2867 if (!aggressive && (dev->nonAggressiveSkip > 0))
2872 (aggressive) ? dev->param.nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2876 dev->internalEndBlock - dev->internalStartBlock + 1;
2879 dev->internalEndBlock - dev->internalStartBlock + 1;
2880 iterations = iterations / 16;
2881 if (iterations > 200)
2885 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2887 if (b < dev->internalStartBlock || b > dev->internalEndBlock)
2888 b = dev->internalStartBlock;
2890 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2891 T(YAFFS_TRACE_ERROR,
2892 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2896 bi = yaffs_GetBlockInfo(dev, b);
2898 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2899 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2900 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2902 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2906 dev->currentDirtyChecker = b;
2910 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2911 dev->param.nChunksPerBlock - pagesInUse, prioritised));
2915 dev->nonAggressiveSkip = 4;
2920 static void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
2922 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2926 /* If the block is still healthy erase it and mark as clean.
2927 * If the block has had a data failure, then retire it.
2930 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2931 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2932 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2934 yaffs_ClearOldestDirtySequence(dev,bi);
2936 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2938 if (!bi->needsRetiring) {
2939 yaffs_InvalidateCheckpoint(dev);
2940 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2942 dev->nErasureFailures++;
2943 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2944 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2949 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2951 for (i = 0; i < dev->param.nChunksPerBlock; i++) {
2952 if (!yaffs_CheckChunkErased
2953 (dev, blockNo * dev->param.nChunksPerBlock + i)) {
2954 T(YAFFS_TRACE_ERROR,
2956 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2957 TENDSTR), blockNo, i));
2963 /* Clean it up... */
2964 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2965 bi->sequenceNumber = 0;
2966 dev->nErasedBlocks++;
2968 bi->softDeletions = 0;
2969 bi->hasShrinkHeader = 0;
2970 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2971 bi->gcPrioritise = 0;
2972 yaffs_ClearChunkBits(dev, blockNo);
2974 T(YAFFS_TRACE_ERASE,
2975 (TSTR("Erased block %d" TENDSTR), blockNo));
2977 dev->nFreeChunks -= dev->param.nChunksPerBlock; /* We lost a block of free space */
2979 yaffs_RetireBlock(dev, blockNo);
2980 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2981 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2985 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2989 yaffs_BlockInfo *bi;
2991 if (dev->nErasedBlocks < 1) {
2992 /* Hoosterman we've got a problem.
2993 * Can't get space to gc
2995 T(YAFFS_TRACE_ERROR,
2996 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
3001 /* Find an empty block. */
3003 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
3004 dev->allocationBlockFinder++;
3005 if (dev->allocationBlockFinder < dev->internalStartBlock
3006 || dev->allocationBlockFinder > dev->internalEndBlock) {
3007 dev->allocationBlockFinder = dev->internalStartBlock;
3010 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
3012 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
3013 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
3014 dev->sequenceNumber++;
3015 bi->sequenceNumber = dev->sequenceNumber;
3016 dev->nErasedBlocks--;
3017 T(YAFFS_TRACE_ALLOCATE,
3018 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
3019 dev->allocationBlockFinder, dev->sequenceNumber,
3020 dev->nErasedBlocks));
3021 return dev->allocationBlockFinder;
3025 T(YAFFS_TRACE_ALWAYS,
3027 ("yaffs tragedy: no more erased blocks, but there should have been %d"
3028 TENDSTR), dev->nErasedBlocks));
3035 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
3037 if (!dev->nCheckpointBlocksRequired &&
3038 dev->param.isYaffs2) {
3039 /* Not a valid value so recalculate */
3042 int devBlocks = (dev->param.endBlock - dev->param.startBlock + 1);
3043 int tnodeSize = yaffs_CalcTnodeSize(dev);
3045 nBytes += sizeof(yaffs_CheckpointValidity);
3046 nBytes += sizeof(yaffs_CheckpointDevice);
3047 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
3048 nBytes += devBlocks * dev->chunkBitmapStride;
3049 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
3050 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
3051 nBytes += sizeof(yaffs_CheckpointValidity);
3052 nBytes += sizeof(__u32); /* checksum*/
3054 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
3056 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->param.nChunksPerBlock)) + 3;
3058 dev->nCheckpointBlocksRequired = nBlocks;
3061 return dev->nCheckpointBlocksRequired;
3065 * Check if there's space to allocate...
3066 * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
3068 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev)
3071 int reservedBlocks = dev->param.nReservedBlocks;
3072 int checkpointBlocks;
3074 if (dev->param.isYaffs2) {
3075 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
3076 dev->blocksInCheckpoint;
3077 if (checkpointBlocks < 0)
3078 checkpointBlocks = 0;
3080 checkpointBlocks = 0;
3083 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->param.nChunksPerBlock);
3085 return (dev->nFreeChunks > reservedChunks);
3088 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
3089 yaffs_BlockInfo **blockUsedPtr)
3092 yaffs_BlockInfo *bi;
3094 if (dev->allocationBlock < 0) {
3095 /* Get next block to allocate off */
3096 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
3097 dev->allocationPage = 0;
3100 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
3101 /* Not enough space to allocate unless we're allowed to use the reserve. */
3105 if (dev->nErasedBlocks < dev->param.nReservedBlocks
3106 && dev->allocationPage == 0) {
3107 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
3110 /* Next page please.... */
3111 if (dev->allocationBlock >= 0) {
3112 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3114 retVal = (dev->allocationBlock * dev->param.nChunksPerBlock) +
3115 dev->allocationPage;
3117 yaffs_SetChunkBit(dev, dev->allocationBlock,
3118 dev->allocationPage);
3120 dev->allocationPage++;
3124 /* If the block is full set the state to full */
3125 if (dev->allocationPage >= dev->param.nChunksPerBlock) {
3126 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3127 dev->allocationBlock = -1;
3136 T(YAFFS_TRACE_ERROR,
3137 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
3142 static int yaffs_GetErasedChunks(yaffs_Device *dev)
3146 n = dev->nErasedBlocks * dev->param.nChunksPerBlock;
3148 if (dev->allocationBlock > 0)
3149 n += (dev->param.nChunksPerBlock - dev->allocationPage);
3156 * yaffs_SkipRestOfBlock() skips over the rest of the allocation block
3157 * if we don't want to write to it.
3159 static void yaffs_SkipRestOfBlock(yaffs_Device *dev)
3161 if(dev->allocationBlock > 0){
3162 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3163 if(bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING){
3164 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3165 dev->allocationBlock = -1;
3171 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
3177 int retVal = YAFFS_OK;
3180 int isCheckpointBlock;
3184 int chunksBefore = yaffs_GetErasedChunks(dev);
3187 yaffs_ExtendedTags tags;
3189 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3191 yaffs_Object *object;
3193 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3196 T(YAFFS_TRACE_TRACING,
3197 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3200 bi->hasShrinkHeader,
3203 /*yaffs_VerifyFreeChunks(dev); */
3205 if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
3206 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3208 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
3210 /* Take off the number of soft deleted entries because
3211 * they're going to get really deleted during GC.
3213 if(dev->gcChunk == 0) /* first time through for this block */
3214 dev->nFreeChunks -= bi->softDeletions;
3218 if (isCheckpointBlock ||
3219 !yaffs_StillSomeChunkBits(dev, block)) {
3220 T(YAFFS_TRACE_TRACING,
3222 ("Collecting block %d that has no chunks in use" TENDSTR),
3224 yaffs_BlockBecameDirty(dev, block);
3227 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3229 yaffs_VerifyBlock(dev, bi, block);
3231 maxCopies = (wholeBlock) ? dev->param.nChunksPerBlock : 10;
3232 oldChunk = block * dev->param.nChunksPerBlock + dev->gcChunk;
3234 for (/* init already done */;
3235 retVal == YAFFS_OK &&
3236 dev->gcChunk < dev->param.nChunksPerBlock &&
3237 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
3239 dev->gcChunk++, oldChunk++) {
3240 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3242 /* This page is in use and might need to be copied off */
3248 yaffs_InitialiseTags(&tags);
3250 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3254 yaffs_FindObjectByNumber(dev,
3257 T(YAFFS_TRACE_GC_DETAIL,
3259 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3260 dev->gcChunk, tags.objectId, tags.chunkId,
3263 if (object && !yaffs_SkipVerification(dev)) {
3264 if (tags.chunkId == 0)
3265 matchingChunk = object->hdrChunk;
3266 else if (object->softDeleted)
3267 matchingChunk = oldChunk; /* Defeat the test */
3269 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
3271 if (oldChunk != matchingChunk)
3272 T(YAFFS_TRACE_ERROR,
3273 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3274 oldChunk, matchingChunk, tags.objectId, tags.chunkId));
3279 T(YAFFS_TRACE_ERROR,
3281 ("page %d in gc has no object: %d %d %d "
3283 tags.objectId, tags.chunkId, tags.byteCount));
3288 object->softDeleted &&
3289 tags.chunkId != 0) {
3290 /* Data chunk in a soft deleted file, throw it away
3291 * It's a soft deleted data chunk,
3292 * No need to copy this, just forget about it and
3293 * fix up the object.
3296 object->nDataChunks--;
3298 if (object->nDataChunks <= 0) {
3299 /* remeber to clean up the object */
3300 dev->gcCleanupList[cleanups] =
3306 /* Todo object && object->deleted && object->nDataChunks == 0 */
3307 /* Deleted object header with no data chunks.
3308 * Can be discarded and the file deleted.
3310 object->hdrChunk = 0;
3311 yaffs_FreeTnode(object->myDev,
3314 object->variant.fileVariant.top = NULL;
3315 yaffs_DoGenericObjectDeletion(object);
3317 } else if (object) {
3318 /* It's either a data chunk in a live file or
3319 * an ObjectHeader, so we're interested in it.
3320 * NB Need to keep the ObjectHeaders of deleted files
3321 * until the whole file has been deleted off
3323 tags.serialNumber++;
3327 if (tags.chunkId == 0) {
3328 /* It is an object Id,
3329 * We need to nuke the shrinkheader flags first
3330 * Also need to clean up shadowing.
3331 * We no longer want the shrinkHeader flag since its work is done
3332 * and if it is left in place it will mess up scanning.
3335 yaffs_ObjectHeader *oh;
3336 oh = (yaffs_ObjectHeader *)buffer;
3338 tags.extraIsShrinkHeader = 0;
3339 oh->shadowsObject = 0;
3340 oh->inbandShadowsObject = 0;
3341 if(object->variantType == YAFFS_OBJECT_TYPE_FILE)
3342 oh->fileSize = object->variant.fileVariant.fileSize;
3343 tags.extraShadows = 0;
3345 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
3347 yaffs_WriteNewChunkWithTagsToNAND(dev,(__u8 *) oh, &tags, 1);
3350 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3353 retVal = YAFFS_FAIL;
3356 /* Ok, now fix up the Tnodes etc. */
3358 if (tags.chunkId == 0) {
3360 object->hdrChunk = newChunk;
3361 object->serial = tags.serialNumber;
3363 /* It's a data chunk */
3365 ok = yaffs_PutChunkIntoFile
3373 if (retVal == YAFFS_OK)
3374 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3379 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3382 /* Do any required cleanups */
3383 for (i = 0; i < cleanups; i++) {
3384 /* Time to delete the file too */
3386 yaffs_FindObjectByNumber(dev,
3387 dev->gcCleanupList[i]);
3389 yaffs_FreeTnode(dev,
3390 object->variant.fileVariant.
3392 object->variant.fileVariant.top = NULL;
3395 ("yaffs: About to finally delete object %d"
3396 TENDSTR), object->objectId));
3397 yaffs_DoGenericObjectDeletion(object);
3398 object->myDev->nDeletedFiles--;
3405 yaffs_VerifyCollectedBlock(dev, bi, block);
3409 /* If the gc completed then clear the current gcBlock so that we find another. */
3410 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING) {
3411 chunksAfter = yaffs_GetErasedChunks(dev);
3412 if (chunksBefore >= chunksAfter) {
3415 ("gc did not increase free chunks before %d after %d"
3416 TENDSTR), chunksBefore, chunksAfter));
3427 /* New garbage collector
3428 * If we're very low on erased blocks then we do aggressive garbage collection
3429 * otherwise we do "leasurely" garbage collection.
3430 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3431 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3433 * The idea is to help clear out space in a more spread-out manner.
3434 * Dunno if it really does anything useful.
3436 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
3440 int gcOk = YAFFS_OK;
3443 int checkpointBlockAdjust;
3445 if (dev->isDoingGC) {
3446 /* Bail out so we don't get recursive gc */
3450 /* This loop should pass the first time.
3451 * We'll only see looping here if the erase of the collected block fails.
3457 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3458 if (checkpointBlockAdjust < 0)
3459 checkpointBlockAdjust = 0;
3461 /* If we need a block soon then do aggressive gc.*/
3462 if (dev->nErasedBlocks < (dev->param.nReservedBlocks + checkpointBlockAdjust + 2))
3467 /* If we don't already have a block being gc'd then see if we should start another */
3469 if (dev->gcBlock < 1 && !aggressive) {
3470 dev->gcBlock = yaffs_FindRefreshBlock(dev);
3473 if (dev->gcBlock < 1) {
3474 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3478 block = dev->gcBlock;
3481 dev->garbageCollections++;
3483 dev->passiveGarbageCollections++;
3487 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3488 dev->nErasedBlocks, aggressive));
3490 gcOk = yaffs_GarbageCollectBlock(dev, block, aggressive);
3493 if (dev->nErasedBlocks < (dev->param.nReservedBlocks) && block > 0) {
3496 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3497 TENDSTR), dev->nErasedBlocks, maxTries, block));
3499 } while ((dev->nErasedBlocks < dev->param.nReservedBlocks) &&
3503 return aggressive ? gcOk : YAFFS_OK;
3506 /*------------------------- TAGS --------------------------------*/
3508 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
3511 return (tags->chunkId == chunkInObject &&
3512 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3517 /*-------------------- Data file manipulation -----------------*/
3519 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
3520 yaffs_ExtendedTags *tags)
3522 /*Get the Tnode, then get the level 0 offset chunk offset */
3525 yaffs_ExtendedTags localTags;
3528 yaffs_Device *dev = in->myDev;
3531 /* Passed a NULL, so use our own tags space */
3535 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3538 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3541 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3547 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
3548 yaffs_ExtendedTags *tags)
3550 /* Get the Tnode, then get the level 0 offset chunk offset */
3553 yaffs_ExtendedTags localTags;
3555 yaffs_Device *dev = in->myDev;
3559 /* Passed a NULL, so use our own tags space */
3563 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3567 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3570 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3573 /* Delete the entry in the filestructure (if found) */
3575 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, 0);
3581 #ifdef YAFFS_PARANOID
3583 static int yaffs_CheckFileSanity(yaffs_Object *in)
3591 yaffs_Tags localTags;
3592 yaffs_Tags *tags = &localTags;
3596 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3599 objId = in->objectId;
3600 fSize = in->variant.fileVariant.fileSize;
3602 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3604 for (chunk = 1; chunk <= nChunks; chunk++) {
3605 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3610 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunk);
3612 if (yaffs_CheckChunkBits
3613 (dev, theChunk / dev->param.nChunksPerBlock,
3614 theChunk % dev->param.nChunksPerBlock)) {
3616 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3620 (tags, in->objectId, chunk, chunkDeleted)) {
3630 /* T(("No level 0 found for %d\n", chunk)); */
3634 return failed ? YAFFS_FAIL : YAFFS_OK;
3639 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
3640 int chunkInNAND, int inScan)
3642 /* NB inScan is zero unless scanning.
3643 * For forward scanning, inScan is > 0;
3644 * for backward scanning inScan is < 0
3646 * chunkInNAND = 0 is a dummy insert to make sure the tnodes are there.
3650 yaffs_Device *dev = in->myDev;
3652 yaffs_ExtendedTags existingTags;
3653 yaffs_ExtendedTags newTags;
3654 unsigned existingSerial, newSerial;
3656 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3657 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3658 * If it is not during Scanning then something went wrong!
3661 T(YAFFS_TRACE_ERROR,
3663 ("yaffs tragedy:attempt to put data chunk into a non-file"
3668 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3672 tn = yaffs_AddOrFindLevel0Tnode(dev,
3673 &in->variant.fileVariant,
3680 /* Dummy insert, bail now */
3683 existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3686 /* If we're scanning then we need to test for duplicates
3687 * NB This does not need to be efficient since it should only ever
3688 * happen when the power fails during a write, then only one
3689 * chunk should ever be affected.
3691 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3692 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3695 if (existingChunk > 0) {
3696 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3697 * thus we have to do a FindChunkInFile to get the real chunk id.
3699 * We have a duplicate now we need to decide which one to use:
3701 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3702 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3703 * YAFFS1: Get both sets of tags and compare serial numbers.
3707 /* Only do this for forward scanning */
3708 yaffs_ReadChunkWithTagsFromNAND(dev,
3712 /* Do a proper find */
3714 yaffs_FindChunkInFile(in, chunkInInode,
3718 if (existingChunk <= 0) {
3719 /*Hoosterman - how did this happen? */
3721 T(YAFFS_TRACE_ERROR,
3723 ("yaffs tragedy: existing chunk < 0 in scan"
3728 /* NB The deleted flags should be false, otherwise the chunks will
3729 * not be loaded during a scan
3733 newSerial = newTags.serialNumber;
3734 existingSerial = existingTags.serialNumber;
3738 (in->myDev->param.isYaffs2 ||
3739 existingChunk <= 0 ||
3740 ((existingSerial + 1) & 3) == newSerial)) {
3741 /* Forward scanning.
3743 * Delete the old one and drop through to update the tnode
3745 yaffs_DeleteChunk(dev, existingChunk, 1,
3748 /* Backward scanning or we want to use the existing one
3750 * Delete the new one and return early so that the tnode isn't changed
3752 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3760 if (existingChunk == 0)
3763 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
3768 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
3771 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3773 if (chunkInNAND >= 0)
3774 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3777 T(YAFFS_TRACE_NANDACCESS,
3778 (TSTR("Chunk %d not found zero instead" TENDSTR),
3780 /* get sane (zero) data if you read a hole */
3781 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3787 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
3791 yaffs_ExtendedTags tags;
3792 yaffs_BlockInfo *bi;
3798 block = chunkId / dev->param.nChunksPerBlock;
3799 page = chunkId % dev->param.nChunksPerBlock;
3802 if (!yaffs_CheckChunkBit(dev, block, page))
3803 T(YAFFS_TRACE_VERIFY,
3804 (TSTR("Deleting invalid chunk %d"TENDSTR),
3807 bi = yaffs_GetBlockInfo(dev, block);
3809 yaffs_UpdateOldestDirtySequence(dev,bi);
3811 T(YAFFS_TRACE_DELETION,
3812 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3815 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->param.isYaffs2) {
3817 yaffs_InitialiseTags(&tags);
3819 tags.chunkDeleted = 1;
3821 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3822 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3824 dev->nUnmarkedDeletions++;
3827 /* Pull out of the management area.
3828 * If the whole block became dirty, this will kick off an erasure.
3830 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3831 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3832 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3833 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3836 yaffs_ClearChunkBit(dev, block, page);
3840 if (bi->pagesInUse == 0 &&
3841 !bi->hasShrinkHeader &&
3842 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3843 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3844 yaffs_BlockBecameDirty(dev, block);
3851 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
3852 const __u8 *buffer, int nBytes,
3855 /* Find old chunk Need to do this to get serial number
3856 * Write new one and patch into tree.
3857 * Invalidate old tags.
3861 yaffs_ExtendedTags prevTags;
3864 yaffs_ExtendedTags newTags;
3866 yaffs_Device *dev = in->myDev;
3868 yaffs_CheckGarbageCollection(dev);
3870 /* Get the previous chunk at this location in the file if it exists.
3871 * If it does not exist then put a zero into the tree. This creates
3872 * the tnode now, rather than later when it is harder to clean up.
3874 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3875 if(prevChunkId < 1 &&
3876 !yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0))
3879 /* Set up new tags */
3880 yaffs_InitialiseTags(&newTags);
3882 newTags.chunkId = chunkInInode;
3883 newTags.objectId = in->objectId;
3884 newTags.serialNumber =
3885 (prevChunkId > 0) ? prevTags.serialNumber + 1 : 1;
3886 newTags.byteCount = nBytes;
3888 if (nBytes < 1 || nBytes > dev->param.totalBytesPerChunk) {
3889 T(YAFFS_TRACE_ERROR,
3890 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3896 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3899 if (newChunkId > 0) {
3900 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3902 if (prevChunkId > 0)
3903 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3905 yaffs_CheckFileSanity(in);
3911 /* UpdateObjectHeader updates the header on NAND for an object.
3912 * If name is not NULL, then that new name is used.
3914 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
3915 int isShrink, int shadows)
3918 yaffs_BlockInfo *bi;
3920 yaffs_Device *dev = in->myDev;
3927 yaffs_ExtendedTags newTags;
3928 yaffs_ExtendedTags oldTags;
3929 YCHAR *alias = NULL;
3931 __u8 *buffer = NULL;
3932 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3934 yaffs_ObjectHeader *oh = NULL;
3936 yaffs_strcpy(oldName, _Y("silly old name"));
3940 in == dev->rootDir || /* The rootDir should also be saved */
3943 yaffs_CheckGarbageCollection(dev);
3944 yaffs_CheckObjectDetailsLoaded(in);
3946 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3947 oh = (yaffs_ObjectHeader *) buffer;
3949 prevChunkId = in->hdrChunk;
3951 if (prevChunkId > 0) {
3952 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3955 yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
3957 memcpy(oldName, oh->name, sizeof(oh->name));
3960 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3962 oh->type = in->variantType;
3963 oh->yst_mode = in->yst_mode;
3964 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3966 #ifdef CONFIG_YAFFS_WINCE
3967 oh->win_atime[0] = in->win_atime[0];
3968 oh->win_ctime[0] = in->win_ctime[0];
3969 oh->win_mtime[0] = in->win_mtime[0];
3970 oh->win_atime[1] = in->win_atime[1];
3971 oh->win_ctime[1] = in->win_ctime[1];
3972 oh->win_mtime[1] = in->win_mtime[1];
3974 oh->yst_uid = in->yst_uid;
3975 oh->yst_gid = in->yst_gid;
3976 oh->yst_atime = in->yst_atime;
3977 oh->yst_mtime = in->yst_mtime;
3978 oh->yst_ctime = in->yst_ctime;
3979 oh->yst_rdev = in->yst_rdev;
3982 oh->parentObjectId = in->parent->objectId;
3984 oh->parentObjectId = 0;
3986 if (name && *name) {
3987 memset(oh->name, 0, sizeof(oh->name));
3988 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3989 } else if (prevChunkId > 0)
3990 memcpy(oh->name, oldName, sizeof(oh->name));
3992 memset(oh->name, 0, sizeof(oh->name));
3994 oh->isShrink = isShrink;
3996 switch (in->variantType) {
3997 case YAFFS_OBJECT_TYPE_UNKNOWN:
3998 /* Should not happen */
4000 case YAFFS_OBJECT_TYPE_FILE:
4002 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
4003 || oh->parentObjectId ==
4004 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
4005 fileVariant.fileSize;
4007 case YAFFS_OBJECT_TYPE_HARDLINK:
4008 oh->equivalentObjectId =
4009 in->variant.hardLinkVariant.equivalentObjectId;
4011 case YAFFS_OBJECT_TYPE_SPECIAL:
4014 case YAFFS_OBJECT_TYPE_DIRECTORY:
4017 case YAFFS_OBJECT_TYPE_SYMLINK:
4018 alias = in->variant.symLinkVariant.alias;
4020 alias = _Y("no alias");
4021 yaffs_strncpy(oh->alias,
4023 YAFFS_MAX_ALIAS_LENGTH);
4024 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
4029 yaffs_InitialiseTags(&newTags);
4031 newTags.chunkId = 0;
4032 newTags.objectId = in->objectId;
4033 newTags.serialNumber = in->serial;
4035 /* Add extra info for file header */
4037 newTags.extraHeaderInfoAvailable = 1;
4038 newTags.extraParentObjectId = oh->parentObjectId;
4039 newTags.extraFileLength = oh->fileSize;
4040 newTags.extraIsShrinkHeader = oh->isShrink;
4041 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
4042 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
4043 newTags.extraObjectType = in->variantType;
4045 yaffs_VerifyObjectHeader(in, oh, &newTags, 1);
4047 /* Create new chunk in NAND */
4049 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
4050 (prevChunkId > 0) ? 1 : 0);
4052 if (newChunkId >= 0) {
4054 in->hdrChunk = newChunkId;
4056 if (prevChunkId > 0) {
4057 yaffs_DeleteChunk(dev, prevChunkId, 1,
4061 if (!yaffs_ObjectHasCachedWriteData(in))
4064 /* If this was a shrink, then mark the block that the chunk lives on */
4066 bi = yaffs_GetBlockInfo(in->myDev,
4067 newChunkId / in->myDev->param.nChunksPerBlock);
4068 bi->hasShrinkHeader = 1;
4073 retVal = newChunkId;
4078 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
4083 /*------------------------ Short Operations Cache ----------------------------------------
4084 * In many situations where there is no high level buffering (eg WinCE) a lot of
4085 * reads might be short sequential reads, and a lot of writes may be short
4086 * sequential writes. eg. scanning/writing a jpeg file.
4087 * In these cases, a short read/write cache can provide a huge perfomance benefit
4088 * with dumb-as-a-rock code.
4089 * In Linux, the page cache provides read buffering aand the short op cache provides write
4092 * There are a limited number (~10) of cache chunks per device so that we don't
4093 * need a very intelligent search.
4096 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
4098 yaffs_Device *dev = obj->myDev;
4100 yaffs_ChunkCache *cache;
4101 int nCaches = obj->myDev->param.nShortOpCaches;
4103 for (i = 0; i < nCaches; i++) {
4104 cache = &dev->srCache[i];
4105 if (cache->object == obj &&
4114 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
4116 yaffs_Device *dev = obj->myDev;
4117 int lowest = -99; /* Stop compiler whining. */
4119 yaffs_ChunkCache *cache;
4120 int chunkWritten = 0;
4121 int nCaches = obj->myDev->param.nShortOpCaches;
4127 /* Find the dirty cache for this object with the lowest chunk id. */
4128 for (i = 0; i < nCaches; i++) {
4129 if (dev->srCache[i].object == obj &&
4130 dev->srCache[i].dirty) {
4132 || dev->srCache[i].chunkId <
4134 cache = &dev->srCache[i];
4135 lowest = cache->chunkId;
4140 if (cache && !cache->locked) {
4141 /* Write it out and free it up */
4144 yaffs_WriteChunkDataToObject(cache->object,
4150 cache->object = NULL;
4153 } while (cache && chunkWritten > 0);
4156 /* Hoosterman, disk full while writing cache out. */
4157 T(YAFFS_TRACE_ERROR,
4158 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
4165 /*yaffs_FlushEntireDeviceCache(dev)
4170 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
4173 int nCaches = dev->param.nShortOpCaches;
4176 /* Find a dirty object in the cache and flush it...
4177 * until there are no further dirty objects.
4181 for (i = 0; i < nCaches && !obj; i++) {
4182 if (dev->srCache[i].object &&
4183 dev->srCache[i].dirty)
4184 obj = dev->srCache[i].object;
4188 yaffs_FlushFilesChunkCache(obj);
4195 /* Grab us a cache chunk for use.
4196 * First look for an empty one.
4197 * Then look for the least recently used non-dirty one.
4198 * Then look for the least recently used dirty one...., flush and look again.
4200 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
4204 if (dev->param.nShortOpCaches > 0) {
4205 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4206 if (!dev->srCache[i].object)
4207 return &dev->srCache[i];
4214 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
4216 yaffs_ChunkCache *cache;
4217 yaffs_Object *theObj;
4222 if (dev->param.nShortOpCaches > 0) {
4223 /* Try find a non-dirty one... */
4225 cache = yaffs_GrabChunkCacheWorker(dev);
4228 /* They were all dirty, find the last recently used object and flush
4229 * its cache, then find again.
4230 * NB what's here is not very accurate, we actually flush the object
4231 * the last recently used page.
4234 /* With locking we can't assume we can use entry zero */
4241 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4242 if (dev->srCache[i].object &&
4243 !dev->srCache[i].locked &&
4244 (dev->srCache[i].lastUse < usage || !cache)) {
4245 usage = dev->srCache[i].lastUse;
4246 theObj = dev->srCache[i].object;
4247 cache = &dev->srCache[i];
4252 if (!cache || cache->dirty) {
4253 /* Flush and try again */
4254 yaffs_FlushFilesChunkCache(theObj);
4255 cache = yaffs_GrabChunkCacheWorker(dev);
4265 /* Find a cached chunk */
4266 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj,
4269 yaffs_Device *dev = obj->myDev;
4271 if (dev->param.nShortOpCaches > 0) {
4272 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4273 if (dev->srCache[i].object == obj &&
4274 dev->srCache[i].chunkId == chunkId) {
4277 return &dev->srCache[i];
4284 /* Mark the chunk for the least recently used algorithym */
4285 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache,
4289 if (dev->param.nShortOpCaches > 0) {
4290 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4291 /* Reset the cache usages */
4293 for (i = 1; i < dev->param.nShortOpCaches; i++)
4294 dev->srCache[i].lastUse = 0;
4301 cache->lastUse = dev->srLastUse;
4308 /* Invalidate a single cache page.
4309 * Do this when a whole page gets written,
4310 * ie the short cache for this page is no longer valid.
4312 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
4314 if (object->myDev->param.nShortOpCaches > 0) {
4315 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4318 cache->object = NULL;
4322 /* Invalidate all the cache pages associated with this object
4323 * Do this whenever ther file is deleted or resized.
4325 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
4328 yaffs_Device *dev = in->myDev;
4330 if (dev->param.nShortOpCaches > 0) {
4331 /* Invalidate it. */
4332 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4333 if (dev->srCache[i].object == in)
4334 dev->srCache[i].object = NULL;
4339 /*--------------------- Checkpointing --------------------*/
4342 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev, int head)
4344 yaffs_CheckpointValidity cp;
4346 memset(&cp, 0, sizeof(cp));
4348 cp.structType = sizeof(cp);
4349 cp.magic = YAFFS_MAGIC;
4350 cp.version = YAFFS_CHECKPOINT_VERSION;
4351 cp.head = (head) ? 1 : 0;
4353 return (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp)) ?
4357 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4359 yaffs_CheckpointValidity cp;
4362 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4365 ok = (cp.structType == sizeof(cp)) &&
4366 (cp.magic == YAFFS_MAGIC) &&
4367 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4368 (cp.head == ((head) ? 1 : 0));
4372 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4375 cp->nErasedBlocks = dev->nErasedBlocks;
4376 cp->allocationBlock = dev->allocationBlock;
4377 cp->allocationPage = dev->allocationPage;
4378 cp->nFreeChunks = dev->nFreeChunks;
4380 cp->nDeletedFiles = dev->nDeletedFiles;
4381 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4382 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4383 cp->sequenceNumber = dev->sequenceNumber;
4387 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4388 yaffs_CheckpointDevice *cp)
4390 dev->nErasedBlocks = cp->nErasedBlocks;
4391 dev->allocationBlock = cp->allocationBlock;
4392 dev->allocationPage = cp->allocationPage;
4393 dev->nFreeChunks = cp->nFreeChunks;
4395 dev->nDeletedFiles = cp->nDeletedFiles;
4396 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4397 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4398 dev->sequenceNumber = cp->sequenceNumber;
4402 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4404 yaffs_CheckpointDevice cp;
4406 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4410 /* Write device runtime values*/
4411 yaffs_DeviceToCheckpointDevice(&cp, dev);
4412 cp.structType = sizeof(cp);
4414 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4416 /* Write block info */
4418 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4419 ok = (yaffs_CheckpointWrite(dev, dev->blockInfo, nBytes) == nBytes);
4422 /* Write chunk bits */
4424 nBytes = nBlocks * dev->chunkBitmapStride;
4425 ok = (yaffs_CheckpointWrite(dev, dev->chunkBits, nBytes) == nBytes);
4431 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4433 yaffs_CheckpointDevice cp;
4435 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4439 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4443 if (cp.structType != sizeof(cp))
4447 yaffs_CheckpointDeviceToDevice(dev, &cp);
4449 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4451 ok = (yaffs_CheckpointRead(dev, dev->blockInfo, nBytes) == nBytes);
4455 nBytes = nBlocks * dev->chunkBitmapStride;
4457 ok = (yaffs_CheckpointRead(dev, dev->chunkBits, nBytes) == nBytes);
4462 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4466 cp->objectId = obj->objectId;
4467 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4468 cp->hdrChunk = obj->hdrChunk;
4469 cp->variantType = obj->variantType;
4470 cp->deleted = obj->deleted;
4471 cp->softDeleted = obj->softDeleted;
4472 cp->unlinked = obj->unlinked;
4473 cp->fake = obj->fake;
4474 cp->renameAllowed = obj->renameAllowed;
4475 cp->unlinkAllowed = obj->unlinkAllowed;
4476 cp->serial = obj->serial;
4477 cp->nDataChunks = obj->nDataChunks;
4479 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4480 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4481 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4482 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4485 static int yaffs_CheckpointObjectToObject(yaffs_Object *obj, yaffs_CheckpointObject *cp)
4488 yaffs_Object *parent;
4490 if (obj->variantType != cp->variantType) {
4491 T(YAFFS_TRACE_ERROR, (TSTR("Checkpoint read object %d type %d "
4492 TCONT("chunk %d does not match existing object type %d")
4493 TENDSTR), cp->objectId, cp->variantType, cp->hdrChunk,
4498 obj->objectId = cp->objectId;
4501 parent = yaffs_FindOrCreateObjectByNumber(
4504 YAFFS_OBJECT_TYPE_DIRECTORY);
4509 if (parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4510 T(YAFFS_TRACE_ALWAYS, (TSTR("Checkpoint read object %d parent %d type %d"
4511 TCONT(" chunk %d Parent type, %d, not directory")
4513 cp->objectId, cp->parentId, cp->variantType,
4514 cp->hdrChunk, parent->variantType));
4517 yaffs_AddObjectToDirectory(parent, obj);
4520 obj->hdrChunk = cp->hdrChunk;
4521 obj->variantType = cp->variantType;
4522 obj->deleted = cp->deleted;
4523 obj->softDeleted = cp->softDeleted;
4524 obj->unlinked = cp->unlinked;
4525 obj->fake = cp->fake;
4526 obj->renameAllowed = cp->renameAllowed;
4527 obj->unlinkAllowed = cp->unlinkAllowed;
4528 obj->serial = cp->serial;
4529 obj->nDataChunks = cp->nDataChunks;
4531 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4532 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4533 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4534 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4536 if (obj->hdrChunk > 0)
4537 obj->lazyLoaded = 1;
4543 static int yaffs_CheckpointTnodeWorker(yaffs_Object *in, yaffs_Tnode *tn,
4544 __u32 level, int chunkOffset)
4547 yaffs_Device *dev = in->myDev;
4549 int tnodeSize = yaffs_CalcTnodeSize(dev);
4554 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
4555 if (tn->internal[i]) {
4556 ok = yaffs_CheckpointTnodeWorker(in,
4559 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4562 } else if (level == 0) {
4563 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4564 ok = (yaffs_CheckpointWrite(dev, &baseOffset, sizeof(baseOffset)) == sizeof(baseOffset));
4566 ok = (yaffs_CheckpointWrite(dev, tn, tnodeSize) == tnodeSize);
4574 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4576 __u32 endMarker = ~0;
4579 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4580 ok = yaffs_CheckpointTnodeWorker(obj,
4581 obj->variant.fileVariant.top,
4582 obj->variant.fileVariant.topLevel,
4585 ok = (yaffs_CheckpointWrite(obj->myDev, &endMarker, sizeof(endMarker)) ==
4592 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4596 yaffs_Device *dev = obj->myDev;
4597 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4600 int tnodeSize = yaffs_CalcTnodeSize(dev);
4602 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4604 while (ok && (~baseChunk)) {
4606 /* Read level 0 tnode */
4609 tn = yaffs_GetTnodeRaw(dev);
4611 ok = (yaffs_CheckpointRead(dev, tn, tnodeSize) == tnodeSize);
4616 ok = yaffs_AddOrFindLevel0Tnode(dev,
4622 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4626 T(YAFFS_TRACE_CHECKPOINT, (
4627 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4628 nread, baseChunk, ok));
4634 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4637 yaffs_CheckpointObject cp;
4640 struct ylist_head *lh;
4643 /* Iterate through the objects in each hash entry,
4644 * dumping them to the checkpointing stream.
4647 for (i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++) {
4648 ylist_for_each(lh, &dev->objectBucket[i].list) {
4650 obj = ylist_entry(lh, yaffs_Object, hashLink);
4651 if (!obj->deferedFree) {
4652 yaffs_ObjectToCheckpointObject(&cp, obj);
4653 cp.structType = sizeof(cp);
4655 T(YAFFS_TRACE_CHECKPOINT, (
4656 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %p" TENDSTR),
4657 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk, obj));
4659 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4661 if (ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4662 ok = yaffs_WriteCheckpointTnodes(obj);
4668 /* Dump end of list */
4669 memset(&cp, 0xFF, sizeof(yaffs_CheckpointObject));
4670 cp.structType = sizeof(cp);
4673 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4678 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4681 yaffs_CheckpointObject cp;
4684 yaffs_Object *hardList = NULL;
4686 while (ok && !done) {
4687 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4688 if (cp.structType != sizeof(cp)) {
4689 T(YAFFS_TRACE_CHECKPOINT, (TSTR("struct size %d instead of %d ok %d"TENDSTR),
4690 cp.structType, (int)sizeof(cp), ok));
4694 T(YAFFS_TRACE_CHECKPOINT, (TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4695 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk));
4697 if (ok && cp.objectId == ~0)
4700 obj = yaffs_FindOrCreateObjectByNumber(dev, cp.objectId, cp.variantType);
4702 ok = yaffs_CheckpointObjectToObject(obj, &cp);
4705 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4706 ok = yaffs_ReadCheckpointTnodes(obj);
4707 } else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4708 obj->hardLinks.next =
4709 (struct ylist_head *) hardList;
4718 yaffs_HardlinkFixup(dev, hardList);
4723 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4725 __u32 checkpointSum;
4728 yaffs_GetCheckpointSum(dev, &checkpointSum);
4730 ok = (yaffs_CheckpointWrite(dev, &checkpointSum, sizeof(checkpointSum)) == sizeof(checkpointSum));
4738 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4740 __u32 checkpointSum0;
4741 __u32 checkpointSum1;
4744 yaffs_GetCheckpointSum(dev, &checkpointSum0);
4746 ok = (yaffs_CheckpointRead(dev, &checkpointSum1, sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4751 if (checkpointSum0 != checkpointSum1)
4758 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4762 if (dev->param.skipCheckpointWrite || !dev->param.isYaffs2) {
4763 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint write" TENDSTR)));
4768 ok = yaffs_CheckpointOpen(dev, 1);
4771 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4772 ok = yaffs_WriteCheckpointValidityMarker(dev, 1);
4775 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint device" TENDSTR)));
4776 ok = yaffs_WriteCheckpointDevice(dev);
4779 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint objects" TENDSTR)));
4780 ok = yaffs_WriteCheckpointObjects(dev);
4783 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4784 ok = yaffs_WriteCheckpointValidityMarker(dev, 0);
4788 ok = yaffs_WriteCheckpointSum(dev);
4790 if (!yaffs_CheckpointClose(dev))
4794 dev->isCheckpointed = 1;
4796 dev->isCheckpointed = 0;
4798 return dev->isCheckpointed;
4801 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4805 if (dev->param.skipCheckpointRead || !dev->param.isYaffs2) {
4806 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint read" TENDSTR)));
4811 ok = yaffs_CheckpointOpen(dev, 0); /* open for read */
4814 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4815 ok = yaffs_ReadCheckpointValidityMarker(dev, 1);
4818 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint device" TENDSTR)));
4819 ok = yaffs_ReadCheckpointDevice(dev);
4822 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint objects" TENDSTR)));
4823 ok = yaffs_ReadCheckpointObjects(dev);
4826 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4827 ok = yaffs_ReadCheckpointValidityMarker(dev, 0);
4831 ok = yaffs_ReadCheckpointSum(dev);
4832 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint checksum %d" TENDSTR), ok));
4835 if (!yaffs_CheckpointClose(dev))
4839 dev->isCheckpointed = 1;
4841 dev->isCheckpointed = 0;
4847 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4849 if (dev->isCheckpointed ||
4850 dev->blocksInCheckpoint > 0) {
4851 dev->isCheckpointed = 0;
4852 yaffs_CheckpointInvalidateStream(dev);
4853 if (dev->param.markSuperBlockDirty)
4854 dev->param.markSuperBlockDirty(dev);
4859 int yaffs_CheckpointSave(yaffs_Device *dev)
4862 T(YAFFS_TRACE_CHECKPOINT, (TSTR("save entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4864 yaffs_VerifyObjects(dev);
4865 yaffs_VerifyBlocks(dev);
4866 yaffs_VerifyFreeChunks(dev);
4868 if (!dev->isCheckpointed) {
4869 yaffs_InvalidateCheckpoint(dev);
4870 yaffs_WriteCheckpointData(dev);
4873 T(YAFFS_TRACE_ALWAYS, (TSTR("save exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4875 return dev->isCheckpointed;
4878 int yaffs_CheckpointRestore(yaffs_Device *dev)
4881 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4883 retval = yaffs_ReadCheckpointData(dev);
4885 if (dev->isCheckpointed) {
4886 yaffs_VerifyObjects(dev);
4887 yaffs_VerifyBlocks(dev);
4888 yaffs_VerifyFreeChunks(dev);
4891 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4896 /*--------------------- File read/write ------------------------
4897 * Read and write have very similar structures.
4898 * In general the read/write has three parts to it
4899 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4900 * Some complete chunks
4901 * An incomplete chunk to end off with
4903 * Curve-balls: the first chunk might also be the last chunk.
4906 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 *buffer, loff_t offset,
4915 yaffs_ChunkCache *cache;
4922 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4923 /* start = offset % dev->nDataBytesPerChunk; */
4924 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4927 /* OK now check for the curveball where the start and end are in
4930 if ((start + n) < dev->nDataBytesPerChunk)
4933 nToCopy = dev->nDataBytesPerChunk - start;
4935 cache = yaffs_FindChunkCache(in, chunk);
4937 /* If the chunk is already in the cache or it is less than a whole chunk
4938 * or we're using inband tags then use the cache (if there is caching)
4939 * else bypass the cache.
4941 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
4942 if (dev->param.nShortOpCaches > 0) {
4944 /* If we can't find the data in the cache, then load it up. */
4947 cache = yaffs_GrabChunkCache(in->myDev);
4949 cache->chunkId = chunk;
4952 yaffs_ReadChunkDataFromObject(in, chunk,
4958 yaffs_UseChunkCache(dev, cache, 0);
4963 memcpy(buffer, &cache->data[start], nToCopy);
4967 /* Read into the local buffer then copy..*/
4970 yaffs_GetTempBuffer(dev, __LINE__);
4971 yaffs_ReadChunkDataFromObject(in, chunk,
4974 memcpy(buffer, &localBuffer[start], nToCopy);
4977 yaffs_ReleaseTempBuffer(dev, localBuffer,
4983 /* A full chunk. Read directly into the supplied buffer. */
4984 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4998 int yaffs_WriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
4999 int nBytes, int writeThrough)
5008 int startOfWrite = offset;
5009 int chunkWritten = 0;
5017 while (n > 0 && chunkWritten >= 0) {
5018 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
5019 /* start = offset % dev->nDataBytesPerChunk; */
5020 yaffs_AddrToChunk(dev, offset, &chunk, &start);
5022 if (chunk * dev->nDataBytesPerChunk + start != offset ||
5023 start >= dev->nDataBytesPerChunk) {
5024 T(YAFFS_TRACE_ERROR, (
5025 TSTR("AddrToChunk of offset %d gives chunk %d start %d"
5027 (int)offset, chunk, start));
5031 /* OK now check for the curveball where the start and end are in
5035 if ((start + n) < dev->nDataBytesPerChunk) {
5038 /* Now folks, to calculate how many bytes to write back....
5039 * If we're overwriting and not writing to then end of file then
5040 * we need to write back as much as was there before.
5043 chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
5045 if (chunkStart > in->variant.fileVariant.fileSize)
5046 nBytesRead = 0; /* Past end of file */
5048 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
5050 if (nBytesRead > dev->nDataBytesPerChunk)
5051 nBytesRead = dev->nDataBytesPerChunk;
5055 (start + n)) ? nBytesRead : (start + n);
5057 if (nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
5061 nToCopy = dev->nDataBytesPerChunk - start;
5062 nToWriteBack = dev->nDataBytesPerChunk;
5065 if (nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
5066 /* An incomplete start or end chunk (or maybe both start and end chunk),
5067 * or we're using inband tags, so we want to use the cache buffers.
5069 if (dev->param.nShortOpCaches > 0) {
5070 yaffs_ChunkCache *cache;
5071 /* If we can't find the data in the cache, then load the cache */
5072 cache = yaffs_FindChunkCache(in, chunk);
5075 && yaffs_CheckSpaceForAllocation(in->
5077 cache = yaffs_GrabChunkCache(in->myDev);
5079 cache->chunkId = chunk;
5082 yaffs_ReadChunkDataFromObject(in, chunk,
5087 !yaffs_CheckSpaceForAllocation(in->myDev)) {
5088 /* Drop the cache if it was a read cache item and
5089 * no space check has been made for it.
5095 yaffs_UseChunkCache(dev, cache, 1);
5099 memcpy(&cache->data[start], buffer,
5104 cache->nBytes = nToWriteBack;
5108 yaffs_WriteChunkDataToObject
5111 cache->data, cache->nBytes,
5117 chunkWritten = -1; /* fail the write */
5120 /* An incomplete start or end chunk (or maybe both start and end chunk)
5121 * Read into the local buffer then copy, then copy over and write back.
5125 yaffs_GetTempBuffer(dev, __LINE__);
5127 yaffs_ReadChunkDataFromObject(in, chunk,
5132 memcpy(&localBuffer[start], buffer, nToCopy);
5135 yaffs_WriteChunkDataToObject(in, chunk,
5140 yaffs_ReleaseTempBuffer(dev, localBuffer,
5146 /* A full chunk. Write directly from the supplied buffer. */
5151 yaffs_WriteChunkDataToObject(in, chunk, buffer,
5152 dev->nDataBytesPerChunk,
5155 /* Since we've overwritten the cached data, we better invalidate it. */
5156 yaffs_InvalidateChunkCache(in, chunk);
5159 if (chunkWritten >= 0) {
5168 /* Update file object */
5170 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
5171 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
5179 /* ---------------------- File resizing stuff ------------------ */
5181 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
5184 yaffs_Device *dev = in->myDev;
5185 int oldFileSize = in->variant.fileVariant.fileSize;
5187 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
5189 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
5190 dev->nDataBytesPerChunk;
5194 /* Delete backwards so that we don't end up with holes if
5195 * power is lost part-way through the operation.
5197 for (i = lastDel; i >= startDel; i--) {
5198 /* NB this could be optimised somewhat,
5199 * eg. could retrieve the tags and write them without
5200 * using yaffs_DeleteChunk
5203 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5206 (dev->internalStartBlock * dev->param.nChunksPerBlock)
5208 ((dev->internalEndBlock +
5209 1) * dev->param.nChunksPerBlock)) {
5210 T(YAFFS_TRACE_ALWAYS,
5211 (TSTR("Found daft chunkId %d for %d" TENDSTR),
5215 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5222 int yaffs_ResizeFile(yaffs_Object *in, loff_t newSize)
5225 int oldFileSize = in->variant.fileVariant.fileSize;
5226 __u32 newSizeOfPartialChunk;
5229 yaffs_Device *dev = in->myDev;
5231 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5233 yaffs_FlushFilesChunkCache(in);
5234 yaffs_InvalidateWholeChunkCache(in);
5236 yaffs_CheckGarbageCollection(dev);
5238 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
5241 if (newSize == oldFileSize)
5244 if (newSize < oldFileSize) {
5246 yaffs_PruneResizedChunks(in, newSize);
5248 if (newSizeOfPartialChunk != 0) {
5249 int lastChunk = 1 + newFullChunks;
5251 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5253 /* Got to read and rewrite the last chunk with its new size and zero pad */
5254 yaffs_ReadChunkDataFromObject(in, lastChunk,
5257 memset(localBuffer + newSizeOfPartialChunk, 0,
5258 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5260 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5261 newSizeOfPartialChunk, 1);
5263 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5266 in->variant.fileVariant.fileSize = newSize;
5268 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5270 /* newsSize > oldFileSize */
5271 in->variant.fileVariant.fileSize = newSize;
5274 /* Write a new object header to reflect the resize.
5275 * show we've shrunk the file, if need be
5276 * Do this only if the file is not in the deleted directories
5277 * and is not shadowed.
5281 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5282 in->parent->objectId != YAFFS_OBJECTID_DELETED)
5283 yaffs_UpdateObjectHeader(in, NULL, 0,
5284 (newSize < oldFileSize) ? 1 : 0, 0);
5289 loff_t yaffs_GetFileSize(yaffs_Object *obj)
5291 YCHAR *alias = NULL;
5292 obj = yaffs_GetEquivalentObject(obj);
5294 switch (obj->variantType) {
5295 case YAFFS_OBJECT_TYPE_FILE:
5296 return obj->variant.fileVariant.fileSize;
5297 case YAFFS_OBJECT_TYPE_SYMLINK:
5298 alias = obj->variant.symLinkVariant.alias;
5301 return yaffs_strnlen(alias,YAFFS_MAX_ALIAS_LENGTH);
5309 int yaffs_FlushFile(yaffs_Object *in, int updateTime, int dataSync)
5313 yaffs_FlushFilesChunkCache(in);
5314 if(dataSync) /* Only sync data */
5318 #ifdef CONFIG_YAFFS_WINCE
5319 yfsd_WinFileTimeNow(in->win_mtime);
5322 in->yst_mtime = Y_CURRENT_TIME;
5327 retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5328 0) ? YAFFS_OK : YAFFS_FAIL;
5338 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
5341 /* First off, invalidate the file's data in the cache, without flushing. */
5342 yaffs_InvalidateWholeChunkCache(in);
5344 if (in->myDev->param.isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5345 /* Move to the unlinked directory so we have a record that it was deleted. */
5346 yaffs_ChangeObjectName(in, in->myDev->deletedDir, _Y("deleted"), 0, 0);
5350 yaffs_RemoveObjectFromDirectory(in);
5351 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5354 yaffs_FreeObject(in);
5359 /* yaffs_DeleteFile deletes the whole file data
5360 * and the inode associated with the file.
5361 * It does not delete the links associated with the file.
5363 static int yaffs_UnlinkFileIfNeeded(yaffs_Object *in)
5367 int immediateDeletion = 0;
5370 immediateDeletion = 1;
5372 if (immediateDeletion) {
5374 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5375 _Y("deleted"), 0, 0);
5376 T(YAFFS_TRACE_TRACING,
5377 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5380 in->myDev->nDeletedFiles++;
5381 if (1 || in->myDev->param.isYaffs2)
5382 yaffs_ResizeFile(in, 0);
5383 yaffs_SoftDeleteFile(in);
5386 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5387 _Y("unlinked"), 0, 0);
5394 int yaffs_DeleteFile(yaffs_Object *in)
5396 int retVal = YAFFS_OK;
5397 int deleted = in->deleted;
5399 yaffs_ResizeFile(in, 0);
5401 if (in->nDataChunks > 0) {
5402 /* Use soft deletion if there is data in the file.
5403 * That won't be the case if it has been resized to zero.
5406 retVal = yaffs_UnlinkFileIfNeeded(in);
5408 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5411 in->myDev->nDeletedFiles++;
5412 yaffs_SoftDeleteFile(in);
5414 return deleted ? YAFFS_OK : YAFFS_FAIL;
5416 /* The file has no data chunks so we toss it immediately */
5417 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5418 in->variant.fileVariant.top = NULL;
5419 yaffs_DoGenericObjectDeletion(in);
5425 static int yaffs_IsNonEmptyDirectory(yaffs_Object *obj)
5427 return (obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) &&
5428 !(ylist_empty(&obj->variant.directoryVariant.children));
5431 static int yaffs_DeleteDirectory(yaffs_Object *obj)
5433 /* First check that the directory is empty. */
5434 if (yaffs_IsNonEmptyDirectory(obj))
5437 return yaffs_DoGenericObjectDeletion(obj);
5440 static int yaffs_DeleteSymLink(yaffs_Object *in)
5442 if(in->variant.symLinkVariant.alias)
5443 YFREE(in->variant.symLinkVariant.alias);
5444 in->variant.symLinkVariant.alias=NULL;
5446 return yaffs_DoGenericObjectDeletion(in);
5449 static int yaffs_DeleteHardLink(yaffs_Object *in)
5451 /* remove this hardlink from the list assocaited with the equivalent
5454 ylist_del_init(&in->hardLinks);
5455 return yaffs_DoGenericObjectDeletion(in);
5458 int yaffs_DeleteObject(yaffs_Object *obj)
5461 switch (obj->variantType) {
5462 case YAFFS_OBJECT_TYPE_FILE:
5463 retVal = yaffs_DeleteFile(obj);
5465 case YAFFS_OBJECT_TYPE_DIRECTORY:
5466 return yaffs_DeleteDirectory(obj);
5468 case YAFFS_OBJECT_TYPE_SYMLINK:
5469 retVal = yaffs_DeleteSymLink(obj);
5471 case YAFFS_OBJECT_TYPE_HARDLINK:
5472 retVal = yaffs_DeleteHardLink(obj);
5474 case YAFFS_OBJECT_TYPE_SPECIAL:
5475 retVal = yaffs_DoGenericObjectDeletion(obj);
5477 case YAFFS_OBJECT_TYPE_UNKNOWN:
5479 break; /* should not happen. */
5485 static int yaffs_UnlinkWorker(yaffs_Object *obj)
5488 int immediateDeletion = 0;
5491 immediateDeletion = 1;
5494 yaffs_UpdateParent(obj->parent);
5496 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5497 return yaffs_DeleteHardLink(obj);
5498 } else if (!ylist_empty(&obj->hardLinks)) {
5499 /* Curve ball: We're unlinking an object that has a hardlink.
5501 * This problem arises because we are not strictly following
5502 * The Linux link/inode model.
5504 * We can't really delete the object.
5505 * Instead, we do the following:
5506 * - Select a hardlink.
5507 * - Unhook it from the hard links
5508 * - Move it from its parent directory (so that the rename can work)
5509 * - Rename the object to the hardlink's name.
5510 * - Delete the hardlink
5514 yaffs_Object *parent;
5516 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5518 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5520 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5521 parent = hl->parent;
5523 ylist_del_init(&hl->hardLinks);
5525 yaffs_AddObjectToDirectory(obj->myDev->unlinkedDir, hl);
5527 retVal = yaffs_ChangeObjectName(obj,parent, name, 0, 0);
5529 if (retVal == YAFFS_OK)
5530 retVal = yaffs_DoGenericObjectDeletion(hl);
5534 } else if (immediateDeletion) {
5535 switch (obj->variantType) {
5536 case YAFFS_OBJECT_TYPE_FILE:
5537 return yaffs_DeleteFile(obj);
5539 case YAFFS_OBJECT_TYPE_DIRECTORY:
5540 return yaffs_DeleteDirectory(obj);
5542 case YAFFS_OBJECT_TYPE_SYMLINK:
5543 return yaffs_DeleteSymLink(obj);
5545 case YAFFS_OBJECT_TYPE_SPECIAL:
5546 return yaffs_DoGenericObjectDeletion(obj);
5548 case YAFFS_OBJECT_TYPE_HARDLINK:
5549 case YAFFS_OBJECT_TYPE_UNKNOWN:
5553 } else if(yaffs_IsNonEmptyDirectory(obj))
5556 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
5557 _Y("unlinked"), 0, 0);
5561 static int yaffs_UnlinkObject(yaffs_Object *obj)
5564 if (obj && obj->unlinkAllowed)
5565 return yaffs_UnlinkWorker(obj);
5570 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
5574 obj = yaffs_FindObjectByName(dir, name);
5575 return yaffs_UnlinkObject(obj);
5578 /*----------------------- Initialisation Scanning ---------------------- */
5580 static void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
5581 int backwardScanning)
5585 if (!backwardScanning) {
5586 /* Handle YAFFS1 forward scanning case
5587 * For YAFFS1 we always do the deletion
5591 /* Handle YAFFS2 case (backward scanning)
5592 * If the shadowed object exists then ignore.
5594 obj = yaffs_FindObjectByNumber(dev, objId);
5599 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5600 * We put it in unlinked dir to be cleaned up after the scanning
5603 yaffs_FindOrCreateObjectByNumber(dev, objId,
5604 YAFFS_OBJECT_TYPE_FILE);
5607 obj->isShadowed = 1;
5608 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5609 obj->variant.fileVariant.shrinkSize = 0;
5610 obj->valid = 1; /* So that we don't read any other info for this file */
5620 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5627 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5629 in = yaffs_FindObjectByNumber(dev,
5630 hl->variant.hardLinkVariant.
5631 equivalentObjectId);
5634 /* Add the hardlink pointers */
5635 hl->variant.hardLinkVariant.equivalentObject = in;
5636 ylist_add(&hl->hardLinks, &in->hardLinks);
5638 /* Todo Need to report/handle this better.
5639 * Got a problem... hardlink to a non-existant object
5641 hl->variant.hardLinkVariant.equivalentObject = NULL;
5642 YINIT_LIST_HEAD(&hl->hardLinks);
5652 static int ybicmp(const void *a, const void *b)
5654 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5655 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5656 register int ablock = ((yaffs_BlockIndex *)a)->block;
5657 register int bblock = ((yaffs_BlockIndex *)b)->block;
5659 return ablock - bblock;
5665 struct yaffs_ShadowFixerStruct {
5668 struct yaffs_ShadowFixerStruct *next;
5672 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5675 * Sort out state of unlinked and deleted objects after scanning.
5677 struct ylist_head *i;
5678 struct ylist_head *n;
5681 /* Soft delete all the unlinked files */
5682 ylist_for_each_safe(i, n,
5683 &dev->unlinkedDir->variant.directoryVariant.children) {
5685 l = ylist_entry(i, yaffs_Object, siblings);
5686 yaffs_DeleteObject(l);
5690 ylist_for_each_safe(i, n,
5691 &dev->deletedDir->variant.directoryVariant.children) {
5693 l = ylist_entry(i, yaffs_Object, siblings);
5694 yaffs_DeleteObject(l);
5701 * This code iterates through all the objects making sure that they are rooted.
5702 * Any unrooted objects are re-rooted in lost+found.
5703 * An object needs to be in one of:
5704 * - Directly under deleted, unlinked
5705 * - Directly or indirectly under root.
5708 * This code assumes that we don't ever change the current relationships between
5710 * rootDir->parent == unlinkedDir->parent == deletedDir->parent == NULL
5711 * lostNfound->parent == rootDir
5713 * This fixes the problem where directories might have inadvertently been deleted
5714 * leaving the object "hanging" without being rooted in the directory tree.
5717 static int yaffs_HasNULLParent(yaffs_Device *dev, yaffs_Object *obj)
5719 return (obj == dev->deletedDir ||
5720 obj == dev->unlinkedDir||
5721 obj == dev->rootDir);
5724 static void yaffs_FixHangingObjects(yaffs_Device *dev)
5727 yaffs_Object *parent;
5729 struct ylist_head *lh;
5730 struct ylist_head *n;
5735 /* Iterate through the objects in each hash entry,
5736 * looking at each object.
5737 * Make sure it is rooted.
5740 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
5741 ylist_for_each_safe(lh, n, &dev->objectBucket[i].list) {
5743 obj = ylist_entry(lh, yaffs_Object, hashLink);
5744 parent= obj->parent;
5746 if(yaffs_HasNULLParent(dev,obj)){
5747 /* These directories are not hanging */
5750 else if(!parent || parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5752 else if(yaffs_HasNULLParent(dev,parent))
5756 * Need to follow the parent chain to see if it is hanging.
5761 while(parent != dev->rootDir &&
5763 parent->parent->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
5765 parent = parent->parent;
5768 if(parent != dev->rootDir)
5773 (TSTR("Hanging object %d moved to lost and found" TENDSTR),
5775 yaffs_AddObjectToDirectory(dev->lostNFoundDir,obj);
5784 * Delete directory contents for cleaning up lost and found.
5786 static void yaffs_DeleteDirectoryContents(yaffs_Object *dir)
5789 struct ylist_head *lh;
5790 struct ylist_head *n;
5792 if(dir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5795 ylist_for_each_safe(lh, n, &dir->variant.directoryVariant.children) {
5797 obj = ylist_entry(lh, yaffs_Object, siblings);
5798 if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
5799 yaffs_DeleteDirectoryContents(obj);
5802 (TSTR("Deleting lost_found object %d" TENDSTR),
5805 /* Need to use UnlinkObject since Delete would not handle
5806 * hardlinked objects correctly.
5808 yaffs_UnlinkObject(obj);
5814 static void yaffs_EmptyLostAndFound(yaffs_Device *dev)
5816 yaffs_DeleteDirectoryContents(dev->lostNFoundDir);
5819 static int yaffs_Scan(yaffs_Device *dev)
5821 yaffs_ExtendedTags tags;
5831 yaffs_BlockState state;
5832 yaffs_Object *hardList = NULL;
5833 yaffs_BlockInfo *bi;
5834 __u32 sequenceNumber;
5835 yaffs_ObjectHeader *oh;
5837 yaffs_Object *parent;
5839 int alloc_failed = 0;
5841 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5849 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5850 dev->internalStartBlock, dev->internalEndBlock));
5852 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5854 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5856 /* Scan all the blocks to determine their state */
5857 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5858 bi = yaffs_GetBlockInfo(dev, blk);
5859 yaffs_ClearChunkBits(dev, blk);
5861 bi->softDeletions = 0;
5863 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5865 bi->blockState = state;
5866 bi->sequenceNumber = sequenceNumber;
5868 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
5869 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
5871 T(YAFFS_TRACE_SCAN_DEBUG,
5872 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5873 state, sequenceNumber));
5875 if (state == YAFFS_BLOCK_STATE_DEAD) {
5876 T(YAFFS_TRACE_BAD_BLOCKS,
5877 (TSTR("block %d is bad" TENDSTR), blk));
5878 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5879 T(YAFFS_TRACE_SCAN_DEBUG,
5880 (TSTR("Block empty " TENDSTR)));
5881 dev->nErasedBlocks++;
5882 dev->nFreeChunks += dev->param.nChunksPerBlock;
5886 startIterator = dev->internalStartBlock;
5887 endIterator = dev->internalEndBlock;
5889 /* For each block.... */
5890 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5897 blk = blockIterator;
5899 bi = yaffs_GetBlockInfo(dev, blk);
5900 state = bi->blockState;
5904 /* For each chunk in each block that needs scanning....*/
5905 for (c = 0; !alloc_failed && c < dev->param.nChunksPerBlock &&
5906 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5907 /* Read the tags and decide what to do */
5908 chunk = blk * dev->param.nChunksPerBlock + c;
5910 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5913 /* Let's have a good look at this chunk... */
5915 if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
5921 /*T((" %d %d deleted\n",blk,c)); */
5922 } else if (!tags.chunkUsed) {
5923 /* An unassigned chunk in the block
5924 * This means that either the block is empty or
5925 * this is the one being allocated from
5929 /* We're looking at the first chunk in the block so the block is unused */
5930 state = YAFFS_BLOCK_STATE_EMPTY;
5931 dev->nErasedBlocks++;
5933 /* this is the block being allocated from */
5936 (" Allocating from %d %d" TENDSTR),
5938 state = YAFFS_BLOCK_STATE_ALLOCATING;
5939 dev->allocationBlock = blk;
5940 dev->allocationPage = c;
5941 dev->allocationBlockFinder = blk;
5942 /* Set block finder here to encourage the allocator to go forth from here. */
5946 dev->nFreeChunks += (dev->param.nChunksPerBlock - c);
5947 } else if (tags.chunkId > 0) {
5948 /* chunkId > 0 so it is a data chunk... */
5949 unsigned int endpos;
5951 yaffs_SetChunkBit(dev, blk, c);
5954 in = yaffs_FindOrCreateObjectByNumber(dev,
5957 YAFFS_OBJECT_TYPE_FILE);
5958 /* PutChunkIntoFile checks for a clash (two data chunks with
5959 * the same chunkId).
5966 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, 1))
5971 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5974 in->variantType == YAFFS_OBJECT_TYPE_FILE
5975 && in->variant.fileVariant.scannedFileSize <
5977 in->variant.fileVariant.
5978 scannedFileSize = endpos;
5979 if (!dev->param.useHeaderFileSize) {
5980 in->variant.fileVariant.
5982 in->variant.fileVariant.
5987 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
5989 /* chunkId == 0, so it is an ObjectHeader.
5990 * Thus, we read in the object header and make the object
5992 yaffs_SetChunkBit(dev, blk, c);
5995 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5999 oh = (yaffs_ObjectHeader *) chunkData;
6001 in = yaffs_FindObjectByNumber(dev,
6003 if (in && in->variantType != oh->type) {
6004 /* This should not happen, but somehow
6005 * Wev'e ended up with an objectId that has been reused but not yet
6006 * deleted, and worse still it has changed type. Delete the old object.
6009 yaffs_DeleteObject(in);
6014 in = yaffs_FindOrCreateObjectByNumber(dev,
6022 if (in && oh->shadowsObject > 0) {
6024 struct yaffs_ShadowFixerStruct *fixer;
6025 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
6027 fixer->next = shadowFixerList;
6028 shadowFixerList = fixer;
6029 fixer->objectId = tags.objectId;
6030 fixer->shadowedId = oh->shadowsObject;
6035 if (in && in->valid) {
6036 /* We have already filled this one. We have a duplicate and need to resolve it. */
6038 unsigned existingSerial = in->serial;
6039 unsigned newSerial = tags.serialNumber;
6041 if (((existingSerial + 1) & 3) == newSerial) {
6042 /* Use new one - destroy the exisiting one */
6043 yaffs_DeleteChunk(dev,
6048 /* Use existing - destroy this one. */
6049 yaffs_DeleteChunk(dev, chunk, 1,
6054 if (in && !in->valid &&
6055 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6056 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
6057 /* We only load some info, don't fiddle with directory structure */
6059 in->variantType = oh->type;
6061 in->yst_mode = oh->yst_mode;
6062 #ifdef CONFIG_YAFFS_WINCE
6063 in->win_atime[0] = oh->win_atime[0];
6064 in->win_ctime[0] = oh->win_ctime[0];
6065 in->win_mtime[0] = oh->win_mtime[0];
6066 in->win_atime[1] = oh->win_atime[1];
6067 in->win_ctime[1] = oh->win_ctime[1];
6068 in->win_mtime[1] = oh->win_mtime[1];
6070 in->yst_uid = oh->yst_uid;
6071 in->yst_gid = oh->yst_gid;
6072 in->yst_atime = oh->yst_atime;
6073 in->yst_mtime = oh->yst_mtime;
6074 in->yst_ctime = oh->yst_ctime;
6075 in->yst_rdev = oh->yst_rdev;
6077 in->hdrChunk = chunk;
6078 in->serial = tags.serialNumber;
6080 } else if (in && !in->valid) {
6081 /* we need to load this info */
6084 in->variantType = oh->type;
6086 in->yst_mode = oh->yst_mode;
6087 #ifdef CONFIG_YAFFS_WINCE
6088 in->win_atime[0] = oh->win_atime[0];
6089 in->win_ctime[0] = oh->win_ctime[0];
6090 in->win_mtime[0] = oh->win_mtime[0];
6091 in->win_atime[1] = oh->win_atime[1];
6092 in->win_ctime[1] = oh->win_ctime[1];
6093 in->win_mtime[1] = oh->win_mtime[1];
6095 in->yst_uid = oh->yst_uid;
6096 in->yst_gid = oh->yst_gid;
6097 in->yst_atime = oh->yst_atime;
6098 in->yst_mtime = oh->yst_mtime;
6099 in->yst_ctime = oh->yst_ctime;
6100 in->yst_rdev = oh->yst_rdev;
6102 in->hdrChunk = chunk;
6103 in->serial = tags.serialNumber;
6105 yaffs_SetObjectName(in, oh->name);
6108 /* directory stuff...
6113 yaffs_FindOrCreateObjectByNumber
6114 (dev, oh->parentObjectId,
6115 YAFFS_OBJECT_TYPE_DIRECTORY);
6118 if (parent && parent->variantType ==
6119 YAFFS_OBJECT_TYPE_UNKNOWN) {
6120 /* Set up as a directory */
6121 parent->variantType =
6122 YAFFS_OBJECT_TYPE_DIRECTORY;
6123 YINIT_LIST_HEAD(&parent->variant.
6126 } else if (!parent || parent->variantType !=
6127 YAFFS_OBJECT_TYPE_DIRECTORY) {
6128 /* Hoosterman, another problem....
6129 * We're trying to use a non-directory as a directory
6132 T(YAFFS_TRACE_ERROR,
6134 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6136 parent = dev->lostNFoundDir;
6139 yaffs_AddObjectToDirectory(parent, in);
6141 if (0 && (parent == dev->deletedDir ||
6142 parent == dev->unlinkedDir)) {
6143 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
6144 dev->nDeletedFiles++;
6146 /* Note re hardlinks.
6147 * Since we might scan a hardlink before its equivalent object is scanned
6148 * we put them all in a list.
6149 * After scanning is complete, we should have all the objects, so we run through this
6150 * list and fix up all the chains.
6153 switch (in->variantType) {
6154 case YAFFS_OBJECT_TYPE_UNKNOWN:
6155 /* Todo got a problem */
6157 case YAFFS_OBJECT_TYPE_FILE:
6158 if (dev->param.useHeaderFileSize)
6160 in->variant.fileVariant.
6165 case YAFFS_OBJECT_TYPE_HARDLINK:
6166 in->variant.hardLinkVariant.
6167 equivalentObjectId =
6168 oh->equivalentObjectId;
6169 in->hardLinks.next =
6170 (struct ylist_head *)
6174 case YAFFS_OBJECT_TYPE_DIRECTORY:
6177 case YAFFS_OBJECT_TYPE_SPECIAL:
6180 case YAFFS_OBJECT_TYPE_SYMLINK:
6181 in->variant.symLinkVariant.alias =
6182 yaffs_CloneString(oh->alias);
6183 if (!in->variant.symLinkVariant.alias)
6192 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6193 /* If we got this far while scanning, then the block is fully allocated.*/
6194 state = YAFFS_BLOCK_STATE_FULL;
6197 if (state == YAFFS_BLOCK_STATE_ALLOCATING) {
6198 /* If the block was partially allocated then treat it as fully allocated.*/
6199 state = YAFFS_BLOCK_STATE_FULL;
6200 dev->allocationBlock = -1;
6203 bi->blockState = state;
6205 /* Now let's see if it was dirty */
6206 if (bi->pagesInUse == 0 &&
6207 !bi->hasShrinkHeader &&
6208 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6209 yaffs_BlockBecameDirty(dev, blk);
6215 /* Ok, we've done all the scanning.
6216 * Fix up the hard link chains.
6217 * We should now have scanned all the objects, now it's time to add these
6221 yaffs_HardlinkFixup(dev, hardList);
6223 /* Fix up any shadowed objects */
6225 struct yaffs_ShadowFixerStruct *fixer;
6228 while (shadowFixerList) {
6229 fixer = shadowFixerList;
6230 shadowFixerList = fixer->next;
6231 /* Complete the rename transaction by deleting the shadowed object
6232 * then setting the object header to unshadowed.
6234 obj = yaffs_FindObjectByNumber(dev, fixer->shadowedId);
6236 yaffs_DeleteObject(obj);
6238 obj = yaffs_FindObjectByNumber(dev, fixer->objectId);
6241 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6247 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6252 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
6258 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
6261 yaffs_ObjectHeader *oh;
6263 yaffs_ExtendedTags tags;
6265 int alloc_failed = 0;
6273 T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
6275 in->lazyLoaded ? "not yet" : "already"));
6278 if (in->lazyLoaded && in->hdrChunk > 0) {
6280 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6282 result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
6283 oh = (yaffs_ObjectHeader *) chunkData;
6285 in->yst_mode = oh->yst_mode;
6286 #ifdef CONFIG_YAFFS_WINCE
6287 in->win_atime[0] = oh->win_atime[0];
6288 in->win_ctime[0] = oh->win_ctime[0];
6289 in->win_mtime[0] = oh->win_mtime[0];
6290 in->win_atime[1] = oh->win_atime[1];
6291 in->win_ctime[1] = oh->win_ctime[1];
6292 in->win_mtime[1] = oh->win_mtime[1];
6294 in->yst_uid = oh->yst_uid;
6295 in->yst_gid = oh->yst_gid;
6296 in->yst_atime = oh->yst_atime;
6297 in->yst_mtime = oh->yst_mtime;
6298 in->yst_ctime = oh->yst_ctime;
6299 in->yst_rdev = oh->yst_rdev;
6302 yaffs_SetObjectName(in, oh->name);
6304 if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6305 in->variant.symLinkVariant.alias =
6306 yaffs_CloneString(oh->alias);
6307 if (!in->variant.symLinkVariant.alias)
6308 alloc_failed = 1; /* Not returned to caller */
6311 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6315 static int yaffs_ScanBackwards(yaffs_Device *dev)
6317 yaffs_ExtendedTags tags;
6322 int nBlocksToScan = 0;
6328 yaffs_BlockState state;
6329 yaffs_Object *hardList = NULL;
6330 yaffs_BlockInfo *bi;
6331 __u32 sequenceNumber;
6332 yaffs_ObjectHeader *oh;
6334 yaffs_Object *parent;
6335 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6341 int foundChunksInBlock;
6342 int equivalentObjectId;
6343 int alloc_failed = 0;
6346 yaffs_BlockIndex *blockIndex = NULL;
6347 int altBlockIndex = 0;
6349 if (!dev->param.isYaffs2) {
6351 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6357 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
6358 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6361 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6363 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6366 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6372 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6376 dev->blocksInCheckpoint = 0;
6378 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6380 /* Scan all the blocks to determine their state */
6381 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6382 bi = yaffs_GetBlockInfo(dev, blk);
6383 yaffs_ClearChunkBits(dev, blk);
6385 bi->softDeletions = 0;
6387 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6389 bi->blockState = state;
6390 bi->sequenceNumber = sequenceNumber;
6392 if (bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6393 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6394 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6395 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6397 T(YAFFS_TRACE_SCAN_DEBUG,
6398 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6399 state, sequenceNumber));
6402 if (state == YAFFS_BLOCK_STATE_CHECKPOINT) {
6403 dev->blocksInCheckpoint++;
6405 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6406 T(YAFFS_TRACE_BAD_BLOCKS,
6407 (TSTR("block %d is bad" TENDSTR), blk));
6408 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6409 T(YAFFS_TRACE_SCAN_DEBUG,
6410 (TSTR("Block empty " TENDSTR)));
6411 dev->nErasedBlocks++;
6412 dev->nFreeChunks += dev->param.nChunksPerBlock;
6413 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6415 /* Determine the highest sequence number */
6416 if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6417 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6419 blockIndex[nBlocksToScan].seq = sequenceNumber;
6420 blockIndex[nBlocksToScan].block = blk;
6424 if (sequenceNumber >= dev->sequenceNumber)
6425 dev->sequenceNumber = sequenceNumber;
6427 /* TODO: Nasty sequence number! */
6430 ("Block scanning block %d has bad sequence number %d"
6431 TENDSTR), blk, sequenceNumber));
6438 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6444 /* Sort the blocks */
6445 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6447 /* Use qsort now. */
6448 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6452 /* Dungy old bubble sort... */
6454 yaffs_BlockIndex temp;
6458 for (i = 0; i < nBlocksToScan; i++)
6459 for (j = i + 1; j < nBlocksToScan; j++)
6460 if (blockIndex[i].seq > blockIndex[j].seq) {
6461 temp = blockIndex[j];
6462 blockIndex[j] = blockIndex[i];
6463 blockIndex[i] = temp;
6470 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6472 /* Now scan the blocks looking at the data. */
6474 endIterator = nBlocksToScan - 1;
6475 T(YAFFS_TRACE_SCAN_DEBUG,
6476 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6478 /* For each block.... backwards */
6479 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6481 /* Cooperative multitasking! This loop can run for so
6482 long that watchdog timers expire. */
6485 /* get the block to scan in the correct order */
6486 blk = blockIndex[blockIterator].block;
6488 bi = yaffs_GetBlockInfo(dev, blk);
6491 state = bi->blockState;
6495 /* For each chunk in each block that needs scanning.... */
6496 foundChunksInBlock = 0;
6497 for (c = dev->param.nChunksPerBlock - 1;
6498 !alloc_failed && c >= 0 &&
6499 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6500 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6501 /* Scan backwards...
6502 * Read the tags and decide what to do
6505 chunk = blk * dev->param.nChunksPerBlock + c;
6507 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6510 /* Let's have a good look at this chunk... */
6512 if (!tags.chunkUsed) {
6513 /* An unassigned chunk in the block.
6514 * If there are used chunks after this one, then
6515 * it is a chunk that was skipped due to failing the erased
6516 * check. Just skip it so that it can be deleted.
6517 * But, more typically, We get here when this is an unallocated
6518 * chunk and his means that either the block is empty or
6519 * this is the one being allocated from
6522 if (foundChunksInBlock) {
6523 /* This is a chunk that was skipped due to failing the erased check */
6524 } else if (c == 0) {
6525 /* We're looking at the first chunk in the block so the block is unused */
6526 state = YAFFS_BLOCK_STATE_EMPTY;
6527 dev->nErasedBlocks++;
6529 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6530 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6531 if (dev->sequenceNumber == bi->sequenceNumber) {
6532 /* this is the block being allocated from */
6536 (" Allocating from %d %d"
6539 state = YAFFS_BLOCK_STATE_ALLOCATING;
6540 dev->allocationBlock = blk;
6541 dev->allocationPage = c;
6542 dev->allocationBlockFinder = blk;
6544 /* This is a partially written block that is not
6545 * the current allocation block.
6548 T(YAFFS_TRACE_ALWAYS,
6549 (TSTR("Partially written block %d detected" TENDSTR),
6557 } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED) {
6559 (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
6564 } else if (tags.chunkId > 0) {
6565 /* chunkId > 0 so it is a data chunk... */
6566 unsigned int endpos;
6568 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6570 foundChunksInBlock = 1;
6573 yaffs_SetChunkBit(dev, blk, c);
6576 in = yaffs_FindOrCreateObjectByNumber(dev,
6579 YAFFS_OBJECT_TYPE_FILE);
6586 in->variantType == YAFFS_OBJECT_TYPE_FILE
6587 && chunkBase < in->variant.fileVariant.shrinkSize) {
6588 /* This has not been invalidated by a resize */
6589 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, -1)) {
6593 /* File size is calculated by looking at the data chunks if we have not
6594 * seen an object header yet. Stop this practice once we find an object header.
6596 endpos = chunkBase + tags.byteCount;
6598 if (!in->valid && /* have not got an object header yet */
6599 in->variant.fileVariant.scannedFileSize < endpos) {
6600 in->variant.fileVariant.scannedFileSize = endpos;
6601 in->variant.fileVariant.fileSize = endpos;
6605 /* This chunk has been invalidated by a resize, or a past file deletion
6606 * so delete the chunk*/
6607 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6611 /* chunkId == 0, so it is an ObjectHeader.
6612 * Thus, we read in the object header and make the object
6614 foundChunksInBlock = 1;
6616 yaffs_SetChunkBit(dev, blk, c);
6622 if (tags.extraHeaderInfoAvailable) {
6623 in = yaffs_FindOrCreateObjectByNumber(dev,
6625 tags.extraObjectType);
6631 (!in->valid && dev->param.disableLazyLoad) ||
6632 tags.extraShadows ||
6634 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6635 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))) {
6637 /* If we don't have valid info then we need to read the chunk
6638 * TODO In future we can probably defer reading the chunk and
6639 * living with invalid data until needed.
6642 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6647 oh = (yaffs_ObjectHeader *) chunkData;
6649 if (dev->param.inbandTags) {
6650 /* Fix up the header if they got corrupted by inband tags */
6651 oh->shadowsObject = oh->inbandShadowsObject;
6652 oh->isShrink = oh->inbandIsShrink;
6656 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6664 /* TODO Hoosterman we have a problem! */
6665 T(YAFFS_TRACE_ERROR,
6667 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6668 TENDSTR), tags.objectId, chunk));
6673 /* We have already filled this one.
6674 * We have a duplicate that will be discarded, but
6675 * we first have to suck out resize info if it is a file.
6678 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6680 oh->type == YAFFS_OBJECT_TYPE_FILE) ||
6681 (tags.extraHeaderInfoAvailable &&
6682 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))) {
6684 (oh) ? oh->fileSize : tags.
6686 __u32 parentObjectId =
6688 parentObjectId : tags.
6689 extraParentObjectId;
6693 (oh) ? oh->isShrink : tags.
6694 extraIsShrinkHeader;
6696 /* If it is deleted (unlinked at start also means deleted)
6697 * we treat the file size as being zeroed at this point.
6699 if (parentObjectId ==
6700 YAFFS_OBJECTID_DELETED
6701 || parentObjectId ==
6702 YAFFS_OBJECTID_UNLINKED) {
6707 if (isShrink && in->variant.fileVariant.shrinkSize > thisSize)
6708 in->variant.fileVariant.shrinkSize = thisSize;
6711 bi->hasShrinkHeader = 1;
6714 /* Use existing - destroy this one. */
6715 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6719 if (!in->valid && in->variantType !=
6720 (oh ? oh->type : tags.extraObjectType))
6721 T(YAFFS_TRACE_ERROR, (
6722 TSTR("yaffs tragedy: Bad object type, "
6723 TCONT("%d != %d, for object %d at chunk ")
6724 TCONT("%d during scan")
6726 oh->type : tags.extraObjectType,
6727 in->variantType, tags.objectId,
6731 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6733 YAFFS_OBJECTID_LOSTNFOUND)) {
6734 /* We only load some info, don't fiddle with directory structure */
6738 in->variantType = oh->type;
6740 in->yst_mode = oh->yst_mode;
6741 #ifdef CONFIG_YAFFS_WINCE
6742 in->win_atime[0] = oh->win_atime[0];
6743 in->win_ctime[0] = oh->win_ctime[0];
6744 in->win_mtime[0] = oh->win_mtime[0];
6745 in->win_atime[1] = oh->win_atime[1];
6746 in->win_ctime[1] = oh->win_ctime[1];
6747 in->win_mtime[1] = oh->win_mtime[1];
6749 in->yst_uid = oh->yst_uid;
6750 in->yst_gid = oh->yst_gid;
6751 in->yst_atime = oh->yst_atime;
6752 in->yst_mtime = oh->yst_mtime;
6753 in->yst_ctime = oh->yst_ctime;
6754 in->yst_rdev = oh->yst_rdev;
6758 in->variantType = tags.extraObjectType;
6762 in->hdrChunk = chunk;
6764 } else if (!in->valid) {
6765 /* we need to load this info */
6768 in->hdrChunk = chunk;
6771 in->variantType = oh->type;
6773 in->yst_mode = oh->yst_mode;
6774 #ifdef CONFIG_YAFFS_WINCE
6775 in->win_atime[0] = oh->win_atime[0];
6776 in->win_ctime[0] = oh->win_ctime[0];
6777 in->win_mtime[0] = oh->win_mtime[0];
6778 in->win_atime[1] = oh->win_atime[1];
6779 in->win_ctime[1] = oh->win_ctime[1];
6780 in->win_mtime[1] = oh->win_mtime[1];
6782 in->yst_uid = oh->yst_uid;
6783 in->yst_gid = oh->yst_gid;
6784 in->yst_atime = oh->yst_atime;
6785 in->yst_mtime = oh->yst_mtime;
6786 in->yst_ctime = oh->yst_ctime;
6787 in->yst_rdev = oh->yst_rdev;
6790 if (oh->shadowsObject > 0)
6791 yaffs_HandleShadowedObject(dev,
6798 yaffs_SetObjectName(in, oh->name);
6800 yaffs_FindOrCreateObjectByNumber
6801 (dev, oh->parentObjectId,
6802 YAFFS_OBJECT_TYPE_DIRECTORY);
6804 fileSize = oh->fileSize;
6805 isShrink = oh->isShrink;
6806 equivalentObjectId = oh->equivalentObjectId;
6809 in->variantType = tags.extraObjectType;
6811 yaffs_FindOrCreateObjectByNumber
6812 (dev, tags.extraParentObjectId,
6813 YAFFS_OBJECT_TYPE_DIRECTORY);
6814 fileSize = tags.extraFileLength;
6815 isShrink = tags.extraIsShrinkHeader;
6816 equivalentObjectId = tags.extraEquivalentObjectId;
6825 /* directory stuff...
6829 if (parent && parent->variantType ==
6830 YAFFS_OBJECT_TYPE_UNKNOWN) {
6831 /* Set up as a directory */
6832 parent->variantType =
6833 YAFFS_OBJECT_TYPE_DIRECTORY;
6834 YINIT_LIST_HEAD(&parent->variant.
6837 } else if (!parent || parent->variantType !=
6838 YAFFS_OBJECT_TYPE_DIRECTORY) {
6839 /* Hoosterman, another problem....
6840 * We're trying to use a non-directory as a directory
6843 T(YAFFS_TRACE_ERROR,
6845 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6847 parent = dev->lostNFoundDir;
6850 yaffs_AddObjectToDirectory(parent, in);
6852 itsUnlinked = (parent == dev->deletedDir) ||
6853 (parent == dev->unlinkedDir);
6856 /* Mark the block as having a shrinkHeader */
6857 bi->hasShrinkHeader = 1;
6860 /* Note re hardlinks.
6861 * Since we might scan a hardlink before its equivalent object is scanned
6862 * we put them all in a list.
6863 * After scanning is complete, we should have all the objects, so we run
6864 * through this list and fix up all the chains.
6867 switch (in->variantType) {
6868 case YAFFS_OBJECT_TYPE_UNKNOWN:
6869 /* Todo got a problem */
6871 case YAFFS_OBJECT_TYPE_FILE:
6873 if (in->variant.fileVariant.
6874 scannedFileSize < fileSize) {
6875 /* This covers the case where the file size is greater
6876 * than where the data is
6877 * This will happen if the file is resized to be larger
6878 * than its current data extents.
6880 in->variant.fileVariant.fileSize = fileSize;
6881 in->variant.fileVariant.scannedFileSize = fileSize;
6884 if (in->variant.fileVariant.shrinkSize > fileSize)
6885 in->variant.fileVariant.shrinkSize = fileSize;
6889 case YAFFS_OBJECT_TYPE_HARDLINK:
6891 in->variant.hardLinkVariant.equivalentObjectId =
6893 in->hardLinks.next =
6894 (struct ylist_head *) hardList;
6898 case YAFFS_OBJECT_TYPE_DIRECTORY:
6901 case YAFFS_OBJECT_TYPE_SPECIAL:
6904 case YAFFS_OBJECT_TYPE_SYMLINK:
6906 in->variant.symLinkVariant.alias =
6907 yaffs_CloneString(oh->alias);
6908 if (!in->variant.symLinkVariant.alias)
6918 } /* End of scanning for each chunk */
6920 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6921 /* If we got this far while scanning, then the block is fully allocated. */
6922 state = YAFFS_BLOCK_STATE_FULL;
6926 bi->blockState = state;
6928 /* Now let's see if it was dirty */
6929 if (bi->pagesInUse == 0 &&
6930 !bi->hasShrinkHeader &&
6931 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6932 yaffs_BlockBecameDirty(dev, blk);
6937 yaffs_SkipRestOfBlock(dev);
6940 YFREE_ALT(blockIndex);
6944 /* Ok, we've done all the scanning.
6945 * Fix up the hard link chains.
6946 * We should now have scanned all the objects, now it's time to add these
6949 yaffs_HardlinkFixup(dev, hardList);
6952 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6957 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6962 /*------------------------------ Directory Functions ----------------------------- */
6964 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
6966 struct ylist_head *lh;
6967 yaffs_Object *listObj;
6972 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
6977 if (yaffs_SkipVerification(obj->myDev))
6981 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
6986 if (obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6987 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
6991 /* Iterate through the objects in each hash entry */
6993 ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
6995 listObj = ylist_entry(lh, yaffs_Object, siblings);
6996 yaffs_VerifyObject(listObj);
7003 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR), count));
7008 static void yaffs_VerifyDirectory(yaffs_Object *directory)
7010 struct ylist_head *lh;
7011 yaffs_Object *listObj;
7018 if (yaffs_SkipFullVerification(directory->myDev))
7021 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7022 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR), directory->variantType));
7026 /* Iterate through the objects in each hash entry */
7028 ylist_for_each(lh, &directory->variant.directoryVariant.children) {
7030 listObj = ylist_entry(lh, yaffs_Object, siblings);
7031 if (listObj->parent != directory) {
7032 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR), listObj->parent));
7035 yaffs_VerifyObjectInDirectory(listObj);
7041 *yaffs_UpdateParent() handles fixing a directories mtime and ctime when a new
7042 * link (ie. name) is created or deleted in the directory.
7045 * create dir/a : update dir's mtime/ctime
7046 * rm dir/a: update dir's mtime/ctime
7047 * modify dir/a: don't update dir's mtimme/ctime
7050 static void yaffs_UpdateParent(yaffs_Object *obj)
7056 obj->yst_mtime = obj->yst_ctime = Y_CURRENT_TIME;
7058 yaffs_UpdateObjectHeader(obj,NULL,0,0,0);
7061 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
7063 yaffs_Device *dev = obj->myDev;
7064 yaffs_Object *parent;
7066 yaffs_VerifyObjectInDirectory(obj);
7067 parent = obj->parent;
7069 yaffs_VerifyDirectory(parent);
7071 if (dev && dev->param.removeObjectCallback)
7072 dev->param.removeObjectCallback(obj);
7075 ylist_del_init(&obj->siblings);
7078 yaffs_VerifyDirectory(parent);
7081 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
7085 T(YAFFS_TRACE_ALWAYS,
7087 ("tragedy: Trying to add an object to a null pointer directory"
7092 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7093 T(YAFFS_TRACE_ALWAYS,
7095 ("tragedy: Trying to add an object to a non-directory"
7100 if (obj->siblings.prev == NULL) {
7101 /* Not initialised */
7106 yaffs_VerifyDirectory(directory);
7108 yaffs_RemoveObjectFromDirectory(obj);
7112 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
7113 obj->parent = directory;
7115 if (directory == obj->myDev->unlinkedDir
7116 || directory == obj->myDev->deletedDir) {
7118 obj->myDev->nUnlinkedFiles++;
7119 obj->renameAllowed = 0;
7122 yaffs_VerifyDirectory(directory);
7123 yaffs_VerifyObjectInDirectory(obj);
7126 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
7131 struct ylist_head *i;
7132 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
7140 T(YAFFS_TRACE_ALWAYS,
7142 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7147 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7148 T(YAFFS_TRACE_ALWAYS,
7150 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7154 sum = yaffs_CalcNameSum(name);
7156 ylist_for_each(i, &directory->variant.directoryVariant.children) {
7158 l = ylist_entry(i, yaffs_Object, siblings);
7160 if (l->parent != directory)
7163 yaffs_CheckObjectDetailsLoaded(l);
7165 /* Special case for lost-n-found */
7166 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7167 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
7169 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
7170 /* LostnFound chunk called Objxxx
7173 yaffs_GetObjectName(l, buffer,
7174 YAFFS_MAX_NAME_LENGTH + 1);
7175 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
7186 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
7187 int (*fn) (yaffs_Object *))
7189 struct ylist_head *i;
7193 T(YAFFS_TRACE_ALWAYS,
7195 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7200 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7201 T(YAFFS_TRACE_ALWAYS,
7203 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7208 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
7210 l = ylist_entry(i, yaffs_Object, siblings);
7221 /* GetEquivalentObject dereferences any hard links to get to the
7225 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
7227 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
7228 /* We want the object id of the equivalent object, not this one */
7229 obj = obj->variant.hardLinkVariant.equivalentObject;
7230 yaffs_CheckObjectDetailsLoaded(obj);
7235 int yaffs_GetObjectName(yaffs_Object *obj, YCHAR *name, int buffSize)
7237 memset(name, 0, buffSize * sizeof(YCHAR));
7239 yaffs_CheckObjectDetailsLoaded(obj);
7241 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7242 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
7243 } else if (obj->hdrChunk <= 0) {
7245 YCHAR numString[20];
7246 YCHAR *x = &numString[19];
7247 unsigned v = obj->objectId;
7251 *x = '0' + (v % 10);
7254 /* make up a name */
7255 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
7256 yaffs_strcat(locName, x);
7257 yaffs_strncpy(name, locName, buffSize - 1);
7260 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
7261 else if (obj->shortName[0])
7262 yaffs_strncpy(name, obj->shortName,YAFFS_SHORT_NAME_LENGTH+1);
7266 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
7268 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
7270 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
7272 if (obj->hdrChunk > 0) {
7273 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
7274 obj->hdrChunk, buffer,
7277 yaffs_strncpy(name, oh->name, buffSize - 1);
7280 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
7283 return yaffs_strnlen(name,buffSize-1);
7286 int yaffs_GetObjectFileLength(yaffs_Object *obj)
7288 /* Dereference any hard linking */
7289 obj = yaffs_GetEquivalentObject(obj);
7291 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
7292 return obj->variant.fileVariant.fileSize;
7293 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
7294 if(!obj->variant.symLinkVariant.alias)
7296 return yaffs_strnlen(obj->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
7298 /* Only a directory should drop through to here */
7299 return obj->myDev->nDataBytesPerChunk;
7303 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
7306 struct ylist_head *i;
7309 count++; /* the object itself */
7311 ylist_for_each(i, &obj->hardLinks)
7312 count++; /* add the hard links; */
7317 int yaffs_GetObjectInode(yaffs_Object *obj)
7319 obj = yaffs_GetEquivalentObject(obj);
7321 return obj->objectId;
7324 unsigned yaffs_GetObjectType(yaffs_Object *obj)
7326 obj = yaffs_GetEquivalentObject(obj);
7328 switch (obj->variantType) {
7329 case YAFFS_OBJECT_TYPE_FILE:
7332 case YAFFS_OBJECT_TYPE_DIRECTORY:
7335 case YAFFS_OBJECT_TYPE_SYMLINK:
7338 case YAFFS_OBJECT_TYPE_HARDLINK:
7341 case YAFFS_OBJECT_TYPE_SPECIAL:
7342 if (S_ISFIFO(obj->yst_mode))
7344 if (S_ISCHR(obj->yst_mode))
7346 if (S_ISBLK(obj->yst_mode))
7348 if (S_ISSOCK(obj->yst_mode))
7356 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
7358 obj = yaffs_GetEquivalentObject(obj);
7359 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
7360 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7362 return yaffs_CloneString(_Y(""));
7365 #ifndef CONFIG_YAFFS_WINCE
7367 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
7369 unsigned int valid = attr->ia_valid;
7371 if (valid & ATTR_MODE)
7372 obj->yst_mode = attr->ia_mode;
7373 if (valid & ATTR_UID)
7374 obj->yst_uid = attr->ia_uid;
7375 if (valid & ATTR_GID)
7376 obj->yst_gid = attr->ia_gid;
7378 if (valid & ATTR_ATIME)
7379 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7380 if (valid & ATTR_CTIME)
7381 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7382 if (valid & ATTR_MTIME)
7383 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7385 if (valid & ATTR_SIZE)
7386 yaffs_ResizeFile(obj, attr->ia_size);
7388 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7393 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
7395 unsigned int valid = 0;
7397 attr->ia_mode = obj->yst_mode;
7399 attr->ia_uid = obj->yst_uid;
7401 attr->ia_gid = obj->yst_gid;
7404 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7405 valid |= ATTR_ATIME;
7406 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7407 valid |= ATTR_CTIME;
7408 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7409 valid |= ATTR_MTIME;
7411 attr->ia_size = yaffs_GetFileSize(obj);
7414 attr->ia_valid = valid;
7422 int yaffs_DumpObject(yaffs_Object *obj)
7426 yaffs_GetObjectName(obj, name, YAFFS_MAX_NAME_LENGTH + 1);
7428 T(YAFFS_TRACE_ALWAYS,
7430 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7431 " chunk %d type %d size %d\n"
7432 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7433 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7434 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7440 /*---------------------------- Initialisation code -------------------------------------- */
7442 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
7445 /* Common functions, gotta have */
7446 if (!dev->param.eraseBlockInNAND || !dev->param.initialiseNAND)
7449 #ifdef CONFIG_YAFFS_YAFFS2
7451 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7452 if (dev->param.writeChunkWithTagsToNAND &&
7453 dev->param.readChunkWithTagsFromNAND &&
7454 !dev->param.writeChunkToNAND &&
7455 !dev->param.readChunkFromNAND &&
7456 dev->param.markNANDBlockBad &&
7457 dev->param.queryNANDBlock)
7461 /* Can use the "spare" style interface for yaffs1 */
7462 if (!dev->param.isYaffs2 &&
7463 !dev->param.writeChunkWithTagsToNAND &&
7464 !dev->param.readChunkWithTagsFromNAND &&
7465 dev->param.writeChunkToNAND &&
7466 dev->param.readChunkFromNAND &&
7467 !dev->param.markNANDBlockBad &&
7468 !dev->param.queryNANDBlock)
7475 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7477 /* Initialise the unlinked, deleted, root and lost and found directories */
7479 dev->lostNFoundDir = dev->rootDir = NULL;
7480 dev->unlinkedDir = dev->deletedDir = NULL;
7483 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7486 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7489 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7490 YAFFS_ROOT_MODE | S_IFDIR);
7491 dev->lostNFoundDir =
7492 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7493 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7495 if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
7496 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7503 int yaffs_GutsInitialise(yaffs_Device *dev)
7505 int init_failed = 0;
7509 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7511 /* Check stuff that must be set */
7514 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7518 dev->internalStartBlock = dev->param.startBlock;
7519 dev->internalEndBlock = dev->param.endBlock;
7520 dev->blockOffset = 0;
7521 dev->chunkOffset = 0;
7522 dev->nFreeChunks = 0;
7526 if (dev->param.startBlock == 0) {
7527 dev->internalStartBlock = dev->param.startBlock + 1;
7528 dev->internalEndBlock = dev->param.endBlock + 1;
7529 dev->blockOffset = 1;
7530 dev->chunkOffset = dev->param.nChunksPerBlock;
7533 /* Check geometry parameters. */
7535 if ((!dev->param.inbandTags && dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 1024) ||
7536 (!dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 512) ||
7537 (dev->param.inbandTags && !dev->param.isYaffs2) ||
7538 dev->param.nChunksPerBlock < 2 ||
7539 dev->param.nReservedBlocks < 2 ||
7540 dev->internalStartBlock <= 0 ||
7541 dev->internalEndBlock <= 0 ||
7542 dev->internalEndBlock <= (dev->internalStartBlock + dev->param.nReservedBlocks + 2)) { /* otherwise it is too small */
7543 T(YAFFS_TRACE_ALWAYS,
7545 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7546 TENDSTR), dev->param.totalBytesPerChunk, dev->param.isYaffs2 ? "2" : "", dev->param.inbandTags));
7550 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7551 T(YAFFS_TRACE_ALWAYS,
7552 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7556 /* Sort out space for inband tags, if required */
7557 if (dev->param.inbandTags)
7558 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7560 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk;
7562 /* Got the right mix of functions? */
7563 if (!yaffs_CheckDevFunctions(dev)) {
7564 /* Function missing */
7565 T(YAFFS_TRACE_ALWAYS,
7567 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7572 /* This is really a compilation check. */
7573 if (!yaffs_CheckStructures()) {
7574 T(YAFFS_TRACE_ALWAYS,
7575 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7579 if (dev->isMounted) {
7580 T(YAFFS_TRACE_ALWAYS,
7581 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7585 /* Finished with most checks. One or two more checks happen later on too. */
7589 /* OK now calculate a few things for the device */
7592 * Calculate all the chunk size manipulation numbers:
7594 x = dev->nDataBytesPerChunk;
7595 /* We always use dev->chunkShift and dev->chunkDiv */
7596 dev->chunkShift = Shifts(x);
7597 x >>= dev->chunkShift;
7599 /* We only use chunk mask if chunkDiv is 1 */
7600 dev->chunkMask = (1<<dev->chunkShift) - 1;
7603 * Calculate chunkGroupBits.
7604 * We need to find the next power of 2 > than internalEndBlock
7607 x = dev->param.nChunksPerBlock * (dev->internalEndBlock + 1);
7611 /* Set up tnode width if wide tnodes are enabled. */
7612 if (!dev->param.wideTnodesDisabled) {
7613 /* bits must be even so that we end up with 32-bit words */
7617 dev->tnodeWidth = 16;
7619 dev->tnodeWidth = bits;
7621 dev->tnodeWidth = 16;
7623 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7625 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7626 * so if the bitwidth of the
7627 * chunk range we're using is greater than 16 we need
7628 * to figure out chunk shift and chunkGroupSize
7631 if (bits <= dev->tnodeWidth)
7632 dev->chunkGroupBits = 0;
7634 dev->chunkGroupBits = bits - dev->tnodeWidth;
7637 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7639 if (dev->param.nChunksPerBlock < dev->chunkGroupSize) {
7640 /* We have a problem because the soft delete won't work if
7641 * the chunk group size > chunks per block.
7642 * This can be remedied by using larger "virtual blocks".
7644 T(YAFFS_TRACE_ALWAYS,
7645 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7650 /* OK, we've finished verifying the device, lets continue with initialisation */
7652 /* More device initialisation */
7653 dev->garbageCollections = 0;
7654 dev->passiveGarbageCollections = 0;
7655 dev->currentDirtyChecker = 0;
7656 dev->bufferedBlock = -1;
7657 dev->doingBufferedBlockRewrite = 0;
7658 dev->nDeletedFiles = 0;
7659 dev->nBackgroundDeletions = 0;
7660 dev->nUnlinkedFiles = 0;
7662 dev->eccUnfixed = 0;
7663 dev->tagsEccFixed = 0;
7664 dev->tagsEccUnfixed = 0;
7665 dev->nErasureFailures = 0;
7666 dev->nErasedBlocks = 0;
7668 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7669 dev->oldestDirtySequence = 0;
7671 /* Initialise temporary buffers and caches. */
7672 if (!yaffs_InitialiseTempBuffers(dev))
7675 dev->srCache = NULL;
7676 dev->gcCleanupList = NULL;
7680 dev->param.nShortOpCaches > 0) {
7683 int srCacheBytes = dev->param.nShortOpCaches * sizeof(yaffs_ChunkCache);
7685 if (dev->param.nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
7686 dev->param.nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7688 dev->srCache = YMALLOC(srCacheBytes);
7690 buf = (__u8 *) dev->srCache;
7693 memset(dev->srCache, 0, srCacheBytes);
7695 for (i = 0; i < dev->param.nShortOpCaches && buf; i++) {
7696 dev->srCache[i].object = NULL;
7697 dev->srCache[i].lastUse = 0;
7698 dev->srCache[i].dirty = 0;
7699 dev->srCache[i].data = buf = YMALLOC_DMA(dev->param.totalBytesPerChunk);
7710 dev->gcCleanupList = YMALLOC(dev->param.nChunksPerBlock * sizeof(__u32));
7711 if (!dev->gcCleanupList)
7715 if (dev->param.isYaffs2)
7716 dev->param.useHeaderFileSize = 1;
7718 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7721 yaffs_InitialiseTnodes(dev);
7722 yaffs_InitialiseObjects(dev);
7724 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7729 /* Now scan the flash. */
7730 if (dev->param.isYaffs2) {
7731 if (yaffs_CheckpointRestore(dev)) {
7732 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7733 T(YAFFS_TRACE_ALWAYS,
7734 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7737 /* Clean up the mess caused by an aborted checkpoint load
7738 * and scan backwards.
7740 yaffs_DeinitialiseBlocks(dev);
7741 yaffs_DeinitialiseTnodes(dev);
7742 yaffs_DeinitialiseObjects(dev);
7745 dev->nErasedBlocks = 0;
7746 dev->nFreeChunks = 0;
7747 dev->allocationBlock = -1;
7748 dev->allocationPage = -1;
7749 dev->nDeletedFiles = 0;
7750 dev->nUnlinkedFiles = 0;
7751 dev->nBackgroundDeletions = 0;
7753 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7756 yaffs_InitialiseTnodes(dev);
7757 yaffs_InitialiseObjects(dev);
7759 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7762 if (!init_failed && !yaffs_ScanBackwards(dev))
7765 } else if (!yaffs_Scan(dev))
7768 yaffs_StripDeletedObjects(dev);
7769 yaffs_FixHangingObjects(dev);
7770 if(dev->param.emptyLostAndFound)
7771 yaffs_EmptyLostAndFound(dev);
7775 /* Clean up the mess */
7776 T(YAFFS_TRACE_TRACING,
7777 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7779 yaffs_Deinitialise(dev);
7783 /* Zero out stats */
7784 dev->nPageReads = 0;
7785 dev->nPageWrites = 0;
7786 dev->nBlockErasures = 0;
7788 dev->nRetriedWrites = 0;
7790 dev->nRetiredBlocks = 0;
7792 yaffs_VerifyFreeChunks(dev);
7793 yaffs_VerifyBlocks(dev);
7795 /* Clean up any aborted checkpoint data */
7796 if(!dev->isCheckpointed && dev->blocksInCheckpoint > 0)
7797 yaffs_InvalidateCheckpoint(dev);
7799 T(YAFFS_TRACE_TRACING,
7800 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7805 void yaffs_Deinitialise(yaffs_Device *dev)
7807 if (dev->isMounted) {
7810 yaffs_DeinitialiseBlocks(dev);
7811 yaffs_DeinitialiseTnodes(dev);
7812 yaffs_DeinitialiseObjects(dev);
7813 if (dev->param.nShortOpCaches > 0 &&
7816 for (i = 0; i < dev->param.nShortOpCaches; i++) {
7817 if (dev->srCache[i].data)
7818 YFREE(dev->srCache[i].data);
7819 dev->srCache[i].data = NULL;
7822 YFREE(dev->srCache);
7823 dev->srCache = NULL;
7826 YFREE(dev->gcCleanupList);
7828 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
7829 YFREE(dev->tempBuffer[i].buffer);
7833 if (dev->param.deinitialiseNAND)
7834 dev->param.deinitialiseNAND(dev);
7838 static int yaffs_CountFreeChunks(yaffs_Device *dev)
7843 yaffs_BlockInfo *blk;
7845 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7847 blk = yaffs_GetBlockInfo(dev, b);
7849 switch (blk->blockState) {
7850 case YAFFS_BLOCK_STATE_EMPTY:
7851 case YAFFS_BLOCK_STATE_ALLOCATING:
7852 case YAFFS_BLOCK_STATE_COLLECTING:
7853 case YAFFS_BLOCK_STATE_FULL:
7855 (dev->param.nChunksPerBlock - blk->pagesInUse +
7856 blk->softDeletions);
7866 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
7868 /* This is what we report to the outside world */
7871 int nDirtyCacheChunks;
7872 int blocksForCheckpoint;
7876 nFree = dev->nFreeChunks;
7878 nFree = yaffs_CountFreeChunks(dev);
7881 nFree += dev->nDeletedFiles;
7883 /* Now count the number of dirty chunks in the cache and subtract those */
7885 for (nDirtyCacheChunks = 0, i = 0; i < dev->param.nShortOpCaches; i++) {
7886 if (dev->srCache[i].dirty)
7887 nDirtyCacheChunks++;
7890 nFree -= nDirtyCacheChunks;
7892 nFree -= ((dev->param.nReservedBlocks + 1) * dev->param.nChunksPerBlock);
7894 /* Now we figure out how much to reserve for the checkpoint and report that... */
7895 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7896 if (blocksForCheckpoint < 0)
7897 blocksForCheckpoint = 0;
7899 nFree -= (blocksForCheckpoint * dev->param.nChunksPerBlock);
7908 static int yaffs_freeVerificationFailures;
7910 static void yaffs_VerifyFreeChunks(yaffs_Device *dev)
7915 if (yaffs_SkipVerification(dev))
7918 counted = yaffs_CountFreeChunks(dev);
7920 difference = dev->nFreeChunks - counted;
7923 T(YAFFS_TRACE_ALWAYS,
7924 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7925 dev->nFreeChunks, counted, difference));
7926 yaffs_freeVerificationFailures++;
7930 /*---------------------------------------- YAFFS test code ----------------------*/
7932 #define yaffs_CheckStruct(structure, syze, name) \
7934 if (sizeof(structure) != syze) { \
7935 T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
7936 name, syze, (int) sizeof(structure))); \
7937 return YAFFS_FAIL; \
7941 static int yaffs_CheckStructures(void)
7943 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
7944 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
7945 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
7946 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7947 /* yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode"); */
7949 #ifndef CONFIG_YAFFS_WINCE
7950 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");