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.85 2009-06-08 23:50:44 charles Exp $";
19 #include "yaffsinterface.h"
20 #include "yaffs_guts.h"
21 #include "yaffs_tagsvalidity.h"
22 #include "yaffs_getblockinfo.h"
24 #include "yaffs_tagscompat.h"
25 #ifndef CONFIG_YAFFS_USE_OWN_SORT
26 #include "yaffs_qsort.h"
28 #include "yaffs_nand.h"
30 #include "yaffs_checkptrw.h"
32 #include "yaffs_nand.h"
33 #include "yaffs_packedtags2.h"
36 #define YAFFS_PASSIVE_GC_CHUNKS 2
38 #include "yaffs_ecc.h"
41 /* Robustification (if it ever comes about...) */
42 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND);
43 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
45 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
47 const yaffs_ExtendedTags *tags);
48 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
49 const yaffs_ExtendedTags *tags);
51 /* Other local prototypes */
52 static void yaffs_UpdateParent(yaffs_Object *obj);
53 static int yaffs_UnlinkObject(yaffs_Object *obj);
54 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
56 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
58 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev,
60 yaffs_ExtendedTags *tags,
62 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
63 int chunkInNAND, int inScan);
65 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
66 yaffs_ObjectType type);
67 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
69 static int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name,
70 int force, int isShrink, int shadows);
71 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
72 static int yaffs_CheckStructures(void);
73 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
74 int chunkOffset, int *limit);
75 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
77 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev, int blockNo);
80 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
83 static int yaffs_UnlinkWorker(yaffs_Object *obj);
85 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
88 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
89 yaffs_BlockInfo **blockUsedPtr);
91 static void yaffs_VerifyFreeChunks(yaffs_Device *dev);
93 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
95 static void yaffs_VerifyDirectory(yaffs_Object *directory);
97 static int yaffs_CheckFileSanity(yaffs_Object *in);
99 #define yaffs_CheckFileSanity(in)
102 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
103 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
105 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
107 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
108 yaffs_ExtendedTags *tags);
110 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
112 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
113 yaffs_FileStructure *fStruct,
117 /* Function to calculate chunk and offset */
119 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut,
125 chunk = (__u32)(addr >> dev->chunkShift);
127 if (dev->chunkDiv == 1) {
128 /* easy power of 2 case */
129 offset = (__u32)(addr & dev->chunkMask);
131 /* Non power-of-2 case */
135 chunk /= dev->chunkDiv;
137 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
138 offset = (__u32)(addr - chunkBase);
145 /* Function to return the number of shifts for a power of 2 greater than or
146 * equal to the given number
147 * Note we don't try to cater for all possible numbers and this does not have to
148 * be hellishly efficient.
151 static __u32 ShiftsGE(__u32 x)
156 nShifts = extraBits = 0;
171 /* Function to return the number of shifts to get a 1 in bit 0
174 static __u32 Shifts(__u32 x)
194 * Temporary buffer manipulations.
197 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
200 __u8 *buf = (__u8 *)1;
202 memset(dev->tempBuffer, 0, sizeof(dev->tempBuffer));
204 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
205 dev->tempBuffer[i].line = 0; /* not in use */
206 dev->tempBuffer[i].buffer = buf =
207 YMALLOC_DMA(dev->totalBytesPerChunk);
210 return buf ? YAFFS_OK : YAFFS_FAIL;
213 __u8 *yaffs_GetTempBuffer(yaffs_Device *dev, int lineNo)
218 if (dev->tempInUse > dev->maxTemp)
219 dev->maxTemp = dev->tempInUse;
221 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
222 if (dev->tempBuffer[i].line == 0) {
223 dev->tempBuffer[i].line = lineNo;
224 if ((i + 1) > dev->maxTemp) {
225 dev->maxTemp = i + 1;
226 for (j = 0; j <= i; j++)
227 dev->tempBuffer[j].maxLine =
228 dev->tempBuffer[j].line;
231 return dev->tempBuffer[i].buffer;
235 T(YAFFS_TRACE_BUFFERS,
236 (TSTR("Out of temp buffers at line %d, other held by lines:"),
238 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
239 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
241 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
244 * If we got here then we have to allocate an unmanaged one
248 dev->unmanagedTempAllocations++;
249 return YMALLOC(dev->nDataBytesPerChunk);
253 void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer,
260 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
261 if (dev->tempBuffer[i].buffer == buffer) {
262 dev->tempBuffer[i].line = 0;
268 /* assume it is an unmanaged one. */
269 T(YAFFS_TRACE_BUFFERS,
270 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
273 dev->unmanagedTempDeallocations++;
279 * Determine if we have a managed buffer.
281 int yaffs_IsManagedTempBuffer(yaffs_Device *dev, const __u8 *buffer)
285 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
286 if (dev->tempBuffer[i].buffer == buffer)
290 for (i = 0; i < dev->nShortOpCaches; i++) {
291 if (dev->srCache[i].data == buffer)
295 if (buffer == dev->checkpointBuffer)
298 T(YAFFS_TRACE_ALWAYS,
299 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
306 * Chunk bitmap manipulations
309 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
311 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
313 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
317 return dev->chunkBits +
318 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
321 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
323 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
324 chunk < 0 || chunk >= dev->nChunksPerBlock) {
326 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),
332 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device *dev, int blk)
334 __u8 *blkBits = yaffs_BlockBits(dev, blk);
336 memset(blkBits, 0, dev->chunkBitmapStride);
339 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device *dev, int blk, int chunk)
341 __u8 *blkBits = yaffs_BlockBits(dev, blk);
343 yaffs_VerifyChunkBitId(dev, blk, chunk);
345 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
348 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device *dev, int blk, int chunk)
350 __u8 *blkBits = yaffs_BlockBits(dev, blk);
352 yaffs_VerifyChunkBitId(dev, blk, chunk);
354 blkBits[chunk / 8] |= (1 << (chunk & 7));
357 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device *dev, int blk, int chunk)
359 __u8 *blkBits = yaffs_BlockBits(dev, blk);
360 yaffs_VerifyChunkBitId(dev, blk, chunk);
362 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
365 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device *dev, int blk)
367 __u8 *blkBits = yaffs_BlockBits(dev, blk);
369 for (i = 0; i < dev->chunkBitmapStride; i++) {
377 static int yaffs_CountChunkBits(yaffs_Device *dev, int blk)
379 __u8 *blkBits = yaffs_BlockBits(dev, blk);
382 for (i = 0; i < dev->chunkBitmapStride; i++) {
399 static int yaffs_SkipVerification(yaffs_Device *dev)
401 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
404 static int yaffs_SkipFullVerification(yaffs_Device *dev)
406 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
409 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
411 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
414 static const char *blockStateName[] = {
427 static void yaffs_VerifyBlock(yaffs_Device *dev, yaffs_BlockInfo *bi, int n)
432 if (yaffs_SkipVerification(dev))
435 /* Report illegal runtime states */
436 if (bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
437 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has undefined state %d"TENDSTR), n, bi->blockState));
439 switch (bi->blockState) {
440 case YAFFS_BLOCK_STATE_UNKNOWN:
441 case YAFFS_BLOCK_STATE_SCANNING:
442 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
443 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has bad run-state %s"TENDSTR),
444 n, blockStateName[bi->blockState]));
447 /* Check pages in use and soft deletions are legal */
449 actuallyUsed = bi->pagesInUse - bi->softDeletions;
451 if (bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
452 bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
453 actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock)
454 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
455 n, bi->pagesInUse, bi->softDeletions));
458 /* Check chunk bitmap legal */
459 inUse = yaffs_CountChunkBits(dev, n);
460 if (inUse != bi->pagesInUse)
461 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
462 n, bi->pagesInUse, inUse));
464 /* Check that the sequence number is valid.
465 * Ten million is legal, but is very unlikely
468 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
469 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000))
470 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has suspect sequence number of %d"TENDSTR),
471 n, bi->sequenceNumber));
474 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev, yaffs_BlockInfo *bi,
477 yaffs_VerifyBlock(dev, bi, n);
479 /* After collection the block should be in the erased state */
480 /* This will need to change if we do partial gc */
482 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
483 bi->blockState != YAFFS_BLOCK_STATE_EMPTY) {
484 T(YAFFS_TRACE_ERROR, (TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
489 static void yaffs_VerifyBlocks(yaffs_Device *dev)
492 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
493 int nIllegalBlockStates = 0;
495 if (yaffs_SkipVerification(dev))
498 memset(nBlocksPerState, 0, sizeof(nBlocksPerState));
500 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
501 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, i);
502 yaffs_VerifyBlock(dev, bi, i);
504 if (bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
505 nBlocksPerState[bi->blockState]++;
507 nIllegalBlockStates++;
510 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
511 T(YAFFS_TRACE_VERIFY, (TSTR("Block summary"TENDSTR)));
513 T(YAFFS_TRACE_VERIFY, (TSTR("%d blocks have illegal states"TENDSTR), nIllegalBlockStates));
514 if (nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
515 T(YAFFS_TRACE_VERIFY, (TSTR("Too many allocating blocks"TENDSTR)));
517 for (i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
518 T(YAFFS_TRACE_VERIFY,
519 (TSTR("%s %d blocks"TENDSTR),
520 blockStateName[i], nBlocksPerState[i]));
522 if (dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
523 T(YAFFS_TRACE_VERIFY,
524 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
525 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
527 if (dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
528 T(YAFFS_TRACE_VERIFY,
529 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
530 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
532 if (nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
533 T(YAFFS_TRACE_VERIFY,
534 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
535 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
537 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
542 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
543 * case those tests will not be performed.
545 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
547 if (obj && yaffs_SkipVerification(obj->myDev))
550 if (!(tags && obj && oh)) {
551 T(YAFFS_TRACE_VERIFY,
552 (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR),
553 (__u32)tags, (__u32)obj, (__u32)oh));
557 if (oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
558 oh->type > YAFFS_OBJECT_TYPE_MAX)
559 T(YAFFS_TRACE_VERIFY,
560 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
561 tags->objectId, oh->type));
563 if (tags->objectId != obj->objectId)
564 T(YAFFS_TRACE_VERIFY,
565 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
566 tags->objectId, obj->objectId));
570 * Check that the object's parent ids match if parentCheck requested.
572 * Tests do not apply to the root object.
575 if (parentCheck && tags->objectId > 1 && !obj->parent)
576 T(YAFFS_TRACE_VERIFY,
577 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
578 tags->objectId, oh->parentObjectId));
580 if (parentCheck && obj->parent &&
581 oh->parentObjectId != obj->parent->objectId &&
582 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
583 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
584 T(YAFFS_TRACE_VERIFY,
585 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
586 tags->objectId, oh->parentObjectId, obj->parent->objectId));
588 if (tags->objectId > 1 && oh->name[0] == 0) /* Null name */
589 T(YAFFS_TRACE_VERIFY,
590 (TSTR("Obj %d header name is NULL"TENDSTR),
593 if (tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
594 T(YAFFS_TRACE_VERIFY,
595 (TSTR("Obj %d header name is 0xFF"TENDSTR),
601 static int yaffs_VerifyTnodeWorker(yaffs_Object *obj, yaffs_Tnode *tn,
602 __u32 level, int chunkOffset)
605 yaffs_Device *dev = obj->myDev;
611 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
612 if (tn->internal[i]) {
613 ok = yaffs_VerifyTnodeWorker(obj,
616 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
619 } else if (level == 0) {
620 yaffs_ExtendedTags tags;
621 __u32 objectId = obj->objectId;
623 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
625 for (i = 0; i < YAFFS_NTNODES_LEVEL0; i++) {
626 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
629 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
630 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
631 if (tags.objectId != objectId || tags.chunkId != chunkOffset) {
632 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
633 objectId, chunkOffset, theChunk,
634 tags.objectId, tags.chunkId));
647 static void yaffs_VerifyFile(yaffs_Object *obj)
649 int requiredTallness;
655 yaffs_ExtendedTags tags;
662 if (yaffs_SkipVerification(obj->myDev))
666 objectId = obj->objectId;
668 /* Check file size is consistent with tnode depth */
669 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
670 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
671 requiredTallness = 0;
673 x >>= YAFFS_TNODES_INTERNAL_BITS;
677 actualTallness = obj->variant.fileVariant.topLevel;
679 if (requiredTallness > actualTallness)
680 T(YAFFS_TRACE_VERIFY,
681 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
682 obj->objectId, actualTallness, requiredTallness));
685 /* Check that the chunks in the tnode tree are all correct.
686 * We do this by scanning through the tnode tree and
687 * checking the tags for every chunk match.
690 if (yaffs_SkipNANDVerification(dev))
693 for (i = 1; i <= lastChunk; i++) {
694 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant, i);
697 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
699 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
700 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
701 if (tags.objectId != objectId || tags.chunkId != i) {
702 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
703 objectId, i, theChunk,
704 tags.objectId, tags.chunkId));
712 static void yaffs_VerifyHardLink(yaffs_Object *obj)
714 if (obj && yaffs_SkipVerification(obj->myDev))
717 /* Verify sane equivalent object */
720 static void yaffs_VerifySymlink(yaffs_Object *obj)
722 if (obj && yaffs_SkipVerification(obj->myDev))
725 /* Verify symlink string */
728 static void yaffs_VerifySpecial(yaffs_Object *obj)
730 if (obj && yaffs_SkipVerification(obj->myDev))
734 static void yaffs_VerifyObject(yaffs_Object *obj)
743 __u32 chunkShouldNotBeDeleted;
749 if (obj->beingCreated)
754 if (yaffs_SkipVerification(dev))
757 /* Check sane object header chunk */
759 chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
760 chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
762 chunkInRange = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
763 chunkIdOk = chunkInRange || obj->hdrChunk == 0;
764 chunkValid = chunkInRange &&
765 yaffs_CheckChunkBit(dev,
766 obj->hdrChunk / dev->nChunksPerBlock,
767 obj->hdrChunk % dev->nChunksPerBlock);
768 chunkShouldNotBeDeleted = chunkInRange && !chunkValid;
771 (!chunkIdOk || chunkShouldNotBeDeleted)) {
772 T(YAFFS_TRACE_VERIFY,
773 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
774 obj->objectId, obj->hdrChunk,
775 chunkIdOk ? "" : ",out of range",
776 chunkShouldNotBeDeleted ? ",marked as deleted" : ""));
779 if (chunkValid && !yaffs_SkipNANDVerification(dev)) {
780 yaffs_ExtendedTags tags;
781 yaffs_ObjectHeader *oh;
782 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
784 oh = (yaffs_ObjectHeader *)buffer;
786 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk, buffer,
789 yaffs_VerifyObjectHeader(obj, oh, &tags, 1);
791 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
794 /* Verify it has a parent */
795 if (obj && !obj->fake &&
796 (!obj->parent || obj->parent->myDev != dev)) {
797 T(YAFFS_TRACE_VERIFY,
798 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
799 obj->objectId, obj->parent));
802 /* Verify parent is a directory */
803 if (obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
804 T(YAFFS_TRACE_VERIFY,
805 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
806 obj->objectId, obj->parent->variantType));
809 switch (obj->variantType) {
810 case YAFFS_OBJECT_TYPE_FILE:
811 yaffs_VerifyFile(obj);
813 case YAFFS_OBJECT_TYPE_SYMLINK:
814 yaffs_VerifySymlink(obj);
816 case YAFFS_OBJECT_TYPE_DIRECTORY:
817 yaffs_VerifyDirectory(obj);
819 case YAFFS_OBJECT_TYPE_HARDLINK:
820 yaffs_VerifyHardLink(obj);
822 case YAFFS_OBJECT_TYPE_SPECIAL:
823 yaffs_VerifySpecial(obj);
825 case YAFFS_OBJECT_TYPE_UNKNOWN:
827 T(YAFFS_TRACE_VERIFY,
828 (TSTR("Obj %d has illegaltype %d"TENDSTR),
829 obj->objectId, obj->variantType));
834 static void yaffs_VerifyObjects(yaffs_Device *dev)
838 struct ylist_head *lh;
840 if (yaffs_SkipVerification(dev))
843 /* Iterate through the objects in each hash entry */
845 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
846 ylist_for_each(lh, &dev->objectBucket[i].list) {
848 obj = ylist_entry(lh, yaffs_Object, hashLink);
849 yaffs_VerifyObject(obj);
857 * Simple hash function. Needs to have a reasonable spread
860 static Y_INLINE int yaffs_HashFunction(int n)
863 return n % YAFFS_NOBJECT_BUCKETS;
867 * Access functions to useful fake objects.
868 * Note that root might have a presence in NAND if permissions are set.
871 yaffs_Object *yaffs_Root(yaffs_Device *dev)
876 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
878 return dev->lostNFoundDir;
883 * Erased NAND checking functions
886 int yaffs_CheckFF(__u8 *buffer, int nBytes)
888 /* Horrible, slow implementation */
897 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
900 int retval = YAFFS_OK;
901 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
902 yaffs_ExtendedTags tags;
905 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
907 if (tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
910 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
911 T(YAFFS_TRACE_NANDACCESS,
912 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
916 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
922 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
924 yaffs_ExtendedTags *tags,
931 yaffs_InvalidateCheckpoint(dev);
934 yaffs_BlockInfo *bi = 0;
937 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
943 /* First check this chunk is erased, if it needs
944 * checking. The checking policy (unless forced
945 * always on) is as follows:
947 * Check the first page we try to write in a block.
948 * If the check passes then we don't need to check any
949 * more. If the check fails, we check again...
950 * If the block has been erased, we don't need to check.
952 * However, if the block has been prioritised for gc,
953 * then we think there might be something odd about
954 * this block and stop using it.
956 * Rationale: We should only ever see chunks that have
957 * not been erased if there was a partially written
958 * chunk due to power loss. This checking policy should
959 * catch that case with very few checks and thus save a
960 * lot of checks that are most likely not needed.
962 if (bi->gcPrioritise) {
963 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
964 /* try another chunk */
968 /* let's give it a try */
971 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
972 bi->skipErasedCheck = 0;
974 if (!bi->skipErasedCheck) {
975 erasedOk = yaffs_CheckChunkErased(dev, chunk);
976 if (erasedOk != YAFFS_OK) {
978 (TSTR("**>> yaffs chunk %d was not erased"
981 /* try another chunk */
984 bi->skipErasedCheck = 1;
987 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
989 if (writeOk != YAFFS_OK) {
990 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
991 /* try another chunk */
995 /* Copy the data into the robustification buffer */
996 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
998 } while (writeOk != YAFFS_OK &&
999 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1005 T(YAFFS_TRACE_ERROR,
1006 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1009 dev->nRetriedWrites += (attempts - 1);
1016 * Block retiring for handling a broken block.
1019 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND)
1021 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1023 yaffs_InvalidateCheckpoint(dev);
1025 if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
1026 if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
1027 T(YAFFS_TRACE_ALWAYS, (TSTR(
1028 "yaffs: Failed to mark bad and erase block %d"
1029 TENDSTR), blockInNAND));
1031 yaffs_ExtendedTags tags;
1032 int chunkId = blockInNAND * dev->nChunksPerBlock;
1034 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
1036 memset(buffer, 0xff, dev->nDataBytesPerChunk);
1037 yaffs_InitialiseTags(&tags);
1038 tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
1039 if (dev->writeChunkWithTagsToNAND(dev, chunkId -
1040 dev->chunkOffset, buffer, &tags) != YAFFS_OK)
1041 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
1042 TCONT("write bad block marker to block %d")
1043 TENDSTR), blockInNAND));
1045 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
1049 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1050 bi->gcPrioritise = 0;
1051 bi->needsRetiring = 0;
1053 dev->nRetiredBlocks++;
1057 * Functions for robustisizing TODO
1061 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
1063 const yaffs_ExtendedTags *tags)
1067 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
1068 const yaffs_ExtendedTags *tags)
1072 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1074 if (!bi->gcPrioritise) {
1075 bi->gcPrioritise = 1;
1076 dev->hasPendingPrioritisedGCs = 1;
1077 bi->chunkErrorStrikes++;
1079 if (bi->chunkErrorStrikes > 3) {
1080 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1081 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1087 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
1090 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1091 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1093 yaffs_HandleChunkError(dev, bi);
1096 /* Was an actual write failure, so mark the block for retirement */
1097 bi->needsRetiring = 1;
1098 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1099 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1102 /* Delete the chunk */
1103 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1107 /*---------------- Name handling functions ------------*/
1109 static __u16 yaffs_CalcNameSum(const YCHAR *name)
1114 const YUCHAR *bname = (const YUCHAR *) name;
1116 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1118 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1119 sum += yaffs_toupper(*bname) * i;
1121 sum += (*bname) * i;
1130 static void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
1132 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1133 memset(obj->shortName, 0, sizeof(YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1134 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH)
1135 yaffs_strcpy(obj->shortName, name);
1137 obj->shortName[0] = _Y('\0');
1139 obj->sum = yaffs_CalcNameSum(name);
1142 /*-------------------- TNODES -------------------
1144 * List of spare tnodes
1145 * The list is hooked together using the first pointer
1149 /* yaffs_CreateTnodes creates a bunch more tnodes and
1150 * adds them to the tnode free list.
1151 * Don't use this function directly
1154 static int yaffs_CreateTnodes(yaffs_Device *dev, int nTnodes)
1158 yaffs_Tnode *newTnodes;
1162 yaffs_TnodeList *tnl;
1167 /* Calculate the tnode size in bytes for variable width tnode support.
1168 * Must be a multiple of 32-bits */
1169 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1171 if (tnodeSize < sizeof(yaffs_Tnode))
1172 tnodeSize = sizeof(yaffs_Tnode);
1174 /* make these things */
1176 newTnodes = YMALLOC(nTnodes * tnodeSize);
1177 mem = (__u8 *)newTnodes;
1180 T(YAFFS_TRACE_ERROR,
1181 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1185 /* Hook them into the free list */
1187 for (i = 0; i < nTnodes - 1; i++) {
1188 newTnodes[i].internal[0] = &newTnodes[i + 1];
1189 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1190 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1194 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1195 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1196 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1198 dev->freeTnodes = newTnodes;
1200 /* New hookup for wide tnodes */
1201 for (i = 0; i < nTnodes - 1; i++) {
1202 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1203 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1204 curr->internal[0] = next;
1207 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1208 curr->internal[0] = dev->freeTnodes;
1209 dev->freeTnodes = (yaffs_Tnode *)mem;
1214 dev->nFreeTnodes += nTnodes;
1215 dev->nTnodesCreated += nTnodes;
1217 /* Now add this bunch of tnodes to a list for freeing up.
1218 * NB If we can't add this to the management list it isn't fatal
1219 * but it just means we can't free this bunch of tnodes later.
1222 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1224 T(YAFFS_TRACE_ERROR,
1226 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1229 tnl->tnodes = newTnodes;
1230 tnl->next = dev->allocatedTnodeList;
1231 dev->allocatedTnodeList = tnl;
1234 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1239 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1241 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device *dev)
1243 yaffs_Tnode *tn = NULL;
1245 /* If there are none left make more */
1246 if (!dev->freeTnodes)
1247 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1249 if (dev->freeTnodes) {
1250 tn = dev->freeTnodes;
1251 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1252 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1253 /* Hoosterman, this thing looks like it isn't in the list */
1254 T(YAFFS_TRACE_ALWAYS,
1255 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1258 dev->freeTnodes = dev->freeTnodes->internal[0];
1262 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1267 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
1269 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1270 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1272 if (tnodeSize < sizeof(yaffs_Tnode))
1273 tnodeSize = sizeof(yaffs_Tnode);
1276 memset(tn, 0, tnodeSize);
1281 /* FreeTnode frees up a tnode and puts it back on the free list */
1282 static void yaffs_FreeTnode(yaffs_Device *dev, yaffs_Tnode *tn)
1285 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1286 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1287 /* Hoosterman, this thing looks like it is already in the list */
1288 T(YAFFS_TRACE_ALWAYS,
1289 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1291 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1293 tn->internal[0] = dev->freeTnodes;
1294 dev->freeTnodes = tn;
1297 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1300 static void yaffs_DeinitialiseTnodes(yaffs_Device *dev)
1302 /* Free the list of allocated tnodes */
1303 yaffs_TnodeList *tmp;
1305 while (dev->allocatedTnodeList) {
1306 tmp = dev->allocatedTnodeList->next;
1308 YFREE(dev->allocatedTnodeList->tnodes);
1309 YFREE(dev->allocatedTnodeList);
1310 dev->allocatedTnodeList = tmp;
1314 dev->freeTnodes = NULL;
1315 dev->nFreeTnodes = 0;
1318 static void yaffs_InitialiseTnodes(yaffs_Device *dev)
1320 dev->allocatedTnodeList = NULL;
1321 dev->freeTnodes = NULL;
1322 dev->nFreeTnodes = 0;
1323 dev->nTnodesCreated = 0;
1327 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
1330 __u32 *map = (__u32 *)tn;
1336 pos &= YAFFS_TNODES_LEVEL0_MASK;
1337 val >>= dev->chunkGroupBits;
1339 bitInMap = pos * dev->tnodeWidth;
1340 wordInMap = bitInMap / 32;
1341 bitInWord = bitInMap & (32 - 1);
1343 mask = dev->tnodeMask << bitInWord;
1345 map[wordInMap] &= ~mask;
1346 map[wordInMap] |= (mask & (val << bitInWord));
1348 if (dev->tnodeWidth > (32 - bitInWord)) {
1349 bitInWord = (32 - bitInWord);
1351 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1352 map[wordInMap] &= ~mask;
1353 map[wordInMap] |= (mask & (val >> bitInWord));
1357 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
1360 __u32 *map = (__u32 *)tn;
1366 pos &= YAFFS_TNODES_LEVEL0_MASK;
1368 bitInMap = pos * dev->tnodeWidth;
1369 wordInMap = bitInMap / 32;
1370 bitInWord = bitInMap & (32 - 1);
1372 val = map[wordInMap] >> bitInWord;
1374 if (dev->tnodeWidth > (32 - bitInWord)) {
1375 bitInWord = (32 - bitInWord);
1377 val |= (map[wordInMap] << bitInWord);
1380 val &= dev->tnodeMask;
1381 val <<= dev->chunkGroupBits;
1386 /* ------------------- End of individual tnode manipulation -----------------*/
1388 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1389 * The look up tree is represented by the top tnode and the number of topLevel
1390 * in the tree. 0 means only the level 0 tnode is in the tree.
1393 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1394 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
1395 yaffs_FileStructure *fStruct,
1398 yaffs_Tnode *tn = fStruct->top;
1400 int requiredTallness;
1401 int level = fStruct->topLevel;
1403 /* Check sane level and chunk Id */
1404 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
1407 if (chunkId > YAFFS_MAX_CHUNK_ID)
1410 /* First check we're tall enough (ie enough topLevel) */
1412 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1413 requiredTallness = 0;
1415 i >>= YAFFS_TNODES_INTERNAL_BITS;
1419 if (requiredTallness > fStruct->topLevel)
1420 return NULL; /* Not tall enough, so we can't find it */
1422 /* Traverse down to level 0 */
1423 while (level > 0 && tn) {
1424 tn = tn->internal[(chunkId >>
1425 (YAFFS_TNODES_LEVEL0_BITS +
1427 YAFFS_TNODES_INTERNAL_BITS)) &
1428 YAFFS_TNODES_INTERNAL_MASK];
1435 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1436 * This happens in two steps:
1437 * 1. If the tree isn't tall enough, then make it taller.
1438 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1440 * Used when modifying the tree.
1442 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1443 * be plugged into the ttree.
1446 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
1447 yaffs_FileStructure *fStruct,
1449 yaffs_Tnode *passedTn)
1451 int requiredTallness;
1459 /* Check sane level and page Id */
1460 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
1463 if (chunkId > YAFFS_MAX_CHUNK_ID)
1466 /* First check we're tall enough (ie enough topLevel) */
1468 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1469 requiredTallness = 0;
1471 x >>= YAFFS_TNODES_INTERNAL_BITS;
1476 if (requiredTallness > fStruct->topLevel) {
1477 /* Not tall enough, gotta make the tree taller */
1478 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1480 tn = yaffs_GetTnode(dev);
1483 tn->internal[0] = fStruct->top;
1486 T(YAFFS_TRACE_ERROR,
1487 (TSTR("yaffs: no more tnodes" TENDSTR)));
1491 fStruct->topLevel = requiredTallness;
1494 /* Traverse down to level 0, adding anything we need */
1496 l = fStruct->topLevel;
1500 while (l > 0 && tn) {
1502 (YAFFS_TNODES_LEVEL0_BITS +
1503 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1504 YAFFS_TNODES_INTERNAL_MASK;
1507 if ((l > 1) && !tn->internal[x]) {
1508 /* Add missing non-level-zero tnode */
1509 tn->internal[x] = yaffs_GetTnode(dev);
1511 } else if (l == 1) {
1512 /* Looking from level 1 at level 0 */
1514 /* If we already have one, then release it.*/
1515 if (tn->internal[x])
1516 yaffs_FreeTnode(dev, tn->internal[x]);
1517 tn->internal[x] = passedTn;
1519 } else if (!tn->internal[x]) {
1520 /* Don't have one, none passed in */
1521 tn->internal[x] = yaffs_GetTnode(dev);
1525 tn = tn->internal[x];
1529 /* top is level 0 */
1531 memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1532 yaffs_FreeTnode(dev, passedTn);
1539 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
1540 yaffs_ExtendedTags *tags, int objectId,
1545 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1546 if (yaffs_CheckChunkBit(dev, theChunk / dev->nChunksPerBlock,
1547 theChunk % dev->nChunksPerBlock)) {
1548 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1550 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1561 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1562 * chunks and tnodes in the file
1563 * Returns 1 if the tree was deleted.
1564 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1567 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
1568 int chunkOffset, int *limit)
1573 yaffs_ExtendedTags tags;
1575 yaffs_Device *dev = in->myDev;
1581 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1583 if (tn->internal[i]) {
1584 if (limit && (*limit) < 0) {
1588 yaffs_DeleteWorker(in,
1596 YAFFS_TNODES_INTERNAL_BITS)
1601 yaffs_FreeTnode(dev,
1604 tn->internal[i] = NULL;
1608 return (allDone) ? 1 : 0;
1609 } else if (level == 0) {
1612 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1614 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1617 chunkInInode = (chunkOffset <<
1618 YAFFS_TNODES_LEVEL0_BITS) + i;
1621 yaffs_FindChunkInGroup(dev,
1627 if (foundChunk > 0) {
1628 yaffs_DeleteChunk(dev,
1633 *limit = *limit - 1;
1640 yaffs_PutLevel0Tnode(dev, tn, i, 0);
1644 return (i < 0) ? 1 : 0;
1654 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1656 yaffs_BlockInfo *theBlock;
1658 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1660 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1662 theBlock->softDeletions++;
1667 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1668 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1670 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1673 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1674 __u32 level, int chunkOffset)
1679 yaffs_Device *dev = in->myDev;
1684 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1686 if (tn->internal[i]) {
1688 yaffs_SoftDeleteWorker(in,
1694 YAFFS_TNODES_INTERNAL_BITS)
1697 yaffs_FreeTnode(dev,
1700 tn->internal[i] = NULL;
1702 /* Hoosterman... how could this happen? */
1706 return (allDone) ? 1 : 0;
1707 } else if (level == 0) {
1709 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1710 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1712 /* Note this does not find the real chunk, only the chunk group.
1713 * We make an assumption that a chunk group is not larger than
1716 yaffs_SoftDeleteChunk(dev, theChunk);
1717 yaffs_PutLevel0Tnode(dev, tn, i, 0);
1731 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1734 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1735 if (obj->nDataChunks <= 0) {
1736 /* Empty file with no duplicate object headers, just delete it immediately */
1737 yaffs_FreeTnode(obj->myDev,
1738 obj->variant.fileVariant.top);
1739 obj->variant.fileVariant.top = NULL;
1740 T(YAFFS_TRACE_TRACING,
1741 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1743 yaffs_DoGenericObjectDeletion(obj);
1745 yaffs_SoftDeleteWorker(obj,
1746 obj->variant.fileVariant.top,
1747 obj->variant.fileVariant.
1749 obj->softDeleted = 1;
1754 /* Pruning removes any part of the file structure tree that is beyond the
1755 * bounds of the file (ie that does not point to chunks).
1757 * A file should only get pruned when its size is reduced.
1759 * Before pruning, the chunks must be pulled from the tree and the
1760 * level 0 tnode entries must be zeroed out.
1761 * Could also use this for file deletion, but that's probably better handled
1762 * by a special case.
1765 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1766 __u32 level, int del0)
1774 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1775 if (tn->internal[i] && level > 0) {
1777 yaffs_PruneWorker(dev, tn->internal[i],
1779 (i == 0) ? del0 : 1);
1782 if (tn->internal[i])
1786 if (hasData == 0 && del0) {
1787 /* Free and return NULL */
1789 yaffs_FreeTnode(dev, tn);
1799 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1800 yaffs_FileStructure *fStruct)
1807 if (fStruct->topLevel > 0) {
1809 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1811 /* Now we have a tree with all the non-zero branches NULL but the height
1812 * is the same as it was.
1813 * Let's see if we can trim internal tnodes to shorten the tree.
1814 * We can do this if only the 0th element in the tnode is in use
1815 * (ie all the non-zero are NULL)
1818 while (fStruct->topLevel && !done) {
1822 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1823 if (tn->internal[i])
1828 fStruct->top = tn->internal[0];
1829 fStruct->topLevel--;
1830 yaffs_FreeTnode(dev, tn);
1840 /*-------------------- End of File Structure functions.-------------------*/
1842 /* yaffs_CreateFreeObjects creates a bunch more objects and
1843 * adds them to the object free list.
1845 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1848 yaffs_Object *newObjects;
1849 yaffs_ObjectList *list;
1854 /* make these things */
1855 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1856 list = YMALLOC(sizeof(yaffs_ObjectList));
1858 if (!newObjects || !list) {
1863 T(YAFFS_TRACE_ALLOCATE,
1864 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1868 /* Hook them into the free list */
1869 for (i = 0; i < nObjects - 1; i++) {
1870 newObjects[i].siblings.next =
1871 (struct ylist_head *)(&newObjects[i + 1]);
1874 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1875 dev->freeObjects = newObjects;
1876 dev->nFreeObjects += nObjects;
1877 dev->nObjectsCreated += nObjects;
1879 /* Now add this bunch of Objects to a list for freeing up. */
1881 list->objects = newObjects;
1882 list->next = dev->allocatedObjectList;
1883 dev->allocatedObjectList = list;
1889 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1890 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1892 yaffs_Object *tn = NULL;
1894 #ifdef VALGRIND_TEST
1895 tn = YMALLOC(sizeof(yaffs_Object));
1897 /* If there are none left make more */
1898 if (!dev->freeObjects)
1899 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1901 if (dev->freeObjects) {
1902 tn = dev->freeObjects;
1904 (yaffs_Object *) (dev->freeObjects->siblings.next);
1905 dev->nFreeObjects--;
1909 /* Now sweeten it up... */
1911 memset(tn, 0, sizeof(yaffs_Object));
1912 tn->beingCreated = 1;
1916 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1917 YINIT_LIST_HEAD(&(tn->hardLinks));
1918 YINIT_LIST_HEAD(&(tn->hashLink));
1919 YINIT_LIST_HEAD(&tn->siblings);
1922 /* Now make the directory sane */
1924 tn->parent = dev->rootDir;
1925 ylist_add(&(tn->siblings), &dev->rootDir->variant.directoryVariant.children);
1928 /* Add it to the lost and found directory.
1929 * NB Can't put root or lostNFound in lostNFound so
1930 * check if lostNFound exists first
1932 if (dev->lostNFoundDir)
1933 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1935 tn->beingCreated = 0;
1938 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1943 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
1948 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1950 obj->fake = 1; /* it is fake so it might have no NAND presence... */
1951 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1952 obj->unlinkAllowed = 0; /* ... or unlink it */
1955 obj->yst_mode = mode;
1957 obj->hdrChunk = 0; /* Not a valid chunk. */
1964 static void yaffs_UnhashObject(yaffs_Object *tn)
1967 yaffs_Device *dev = tn->myDev;
1969 /* If it is still linked into the bucket list, free from the list */
1970 if (!ylist_empty(&tn->hashLink)) {
1971 ylist_del_init(&tn->hashLink);
1972 bucket = yaffs_HashFunction(tn->objectId);
1973 dev->objectBucket[bucket].count--;
1977 /* FreeObject frees up a Object and puts it back on the free list */
1978 static void yaffs_FreeObject(yaffs_Object *tn)
1980 yaffs_Device *dev = tn->myDev;
1983 T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), tn, tn->myInode));
1988 if (!ylist_empty(&tn->siblings))
1994 /* We're still hooked up to a cached inode.
1995 * Don't delete now, but mark for later deletion
1997 tn->deferedFree = 1;
2002 yaffs_UnhashObject(tn);
2004 #ifdef VALGRIND_TEST
2007 /* Link into the free list. */
2008 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2009 dev->freeObjects = tn;
2010 dev->nFreeObjects++;
2012 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2017 void yaffs_HandleDeferedFree(yaffs_Object *obj)
2019 if (obj->deferedFree)
2020 yaffs_FreeObject(obj);
2025 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
2027 /* Free the list of allocated Objects */
2029 yaffs_ObjectList *tmp;
2031 while (dev->allocatedObjectList) {
2032 tmp = dev->allocatedObjectList->next;
2033 YFREE(dev->allocatedObjectList->objects);
2034 YFREE(dev->allocatedObjectList);
2036 dev->allocatedObjectList = tmp;
2039 dev->freeObjects = NULL;
2040 dev->nFreeObjects = 0;
2043 static void yaffs_InitialiseObjects(yaffs_Device *dev)
2047 dev->allocatedObjectList = NULL;
2048 dev->freeObjects = NULL;
2049 dev->nFreeObjects = 0;
2051 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2052 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2053 dev->objectBucket[i].count = 0;
2057 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
2062 int lowest = 999999;
2064 /* First let's see if we can find one that's empty. */
2066 for (i = 0; i < 10 && lowest > 0; i++) {
2068 x %= YAFFS_NOBJECT_BUCKETS;
2069 if (dev->objectBucket[x].count < lowest) {
2070 lowest = dev->objectBucket[x].count;
2076 /* If we didn't find an empty list, then try
2077 * looking a bit further for a short one
2080 for (i = 0; i < 10 && lowest > 3; i++) {
2082 x %= YAFFS_NOBJECT_BUCKETS;
2083 if (dev->objectBucket[x].count < lowest) {
2084 lowest = dev->objectBucket[x].count;
2093 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
2095 int bucket = yaffs_FindNiceObjectBucket(dev);
2097 /* Now find an object value that has not already been taken
2098 * by scanning the list.
2102 struct ylist_head *i;
2104 __u32 n = (__u32) bucket;
2106 /* yaffs_CheckObjectHashSanity(); */
2110 n += YAFFS_NOBJECT_BUCKETS;
2111 if (1 || dev->objectBucket[bucket].count > 0) {
2112 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2113 /* If there is already one in the list */
2114 if (i && ylist_entry(i, yaffs_Object,
2115 hashLink)->objectId == n) {
2125 static void yaffs_HashObject(yaffs_Object *in)
2127 int bucket = yaffs_HashFunction(in->objectId);
2128 yaffs_Device *dev = in->myDev;
2130 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2131 dev->objectBucket[bucket].count++;
2134 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
2136 int bucket = yaffs_HashFunction(number);
2137 struct ylist_head *i;
2140 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2141 /* Look if it is in the list */
2143 in = ylist_entry(i, yaffs_Object, hashLink);
2144 if (in->objectId == number) {
2146 /* Don't tell the VFS about this one if it is defered free */
2147 if (in->deferedFree)
2159 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
2160 yaffs_ObjectType type)
2162 yaffs_Object *theObject;
2163 yaffs_Tnode *tn = NULL;
2166 number = yaffs_CreateNewObjectNumber(dev);
2168 theObject = yaffs_AllocateEmptyObject(dev);
2172 if (type == YAFFS_OBJECT_TYPE_FILE) {
2173 tn = yaffs_GetTnode(dev);
2175 yaffs_FreeObject(theObject);
2181 theObject->fake = 0;
2182 theObject->renameAllowed = 1;
2183 theObject->unlinkAllowed = 1;
2184 theObject->objectId = number;
2185 yaffs_HashObject(theObject);
2186 theObject->variantType = type;
2187 #ifdef CONFIG_YAFFS_WINCE
2188 yfsd_WinFileTimeNow(theObject->win_atime);
2189 theObject->win_ctime[0] = theObject->win_mtime[0] =
2190 theObject->win_atime[0];
2191 theObject->win_ctime[1] = theObject->win_mtime[1] =
2192 theObject->win_atime[1];
2196 theObject->yst_atime = theObject->yst_mtime =
2197 theObject->yst_ctime = Y_CURRENT_TIME;
2200 case YAFFS_OBJECT_TYPE_FILE:
2201 theObject->variant.fileVariant.fileSize = 0;
2202 theObject->variant.fileVariant.scannedFileSize = 0;
2203 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2204 theObject->variant.fileVariant.topLevel = 0;
2205 theObject->variant.fileVariant.top = tn;
2207 case YAFFS_OBJECT_TYPE_DIRECTORY:
2208 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2211 case YAFFS_OBJECT_TYPE_SYMLINK:
2212 case YAFFS_OBJECT_TYPE_HARDLINK:
2213 case YAFFS_OBJECT_TYPE_SPECIAL:
2214 /* No action required */
2216 case YAFFS_OBJECT_TYPE_UNKNOWN:
2217 /* todo this should not happen */
2225 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
2227 yaffs_ObjectType type)
2229 yaffs_Object *theObject = NULL;
2232 theObject = yaffs_FindObjectByNumber(dev, number);
2235 theObject = yaffs_CreateNewObject(dev, number, type);
2242 static YCHAR *yaffs_CloneString(const YCHAR *str)
2244 YCHAR *newStr = NULL;
2247 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2249 yaffs_strcpy(newStr, str);
2257 * Mknod (create) a new object.
2258 * equivalentObject only has meaning for a hard link;
2259 * aliasString only has meaning for a sumlink.
2260 * rdev only has meaning for devices (a subset of special objects)
2263 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2264 yaffs_Object *parent,
2269 yaffs_Object *equivalentObject,
2270 const YCHAR *aliasString, __u32 rdev)
2275 yaffs_Device *dev = parent->myDev;
2277 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2278 if (yaffs_FindObjectByName(parent, name))
2281 in = yaffs_CreateNewObject(dev, -1, type);
2286 if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2287 str = yaffs_CloneString(aliasString);
2289 yaffs_FreeObject(in);
2299 in->variantType = type;
2301 in->yst_mode = mode;
2303 #ifdef CONFIG_YAFFS_WINCE
2304 yfsd_WinFileTimeNow(in->win_atime);
2305 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2306 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2309 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2311 in->yst_rdev = rdev;
2315 in->nDataChunks = 0;
2317 yaffs_SetObjectName(in, name);
2320 yaffs_AddObjectToDirectory(parent, in);
2322 in->myDev = parent->myDev;
2325 case YAFFS_OBJECT_TYPE_SYMLINK:
2326 in->variant.symLinkVariant.alias = str;
2328 case YAFFS_OBJECT_TYPE_HARDLINK:
2329 in->variant.hardLinkVariant.equivalentObject =
2331 in->variant.hardLinkVariant.equivalentObjectId =
2332 equivalentObject->objectId;
2333 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2335 case YAFFS_OBJECT_TYPE_FILE:
2336 case YAFFS_OBJECT_TYPE_DIRECTORY:
2337 case YAFFS_OBJECT_TYPE_SPECIAL:
2338 case YAFFS_OBJECT_TYPE_UNKNOWN:
2343 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2344 /* Could not create the object header, fail the creation */
2345 yaffs_DeleteObject(in);
2349 yaffs_UpdateParent(parent);
2355 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
2356 __u32 mode, __u32 uid, __u32 gid)
2358 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2359 uid, gid, NULL, NULL, 0);
2362 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
2363 __u32 mode, __u32 uid, __u32 gid)
2365 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2366 mode, uid, gid, NULL, NULL, 0);
2369 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
2370 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2372 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2373 uid, gid, NULL, NULL, rdev);
2376 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
2377 __u32 mode, __u32 uid, __u32 gid,
2380 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2381 uid, gid, NULL, alias, 0);
2384 /* yaffs_Link returns the object id of the equivalent object.*/
2385 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
2386 yaffs_Object *equivalentObject)
2388 /* Get the real object in case we were fed a hard link as an equivalent object */
2389 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2391 if (yaffs_MknodObject
2392 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2393 equivalentObject, NULL, 0)) {
2394 return equivalentObject;
2401 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
2402 const YCHAR *newName, int force, int shadows)
2407 yaffs_Object *existingTarget;
2410 newDir = obj->parent; /* use the old directory */
2412 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2413 T(YAFFS_TRACE_ALWAYS,
2415 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2420 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2421 if (obj->myDev->isYaffs2)
2422 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2424 unlinkOp = (newDir == obj->myDev->unlinkedDir
2425 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2427 deleteOp = (newDir == obj->myDev->deletedDir);
2429 existingTarget = yaffs_FindObjectByName(newDir, newName);
2431 /* If the object is a file going into the unlinked directory,
2432 * then it is OK to just stuff it in since duplicate names are allowed.
2433 * else only proceed if the new name does not exist and if we're putting
2434 * it into a directory.
2441 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2442 yaffs_SetObjectName(obj, newName);
2445 yaffs_AddObjectToDirectory(newDir, obj);
2450 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2451 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows) >= 0)
2458 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
2459 yaffs_Object *newDir, const YCHAR *newName)
2461 yaffs_Object *obj = NULL;
2462 yaffs_Object *existingTarget = NULL;
2466 if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2468 if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2471 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2472 /* Special case for case insemsitive systems (eg. WinCE).
2473 * While look-up is case insensitive, the name isn't.
2474 * Therefore we might want to change x.txt to X.txt
2476 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
2480 else if (yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2484 obj = yaffs_FindObjectByName(oldDir, oldName);
2486 if (obj && obj->renameAllowed) {
2488 /* Now do the handling for an existing target, if there is one */
2490 existingTarget = yaffs_FindObjectByName(newDir, newName);
2491 if (existingTarget &&
2492 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2493 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2494 /* There is a target that is a non-empty directory, so we fail */
2495 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2496 } else if (existingTarget && existingTarget != obj) {
2497 /* Nuke the target first, using shadowing,
2498 * but only if it isn't the same object
2500 yaffs_ChangeObjectName(obj, newDir, newName, force,
2501 existingTarget->objectId);
2502 yaffs_UnlinkObject(existingTarget);
2504 yaffs_UpdateParent(oldDir);
2505 if(newDir != oldDir)
2506 yaffs_UpdateParent(newDir);
2508 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2513 /*------------------------- Block Management and Page Allocation ----------------*/
2515 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
2517 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2519 dev->blockInfo = NULL;
2520 dev->chunkBits = NULL;
2522 dev->allocationBlock = -1; /* force it to get a new one */
2524 /* If the first allocation strategy fails, thry the alternate one */
2525 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2526 if (!dev->blockInfo) {
2527 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2528 dev->blockInfoAlt = 1;
2530 dev->blockInfoAlt = 0;
2532 if (dev->blockInfo) {
2533 /* Set up dynamic blockinfo stuff. */
2534 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2535 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2536 if (!dev->chunkBits) {
2537 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2538 dev->chunkBitsAlt = 1;
2540 dev->chunkBitsAlt = 0;
2543 if (dev->blockInfo && dev->chunkBits) {
2544 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2545 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2552 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2554 if (dev->blockInfoAlt && dev->blockInfo)
2555 YFREE_ALT(dev->blockInfo);
2556 else if (dev->blockInfo)
2557 YFREE(dev->blockInfo);
2559 dev->blockInfoAlt = 0;
2561 dev->blockInfo = NULL;
2563 if (dev->chunkBitsAlt && dev->chunkBits)
2564 YFREE_ALT(dev->chunkBits);
2565 else if (dev->chunkBits)
2566 YFREE(dev->chunkBits);
2567 dev->chunkBitsAlt = 0;
2568 dev->chunkBits = NULL;
2571 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
2572 yaffs_BlockInfo *bi)
2579 return 1; /* disqualification only applies to yaffs2. */
2581 if (!bi->hasShrinkHeader)
2582 return 1; /* can gc */
2584 /* Find the oldest dirty sequence number if we don't know it and save it
2585 * so we don't have to keep recomputing it.
2587 if (!dev->oldestDirtySequence) {
2588 seq = dev->sequenceNumber;
2590 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2592 b = yaffs_GetBlockInfo(dev, i);
2593 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2594 (b->pagesInUse - b->softDeletions) <
2595 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2596 seq = b->sequenceNumber;
2599 dev->oldestDirtySequence = seq;
2602 /* Can't do gc of this block if there are any blocks older than this one that have
2605 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2608 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2609 * for garbage collection.
2612 static int yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
2615 int b = dev->currentDirtyChecker;
2621 int prioritised = 0;
2622 yaffs_BlockInfo *bi;
2623 int pendingPrioritisedExist = 0;
2625 /* First let's see if we need to grab a prioritised block */
2626 if (dev->hasPendingPrioritisedGCs) {
2627 for (i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++) {
2629 bi = yaffs_GetBlockInfo(dev, i);
2630 /* yaffs_VerifyBlock(dev,bi,i); */
2632 if (bi->gcPrioritise) {
2633 pendingPrioritisedExist = 1;
2634 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2635 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2636 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2639 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2644 if (!pendingPrioritisedExist) /* None found, so we can clear this */
2645 dev->hasPendingPrioritisedGCs = 0;
2648 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2650 * else (we're doing a leasurely gc), then we only bother to do this if the
2651 * block has only a few pages in use.
2654 dev->nonAggressiveSkip--;
2656 if (!aggressive && (dev->nonAggressiveSkip > 0))
2661 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2665 dev->internalEndBlock - dev->internalStartBlock + 1;
2668 dev->internalEndBlock - dev->internalStartBlock + 1;
2669 iterations = iterations / 16;
2670 if (iterations > 200)
2674 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2676 if (b < dev->internalStartBlock || b > dev->internalEndBlock)
2677 b = dev->internalStartBlock;
2679 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2680 T(YAFFS_TRACE_ERROR,
2681 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2685 bi = yaffs_GetBlockInfo(dev, b);
2687 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2688 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2689 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2691 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2695 dev->currentDirtyChecker = b;
2699 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2700 dev->nChunksPerBlock - pagesInUse, prioritised));
2703 dev->oldestDirtySequence = 0;
2706 dev->nonAggressiveSkip = 4;
2711 static void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
2713 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2717 /* If the block is still healthy erase it and mark as clean.
2718 * If the block has had a data failure, then retire it.
2721 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2722 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2723 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2725 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2727 if (!bi->needsRetiring) {
2728 yaffs_InvalidateCheckpoint(dev);
2729 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2731 dev->nErasureFailures++;
2732 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2733 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2738 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2740 for (i = 0; i < dev->nChunksPerBlock; i++) {
2741 if (!yaffs_CheckChunkErased
2742 (dev, blockNo * dev->nChunksPerBlock + i)) {
2743 T(YAFFS_TRACE_ERROR,
2745 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2746 TENDSTR), blockNo, i));
2752 /* Clean it up... */
2753 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2754 dev->nErasedBlocks++;
2756 bi->softDeletions = 0;
2757 bi->hasShrinkHeader = 0;
2758 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2759 bi->gcPrioritise = 0;
2760 yaffs_ClearChunkBits(dev, blockNo);
2762 T(YAFFS_TRACE_ERASE,
2763 (TSTR("Erased block %d" TENDSTR), blockNo));
2765 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2767 yaffs_RetireBlock(dev, blockNo);
2768 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2769 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2773 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2777 yaffs_BlockInfo *bi;
2779 if (dev->nErasedBlocks < 1) {
2780 /* Hoosterman we've got a problem.
2781 * Can't get space to gc
2783 T(YAFFS_TRACE_ERROR,
2784 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2789 /* Find an empty block. */
2791 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2792 dev->allocationBlockFinder++;
2793 if (dev->allocationBlockFinder < dev->internalStartBlock
2794 || dev->allocationBlockFinder > dev->internalEndBlock) {
2795 dev->allocationBlockFinder = dev->internalStartBlock;
2798 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2800 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2801 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2802 dev->sequenceNumber++;
2803 bi->sequenceNumber = dev->sequenceNumber;
2804 dev->nErasedBlocks--;
2805 T(YAFFS_TRACE_ALLOCATE,
2806 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2807 dev->allocationBlockFinder, dev->sequenceNumber,
2808 dev->nErasedBlocks));
2809 return dev->allocationBlockFinder;
2813 T(YAFFS_TRACE_ALWAYS,
2815 ("yaffs tragedy: no more erased blocks, but there should have been %d"
2816 TENDSTR), dev->nErasedBlocks));
2823 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2825 if (!dev->nCheckpointBlocksRequired &&
2827 /* Not a valid value so recalculate */
2830 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2833 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2835 if (tnodeSize < sizeof(yaffs_Tnode))
2836 tnodeSize = sizeof(yaffs_Tnode);
2838 nBytes += sizeof(yaffs_CheckpointValidity);
2839 nBytes += sizeof(yaffs_CheckpointDevice);
2840 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2841 nBytes += devBlocks * dev->chunkBitmapStride;
2842 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2843 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2844 nBytes += sizeof(yaffs_CheckpointValidity);
2845 nBytes += sizeof(__u32); /* checksum*/
2847 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2849 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2851 dev->nCheckpointBlocksRequired = nBlocks;
2854 return dev->nCheckpointBlocksRequired;
2858 * Check if there's space to allocate...
2859 * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2861 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev)
2864 int reservedBlocks = dev->nReservedBlocks;
2865 int checkpointBlocks;
2867 if (dev->isYaffs2) {
2868 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
2869 dev->blocksInCheckpoint;
2870 if (checkpointBlocks < 0)
2871 checkpointBlocks = 0;
2873 checkpointBlocks = 0;
2876 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2878 return (dev->nFreeChunks > reservedChunks);
2881 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
2882 yaffs_BlockInfo **blockUsedPtr)
2885 yaffs_BlockInfo *bi;
2887 if (dev->allocationBlock < 0) {
2888 /* Get next block to allocate off */
2889 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2890 dev->allocationPage = 0;
2893 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2894 /* Not enough space to allocate unless we're allowed to use the reserve. */
2898 if (dev->nErasedBlocks < dev->nReservedBlocks
2899 && dev->allocationPage == 0) {
2900 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2903 /* Next page please.... */
2904 if (dev->allocationBlock >= 0) {
2905 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2907 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2908 dev->allocationPage;
2910 yaffs_SetChunkBit(dev, dev->allocationBlock,
2911 dev->allocationPage);
2913 dev->allocationPage++;
2917 /* If the block is full set the state to full */
2918 if (dev->allocationPage >= dev->nChunksPerBlock) {
2919 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2920 dev->allocationBlock = -1;
2929 T(YAFFS_TRACE_ERROR,
2930 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2935 static int yaffs_GetErasedChunks(yaffs_Device *dev)
2939 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2941 if (dev->allocationBlock > 0)
2942 n += (dev->nChunksPerBlock - dev->allocationPage);
2948 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
2954 int retVal = YAFFS_OK;
2957 int isCheckpointBlock;
2961 int chunksBefore = yaffs_GetErasedChunks(dev);
2964 yaffs_ExtendedTags tags;
2966 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2968 yaffs_Object *object;
2970 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2972 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2974 T(YAFFS_TRACE_TRACING,
2975 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
2978 bi->hasShrinkHeader,
2981 /*yaffs_VerifyFreeChunks(dev); */
2983 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2985 /* Take off the number of soft deleted entries because
2986 * they're going to get really deleted during GC.
2988 if(dev->gcChunk == 0) /* first time through for this block */
2989 dev->nFreeChunks -= bi->softDeletions;
2993 if (isCheckpointBlock ||
2994 !yaffs_StillSomeChunkBits(dev, block)) {
2995 T(YAFFS_TRACE_TRACING,
2997 ("Collecting block %d that has no chunks in use" TENDSTR),
2999 yaffs_BlockBecameDirty(dev, block);
3002 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3004 yaffs_VerifyBlock(dev, bi, block);
3006 maxCopies = (wholeBlock) ? dev->nChunksPerBlock : 10;
3007 oldChunk = block * dev->nChunksPerBlock + dev->gcChunk;
3009 for (/* init already done */;
3010 retVal == YAFFS_OK &&
3011 dev->gcChunk < dev->nChunksPerBlock &&
3012 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
3014 dev->gcChunk++, oldChunk++) {
3015 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3017 /* This page is in use and might need to be copied off */
3023 yaffs_InitialiseTags(&tags);
3025 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3029 yaffs_FindObjectByNumber(dev,
3032 T(YAFFS_TRACE_GC_DETAIL,
3034 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3035 dev->gcChunk, tags.objectId, tags.chunkId,
3038 if (object && !yaffs_SkipVerification(dev)) {
3039 if (tags.chunkId == 0)
3040 matchingChunk = object->hdrChunk;
3041 else if (object->softDeleted)
3042 matchingChunk = oldChunk; /* Defeat the test */
3044 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
3046 if (oldChunk != matchingChunk)
3047 T(YAFFS_TRACE_ERROR,
3048 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3049 oldChunk, matchingChunk, tags.objectId, tags.chunkId));
3054 T(YAFFS_TRACE_ERROR,
3056 ("page %d in gc has no object: %d %d %d "
3058 tags.objectId, tags.chunkId, tags.byteCount));
3063 object->softDeleted &&
3064 tags.chunkId != 0) {
3065 /* Data chunk in a soft deleted file, throw it away
3066 * It's a soft deleted data chunk,
3067 * No need to copy this, just forget about it and
3068 * fix up the object.
3071 object->nDataChunks--;
3073 if (object->nDataChunks <= 0) {
3074 /* remeber to clean up the object */
3075 dev->gcCleanupList[cleanups] =
3081 /* Todo object && object->deleted && object->nDataChunks == 0 */
3082 /* Deleted object header with no data chunks.
3083 * Can be discarded and the file deleted.
3085 object->hdrChunk = 0;
3086 yaffs_FreeTnode(object->myDev,
3089 object->variant.fileVariant.top = NULL;
3090 yaffs_DoGenericObjectDeletion(object);
3092 } else if (object) {
3093 /* It's either a data chunk in a live file or
3094 * an ObjectHeader, so we're interested in it.
3095 * NB Need to keep the ObjectHeaders of deleted files
3096 * until the whole file has been deleted off
3098 tags.serialNumber++;
3102 if (tags.chunkId == 0) {
3103 /* It is an object Id,
3104 * We need to nuke the shrinkheader flags first
3105 * We no longer want the shrinkHeader flag since its work is done
3106 * and if it is left in place it will mess up scanning.
3109 yaffs_ObjectHeader *oh;
3110 oh = (yaffs_ObjectHeader *)buffer;
3112 tags.extraIsShrinkHeader = 0;
3114 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
3118 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3121 retVal = YAFFS_FAIL;
3124 /* Ok, now fix up the Tnodes etc. */
3126 if (tags.chunkId == 0) {
3128 object->hdrChunk = newChunk;
3129 object->serial = tags.serialNumber;
3131 /* It's a data chunk */
3132 yaffs_PutChunkIntoFile
3140 if (retVal == YAFFS_OK)
3141 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3146 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3149 /* Do any required cleanups */
3150 for (i = 0; i < cleanups; i++) {
3151 /* Time to delete the file too */
3153 yaffs_FindObjectByNumber(dev,
3154 dev->gcCleanupList[i]);
3156 yaffs_FreeTnode(dev,
3157 object->variant.fileVariant.
3159 object->variant.fileVariant.top = NULL;
3162 ("yaffs: About to finally delete object %d"
3163 TENDSTR), object->objectId));
3164 yaffs_DoGenericObjectDeletion(object);
3165 object->myDev->nDeletedFiles--;
3172 yaffs_VerifyCollectedBlock(dev, bi, block);
3174 chunksAfter = yaffs_GetErasedChunks(dev);
3175 if (chunksBefore >= chunksAfter) {
3178 ("gc did not increase free chunks before %d after %d"
3179 TENDSTR), chunksBefore, chunksAfter));
3182 /* If the gc completed then clear the current gcBlock so that we find another. */
3183 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING) {
3193 /* New garbage collector
3194 * If we're very low on erased blocks then we do aggressive garbage collection
3195 * otherwise we do "leasurely" garbage collection.
3196 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3197 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3199 * The idea is to help clear out space in a more spread-out manner.
3200 * Dunno if it really does anything useful.
3202 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
3206 int gcOk = YAFFS_OK;
3209 int checkpointBlockAdjust;
3211 if (dev->isDoingGC) {
3212 /* Bail out so we don't get recursive gc */
3216 /* This loop should pass the first time.
3217 * We'll only see looping here if the erase of the collected block fails.
3223 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3224 if (checkpointBlockAdjust < 0)
3225 checkpointBlockAdjust = 0;
3227 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3228 /* We need a block soon...*/
3231 /* We're in no hurry */
3235 if (dev->gcBlock <= 0) {
3236 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3240 block = dev->gcBlock;
3243 dev->garbageCollections++;
3245 dev->passiveGarbageCollections++;
3249 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3250 dev->nErasedBlocks, aggressive));
3252 gcOk = yaffs_GarbageCollectBlock(dev, block, aggressive);
3255 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3258 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3259 TENDSTR), dev->nErasedBlocks, maxTries, block));
3261 } while ((dev->nErasedBlocks < dev->nReservedBlocks) &&
3265 return aggressive ? gcOk : YAFFS_OK;
3268 /*------------------------- TAGS --------------------------------*/
3270 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
3273 return (tags->chunkId == chunkInObject &&
3274 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3279 /*-------------------- Data file manipulation -----------------*/
3281 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
3282 yaffs_ExtendedTags *tags)
3284 /*Get the Tnode, then get the level 0 offset chunk offset */
3287 yaffs_ExtendedTags localTags;
3290 yaffs_Device *dev = in->myDev;
3293 /* Passed a NULL, so use our own tags space */
3297 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3300 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3303 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3309 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
3310 yaffs_ExtendedTags *tags)
3312 /* Get the Tnode, then get the level 0 offset chunk offset */
3315 yaffs_ExtendedTags localTags;
3317 yaffs_Device *dev = in->myDev;
3321 /* Passed a NULL, so use our own tags space */
3325 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3329 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3332 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3335 /* Delete the entry in the filestructure (if found) */
3337 yaffs_PutLevel0Tnode(dev, tn, chunkInInode, 0);
3343 #ifdef YAFFS_PARANOID
3345 static int yaffs_CheckFileSanity(yaffs_Object *in)
3353 yaffs_Tags localTags;
3354 yaffs_Tags *tags = &localTags;
3358 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3361 objId = in->objectId;
3362 fSize = in->variant.fileVariant.fileSize;
3364 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3366 for (chunk = 1; chunk <= nChunks; chunk++) {
3367 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3372 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunk);
3374 if (yaffs_CheckChunkBits
3375 (dev, theChunk / dev->nChunksPerBlock,
3376 theChunk % dev->nChunksPerBlock)) {
3378 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3382 (tags, in->objectId, chunk, chunkDeleted)) {
3392 /* T(("No level 0 found for %d\n", chunk)); */
3396 return failed ? YAFFS_FAIL : YAFFS_OK;
3401 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
3402 int chunkInNAND, int inScan)
3404 /* NB inScan is zero unless scanning.
3405 * For forward scanning, inScan is > 0;
3406 * for backward scanning inScan is < 0
3410 yaffs_Device *dev = in->myDev;
3412 yaffs_ExtendedTags existingTags;
3413 yaffs_ExtendedTags newTags;
3414 unsigned existingSerial, newSerial;
3416 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3417 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3418 * If it is not during Scanning then something went wrong!
3421 T(YAFFS_TRACE_ERROR,
3423 ("yaffs tragedy:attempt to put data chunk into a non-file"
3428 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3432 tn = yaffs_AddOrFindLevel0Tnode(dev,
3433 &in->variant.fileVariant,
3439 existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3442 /* If we're scanning then we need to test for duplicates
3443 * NB This does not need to be efficient since it should only ever
3444 * happen when the power fails during a write, then only one
3445 * chunk should ever be affected.
3447 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3448 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3451 if (existingChunk > 0) {
3452 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3453 * thus we have to do a FindChunkInFile to get the real chunk id.
3455 * We have a duplicate now we need to decide which one to use:
3457 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3458 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3459 * YAFFS1: Get both sets of tags and compare serial numbers.
3463 /* Only do this for forward scanning */
3464 yaffs_ReadChunkWithTagsFromNAND(dev,
3468 /* Do a proper find */
3470 yaffs_FindChunkInFile(in, chunkInInode,
3474 if (existingChunk <= 0) {
3475 /*Hoosterman - how did this happen? */
3477 T(YAFFS_TRACE_ERROR,
3479 ("yaffs tragedy: existing chunk < 0 in scan"
3484 /* NB The deleted flags should be false, otherwise the chunks will
3485 * not be loaded during a scan
3489 newSerial = newTags.serialNumber;
3490 existingSerial = existingTags.serialNumber;
3494 (in->myDev->isYaffs2 ||
3495 existingChunk <= 0 ||
3496 ((existingSerial + 1) & 3) == newSerial)) {
3497 /* Forward scanning.
3499 * Delete the old one and drop through to update the tnode
3501 yaffs_DeleteChunk(dev, existingChunk, 1,
3504 /* Backward scanning or we want to use the existing one
3506 * Delete the new one and return early so that the tnode isn't changed
3508 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3516 if (existingChunk == 0)
3519 yaffs_PutLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
3524 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
3527 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3529 if (chunkInNAND >= 0)
3530 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3533 T(YAFFS_TRACE_NANDACCESS,
3534 (TSTR("Chunk %d not found zero instead" TENDSTR),
3536 /* get sane (zero) data if you read a hole */
3537 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3543 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
3547 yaffs_ExtendedTags tags;
3548 yaffs_BlockInfo *bi;
3554 block = chunkId / dev->nChunksPerBlock;
3555 page = chunkId % dev->nChunksPerBlock;
3558 if (!yaffs_CheckChunkBit(dev, block, page))
3559 T(YAFFS_TRACE_VERIFY,
3560 (TSTR("Deleting invalid chunk %d"TENDSTR),
3563 bi = yaffs_GetBlockInfo(dev, block);
3565 T(YAFFS_TRACE_DELETION,
3566 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3569 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3571 yaffs_InitialiseTags(&tags);
3573 tags.chunkDeleted = 1;
3575 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3576 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3578 dev->nUnmarkedDeletions++;
3581 /* Pull out of the management area.
3582 * If the whole block became dirty, this will kick off an erasure.
3584 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3585 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3586 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3587 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3590 yaffs_ClearChunkBit(dev, block, page);
3594 if (bi->pagesInUse == 0 &&
3595 !bi->hasShrinkHeader &&
3596 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3597 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3598 yaffs_BlockBecameDirty(dev, block);
3605 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
3606 const __u8 *buffer, int nBytes,
3609 /* Find old chunk Need to do this to get serial number
3610 * Write new one and patch into tree.
3611 * Invalidate old tags.
3615 yaffs_ExtendedTags prevTags;
3618 yaffs_ExtendedTags newTags;
3620 yaffs_Device *dev = in->myDev;
3622 yaffs_CheckGarbageCollection(dev);
3624 /* Get the previous chunk at this location in the file if it exists */
3625 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3627 /* Set up new tags */
3628 yaffs_InitialiseTags(&newTags);
3630 newTags.chunkId = chunkInInode;
3631 newTags.objectId = in->objectId;
3632 newTags.serialNumber =
3633 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
3634 newTags.byteCount = nBytes;
3636 if (nBytes < 1 || nBytes > dev->totalBytesPerChunk) {
3637 T(YAFFS_TRACE_ERROR,
3638 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3643 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3646 if (newChunkId >= 0) {
3647 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3649 if (prevChunkId >= 0)
3650 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3652 yaffs_CheckFileSanity(in);
3658 /* UpdateObjectHeader updates the header on NAND for an object.
3659 * If name is not NULL, then that new name is used.
3661 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
3662 int isShrink, int shadows)
3665 yaffs_BlockInfo *bi;
3667 yaffs_Device *dev = in->myDev;
3674 yaffs_ExtendedTags newTags;
3675 yaffs_ExtendedTags oldTags;
3677 __u8 *buffer = NULL;
3678 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3680 yaffs_ObjectHeader *oh = NULL;
3682 yaffs_strcpy(oldName, _Y("silly old name"));
3686 in == dev->rootDir || /* The rootDir should also be saved */
3689 yaffs_CheckGarbageCollection(dev);
3690 yaffs_CheckObjectDetailsLoaded(in);
3692 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3693 oh = (yaffs_ObjectHeader *) buffer;
3695 prevChunkId = in->hdrChunk;
3697 if (prevChunkId > 0) {
3698 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3701 yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
3703 memcpy(oldName, oh->name, sizeof(oh->name));
3706 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3708 oh->type = in->variantType;
3709 oh->yst_mode = in->yst_mode;
3710 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3712 #ifdef CONFIG_YAFFS_WINCE
3713 oh->win_atime[0] = in->win_atime[0];
3714 oh->win_ctime[0] = in->win_ctime[0];
3715 oh->win_mtime[0] = in->win_mtime[0];
3716 oh->win_atime[1] = in->win_atime[1];
3717 oh->win_ctime[1] = in->win_ctime[1];
3718 oh->win_mtime[1] = in->win_mtime[1];
3720 oh->yst_uid = in->yst_uid;
3721 oh->yst_gid = in->yst_gid;
3722 oh->yst_atime = in->yst_atime;
3723 oh->yst_mtime = in->yst_mtime;
3724 oh->yst_ctime = in->yst_ctime;
3725 oh->yst_rdev = in->yst_rdev;
3728 oh->parentObjectId = in->parent->objectId;
3730 oh->parentObjectId = 0;
3732 if (name && *name) {
3733 memset(oh->name, 0, sizeof(oh->name));
3734 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3735 } else if (prevChunkId >= 0)
3736 memcpy(oh->name, oldName, sizeof(oh->name));
3738 memset(oh->name, 0, sizeof(oh->name));
3740 oh->isShrink = isShrink;
3742 switch (in->variantType) {
3743 case YAFFS_OBJECT_TYPE_UNKNOWN:
3744 /* Should not happen */
3746 case YAFFS_OBJECT_TYPE_FILE:
3748 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3749 || oh->parentObjectId ==
3750 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3751 fileVariant.fileSize;
3753 case YAFFS_OBJECT_TYPE_HARDLINK:
3754 oh->equivalentObjectId =
3755 in->variant.hardLinkVariant.equivalentObjectId;
3757 case YAFFS_OBJECT_TYPE_SPECIAL:
3760 case YAFFS_OBJECT_TYPE_DIRECTORY:
3763 case YAFFS_OBJECT_TYPE_SYMLINK:
3764 yaffs_strncpy(oh->alias,
3765 in->variant.symLinkVariant.alias,
3766 YAFFS_MAX_ALIAS_LENGTH);
3767 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3772 yaffs_InitialiseTags(&newTags);
3774 newTags.chunkId = 0;
3775 newTags.objectId = in->objectId;
3776 newTags.serialNumber = in->serial;
3778 /* Add extra info for file header */
3780 newTags.extraHeaderInfoAvailable = 1;
3781 newTags.extraParentObjectId = oh->parentObjectId;
3782 newTags.extraFileLength = oh->fileSize;
3783 newTags.extraIsShrinkHeader = oh->isShrink;
3784 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3785 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3786 newTags.extraObjectType = in->variantType;
3788 yaffs_VerifyObjectHeader(in, oh, &newTags, 1);
3790 /* Create new chunk in NAND */
3792 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3793 (prevChunkId >= 0) ? 1 : 0);
3795 if (newChunkId >= 0) {
3797 in->hdrChunk = newChunkId;
3799 if (prevChunkId >= 0) {
3800 yaffs_DeleteChunk(dev, prevChunkId, 1,
3804 if (!yaffs_ObjectHasCachedWriteData(in))
3807 /* If this was a shrink, then mark the block that the chunk lives on */
3809 bi = yaffs_GetBlockInfo(in->myDev,
3810 newChunkId / in->myDev->nChunksPerBlock);
3811 bi->hasShrinkHeader = 1;
3816 retVal = newChunkId;
3821 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3826 /*------------------------ Short Operations Cache ----------------------------------------
3827 * In many situations where there is no high level buffering (eg WinCE) a lot of
3828 * reads might be short sequential reads, and a lot of writes may be short
3829 * sequential writes. eg. scanning/writing a jpeg file.
3830 * In these cases, a short read/write cache can provide a huge perfomance benefit
3831 * with dumb-as-a-rock code.
3832 * In Linux, the page cache provides read buffering aand the short op cache provides write
3835 * There are a limited number (~10) of cache chunks per device so that we don't
3836 * need a very intelligent search.
3839 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3841 yaffs_Device *dev = obj->myDev;
3843 yaffs_ChunkCache *cache;
3844 int nCaches = obj->myDev->nShortOpCaches;
3846 for (i = 0; i < nCaches; i++) {
3847 cache = &dev->srCache[i];
3848 if (cache->object == obj &&
3857 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
3859 yaffs_Device *dev = obj->myDev;
3860 int lowest = -99; /* Stop compiler whining. */
3862 yaffs_ChunkCache *cache;
3863 int chunkWritten = 0;
3864 int nCaches = obj->myDev->nShortOpCaches;
3870 /* Find the dirty cache for this object with the lowest chunk id. */
3871 for (i = 0; i < nCaches; i++) {
3872 if (dev->srCache[i].object == obj &&
3873 dev->srCache[i].dirty) {
3875 || dev->srCache[i].chunkId <
3877 cache = &dev->srCache[i];
3878 lowest = cache->chunkId;
3883 if (cache && !cache->locked) {
3884 /* Write it out and free it up */
3887 yaffs_WriteChunkDataToObject(cache->object,
3893 cache->object = NULL;
3896 } while (cache && chunkWritten > 0);
3899 /* Hoosterman, disk full while writing cache out. */
3900 T(YAFFS_TRACE_ERROR,
3901 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3908 /*yaffs_FlushEntireDeviceCache(dev)
3913 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3916 int nCaches = dev->nShortOpCaches;
3919 /* Find a dirty object in the cache and flush it...
3920 * until there are no further dirty objects.
3924 for (i = 0; i < nCaches && !obj; i++) {
3925 if (dev->srCache[i].object &&
3926 dev->srCache[i].dirty)
3927 obj = dev->srCache[i].object;
3931 yaffs_FlushFilesChunkCache(obj);
3938 /* Grab us a cache chunk for use.
3939 * First look for an empty one.
3940 * Then look for the least recently used non-dirty one.
3941 * Then look for the least recently used dirty one...., flush and look again.
3943 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
3947 if (dev->nShortOpCaches > 0) {
3948 for (i = 0; i < dev->nShortOpCaches; i++) {
3949 if (!dev->srCache[i].object)
3950 return &dev->srCache[i];
3957 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
3959 yaffs_ChunkCache *cache;
3960 yaffs_Object *theObj;
3965 if (dev->nShortOpCaches > 0) {
3966 /* Try find a non-dirty one... */
3968 cache = yaffs_GrabChunkCacheWorker(dev);
3971 /* They were all dirty, find the last recently used object and flush
3972 * its cache, then find again.
3973 * NB what's here is not very accurate, we actually flush the object
3974 * the last recently used page.
3977 /* With locking we can't assume we can use entry zero */
3984 for (i = 0; i < dev->nShortOpCaches; i++) {
3985 if (dev->srCache[i].object &&
3986 !dev->srCache[i].locked &&
3987 (dev->srCache[i].lastUse < usage || !cache)) {
3988 usage = dev->srCache[i].lastUse;
3989 theObj = dev->srCache[i].object;
3990 cache = &dev->srCache[i];
3995 if (!cache || cache->dirty) {
3996 /* Flush and try again */
3997 yaffs_FlushFilesChunkCache(theObj);
3998 cache = yaffs_GrabChunkCacheWorker(dev);
4008 /* Find a cached chunk */
4009 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj,
4012 yaffs_Device *dev = obj->myDev;
4014 if (dev->nShortOpCaches > 0) {
4015 for (i = 0; i < dev->nShortOpCaches; i++) {
4016 if (dev->srCache[i].object == obj &&
4017 dev->srCache[i].chunkId == chunkId) {
4020 return &dev->srCache[i];
4027 /* Mark the chunk for the least recently used algorithym */
4028 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache,
4032 if (dev->nShortOpCaches > 0) {
4033 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4034 /* Reset the cache usages */
4036 for (i = 1; i < dev->nShortOpCaches; i++)
4037 dev->srCache[i].lastUse = 0;
4044 cache->lastUse = dev->srLastUse;
4051 /* Invalidate a single cache page.
4052 * Do this when a whole page gets written,
4053 * ie the short cache for this page is no longer valid.
4055 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
4057 if (object->myDev->nShortOpCaches > 0) {
4058 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4061 cache->object = NULL;
4065 /* Invalidate all the cache pages associated with this object
4066 * Do this whenever ther file is deleted or resized.
4068 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
4071 yaffs_Device *dev = in->myDev;
4073 if (dev->nShortOpCaches > 0) {
4074 /* Invalidate it. */
4075 for (i = 0; i < dev->nShortOpCaches; i++) {
4076 if (dev->srCache[i].object == in)
4077 dev->srCache[i].object = NULL;
4082 /*--------------------- Checkpointing --------------------*/
4085 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev, int head)
4087 yaffs_CheckpointValidity cp;
4089 memset(&cp, 0, sizeof(cp));
4091 cp.structType = sizeof(cp);
4092 cp.magic = YAFFS_MAGIC;
4093 cp.version = YAFFS_CHECKPOINT_VERSION;
4094 cp.head = (head) ? 1 : 0;
4096 return (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp)) ?
4100 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4102 yaffs_CheckpointValidity cp;
4105 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4108 ok = (cp.structType == sizeof(cp)) &&
4109 (cp.magic == YAFFS_MAGIC) &&
4110 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4111 (cp.head == ((head) ? 1 : 0));
4115 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4118 cp->nErasedBlocks = dev->nErasedBlocks;
4119 cp->allocationBlock = dev->allocationBlock;
4120 cp->allocationPage = dev->allocationPage;
4121 cp->nFreeChunks = dev->nFreeChunks;
4123 cp->nDeletedFiles = dev->nDeletedFiles;
4124 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4125 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4126 cp->sequenceNumber = dev->sequenceNumber;
4127 cp->oldestDirtySequence = dev->oldestDirtySequence;
4131 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4132 yaffs_CheckpointDevice *cp)
4134 dev->nErasedBlocks = cp->nErasedBlocks;
4135 dev->allocationBlock = cp->allocationBlock;
4136 dev->allocationPage = cp->allocationPage;
4137 dev->nFreeChunks = cp->nFreeChunks;
4139 dev->nDeletedFiles = cp->nDeletedFiles;
4140 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4141 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4142 dev->sequenceNumber = cp->sequenceNumber;
4143 dev->oldestDirtySequence = cp->oldestDirtySequence;
4147 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4149 yaffs_CheckpointDevice cp;
4151 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4155 /* Write device runtime values*/
4156 yaffs_DeviceToCheckpointDevice(&cp, dev);
4157 cp.structType = sizeof(cp);
4159 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4161 /* Write block info */
4163 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4164 ok = (yaffs_CheckpointWrite(dev, dev->blockInfo, nBytes) == nBytes);
4167 /* Write chunk bits */
4169 nBytes = nBlocks * dev->chunkBitmapStride;
4170 ok = (yaffs_CheckpointWrite(dev, dev->chunkBits, nBytes) == nBytes);
4176 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4178 yaffs_CheckpointDevice cp;
4180 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4184 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4188 if (cp.structType != sizeof(cp))
4192 yaffs_CheckpointDeviceToDevice(dev, &cp);
4194 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4196 ok = (yaffs_CheckpointRead(dev, dev->blockInfo, nBytes) == nBytes);
4200 nBytes = nBlocks * dev->chunkBitmapStride;
4202 ok = (yaffs_CheckpointRead(dev, dev->chunkBits, nBytes) == nBytes);
4207 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4211 cp->objectId = obj->objectId;
4212 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4213 cp->hdrChunk = obj->hdrChunk;
4214 cp->variantType = obj->variantType;
4215 cp->deleted = obj->deleted;
4216 cp->softDeleted = obj->softDeleted;
4217 cp->unlinked = obj->unlinked;
4218 cp->fake = obj->fake;
4219 cp->renameAllowed = obj->renameAllowed;
4220 cp->unlinkAllowed = obj->unlinkAllowed;
4221 cp->serial = obj->serial;
4222 cp->nDataChunks = obj->nDataChunks;
4224 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4225 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4226 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4227 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4230 static int yaffs_CheckpointObjectToObject(yaffs_Object *obj, yaffs_CheckpointObject *cp)
4233 yaffs_Object *parent;
4235 if (obj->variantType != cp->variantType) {
4236 T(YAFFS_TRACE_ERROR, (TSTR("Checkpoint read object %d type %d "
4237 TCONT("chunk %d does not match existing object type %d")
4238 TENDSTR), cp->objectId, cp->variantType, cp->hdrChunk,
4243 obj->objectId = cp->objectId;
4246 parent = yaffs_FindOrCreateObjectByNumber(
4249 YAFFS_OBJECT_TYPE_DIRECTORY);
4254 if (parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4255 T(YAFFS_TRACE_ALWAYS, (TSTR("Checkpoint read object %d parent %d type %d"
4256 TCONT(" chunk %d Parent type, %d, not directory")
4258 cp->objectId, cp->parentId, cp->variantType,
4259 cp->hdrChunk, parent->variantType));
4262 yaffs_AddObjectToDirectory(parent, obj);
4265 obj->hdrChunk = cp->hdrChunk;
4266 obj->variantType = cp->variantType;
4267 obj->deleted = cp->deleted;
4268 obj->softDeleted = cp->softDeleted;
4269 obj->unlinked = cp->unlinked;
4270 obj->fake = cp->fake;
4271 obj->renameAllowed = cp->renameAllowed;
4272 obj->unlinkAllowed = cp->unlinkAllowed;
4273 obj->serial = cp->serial;
4274 obj->nDataChunks = cp->nDataChunks;
4276 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4277 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4278 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4279 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4281 if (obj->hdrChunk > 0)
4282 obj->lazyLoaded = 1;
4288 static int yaffs_CheckpointTnodeWorker(yaffs_Object *in, yaffs_Tnode *tn,
4289 __u32 level, int chunkOffset)
4292 yaffs_Device *dev = in->myDev;
4294 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4296 if (tnodeSize < sizeof(yaffs_Tnode))
4297 tnodeSize = sizeof(yaffs_Tnode);
4303 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
4304 if (tn->internal[i]) {
4305 ok = yaffs_CheckpointTnodeWorker(in,
4308 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4311 } else if (level == 0) {
4312 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4313 ok = (yaffs_CheckpointWrite(dev, &baseOffset, sizeof(baseOffset)) == sizeof(baseOffset));
4315 ok = (yaffs_CheckpointWrite(dev, tn, tnodeSize) == tnodeSize);
4323 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4325 __u32 endMarker = ~0;
4328 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4329 ok = yaffs_CheckpointTnodeWorker(obj,
4330 obj->variant.fileVariant.top,
4331 obj->variant.fileVariant.topLevel,
4334 ok = (yaffs_CheckpointWrite(obj->myDev, &endMarker, sizeof(endMarker)) ==
4341 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4345 yaffs_Device *dev = obj->myDev;
4346 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4349 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4351 if (tnodeSize < sizeof(yaffs_Tnode))
4352 tnodeSize = sizeof(yaffs_Tnode);
4354 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4356 while (ok && (~baseChunk)) {
4358 /* Read level 0 tnode */
4361 tn = yaffs_GetTnodeRaw(dev);
4363 ok = (yaffs_CheckpointRead(dev, tn, tnodeSize) == tnodeSize);
4368 ok = yaffs_AddOrFindLevel0Tnode(dev,
4374 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4378 T(YAFFS_TRACE_CHECKPOINT, (
4379 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4380 nread, baseChunk, ok));
4386 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4389 yaffs_CheckpointObject cp;
4392 struct ylist_head *lh;
4395 /* Iterate through the objects in each hash entry,
4396 * dumping them to the checkpointing stream.
4399 for (i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++) {
4400 ylist_for_each(lh, &dev->objectBucket[i].list) {
4402 obj = ylist_entry(lh, yaffs_Object, hashLink);
4403 if (!obj->deferedFree) {
4404 yaffs_ObjectToCheckpointObject(&cp, obj);
4405 cp.structType = sizeof(cp);
4407 T(YAFFS_TRACE_CHECKPOINT, (
4408 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
4409 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk, (unsigned) obj));
4411 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4413 if (ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4414 ok = yaffs_WriteCheckpointTnodes(obj);
4420 /* Dump end of list */
4421 memset(&cp, 0xFF, sizeof(yaffs_CheckpointObject));
4422 cp.structType = sizeof(cp);
4425 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4430 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4433 yaffs_CheckpointObject cp;
4436 yaffs_Object *hardList = NULL;
4438 while (ok && !done) {
4439 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4440 if (cp.structType != sizeof(cp)) {
4441 T(YAFFS_TRACE_CHECKPOINT, (TSTR("struct size %d instead of %d ok %d"TENDSTR),
4442 cp.structType, sizeof(cp), ok));
4446 T(YAFFS_TRACE_CHECKPOINT, (TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4447 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk));
4449 if (ok && cp.objectId == ~0)
4452 obj = yaffs_FindOrCreateObjectByNumber(dev, cp.objectId, cp.variantType);
4454 ok = yaffs_CheckpointObjectToObject(obj, &cp);
4457 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4458 ok = yaffs_ReadCheckpointTnodes(obj);
4459 } else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4460 obj->hardLinks.next =
4461 (struct ylist_head *) hardList;
4470 yaffs_HardlinkFixup(dev, hardList);
4475 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4477 __u32 checkpointSum;
4480 yaffs_GetCheckpointSum(dev, &checkpointSum);
4482 ok = (yaffs_CheckpointWrite(dev, &checkpointSum, sizeof(checkpointSum)) == sizeof(checkpointSum));
4490 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4492 __u32 checkpointSum0;
4493 __u32 checkpointSum1;
4496 yaffs_GetCheckpointSum(dev, &checkpointSum0);
4498 ok = (yaffs_CheckpointRead(dev, &checkpointSum1, sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4503 if (checkpointSum0 != checkpointSum1)
4510 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4514 if (dev->skipCheckpointWrite || !dev->isYaffs2) {
4515 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint write" TENDSTR)));
4520 ok = yaffs_CheckpointOpen(dev, 1);
4523 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4524 ok = yaffs_WriteCheckpointValidityMarker(dev, 1);
4527 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint device" TENDSTR)));
4528 ok = yaffs_WriteCheckpointDevice(dev);
4531 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint objects" TENDSTR)));
4532 ok = yaffs_WriteCheckpointObjects(dev);
4535 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4536 ok = yaffs_WriteCheckpointValidityMarker(dev, 0);
4540 ok = yaffs_WriteCheckpointSum(dev);
4542 if (!yaffs_CheckpointClose(dev))
4546 dev->isCheckpointed = 1;
4548 dev->isCheckpointed = 0;
4550 return dev->isCheckpointed;
4553 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4557 if (dev->skipCheckpointRead || !dev->isYaffs2) {
4558 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint read" TENDSTR)));
4563 ok = yaffs_CheckpointOpen(dev, 0); /* open for read */
4566 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4567 ok = yaffs_ReadCheckpointValidityMarker(dev, 1);
4570 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint device" TENDSTR)));
4571 ok = yaffs_ReadCheckpointDevice(dev);
4574 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint objects" TENDSTR)));
4575 ok = yaffs_ReadCheckpointObjects(dev);
4578 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4579 ok = yaffs_ReadCheckpointValidityMarker(dev, 0);
4583 ok = yaffs_ReadCheckpointSum(dev);
4584 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint checksum %d" TENDSTR), ok));
4587 if (!yaffs_CheckpointClose(dev))
4591 dev->isCheckpointed = 1;
4593 dev->isCheckpointed = 0;
4599 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4601 if (dev->isCheckpointed ||
4602 dev->blocksInCheckpoint > 0) {
4603 dev->isCheckpointed = 0;
4604 yaffs_CheckpointInvalidateStream(dev);
4605 if (dev->superBlock && dev->markSuperBlockDirty)
4606 dev->markSuperBlockDirty(dev->superBlock);
4611 int yaffs_CheckpointSave(yaffs_Device *dev)
4614 T(YAFFS_TRACE_CHECKPOINT, (TSTR("save entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4616 yaffs_VerifyObjects(dev);
4617 yaffs_VerifyBlocks(dev);
4618 yaffs_VerifyFreeChunks(dev);
4620 if (!dev->isCheckpointed) {
4621 yaffs_InvalidateCheckpoint(dev);
4622 yaffs_WriteCheckpointData(dev);
4625 T(YAFFS_TRACE_ALWAYS, (TSTR("save exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4627 return dev->isCheckpointed;
4630 int yaffs_CheckpointRestore(yaffs_Device *dev)
4633 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4635 retval = yaffs_ReadCheckpointData(dev);
4637 if (dev->isCheckpointed) {
4638 yaffs_VerifyObjects(dev);
4639 yaffs_VerifyBlocks(dev);
4640 yaffs_VerifyFreeChunks(dev);
4643 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4648 /*--------------------- File read/write ------------------------
4649 * Read and write have very similar structures.
4650 * In general the read/write has three parts to it
4651 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4652 * Some complete chunks
4653 * An incomplete chunk to end off with
4655 * Curve-balls: the first chunk might also be the last chunk.
4658 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 *buffer, loff_t offset,
4667 yaffs_ChunkCache *cache;
4674 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4675 /* start = offset % dev->nDataBytesPerChunk; */
4676 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4679 /* OK now check for the curveball where the start and end are in
4682 if ((start + n) < dev->nDataBytesPerChunk)
4685 nToCopy = dev->nDataBytesPerChunk - start;
4687 cache = yaffs_FindChunkCache(in, chunk);
4689 /* If the chunk is already in the cache or it is less than a whole chunk
4690 * or we're using inband tags then use the cache (if there is caching)
4691 * else bypass the cache.
4693 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4694 if (dev->nShortOpCaches > 0) {
4696 /* If we can't find the data in the cache, then load it up. */
4699 cache = yaffs_GrabChunkCache(in->myDev);
4701 cache->chunkId = chunk;
4704 yaffs_ReadChunkDataFromObject(in, chunk,
4710 yaffs_UseChunkCache(dev, cache, 0);
4715 memcpy(buffer, &cache->data[start], nToCopy);
4719 /* Read into the local buffer then copy..*/
4722 yaffs_GetTempBuffer(dev, __LINE__);
4723 yaffs_ReadChunkDataFromObject(in, chunk,
4726 memcpy(buffer, &localBuffer[start], nToCopy);
4729 yaffs_ReleaseTempBuffer(dev, localBuffer,
4735 /* A full chunk. Read directly into the supplied buffer. */
4736 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4750 int yaffs_WriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
4751 int nBytes, int writeThrough)
4760 int startOfWrite = offset;
4761 int chunkWritten = 0;
4769 while (n > 0 && chunkWritten >= 0) {
4770 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4771 /* start = offset % dev->nDataBytesPerChunk; */
4772 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4774 if (chunk * dev->nDataBytesPerChunk + start != offset ||
4775 start >= dev->nDataBytesPerChunk) {
4776 T(YAFFS_TRACE_ERROR, (
4777 TSTR("AddrToChunk of offset %d gives chunk %d start %d"
4779 (int)offset, chunk, start));
4783 /* OK now check for the curveball where the start and end are in
4787 if ((start + n) < dev->nDataBytesPerChunk) {
4790 /* Now folks, to calculate how many bytes to write back....
4791 * If we're overwriting and not writing to then end of file then
4792 * we need to write back as much as was there before.
4795 chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
4797 if (chunkStart > in->variant.fileVariant.fileSize)
4798 nBytesRead = 0; /* Past end of file */
4800 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
4802 if (nBytesRead > dev->nDataBytesPerChunk)
4803 nBytesRead = dev->nDataBytesPerChunk;
4807 (start + n)) ? nBytesRead : (start + n);
4809 if (nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
4813 nToCopy = dev->nDataBytesPerChunk - start;
4814 nToWriteBack = dev->nDataBytesPerChunk;
4817 if (nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4818 /* An incomplete start or end chunk (or maybe both start and end chunk),
4819 * or we're using inband tags, so we want to use the cache buffers.
4821 if (dev->nShortOpCaches > 0) {
4822 yaffs_ChunkCache *cache;
4823 /* If we can't find the data in the cache, then load the cache */
4824 cache = yaffs_FindChunkCache(in, chunk);
4827 && yaffs_CheckSpaceForAllocation(in->
4829 cache = yaffs_GrabChunkCache(in->myDev);
4831 cache->chunkId = chunk;
4834 yaffs_ReadChunkDataFromObject(in, chunk,
4839 !yaffs_CheckSpaceForAllocation(in->myDev)) {
4840 /* Drop the cache if it was a read cache item and
4841 * no space check has been made for it.
4847 yaffs_UseChunkCache(dev, cache, 1);
4851 memcpy(&cache->data[start], buffer,
4856 cache->nBytes = nToWriteBack;
4860 yaffs_WriteChunkDataToObject
4863 cache->data, cache->nBytes,
4869 chunkWritten = -1; /* fail the write */
4872 /* An incomplete start or end chunk (or maybe both start and end chunk)
4873 * Read into the local buffer then copy, then copy over and write back.
4877 yaffs_GetTempBuffer(dev, __LINE__);
4879 yaffs_ReadChunkDataFromObject(in, chunk,
4884 memcpy(&localBuffer[start], buffer, nToCopy);
4887 yaffs_WriteChunkDataToObject(in, chunk,
4892 yaffs_ReleaseTempBuffer(dev, localBuffer,
4898 /* A full chunk. Write directly from the supplied buffer. */
4903 yaffs_WriteChunkDataToObject(in, chunk, buffer,
4904 dev->nDataBytesPerChunk,
4907 /* Since we've overwritten the cached data, we better invalidate it. */
4908 yaffs_InvalidateChunkCache(in, chunk);
4911 if (chunkWritten >= 0) {
4920 /* Update file object */
4922 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
4923 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4931 /* ---------------------- File resizing stuff ------------------ */
4933 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
4936 yaffs_Device *dev = in->myDev;
4937 int oldFileSize = in->variant.fileVariant.fileSize;
4939 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
4941 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
4942 dev->nDataBytesPerChunk;
4946 /* Delete backwards so that we don't end up with holes if
4947 * power is lost part-way through the operation.
4949 for (i = lastDel; i >= startDel; i--) {
4950 /* NB this could be optimised somewhat,
4951 * eg. could retrieve the tags and write them without
4952 * using yaffs_DeleteChunk
4955 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
4958 (dev->internalStartBlock * dev->nChunksPerBlock)
4960 ((dev->internalEndBlock +
4961 1) * dev->nChunksPerBlock)) {
4962 T(YAFFS_TRACE_ALWAYS,
4963 (TSTR("Found daft chunkId %d for %d" TENDSTR),
4967 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
4974 int yaffs_ResizeFile(yaffs_Object *in, loff_t newSize)
4977 int oldFileSize = in->variant.fileVariant.fileSize;
4978 __u32 newSizeOfPartialChunk;
4981 yaffs_Device *dev = in->myDev;
4983 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
4985 yaffs_FlushFilesChunkCache(in);
4986 yaffs_InvalidateWholeChunkCache(in);
4988 yaffs_CheckGarbageCollection(dev);
4990 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
4993 if (newSize == oldFileSize)
4996 if (newSize < oldFileSize) {
4998 yaffs_PruneResizedChunks(in, newSize);
5000 if (newSizeOfPartialChunk != 0) {
5001 int lastChunk = 1 + newFullChunks;
5003 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5005 /* Got to read and rewrite the last chunk with its new size and zero pad */
5006 yaffs_ReadChunkDataFromObject(in, lastChunk,
5009 memset(localBuffer + newSizeOfPartialChunk, 0,
5010 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5012 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5013 newSizeOfPartialChunk, 1);
5015 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5018 in->variant.fileVariant.fileSize = newSize;
5020 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5022 /* newsSize > oldFileSize */
5023 in->variant.fileVariant.fileSize = newSize;
5027 /* Write a new object header.
5028 * show we've shrunk the file, if need be
5029 * Do this only if the file is not in the deleted directories.
5032 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5033 in->parent->objectId != YAFFS_OBJECTID_DELETED)
5034 yaffs_UpdateObjectHeader(in, NULL, 0,
5035 (newSize < oldFileSize) ? 1 : 0, 0);
5040 loff_t yaffs_GetFileSize(yaffs_Object *obj)
5042 obj = yaffs_GetEquivalentObject(obj);
5044 switch (obj->variantType) {
5045 case YAFFS_OBJECT_TYPE_FILE:
5046 return obj->variant.fileVariant.fileSize;
5047 case YAFFS_OBJECT_TYPE_SYMLINK:
5048 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5056 int yaffs_FlushFile(yaffs_Object *in, int updateTime)
5060 yaffs_FlushFilesChunkCache(in);
5062 #ifdef CONFIG_YAFFS_WINCE
5063 yfsd_WinFileTimeNow(in->win_mtime);
5066 in->yst_mtime = Y_CURRENT_TIME;
5071 retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5072 0) ? YAFFS_OK : YAFFS_FAIL;
5081 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
5084 /* First off, invalidate the file's data in the cache, without flushing. */
5085 yaffs_InvalidateWholeChunkCache(in);
5087 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5088 /* Move to the unlinked directory so we have a record that it was deleted. */
5089 yaffs_ChangeObjectName(in, in->myDev->deletedDir, _Y("deleted"), 0, 0);
5093 yaffs_RemoveObjectFromDirectory(in);
5094 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5097 yaffs_FreeObject(in);
5102 /* yaffs_DeleteFile deletes the whole file data
5103 * and the inode associated with the file.
5104 * It does not delete the links associated with the file.
5106 static int yaffs_UnlinkFileIfNeeded(yaffs_Object *in)
5110 int immediateDeletion = 0;
5114 immediateDeletion = 1;
5117 immediateDeletion = 1;
5120 if (immediateDeletion) {
5122 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5123 _Y("deleted"), 0, 0);
5124 T(YAFFS_TRACE_TRACING,
5125 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5128 in->myDev->nDeletedFiles++;
5129 if (1 || in->myDev->isYaffs2)
5130 yaffs_ResizeFile(in, 0);
5131 yaffs_SoftDeleteFile(in);
5134 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5135 _Y("unlinked"), 0, 0);
5142 int yaffs_DeleteFile(yaffs_Object *in)
5144 int retVal = YAFFS_OK;
5145 int deleted = in->deleted;
5147 yaffs_ResizeFile(in, 0);
5149 if (in->nDataChunks > 0) {
5150 /* Use soft deletion if there is data in the file.
5151 * That won't be the case if it has been resized to zero.
5154 retVal = yaffs_UnlinkFileIfNeeded(in);
5156 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5159 in->myDev->nDeletedFiles++;
5160 yaffs_SoftDeleteFile(in);
5162 return deleted ? YAFFS_OK : YAFFS_FAIL;
5164 /* The file has no data chunks so we toss it immediately */
5165 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5166 in->variant.fileVariant.top = NULL;
5167 yaffs_DoGenericObjectDeletion(in);
5173 static int yaffs_DeleteDirectory(yaffs_Object *in)
5175 /* First check that the directory is empty. */
5176 if (ylist_empty(&in->variant.directoryVariant.children))
5177 return yaffs_DoGenericObjectDeletion(in);
5183 static int yaffs_DeleteSymLink(yaffs_Object *in)
5185 YFREE(in->variant.symLinkVariant.alias);
5187 return yaffs_DoGenericObjectDeletion(in);
5190 static int yaffs_DeleteHardLink(yaffs_Object *in)
5192 /* remove this hardlink from the list assocaited with the equivalent
5195 ylist_del_init(&in->hardLinks);
5196 return yaffs_DoGenericObjectDeletion(in);
5199 int yaffs_DeleteObject(yaffs_Object *obj)
5202 switch (obj->variantType) {
5203 case YAFFS_OBJECT_TYPE_FILE:
5204 retVal = yaffs_DeleteFile(obj);
5206 case YAFFS_OBJECT_TYPE_DIRECTORY:
5207 return yaffs_DeleteDirectory(obj);
5209 case YAFFS_OBJECT_TYPE_SYMLINK:
5210 retVal = yaffs_DeleteSymLink(obj);
5212 case YAFFS_OBJECT_TYPE_HARDLINK:
5213 retVal = yaffs_DeleteHardLink(obj);
5215 case YAFFS_OBJECT_TYPE_SPECIAL:
5216 retVal = yaffs_DoGenericObjectDeletion(obj);
5218 case YAFFS_OBJECT_TYPE_UNKNOWN:
5220 break; /* should not happen. */
5226 static int yaffs_UnlinkWorker(yaffs_Object *obj)
5229 int immediateDeletion = 0;
5233 immediateDeletion = 1;
5235 if (obj->inUse <= 0)
5236 immediateDeletion = 1;
5240 yaffs_UpdateParent(obj->parent);
5242 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5243 return yaffs_DeleteHardLink(obj);
5244 } else if (!ylist_empty(&obj->hardLinks)) {
5245 /* Curve ball: We're unlinking an object that has a hardlink.
5247 * This problem arises because we are not strictly following
5248 * The Linux link/inode model.
5250 * We can't really delete the object.
5251 * Instead, we do the following:
5252 * - Select a hardlink.
5253 * - Unhook it from the hard links
5254 * - Unhook it from its parent directory (so that the rename can work)
5255 * - Rename the object to the hardlink's name.
5256 * - Delete the hardlink
5261 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5263 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5265 ylist_del_init(&hl->hardLinks);
5266 ylist_del_init(&hl->siblings);
5268 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5270 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
5272 if (retVal == YAFFS_OK)
5273 retVal = yaffs_DoGenericObjectDeletion(hl);
5277 } else if (immediateDeletion) {
5278 switch (obj->variantType) {
5279 case YAFFS_OBJECT_TYPE_FILE:
5280 return yaffs_DeleteFile(obj);
5282 case YAFFS_OBJECT_TYPE_DIRECTORY:
5283 return yaffs_DeleteDirectory(obj);
5285 case YAFFS_OBJECT_TYPE_SYMLINK:
5286 return yaffs_DeleteSymLink(obj);
5288 case YAFFS_OBJECT_TYPE_SPECIAL:
5289 return yaffs_DoGenericObjectDeletion(obj);
5291 case YAFFS_OBJECT_TYPE_HARDLINK:
5292 case YAFFS_OBJECT_TYPE_UNKNOWN:
5297 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
5298 _Y("unlinked"), 0, 0);
5302 static int yaffs_UnlinkObject(yaffs_Object *obj)
5305 if (obj && obj->unlinkAllowed)
5306 return yaffs_UnlinkWorker(obj);
5311 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
5315 obj = yaffs_FindObjectByName(dir, name);
5316 return yaffs_UnlinkObject(obj);
5319 /*----------------------- Initialisation Scanning ---------------------- */
5321 static void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
5322 int backwardScanning)
5326 if (!backwardScanning) {
5327 /* Handle YAFFS1 forward scanning case
5328 * For YAFFS1 we always do the deletion
5332 /* Handle YAFFS2 case (backward scanning)
5333 * If the shadowed object exists then ignore.
5335 if (yaffs_FindObjectByNumber(dev, objId))
5339 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5340 * We put it in unlinked dir to be cleaned up after the scanning
5343 yaffs_FindOrCreateObjectByNumber(dev, objId,
5344 YAFFS_OBJECT_TYPE_FILE);
5347 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5348 obj->variant.fileVariant.shrinkSize = 0;
5349 obj->valid = 1; /* So that we don't read any other info for this file */
5359 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5366 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5368 in = yaffs_FindObjectByNumber(dev,
5369 hl->variant.hardLinkVariant.
5370 equivalentObjectId);
5373 /* Add the hardlink pointers */
5374 hl->variant.hardLinkVariant.equivalentObject = in;
5375 ylist_add(&hl->hardLinks, &in->hardLinks);
5377 /* Todo Need to report/handle this better.
5378 * Got a problem... hardlink to a non-existant object
5380 hl->variant.hardLinkVariant.equivalentObject = NULL;
5381 YINIT_LIST_HEAD(&hl->hardLinks);
5391 static int ybicmp(const void *a, const void *b)
5393 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5394 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5395 register int ablock = ((yaffs_BlockIndex *)a)->block;
5396 register int bblock = ((yaffs_BlockIndex *)b)->block;
5398 return ablock - bblock;
5404 struct yaffs_ShadowFixerStruct {
5407 struct yaffs_ShadowFixerStruct *next;
5411 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5414 * Sort out state of unlinked and deleted objects after scanning.
5416 struct ylist_head *i;
5417 struct ylist_head *n;
5420 /* Soft delete all the unlinked files */
5421 ylist_for_each_safe(i, n,
5422 &dev->unlinkedDir->variant.directoryVariant.children) {
5424 l = ylist_entry(i, yaffs_Object, siblings);
5425 yaffs_DeleteObject(l);
5429 ylist_for_each_safe(i, n,
5430 &dev->deletedDir->variant.directoryVariant.children) {
5432 l = ylist_entry(i, yaffs_Object, siblings);
5433 yaffs_DeleteObject(l);
5439 static int yaffs_Scan(yaffs_Device *dev)
5441 yaffs_ExtendedTags tags;
5451 yaffs_BlockState state;
5452 yaffs_Object *hardList = NULL;
5453 yaffs_BlockInfo *bi;
5454 __u32 sequenceNumber;
5455 yaffs_ObjectHeader *oh;
5457 yaffs_Object *parent;
5459 int alloc_failed = 0;
5461 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5469 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5470 dev->internalStartBlock, dev->internalEndBlock));
5472 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5474 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5476 /* Scan all the blocks to determine their state */
5477 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5478 bi = yaffs_GetBlockInfo(dev, blk);
5479 yaffs_ClearChunkBits(dev, blk);
5481 bi->softDeletions = 0;
5483 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5485 bi->blockState = state;
5486 bi->sequenceNumber = sequenceNumber;
5488 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
5489 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
5491 T(YAFFS_TRACE_SCAN_DEBUG,
5492 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5493 state, sequenceNumber));
5495 if (state == YAFFS_BLOCK_STATE_DEAD) {
5496 T(YAFFS_TRACE_BAD_BLOCKS,
5497 (TSTR("block %d is bad" TENDSTR), blk));
5498 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5499 T(YAFFS_TRACE_SCAN_DEBUG,
5500 (TSTR("Block empty " TENDSTR)));
5501 dev->nErasedBlocks++;
5502 dev->nFreeChunks += dev->nChunksPerBlock;
5506 startIterator = dev->internalStartBlock;
5507 endIterator = dev->internalEndBlock;
5509 /* For each block.... */
5510 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5517 blk = blockIterator;
5519 bi = yaffs_GetBlockInfo(dev, blk);
5520 state = bi->blockState;
5524 /* For each chunk in each block that needs scanning....*/
5525 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5526 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5527 /* Read the tags and decide what to do */
5528 chunk = blk * dev->nChunksPerBlock + c;
5530 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5533 /* Let's have a good look at this chunk... */
5535 if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
5541 /*T((" %d %d deleted\n",blk,c)); */
5542 } else if (!tags.chunkUsed) {
5543 /* An unassigned chunk in the block
5544 * This means that either the block is empty or
5545 * this is the one being allocated from
5549 /* We're looking at the first chunk in the block so the block is unused */
5550 state = YAFFS_BLOCK_STATE_EMPTY;
5551 dev->nErasedBlocks++;
5553 /* this is the block being allocated from */
5556 (" Allocating from %d %d" TENDSTR),
5558 state = YAFFS_BLOCK_STATE_ALLOCATING;
5559 dev->allocationBlock = blk;
5560 dev->allocationPage = c;
5561 dev->allocationBlockFinder = blk;
5562 /* Set it to here to encourage the allocator to go forth from here. */
5566 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5567 } else if (tags.chunkId > 0) {
5568 /* chunkId > 0 so it is a data chunk... */
5569 unsigned int endpos;
5571 yaffs_SetChunkBit(dev, blk, c);
5574 in = yaffs_FindOrCreateObjectByNumber(dev,
5577 YAFFS_OBJECT_TYPE_FILE);
5578 /* PutChunkIntoFile checks for a clash (two data chunks with
5579 * the same chunkId).
5586 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, 1))
5591 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5594 in->variantType == YAFFS_OBJECT_TYPE_FILE
5595 && in->variant.fileVariant.scannedFileSize <
5597 in->variant.fileVariant.
5598 scannedFileSize = endpos;
5599 if (!dev->useHeaderFileSize) {
5600 in->variant.fileVariant.
5602 in->variant.fileVariant.
5607 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
5609 /* chunkId == 0, so it is an ObjectHeader.
5610 * Thus, we read in the object header and make the object
5612 yaffs_SetChunkBit(dev, blk, c);
5615 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5619 oh = (yaffs_ObjectHeader *) chunkData;
5621 in = yaffs_FindObjectByNumber(dev,
5623 if (in && in->variantType != oh->type) {
5624 /* This should not happen, but somehow
5625 * Wev'e ended up with an objectId that has been reused but not yet
5626 * deleted, and worse still it has changed type. Delete the old object.
5629 yaffs_DeleteObject(in);
5634 in = yaffs_FindOrCreateObjectByNumber(dev,
5642 if (in && oh->shadowsObject > 0) {
5644 struct yaffs_ShadowFixerStruct *fixer;
5645 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
5647 fixer->next = shadowFixerList;
5648 shadowFixerList = fixer;
5649 fixer->objectId = tags.objectId;
5650 fixer->shadowedId = oh->shadowsObject;
5655 if (in && in->valid) {
5656 /* We have already filled this one. We have a duplicate and need to resolve it. */
5658 unsigned existingSerial = in->serial;
5659 unsigned newSerial = tags.serialNumber;
5661 if (((existingSerial + 1) & 3) == newSerial) {
5662 /* Use new one - destroy the exisiting one */
5663 yaffs_DeleteChunk(dev,
5668 /* Use existing - destroy this one. */
5669 yaffs_DeleteChunk(dev, chunk, 1,
5674 if (in && !in->valid &&
5675 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5676 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5677 /* We only load some info, don't fiddle with directory structure */
5679 in->variantType = oh->type;
5681 in->yst_mode = oh->yst_mode;
5682 #ifdef CONFIG_YAFFS_WINCE
5683 in->win_atime[0] = oh->win_atime[0];
5684 in->win_ctime[0] = oh->win_ctime[0];
5685 in->win_mtime[0] = oh->win_mtime[0];
5686 in->win_atime[1] = oh->win_atime[1];
5687 in->win_ctime[1] = oh->win_ctime[1];
5688 in->win_mtime[1] = oh->win_mtime[1];
5690 in->yst_uid = oh->yst_uid;
5691 in->yst_gid = oh->yst_gid;
5692 in->yst_atime = oh->yst_atime;
5693 in->yst_mtime = oh->yst_mtime;
5694 in->yst_ctime = oh->yst_ctime;
5695 in->yst_rdev = oh->yst_rdev;
5697 in->hdrChunk = chunk;
5698 in->serial = tags.serialNumber;
5700 } else if (in && !in->valid) {
5701 /* we need to load this info */
5704 in->variantType = oh->type;
5706 in->yst_mode = oh->yst_mode;
5707 #ifdef CONFIG_YAFFS_WINCE
5708 in->win_atime[0] = oh->win_atime[0];
5709 in->win_ctime[0] = oh->win_ctime[0];
5710 in->win_mtime[0] = oh->win_mtime[0];
5711 in->win_atime[1] = oh->win_atime[1];
5712 in->win_ctime[1] = oh->win_ctime[1];
5713 in->win_mtime[1] = oh->win_mtime[1];
5715 in->yst_uid = oh->yst_uid;
5716 in->yst_gid = oh->yst_gid;
5717 in->yst_atime = oh->yst_atime;
5718 in->yst_mtime = oh->yst_mtime;
5719 in->yst_ctime = oh->yst_ctime;
5720 in->yst_rdev = oh->yst_rdev;
5722 in->hdrChunk = chunk;
5723 in->serial = tags.serialNumber;
5725 yaffs_SetObjectName(in, oh->name);
5728 /* directory stuff...
5733 yaffs_FindOrCreateObjectByNumber
5734 (dev, oh->parentObjectId,
5735 YAFFS_OBJECT_TYPE_DIRECTORY);
5738 if (parent && parent->variantType ==
5739 YAFFS_OBJECT_TYPE_UNKNOWN) {
5740 /* Set up as a directory */
5741 parent->variantType =
5742 YAFFS_OBJECT_TYPE_DIRECTORY;
5743 YINIT_LIST_HEAD(&parent->variant.
5746 } else if (!parent || parent->variantType !=
5747 YAFFS_OBJECT_TYPE_DIRECTORY) {
5748 /* Hoosterman, another problem....
5749 * We're trying to use a non-directory as a directory
5752 T(YAFFS_TRACE_ERROR,
5754 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
5756 parent = dev->lostNFoundDir;
5759 yaffs_AddObjectToDirectory(parent, in);
5761 if (0 && (parent == dev->deletedDir ||
5762 parent == dev->unlinkedDir)) {
5763 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
5764 dev->nDeletedFiles++;
5766 /* Note re hardlinks.
5767 * Since we might scan a hardlink before its equivalent object is scanned
5768 * we put them all in a list.
5769 * After scanning is complete, we should have all the objects, so we run through this
5770 * list and fix up all the chains.
5773 switch (in->variantType) {
5774 case YAFFS_OBJECT_TYPE_UNKNOWN:
5775 /* Todo got a problem */
5777 case YAFFS_OBJECT_TYPE_FILE:
5778 if (dev->useHeaderFileSize)
5780 in->variant.fileVariant.
5785 case YAFFS_OBJECT_TYPE_HARDLINK:
5786 in->variant.hardLinkVariant.
5787 equivalentObjectId =
5788 oh->equivalentObjectId;
5789 in->hardLinks.next =
5790 (struct ylist_head *)
5794 case YAFFS_OBJECT_TYPE_DIRECTORY:
5797 case YAFFS_OBJECT_TYPE_SPECIAL:
5800 case YAFFS_OBJECT_TYPE_SYMLINK:
5801 in->variant.symLinkVariant.alias =
5802 yaffs_CloneString(oh->alias);
5803 if (!in->variant.symLinkVariant.alias)
5809 if (parent == dev->deletedDir) {
5810 yaffs_DestroyObject(in);
5811 bi->hasShrinkHeader = 1;
5818 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5819 /* If we got this far while scanning, then the block is fully allocated.*/
5820 state = YAFFS_BLOCK_STATE_FULL;
5823 bi->blockState = state;
5825 /* Now let's see if it was dirty */
5826 if (bi->pagesInUse == 0 &&
5827 !bi->hasShrinkHeader &&
5828 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5829 yaffs_BlockBecameDirty(dev, blk);
5835 /* Ok, we've done all the scanning.
5836 * Fix up the hard link chains.
5837 * We should now have scanned all the objects, now it's time to add these
5841 yaffs_HardlinkFixup(dev, hardList);
5843 /* Fix up any shadowed objects */
5845 struct yaffs_ShadowFixerStruct *fixer;
5848 while (shadowFixerList) {
5849 fixer = shadowFixerList;
5850 shadowFixerList = fixer->next;
5851 /* Complete the rename transaction by deleting the shadowed object
5852 * then setting the object header to unshadowed.
5854 obj = yaffs_FindObjectByNumber(dev, fixer->shadowedId);
5856 yaffs_DeleteObject(obj);
5858 obj = yaffs_FindObjectByNumber(dev, fixer->objectId);
5861 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
5867 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5872 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5878 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5881 yaffs_ObjectHeader *oh;
5883 yaffs_ExtendedTags tags;
5885 int alloc_failed = 0;
5893 T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
5895 in->lazyLoaded ? "not yet" : "already"));
5898 if (in->lazyLoaded && in->hdrChunk > 0) {
5900 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5902 result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
5903 oh = (yaffs_ObjectHeader *) chunkData;
5905 in->yst_mode = oh->yst_mode;
5906 #ifdef CONFIG_YAFFS_WINCE
5907 in->win_atime[0] = oh->win_atime[0];
5908 in->win_ctime[0] = oh->win_ctime[0];
5909 in->win_mtime[0] = oh->win_mtime[0];
5910 in->win_atime[1] = oh->win_atime[1];
5911 in->win_ctime[1] = oh->win_ctime[1];
5912 in->win_mtime[1] = oh->win_mtime[1];
5914 in->yst_uid = oh->yst_uid;
5915 in->yst_gid = oh->yst_gid;
5916 in->yst_atime = oh->yst_atime;
5917 in->yst_mtime = oh->yst_mtime;
5918 in->yst_ctime = oh->yst_ctime;
5919 in->yst_rdev = oh->yst_rdev;
5922 yaffs_SetObjectName(in, oh->name);
5924 if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
5925 in->variant.symLinkVariant.alias =
5926 yaffs_CloneString(oh->alias);
5927 if (!in->variant.symLinkVariant.alias)
5928 alloc_failed = 1; /* Not returned to caller */
5931 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5935 static int yaffs_ScanBackwards(yaffs_Device *dev)
5937 yaffs_ExtendedTags tags;
5942 int nBlocksToScan = 0;
5948 yaffs_BlockState state;
5949 yaffs_Object *hardList = NULL;
5950 yaffs_BlockInfo *bi;
5951 __u32 sequenceNumber;
5952 yaffs_ObjectHeader *oh;
5954 yaffs_Object *parent;
5955 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5961 int foundChunksInBlock;
5962 int equivalentObjectId;
5963 int alloc_failed = 0;
5966 yaffs_BlockIndex *blockIndex = NULL;
5967 int altBlockIndex = 0;
5969 if (!dev->isYaffs2) {
5971 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
5977 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
5978 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
5981 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5983 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
5986 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
5992 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
5996 dev->blocksInCheckpoint = 0;
5998 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6000 /* Scan all the blocks to determine their state */
6001 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6002 bi = yaffs_GetBlockInfo(dev, blk);
6003 yaffs_ClearChunkBits(dev, blk);
6005 bi->softDeletions = 0;
6007 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6009 bi->blockState = state;
6010 bi->sequenceNumber = sequenceNumber;
6012 if (bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6013 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6014 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6015 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6017 T(YAFFS_TRACE_SCAN_DEBUG,
6018 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6019 state, sequenceNumber));
6022 if (state == YAFFS_BLOCK_STATE_CHECKPOINT) {
6023 dev->blocksInCheckpoint++;
6025 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6026 T(YAFFS_TRACE_BAD_BLOCKS,
6027 (TSTR("block %d is bad" TENDSTR), blk));
6028 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6029 T(YAFFS_TRACE_SCAN_DEBUG,
6030 (TSTR("Block empty " TENDSTR)));
6031 dev->nErasedBlocks++;
6032 dev->nFreeChunks += dev->nChunksPerBlock;
6033 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6035 /* Determine the highest sequence number */
6036 if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6037 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6039 blockIndex[nBlocksToScan].seq = sequenceNumber;
6040 blockIndex[nBlocksToScan].block = blk;
6044 if (sequenceNumber >= dev->sequenceNumber)
6045 dev->sequenceNumber = sequenceNumber;
6047 /* TODO: Nasty sequence number! */
6050 ("Block scanning block %d has bad sequence number %d"
6051 TENDSTR), blk, sequenceNumber));
6058 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6064 /* Sort the blocks */
6065 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6067 /* Use qsort now. */
6068 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6072 /* Dungy old bubble sort... */
6074 yaffs_BlockIndex temp;
6078 for (i = 0; i < nBlocksToScan; i++)
6079 for (j = i + 1; j < nBlocksToScan; j++)
6080 if (blockIndex[i].seq > blockIndex[j].seq) {
6081 temp = blockIndex[j];
6082 blockIndex[j] = blockIndex[i];
6083 blockIndex[i] = temp;
6090 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6092 /* Now scan the blocks looking at the data. */
6094 endIterator = nBlocksToScan - 1;
6095 T(YAFFS_TRACE_SCAN_DEBUG,
6096 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6098 /* For each block.... backwards */
6099 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6101 /* Cooperative multitasking! This loop can run for so
6102 long that watchdog timers expire. */
6105 /* get the block to scan in the correct order */
6106 blk = blockIndex[blockIterator].block;
6108 bi = yaffs_GetBlockInfo(dev, blk);
6111 state = bi->blockState;
6115 /* For each chunk in each block that needs scanning.... */
6116 foundChunksInBlock = 0;
6117 for (c = dev->nChunksPerBlock - 1;
6118 !alloc_failed && c >= 0 &&
6119 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6120 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6121 /* Scan backwards...
6122 * Read the tags and decide what to do
6125 chunk = blk * dev->nChunksPerBlock + c;
6127 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6130 /* Let's have a good look at this chunk... */
6132 if (!tags.chunkUsed) {
6133 /* An unassigned chunk in the block.
6134 * If there are used chunks after this one, then
6135 * it is a chunk that was skipped due to failing the erased
6136 * check. Just skip it so that it can be deleted.
6137 * But, more typically, We get here when this is an unallocated
6138 * chunk and his means that either the block is empty or
6139 * this is the one being allocated from
6142 if (foundChunksInBlock) {
6143 /* This is a chunk that was skipped due to failing the erased check */
6144 } else if (c == 0) {
6145 /* We're looking at the first chunk in the block so the block is unused */
6146 state = YAFFS_BLOCK_STATE_EMPTY;
6147 dev->nErasedBlocks++;
6149 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6150 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6151 if (dev->sequenceNumber == bi->sequenceNumber) {
6152 /* this is the block being allocated from */
6156 (" Allocating from %d %d"
6159 state = YAFFS_BLOCK_STATE_ALLOCATING;
6160 dev->allocationBlock = blk;
6161 dev->allocationPage = c;
6162 dev->allocationBlockFinder = blk;
6164 /* This is a partially written block that is not
6165 * the current allocation block. This block must have
6166 * had a write failure, so set up for retirement.
6169 /* bi->needsRetiring = 1; ??? TODO */
6170 bi->gcPrioritise = 1;
6172 T(YAFFS_TRACE_ALWAYS,
6173 (TSTR("Partially written block %d detected" TENDSTR),
6181 } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED) {
6183 (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
6188 } else if (tags.chunkId > 0) {
6189 /* chunkId > 0 so it is a data chunk... */
6190 unsigned int endpos;
6192 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6194 foundChunksInBlock = 1;
6197 yaffs_SetChunkBit(dev, blk, c);
6200 in = yaffs_FindOrCreateObjectByNumber(dev,
6203 YAFFS_OBJECT_TYPE_FILE);
6210 in->variantType == YAFFS_OBJECT_TYPE_FILE
6212 in->variant.fileVariant.shrinkSize) {
6213 /* This has not been invalidated by a resize */
6214 if (!yaffs_PutChunkIntoFile(in, tags.chunkId,
6219 /* File size is calculated by looking at the data chunks if we have not
6220 * seen an object header yet. Stop this practice once we find an object header.
6224 1) * dev->nDataBytesPerChunk +
6227 if (!in->valid && /* have not got an object header yet */
6228 in->variant.fileVariant.
6229 scannedFileSize < endpos) {
6230 in->variant.fileVariant.
6231 scannedFileSize = endpos;
6232 in->variant.fileVariant.
6234 in->variant.fileVariant.
6239 /* This chunk has been invalidated by a resize, so delete */
6240 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6244 /* chunkId == 0, so it is an ObjectHeader.
6245 * Thus, we read in the object header and make the object
6247 foundChunksInBlock = 1;
6249 yaffs_SetChunkBit(dev, blk, c);
6255 if (tags.extraHeaderInfoAvailable) {
6256 in = yaffs_FindOrCreateObjectByNumber
6257 (dev, tags.objectId,
6258 tags.extraObjectType);
6264 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
6267 tags.extraShadows ||
6269 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6270 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))) {
6272 /* If we don't have valid info then we need to read the chunk
6273 * TODO In future we can probably defer reading the chunk and
6274 * living with invalid data until needed.
6277 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6282 oh = (yaffs_ObjectHeader *) chunkData;
6284 if (dev->inbandTags) {
6285 /* Fix up the header if they got corrupted by inband tags */
6286 oh->shadowsObject = oh->inbandShadowsObject;
6287 oh->isShrink = oh->inbandIsShrink;
6291 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6299 /* TODO Hoosterman we have a problem! */
6300 T(YAFFS_TRACE_ERROR,
6302 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6303 TENDSTR), tags.objectId, chunk));
6308 /* We have already filled this one.
6309 * We have a duplicate that will be discarded, but
6310 * we first have to suck out resize info if it is a file.
6313 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6315 oh->type == YAFFS_OBJECT_TYPE_FILE) ||
6316 (tags.extraHeaderInfoAvailable &&
6317 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))) {
6319 (oh) ? oh->fileSize : tags.
6321 __u32 parentObjectId =
6323 parentObjectId : tags.
6324 extraParentObjectId;
6328 (oh) ? oh->isShrink : tags.
6329 extraIsShrinkHeader;
6331 /* If it is deleted (unlinked at start also means deleted)
6332 * we treat the file size as being zeroed at this point.
6334 if (parentObjectId ==
6335 YAFFS_OBJECTID_DELETED
6336 || parentObjectId ==
6337 YAFFS_OBJECTID_UNLINKED) {
6343 in->variant.fileVariant.
6344 shrinkSize > thisSize) {
6345 in->variant.fileVariant.
6351 bi->hasShrinkHeader = 1;
6354 /* Use existing - destroy this one. */
6355 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6359 if (!in->valid && in->variantType !=
6360 (oh ? oh->type : tags.extraObjectType))
6361 T(YAFFS_TRACE_ERROR, (
6362 TSTR("yaffs tragedy: Bad object type, "
6363 TCONT("%d != %d, for object %d at chunk ")
6364 TCONT("%d during scan")
6366 oh->type : tags.extraObjectType,
6367 in->variantType, tags.objectId,
6371 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6373 YAFFS_OBJECTID_LOSTNFOUND)) {
6374 /* We only load some info, don't fiddle with directory structure */
6378 in->variantType = oh->type;
6380 in->yst_mode = oh->yst_mode;
6381 #ifdef CONFIG_YAFFS_WINCE
6382 in->win_atime[0] = oh->win_atime[0];
6383 in->win_ctime[0] = oh->win_ctime[0];
6384 in->win_mtime[0] = oh->win_mtime[0];
6385 in->win_atime[1] = oh->win_atime[1];
6386 in->win_ctime[1] = oh->win_ctime[1];
6387 in->win_mtime[1] = oh->win_mtime[1];
6389 in->yst_uid = oh->yst_uid;
6390 in->yst_gid = oh->yst_gid;
6391 in->yst_atime = oh->yst_atime;
6392 in->yst_mtime = oh->yst_mtime;
6393 in->yst_ctime = oh->yst_ctime;
6394 in->yst_rdev = oh->yst_rdev;
6398 in->variantType = tags.extraObjectType;
6402 in->hdrChunk = chunk;
6404 } else if (!in->valid) {
6405 /* we need to load this info */
6408 in->hdrChunk = chunk;
6411 in->variantType = oh->type;
6413 in->yst_mode = oh->yst_mode;
6414 #ifdef CONFIG_YAFFS_WINCE
6415 in->win_atime[0] = oh->win_atime[0];
6416 in->win_ctime[0] = oh->win_ctime[0];
6417 in->win_mtime[0] = oh->win_mtime[0];
6418 in->win_atime[1] = oh->win_atime[1];
6419 in->win_ctime[1] = oh->win_ctime[1];
6420 in->win_mtime[1] = oh->win_mtime[1];
6422 in->yst_uid = oh->yst_uid;
6423 in->yst_gid = oh->yst_gid;
6424 in->yst_atime = oh->yst_atime;
6425 in->yst_mtime = oh->yst_mtime;
6426 in->yst_ctime = oh->yst_ctime;
6427 in->yst_rdev = oh->yst_rdev;
6430 if (oh->shadowsObject > 0)
6431 yaffs_HandleShadowedObject(dev,
6437 yaffs_SetObjectName(in, oh->name);
6439 yaffs_FindOrCreateObjectByNumber
6440 (dev, oh->parentObjectId,
6441 YAFFS_OBJECT_TYPE_DIRECTORY);
6443 fileSize = oh->fileSize;
6444 isShrink = oh->isShrink;
6445 equivalentObjectId = oh->equivalentObjectId;
6448 in->variantType = tags.extraObjectType;
6450 yaffs_FindOrCreateObjectByNumber
6451 (dev, tags.extraParentObjectId,
6452 YAFFS_OBJECT_TYPE_DIRECTORY);
6453 fileSize = tags.extraFileLength;
6454 isShrink = tags.extraIsShrinkHeader;
6455 equivalentObjectId = tags.extraEquivalentObjectId;
6464 /* directory stuff...
6468 if (parent && parent->variantType ==
6469 YAFFS_OBJECT_TYPE_UNKNOWN) {
6470 /* Set up as a directory */
6471 parent->variantType =
6472 YAFFS_OBJECT_TYPE_DIRECTORY;
6473 YINIT_LIST_HEAD(&parent->variant.
6476 } else if (!parent || parent->variantType !=
6477 YAFFS_OBJECT_TYPE_DIRECTORY) {
6478 /* Hoosterman, another problem....
6479 * We're trying to use a non-directory as a directory
6482 T(YAFFS_TRACE_ERROR,
6484 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6486 parent = dev->lostNFoundDir;
6489 yaffs_AddObjectToDirectory(parent, in);
6491 itsUnlinked = (parent == dev->deletedDir) ||
6492 (parent == dev->unlinkedDir);
6495 /* Mark the block as having a shrinkHeader */
6496 bi->hasShrinkHeader = 1;
6499 /* Note re hardlinks.
6500 * Since we might scan a hardlink before its equivalent object is scanned
6501 * we put them all in a list.
6502 * After scanning is complete, we should have all the objects, so we run
6503 * through this list and fix up all the chains.
6506 switch (in->variantType) {
6507 case YAFFS_OBJECT_TYPE_UNKNOWN:
6508 /* Todo got a problem */
6510 case YAFFS_OBJECT_TYPE_FILE:
6512 if (in->variant.fileVariant.
6513 scannedFileSize < fileSize) {
6514 /* This covers the case where the file size is greater
6515 * than where the data is
6516 * This will happen if the file is resized to be larger
6517 * than its current data extents.
6519 in->variant.fileVariant.fileSize = fileSize;
6520 in->variant.fileVariant.scannedFileSize =
6521 in->variant.fileVariant.fileSize;
6525 in->variant.fileVariant.shrinkSize > fileSize) {
6526 in->variant.fileVariant.shrinkSize = fileSize;
6530 case YAFFS_OBJECT_TYPE_HARDLINK:
6532 in->variant.hardLinkVariant.equivalentObjectId =
6534 in->hardLinks.next =
6535 (struct ylist_head *) hardList;
6539 case YAFFS_OBJECT_TYPE_DIRECTORY:
6542 case YAFFS_OBJECT_TYPE_SPECIAL:
6545 case YAFFS_OBJECT_TYPE_SYMLINK:
6547 in->variant.symLinkVariant.alias =
6548 yaffs_CloneString(oh->alias);
6549 if (!in->variant.symLinkVariant.alias)
6559 } /* End of scanning for each chunk */
6561 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6562 /* If we got this far while scanning, then the block is fully allocated. */
6563 state = YAFFS_BLOCK_STATE_FULL;
6566 bi->blockState = state;
6568 /* Now let's see if it was dirty */
6569 if (bi->pagesInUse == 0 &&
6570 !bi->hasShrinkHeader &&
6571 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6572 yaffs_BlockBecameDirty(dev, blk);
6578 YFREE_ALT(blockIndex);
6582 /* Ok, we've done all the scanning.
6583 * Fix up the hard link chains.
6584 * We should now have scanned all the objects, now it's time to add these
6587 yaffs_HardlinkFixup(dev, hardList);
6590 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6595 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6600 /*------------------------------ Directory Functions ----------------------------- */
6602 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
6604 struct ylist_head *lh;
6605 yaffs_Object *listObj;
6610 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
6615 if (yaffs_SkipVerification(obj->myDev))
6619 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
6624 if (obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6625 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
6629 /* Iterate through the objects in each hash entry */
6631 ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
6633 listObj = ylist_entry(lh, yaffs_Object, siblings);
6634 yaffs_VerifyObject(listObj);
6641 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR), count));
6646 static void yaffs_VerifyDirectory(yaffs_Object *directory)
6648 struct ylist_head *lh;
6649 yaffs_Object *listObj;
6656 if (yaffs_SkipFullVerification(directory->myDev))
6659 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6660 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR), directory->variantType));
6664 /* Iterate through the objects in each hash entry */
6666 ylist_for_each(lh, &directory->variant.directoryVariant.children) {
6668 listObj = ylist_entry(lh, yaffs_Object, siblings);
6669 if (listObj->parent != directory) {
6670 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR), listObj->parent));
6673 yaffs_VerifyObjectInDirectory(listObj);
6679 *yaffs_UpdateParent() handles fixing a directories mtime and ctime when a new
6680 * link (ie. name) is created or deleted in the directory.
6683 * create dir/a : update dir's mtime/ctime
6684 * rm dir/a: update dir's mtime/ctime
6685 * modify dir/a: don't update dir's mtimme/ctime
6688 static void yaffs_UpdateParent(yaffs_Object *obj)
6694 obj->yst_mtime = obj->yst_ctime = Y_CURRENT_TIME;
6696 yaffs_UpdateObjectHeader(obj,NULL,0,0,0);
6699 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
6701 yaffs_Device *dev = obj->myDev;
6702 yaffs_Object *parent;
6704 yaffs_VerifyObjectInDirectory(obj);
6705 parent = obj->parent;
6707 yaffs_VerifyDirectory(parent);
6709 if (dev && dev->removeObjectCallback)
6710 dev->removeObjectCallback(obj);
6713 ylist_del_init(&obj->siblings);
6716 yaffs_VerifyDirectory(parent);
6719 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
6723 T(YAFFS_TRACE_ALWAYS,
6725 ("tragedy: Trying to add an object to a null pointer directory"
6730 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6731 T(YAFFS_TRACE_ALWAYS,
6733 ("tragedy: Trying to add an object to a non-directory"
6738 if (obj->siblings.prev == NULL) {
6739 /* Not initialised */
6744 yaffs_VerifyDirectory(directory);
6746 yaffs_RemoveObjectFromDirectory(obj);
6750 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
6751 obj->parent = directory;
6753 if (directory == obj->myDev->unlinkedDir
6754 || directory == obj->myDev->deletedDir) {
6756 obj->myDev->nUnlinkedFiles++;
6757 obj->renameAllowed = 0;
6760 yaffs_VerifyDirectory(directory);
6761 yaffs_VerifyObjectInDirectory(obj);
6764 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
6769 struct ylist_head *i;
6770 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
6778 T(YAFFS_TRACE_ALWAYS,
6780 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6785 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6786 T(YAFFS_TRACE_ALWAYS,
6788 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6792 sum = yaffs_CalcNameSum(name);
6794 ylist_for_each(i, &directory->variant.directoryVariant.children) {
6796 l = ylist_entry(i, yaffs_Object, siblings);
6798 if (l->parent != directory)
6801 yaffs_CheckObjectDetailsLoaded(l);
6803 /* Special case for lost-n-found */
6804 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6805 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
6807 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
6808 /* LostnFound chunk called Objxxx
6811 yaffs_GetObjectName(l, buffer,
6812 YAFFS_MAX_NAME_LENGTH);
6813 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
6824 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
6825 int (*fn) (yaffs_Object *))
6827 struct ylist_head *i;
6831 T(YAFFS_TRACE_ALWAYS,
6833 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6838 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6839 T(YAFFS_TRACE_ALWAYS,
6841 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6846 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
6848 l = ylist_entry(i, yaffs_Object, siblings);
6859 /* GetEquivalentObject dereferences any hard links to get to the
6863 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
6865 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
6866 /* We want the object id of the equivalent object, not this one */
6867 obj = obj->variant.hardLinkVariant.equivalentObject;
6868 yaffs_CheckObjectDetailsLoaded(obj);
6873 int yaffs_GetObjectName(yaffs_Object *obj, YCHAR *name, int buffSize)
6875 memset(name, 0, buffSize * sizeof(YCHAR));
6877 yaffs_CheckObjectDetailsLoaded(obj);
6879 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6880 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
6881 } else if (obj->hdrChunk <= 0) {
6883 YCHAR numString[20];
6884 YCHAR *x = &numString[19];
6885 unsigned v = obj->objectId;
6889 *x = '0' + (v % 10);
6892 /* make up a name */
6893 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
6894 yaffs_strcat(locName, x);
6895 yaffs_strncpy(name, locName, buffSize - 1);
6898 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
6899 else if (obj->shortName[0])
6900 yaffs_strcpy(name, obj->shortName);
6904 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
6906 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
6908 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
6910 if (obj->hdrChunk > 0) {
6911 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
6912 obj->hdrChunk, buffer,
6915 yaffs_strncpy(name, oh->name, buffSize - 1);
6917 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
6920 return yaffs_strlen(name);
6923 int yaffs_GetObjectFileLength(yaffs_Object *obj)
6925 /* Dereference any hard linking */
6926 obj = yaffs_GetEquivalentObject(obj);
6928 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
6929 return obj->variant.fileVariant.fileSize;
6930 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
6931 return yaffs_strlen(obj->variant.symLinkVariant.alias);
6933 /* Only a directory should drop through to here */
6934 return obj->myDev->nDataBytesPerChunk;
6938 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
6941 struct ylist_head *i;
6944 count++; /* the object itself */
6946 ylist_for_each(i, &obj->hardLinks)
6947 count++; /* add the hard links; */
6952 int yaffs_GetObjectInode(yaffs_Object *obj)
6954 obj = yaffs_GetEquivalentObject(obj);
6956 return obj->objectId;
6959 unsigned yaffs_GetObjectType(yaffs_Object *obj)
6961 obj = yaffs_GetEquivalentObject(obj);
6963 switch (obj->variantType) {
6964 case YAFFS_OBJECT_TYPE_FILE:
6967 case YAFFS_OBJECT_TYPE_DIRECTORY:
6970 case YAFFS_OBJECT_TYPE_SYMLINK:
6973 case YAFFS_OBJECT_TYPE_HARDLINK:
6976 case YAFFS_OBJECT_TYPE_SPECIAL:
6977 if (S_ISFIFO(obj->yst_mode))
6979 if (S_ISCHR(obj->yst_mode))
6981 if (S_ISBLK(obj->yst_mode))
6983 if (S_ISSOCK(obj->yst_mode))
6991 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
6993 obj = yaffs_GetEquivalentObject(obj);
6994 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
6995 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
6997 return yaffs_CloneString(_Y(""));
7000 #ifndef CONFIG_YAFFS_WINCE
7002 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
7004 unsigned int valid = attr->ia_valid;
7006 if (valid & ATTR_MODE)
7007 obj->yst_mode = attr->ia_mode;
7008 if (valid & ATTR_UID)
7009 obj->yst_uid = attr->ia_uid;
7010 if (valid & ATTR_GID)
7011 obj->yst_gid = attr->ia_gid;
7013 if (valid & ATTR_ATIME)
7014 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7015 if (valid & ATTR_CTIME)
7016 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7017 if (valid & ATTR_MTIME)
7018 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7020 if (valid & ATTR_SIZE)
7021 yaffs_ResizeFile(obj, attr->ia_size);
7023 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7028 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
7030 unsigned int valid = 0;
7032 attr->ia_mode = obj->yst_mode;
7034 attr->ia_uid = obj->yst_uid;
7036 attr->ia_gid = obj->yst_gid;
7039 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7040 valid |= ATTR_ATIME;
7041 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7042 valid |= ATTR_CTIME;
7043 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7044 valid |= ATTR_MTIME;
7046 attr->ia_size = yaffs_GetFileSize(obj);
7049 attr->ia_valid = valid;
7057 int yaffs_DumpObject(yaffs_Object *obj)
7061 yaffs_GetObjectName(obj, name, 256);
7063 T(YAFFS_TRACE_ALWAYS,
7065 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7066 " chunk %d type %d size %d\n"
7067 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7068 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7069 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7075 /*---------------------------- Initialisation code -------------------------------------- */
7077 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
7080 /* Common functions, gotta have */
7081 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
7084 #ifdef CONFIG_YAFFS_YAFFS2
7086 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7087 if (dev->writeChunkWithTagsToNAND &&
7088 dev->readChunkWithTagsFromNAND &&
7089 !dev->writeChunkToNAND &&
7090 !dev->readChunkFromNAND &&
7091 dev->markNANDBlockBad && dev->queryNANDBlock)
7095 /* Can use the "spare" style interface for yaffs1 */
7096 if (!dev->isYaffs2 &&
7097 !dev->writeChunkWithTagsToNAND &&
7098 !dev->readChunkWithTagsFromNAND &&
7099 dev->writeChunkToNAND &&
7100 dev->readChunkFromNAND &&
7101 !dev->markNANDBlockBad && !dev->queryNANDBlock)
7108 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7110 /* Initialise the unlinked, deleted, root and lost and found directories */
7112 dev->lostNFoundDir = dev->rootDir = NULL;
7113 dev->unlinkedDir = dev->deletedDir = NULL;
7116 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7119 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7122 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7123 YAFFS_ROOT_MODE | S_IFDIR);
7124 dev->lostNFoundDir =
7125 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7126 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7128 if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
7129 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7136 int yaffs_GutsInitialise(yaffs_Device *dev)
7138 int init_failed = 0;
7142 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7144 /* Check stuff that must be set */
7147 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7151 dev->internalStartBlock = dev->startBlock;
7152 dev->internalEndBlock = dev->endBlock;
7153 dev->blockOffset = 0;
7154 dev->chunkOffset = 0;
7155 dev->nFreeChunks = 0;
7159 if (dev->startBlock == 0) {
7160 dev->internalStartBlock = dev->startBlock + 1;
7161 dev->internalEndBlock = dev->endBlock + 1;
7162 dev->blockOffset = 1;
7163 dev->chunkOffset = dev->nChunksPerBlock;
7166 /* Check geometry parameters. */
7168 if ((!dev->inbandTags && dev->isYaffs2 && dev->totalBytesPerChunk < 1024) ||
7169 (!dev->isYaffs2 && dev->totalBytesPerChunk < 512) ||
7170 (dev->inbandTags && !dev->isYaffs2) ||
7171 dev->nChunksPerBlock < 2 ||
7172 dev->nReservedBlocks < 2 ||
7173 dev->internalStartBlock <= 0 ||
7174 dev->internalEndBlock <= 0 ||
7175 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2)) { /* otherwise it is too small */
7176 T(YAFFS_TRACE_ALWAYS,
7178 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7179 TENDSTR), dev->totalBytesPerChunk, dev->isYaffs2 ? "2" : "", dev->inbandTags));
7183 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7184 T(YAFFS_TRACE_ALWAYS,
7185 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7189 /* Sort out space for inband tags, if required */
7190 if (dev->inbandTags)
7191 dev->nDataBytesPerChunk = dev->totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7193 dev->nDataBytesPerChunk = dev->totalBytesPerChunk;
7195 /* Got the right mix of functions? */
7196 if (!yaffs_CheckDevFunctions(dev)) {
7197 /* Function missing */
7198 T(YAFFS_TRACE_ALWAYS,
7200 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7205 /* This is really a compilation check. */
7206 if (!yaffs_CheckStructures()) {
7207 T(YAFFS_TRACE_ALWAYS,
7208 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7212 if (dev->isMounted) {
7213 T(YAFFS_TRACE_ALWAYS,
7214 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7218 /* Finished with most checks. One or two more checks happen later on too. */
7222 /* OK now calculate a few things for the device */
7225 * Calculate all the chunk size manipulation numbers:
7227 x = dev->nDataBytesPerChunk;
7228 /* We always use dev->chunkShift and dev->chunkDiv */
7229 dev->chunkShift = Shifts(x);
7230 x >>= dev->chunkShift;
7232 /* We only use chunk mask if chunkDiv is 1 */
7233 dev->chunkMask = (1<<dev->chunkShift) - 1;
7236 * Calculate chunkGroupBits.
7237 * We need to find the next power of 2 > than internalEndBlock
7240 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7244 /* Set up tnode width if wide tnodes are enabled. */
7245 if (!dev->wideTnodesDisabled) {
7246 /* bits must be even so that we end up with 32-bit words */
7250 dev->tnodeWidth = 16;
7252 dev->tnodeWidth = bits;
7254 dev->tnodeWidth = 16;
7256 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7258 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7259 * so if the bitwidth of the
7260 * chunk range we're using is greater than 16 we need
7261 * to figure out chunk shift and chunkGroupSize
7264 if (bits <= dev->tnodeWidth)
7265 dev->chunkGroupBits = 0;
7267 dev->chunkGroupBits = bits - dev->tnodeWidth;
7270 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7272 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7273 /* We have a problem because the soft delete won't work if
7274 * the chunk group size > chunks per block.
7275 * This can be remedied by using larger "virtual blocks".
7277 T(YAFFS_TRACE_ALWAYS,
7278 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7283 /* OK, we've finished verifying the device, lets continue with initialisation */
7285 /* More device initialisation */
7286 dev->garbageCollections = 0;
7287 dev->passiveGarbageCollections = 0;
7288 dev->currentDirtyChecker = 0;
7289 dev->bufferedBlock = -1;
7290 dev->doingBufferedBlockRewrite = 0;
7291 dev->nDeletedFiles = 0;
7292 dev->nBackgroundDeletions = 0;
7293 dev->nUnlinkedFiles = 0;
7295 dev->eccUnfixed = 0;
7296 dev->tagsEccFixed = 0;
7297 dev->tagsEccUnfixed = 0;
7298 dev->nErasureFailures = 0;
7299 dev->nErasedBlocks = 0;
7301 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7303 /* Initialise temporary buffers and caches. */
7304 if (!yaffs_InitialiseTempBuffers(dev))
7307 dev->srCache = NULL;
7308 dev->gcCleanupList = NULL;
7312 dev->nShortOpCaches > 0) {
7315 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7317 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
7318 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7320 dev->srCache = YMALLOC(srCacheBytes);
7322 buf = (__u8 *) dev->srCache;
7325 memset(dev->srCache, 0, srCacheBytes);
7327 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7328 dev->srCache[i].object = NULL;
7329 dev->srCache[i].lastUse = 0;
7330 dev->srCache[i].dirty = 0;
7331 dev->srCache[i].data = buf = YMALLOC_DMA(dev->totalBytesPerChunk);
7342 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7343 if (!dev->gcCleanupList)
7348 dev->useHeaderFileSize = 1;
7350 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7353 yaffs_InitialiseTnodes(dev);
7354 yaffs_InitialiseObjects(dev);
7356 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7361 /* Now scan the flash. */
7362 if (dev->isYaffs2) {
7363 if (yaffs_CheckpointRestore(dev)) {
7364 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7365 T(YAFFS_TRACE_ALWAYS,
7366 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7369 /* Clean up the mess caused by an aborted checkpoint load
7370 * and scan backwards.
7372 yaffs_DeinitialiseBlocks(dev);
7373 yaffs_DeinitialiseTnodes(dev);
7374 yaffs_DeinitialiseObjects(dev);
7377 dev->nErasedBlocks = 0;
7378 dev->nFreeChunks = 0;
7379 dev->allocationBlock = -1;
7380 dev->allocationPage = -1;
7381 dev->nDeletedFiles = 0;
7382 dev->nUnlinkedFiles = 0;
7383 dev->nBackgroundDeletions = 0;
7384 dev->oldestDirtySequence = 0;
7386 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7389 yaffs_InitialiseTnodes(dev);
7390 yaffs_InitialiseObjects(dev);
7392 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7395 if (!init_failed && !yaffs_ScanBackwards(dev))
7398 } else if (!yaffs_Scan(dev))
7401 yaffs_StripDeletedObjects(dev);
7405 /* Clean up the mess */
7406 T(YAFFS_TRACE_TRACING,
7407 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7409 yaffs_Deinitialise(dev);
7413 /* Zero out stats */
7414 dev->nPageReads = 0;
7415 dev->nPageWrites = 0;
7416 dev->nBlockErasures = 0;
7418 dev->nRetriedWrites = 0;
7420 dev->nRetiredBlocks = 0;
7422 yaffs_VerifyFreeChunks(dev);
7423 yaffs_VerifyBlocks(dev);
7426 T(YAFFS_TRACE_TRACING,
7427 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7432 void yaffs_Deinitialise(yaffs_Device *dev)
7434 if (dev->isMounted) {
7437 yaffs_DeinitialiseBlocks(dev);
7438 yaffs_DeinitialiseTnodes(dev);
7439 yaffs_DeinitialiseObjects(dev);
7440 if (dev->nShortOpCaches > 0 &&
7443 for (i = 0; i < dev->nShortOpCaches; i++) {
7444 if (dev->srCache[i].data)
7445 YFREE(dev->srCache[i].data);
7446 dev->srCache[i].data = NULL;
7449 YFREE(dev->srCache);
7450 dev->srCache = NULL;
7453 YFREE(dev->gcCleanupList);
7455 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
7456 YFREE(dev->tempBuffer[i].buffer);
7460 if (dev->deinitialiseNAND)
7461 dev->deinitialiseNAND(dev);
7465 static int yaffs_CountFreeChunks(yaffs_Device *dev)
7470 yaffs_BlockInfo *blk;
7472 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7474 blk = yaffs_GetBlockInfo(dev, b);
7476 switch (blk->blockState) {
7477 case YAFFS_BLOCK_STATE_EMPTY:
7478 case YAFFS_BLOCK_STATE_ALLOCATING:
7479 case YAFFS_BLOCK_STATE_COLLECTING:
7480 case YAFFS_BLOCK_STATE_FULL:
7482 (dev->nChunksPerBlock - blk->pagesInUse +
7483 blk->softDeletions);
7493 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
7495 /* This is what we report to the outside world */
7498 int nDirtyCacheChunks;
7499 int blocksForCheckpoint;
7503 nFree = dev->nFreeChunks;
7505 nFree = yaffs_CountFreeChunks(dev);
7508 nFree += dev->nDeletedFiles;
7510 /* Now count the number of dirty chunks in the cache and subtract those */
7512 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7513 if (dev->srCache[i].dirty)
7514 nDirtyCacheChunks++;
7517 nFree -= nDirtyCacheChunks;
7519 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7521 /* Now we figure out how much to reserve for the checkpoint and report that... */
7522 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7523 if (blocksForCheckpoint < 0)
7524 blocksForCheckpoint = 0;
7526 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7535 static int yaffs_freeVerificationFailures;
7537 static void yaffs_VerifyFreeChunks(yaffs_Device *dev)
7542 if (yaffs_SkipVerification(dev))
7545 counted = yaffs_CountFreeChunks(dev);
7547 difference = dev->nFreeChunks - counted;
7550 T(YAFFS_TRACE_ALWAYS,
7551 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7552 dev->nFreeChunks, counted, difference));
7553 yaffs_freeVerificationFailures++;
7557 /*---------------------------------------- YAFFS test code ----------------------*/
7559 #define yaffs_CheckStruct(structure, syze, name) \
7561 if (sizeof(structure) != syze) { \
7562 T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
7563 name, syze, sizeof(structure))); \
7564 return YAFFS_FAIL; \
7568 static int yaffs_CheckStructures(void)
7570 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
7571 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
7572 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
7573 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7574 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode");
7576 #ifndef CONFIG_YAFFS_WINCE
7577 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");