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.90 2009-09-23 23:24:55 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)) {
1549 if(dev->chunkGroupSize == 1)
1552 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1554 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1566 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1567 * chunks and tnodes in the file
1568 * Returns 1 if the tree was deleted.
1569 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1572 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
1573 int chunkOffset, int *limit)
1578 yaffs_ExtendedTags tags;
1580 yaffs_Device *dev = in->myDev;
1586 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1588 if (tn->internal[i]) {
1589 if (limit && (*limit) < 0) {
1593 yaffs_DeleteWorker(in,
1601 YAFFS_TNODES_INTERNAL_BITS)
1606 yaffs_FreeTnode(dev,
1609 tn->internal[i] = NULL;
1613 return (allDone) ? 1 : 0;
1614 } else if (level == 0) {
1617 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1619 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1622 chunkInInode = (chunkOffset <<
1623 YAFFS_TNODES_LEVEL0_BITS) + i;
1626 yaffs_FindChunkInGroup(dev,
1632 if (foundChunk > 0) {
1633 yaffs_DeleteChunk(dev,
1638 *limit = *limit - 1;
1645 yaffs_PutLevel0Tnode(dev, tn, i, 0);
1649 return (i < 0) ? 1 : 0;
1659 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1661 yaffs_BlockInfo *theBlock;
1663 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1665 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1667 theBlock->softDeletions++;
1672 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1673 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1675 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1678 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1679 __u32 level, int chunkOffset)
1684 yaffs_Device *dev = in->myDev;
1689 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1691 if (tn->internal[i]) {
1693 yaffs_SoftDeleteWorker(in,
1699 YAFFS_TNODES_INTERNAL_BITS)
1702 yaffs_FreeTnode(dev,
1705 tn->internal[i] = NULL;
1707 /* Hoosterman... how could this happen? */
1711 return (allDone) ? 1 : 0;
1712 } else if (level == 0) {
1714 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1715 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1717 /* Note this does not find the real chunk, only the chunk group.
1718 * We make an assumption that a chunk group is not larger than
1721 yaffs_SoftDeleteChunk(dev, theChunk);
1722 yaffs_PutLevel0Tnode(dev, tn, i, 0);
1736 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1739 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1740 if (obj->nDataChunks <= 0) {
1741 /* Empty file with no duplicate object headers, just delete it immediately */
1742 yaffs_FreeTnode(obj->myDev,
1743 obj->variant.fileVariant.top);
1744 obj->variant.fileVariant.top = NULL;
1745 T(YAFFS_TRACE_TRACING,
1746 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1748 yaffs_DoGenericObjectDeletion(obj);
1750 yaffs_SoftDeleteWorker(obj,
1751 obj->variant.fileVariant.top,
1752 obj->variant.fileVariant.
1754 obj->softDeleted = 1;
1759 /* Pruning removes any part of the file structure tree that is beyond the
1760 * bounds of the file (ie that does not point to chunks).
1762 * A file should only get pruned when its size is reduced.
1764 * Before pruning, the chunks must be pulled from the tree and the
1765 * level 0 tnode entries must be zeroed out.
1766 * Could also use this for file deletion, but that's probably better handled
1767 * by a special case.
1770 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1771 __u32 level, int del0)
1779 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1780 if (tn->internal[i] && level > 0) {
1782 yaffs_PruneWorker(dev, tn->internal[i],
1784 (i == 0) ? del0 : 1);
1787 if (tn->internal[i])
1791 if (hasData == 0 && del0) {
1792 /* Free and return NULL */
1794 yaffs_FreeTnode(dev, tn);
1804 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1805 yaffs_FileStructure *fStruct)
1812 if (fStruct->topLevel > 0) {
1814 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1816 /* Now we have a tree with all the non-zero branches NULL but the height
1817 * is the same as it was.
1818 * Let's see if we can trim internal tnodes to shorten the tree.
1819 * We can do this if only the 0th element in the tnode is in use
1820 * (ie all the non-zero are NULL)
1823 while (fStruct->topLevel && !done) {
1827 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1828 if (tn->internal[i])
1833 fStruct->top = tn->internal[0];
1834 fStruct->topLevel--;
1835 yaffs_FreeTnode(dev, tn);
1845 /*-------------------- End of File Structure functions.-------------------*/
1847 /* yaffs_CreateFreeObjects creates a bunch more objects and
1848 * adds them to the object free list.
1850 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1853 yaffs_Object *newObjects;
1854 yaffs_ObjectList *list;
1859 /* make these things */
1860 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1861 list = YMALLOC(sizeof(yaffs_ObjectList));
1863 if (!newObjects || !list) {
1868 T(YAFFS_TRACE_ALLOCATE,
1869 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1873 /* Hook them into the free list */
1874 for (i = 0; i < nObjects - 1; i++) {
1875 newObjects[i].siblings.next =
1876 (struct ylist_head *)(&newObjects[i + 1]);
1879 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1880 dev->freeObjects = newObjects;
1881 dev->nFreeObjects += nObjects;
1882 dev->nObjectsCreated += nObjects;
1884 /* Now add this bunch of Objects to a list for freeing up. */
1886 list->objects = newObjects;
1887 list->next = dev->allocatedObjectList;
1888 dev->allocatedObjectList = list;
1894 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1895 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1897 yaffs_Object *tn = NULL;
1899 #ifdef VALGRIND_TEST
1900 tn = YMALLOC(sizeof(yaffs_Object));
1902 /* If there are none left make more */
1903 if (!dev->freeObjects)
1904 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1906 if (dev->freeObjects) {
1907 tn = dev->freeObjects;
1909 (yaffs_Object *) (dev->freeObjects->siblings.next);
1910 dev->nFreeObjects--;
1914 /* Now sweeten it up... */
1916 memset(tn, 0, sizeof(yaffs_Object));
1917 tn->beingCreated = 1;
1921 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1922 YINIT_LIST_HEAD(&(tn->hardLinks));
1923 YINIT_LIST_HEAD(&(tn->hashLink));
1924 YINIT_LIST_HEAD(&tn->siblings);
1927 /* Now make the directory sane */
1929 tn->parent = dev->rootDir;
1930 ylist_add(&(tn->siblings), &dev->rootDir->variant.directoryVariant.children);
1933 /* Add it to the lost and found directory.
1934 * NB Can't put root or lostNFound in lostNFound so
1935 * check if lostNFound exists first
1937 if (dev->lostNFoundDir)
1938 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1940 tn->beingCreated = 0;
1943 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1948 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
1953 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1955 obj->fake = 1; /* it is fake so it might have no NAND presence... */
1956 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1957 obj->unlinkAllowed = 0; /* ... or unlink it */
1960 obj->yst_mode = mode;
1962 obj->hdrChunk = 0; /* Not a valid chunk. */
1969 static void yaffs_UnhashObject(yaffs_Object *tn)
1972 yaffs_Device *dev = tn->myDev;
1974 /* If it is still linked into the bucket list, free from the list */
1975 if (!ylist_empty(&tn->hashLink)) {
1976 ylist_del_init(&tn->hashLink);
1977 bucket = yaffs_HashFunction(tn->objectId);
1978 dev->objectBucket[bucket].count--;
1982 /* FreeObject frees up a Object and puts it back on the free list */
1983 static void yaffs_FreeObject(yaffs_Object *tn)
1985 yaffs_Device *dev = tn->myDev;
1988 T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), tn, tn->myInode));
1993 if (!ylist_empty(&tn->siblings))
1999 /* We're still hooked up to a cached inode.
2000 * Don't delete now, but mark for later deletion
2002 tn->deferedFree = 1;
2007 yaffs_UnhashObject(tn);
2009 #ifdef VALGRIND_TEST
2012 /* Link into the free list. */
2013 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2014 dev->freeObjects = tn;
2015 dev->nFreeObjects++;
2017 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2022 void yaffs_HandleDeferedFree(yaffs_Object *obj)
2024 if (obj->deferedFree)
2025 yaffs_FreeObject(obj);
2030 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
2032 /* Free the list of allocated Objects */
2034 yaffs_ObjectList *tmp;
2036 while (dev->allocatedObjectList) {
2037 tmp = dev->allocatedObjectList->next;
2038 YFREE(dev->allocatedObjectList->objects);
2039 YFREE(dev->allocatedObjectList);
2041 dev->allocatedObjectList = tmp;
2044 dev->freeObjects = NULL;
2045 dev->nFreeObjects = 0;
2048 static void yaffs_InitialiseObjects(yaffs_Device *dev)
2052 dev->allocatedObjectList = NULL;
2053 dev->freeObjects = NULL;
2054 dev->nFreeObjects = 0;
2056 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2057 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2058 dev->objectBucket[i].count = 0;
2062 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
2067 int lowest = 999999;
2069 /* First let's see if we can find one that's empty. */
2071 for (i = 0; i < 10 && lowest > 0; i++) {
2073 x %= YAFFS_NOBJECT_BUCKETS;
2074 if (dev->objectBucket[x].count < lowest) {
2075 lowest = dev->objectBucket[x].count;
2081 /* If we didn't find an empty list, then try
2082 * looking a bit further for a short one
2085 for (i = 0; i < 10 && lowest > 3; i++) {
2087 x %= YAFFS_NOBJECT_BUCKETS;
2088 if (dev->objectBucket[x].count < lowest) {
2089 lowest = dev->objectBucket[x].count;
2098 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
2100 int bucket = yaffs_FindNiceObjectBucket(dev);
2102 /* Now find an object value that has not already been taken
2103 * by scanning the list.
2107 struct ylist_head *i;
2109 __u32 n = (__u32) bucket;
2111 /* yaffs_CheckObjectHashSanity(); */
2115 n += YAFFS_NOBJECT_BUCKETS;
2116 if (1 || dev->objectBucket[bucket].count > 0) {
2117 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2118 /* If there is already one in the list */
2119 if (i && ylist_entry(i, yaffs_Object,
2120 hashLink)->objectId == n) {
2130 static void yaffs_HashObject(yaffs_Object *in)
2132 int bucket = yaffs_HashFunction(in->objectId);
2133 yaffs_Device *dev = in->myDev;
2135 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2136 dev->objectBucket[bucket].count++;
2139 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
2141 int bucket = yaffs_HashFunction(number);
2142 struct ylist_head *i;
2145 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2146 /* Look if it is in the list */
2148 in = ylist_entry(i, yaffs_Object, hashLink);
2149 if (in->objectId == number) {
2151 /* Don't tell the VFS about this one if it is defered free */
2152 if (in->deferedFree)
2164 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
2165 yaffs_ObjectType type)
2167 yaffs_Object *theObject;
2168 yaffs_Tnode *tn = NULL;
2171 number = yaffs_CreateNewObjectNumber(dev);
2173 theObject = yaffs_AllocateEmptyObject(dev);
2177 if (type == YAFFS_OBJECT_TYPE_FILE) {
2178 tn = yaffs_GetTnode(dev);
2180 yaffs_FreeObject(theObject);
2186 theObject->fake = 0;
2187 theObject->renameAllowed = 1;
2188 theObject->unlinkAllowed = 1;
2189 theObject->objectId = number;
2190 yaffs_HashObject(theObject);
2191 theObject->variantType = type;
2192 #ifdef CONFIG_YAFFS_WINCE
2193 yfsd_WinFileTimeNow(theObject->win_atime);
2194 theObject->win_ctime[0] = theObject->win_mtime[0] =
2195 theObject->win_atime[0];
2196 theObject->win_ctime[1] = theObject->win_mtime[1] =
2197 theObject->win_atime[1];
2201 theObject->yst_atime = theObject->yst_mtime =
2202 theObject->yst_ctime = Y_CURRENT_TIME;
2205 case YAFFS_OBJECT_TYPE_FILE:
2206 theObject->variant.fileVariant.fileSize = 0;
2207 theObject->variant.fileVariant.scannedFileSize = 0;
2208 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2209 theObject->variant.fileVariant.topLevel = 0;
2210 theObject->variant.fileVariant.top = tn;
2212 case YAFFS_OBJECT_TYPE_DIRECTORY:
2213 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2216 case YAFFS_OBJECT_TYPE_SYMLINK:
2217 case YAFFS_OBJECT_TYPE_HARDLINK:
2218 case YAFFS_OBJECT_TYPE_SPECIAL:
2219 /* No action required */
2221 case YAFFS_OBJECT_TYPE_UNKNOWN:
2222 /* todo this should not happen */
2230 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
2232 yaffs_ObjectType type)
2234 yaffs_Object *theObject = NULL;
2237 theObject = yaffs_FindObjectByNumber(dev, number);
2240 theObject = yaffs_CreateNewObject(dev, number, type);
2247 static YCHAR *yaffs_CloneString(const YCHAR *str)
2249 YCHAR *newStr = NULL;
2252 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2254 yaffs_strcpy(newStr, str);
2262 * Mknod (create) a new object.
2263 * equivalentObject only has meaning for a hard link;
2264 * aliasString only has meaning for a sumlink.
2265 * rdev only has meaning for devices (a subset of special objects)
2268 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2269 yaffs_Object *parent,
2274 yaffs_Object *equivalentObject,
2275 const YCHAR *aliasString, __u32 rdev)
2280 yaffs_Device *dev = parent->myDev;
2282 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2283 if (yaffs_FindObjectByName(parent, name))
2286 in = yaffs_CreateNewObject(dev, -1, type);
2291 if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2292 str = yaffs_CloneString(aliasString);
2294 yaffs_FreeObject(in);
2304 in->variantType = type;
2306 in->yst_mode = mode;
2308 #ifdef CONFIG_YAFFS_WINCE
2309 yfsd_WinFileTimeNow(in->win_atime);
2310 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2311 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2314 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2316 in->yst_rdev = rdev;
2320 in->nDataChunks = 0;
2322 yaffs_SetObjectName(in, name);
2325 yaffs_AddObjectToDirectory(parent, in);
2327 in->myDev = parent->myDev;
2330 case YAFFS_OBJECT_TYPE_SYMLINK:
2331 in->variant.symLinkVariant.alias = str;
2333 case YAFFS_OBJECT_TYPE_HARDLINK:
2334 in->variant.hardLinkVariant.equivalentObject =
2336 in->variant.hardLinkVariant.equivalentObjectId =
2337 equivalentObject->objectId;
2338 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2340 case YAFFS_OBJECT_TYPE_FILE:
2341 case YAFFS_OBJECT_TYPE_DIRECTORY:
2342 case YAFFS_OBJECT_TYPE_SPECIAL:
2343 case YAFFS_OBJECT_TYPE_UNKNOWN:
2348 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2349 /* Could not create the object header, fail the creation */
2350 yaffs_DeleteObject(in);
2354 yaffs_UpdateParent(parent);
2360 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
2361 __u32 mode, __u32 uid, __u32 gid)
2363 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2364 uid, gid, NULL, NULL, 0);
2367 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
2368 __u32 mode, __u32 uid, __u32 gid)
2370 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2371 mode, uid, gid, NULL, NULL, 0);
2374 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
2375 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2377 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2378 uid, gid, NULL, NULL, rdev);
2381 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
2382 __u32 mode, __u32 uid, __u32 gid,
2385 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2386 uid, gid, NULL, alias, 0);
2389 /* yaffs_Link returns the object id of the equivalent object.*/
2390 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
2391 yaffs_Object *equivalentObject)
2393 /* Get the real object in case we were fed a hard link as an equivalent object */
2394 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2396 if (yaffs_MknodObject
2397 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2398 equivalentObject, NULL, 0)) {
2399 return equivalentObject;
2406 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
2407 const YCHAR *newName, int force, int shadows)
2412 yaffs_Object *existingTarget;
2415 newDir = obj->parent; /* use the old directory */
2417 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2418 T(YAFFS_TRACE_ALWAYS,
2420 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2425 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2426 if (obj->myDev->isYaffs2)
2427 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2429 unlinkOp = (newDir == obj->myDev->unlinkedDir
2430 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2432 deleteOp = (newDir == obj->myDev->deletedDir);
2434 existingTarget = yaffs_FindObjectByName(newDir, newName);
2436 /* If the object is a file going into the unlinked directory,
2437 * then it is OK to just stuff it in since duplicate names are allowed.
2438 * else only proceed if the new name does not exist and if we're putting
2439 * it into a directory.
2446 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2447 yaffs_SetObjectName(obj, newName);
2450 yaffs_AddObjectToDirectory(newDir, obj);
2455 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2456 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows) >= 0)
2463 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
2464 yaffs_Object *newDir, const YCHAR *newName)
2466 yaffs_Object *obj = NULL;
2467 yaffs_Object *existingTarget = NULL;
2471 if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2473 if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2476 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2477 /* Special case for case insemsitive systems (eg. WinCE).
2478 * While look-up is case insensitive, the name isn't.
2479 * Therefore we might want to change x.txt to X.txt
2481 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
2485 else if (yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2489 obj = yaffs_FindObjectByName(oldDir, oldName);
2491 if (obj && obj->renameAllowed) {
2493 /* Now do the handling for an existing target, if there is one */
2495 existingTarget = yaffs_FindObjectByName(newDir, newName);
2496 if (existingTarget &&
2497 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2498 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2499 /* There is a target that is a non-empty directory, so we fail */
2500 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2501 } else if (existingTarget && existingTarget != obj) {
2502 /* Nuke the target first, using shadowing,
2503 * but only if it isn't the same object
2505 yaffs_ChangeObjectName(obj, newDir, newName, force,
2506 existingTarget->objectId);
2507 yaffs_UnlinkObject(existingTarget);
2509 yaffs_UpdateParent(oldDir);
2510 if(newDir != oldDir)
2511 yaffs_UpdateParent(newDir);
2513 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2518 /*------------------------- Block Management and Page Allocation ----------------*/
2520 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
2522 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2524 dev->blockInfo = NULL;
2525 dev->chunkBits = NULL;
2527 dev->allocationBlock = -1; /* force it to get a new one */
2529 /* If the first allocation strategy fails, thry the alternate one */
2530 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2531 if (!dev->blockInfo) {
2532 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2533 dev->blockInfoAlt = 1;
2535 dev->blockInfoAlt = 0;
2537 if (dev->blockInfo) {
2538 /* Set up dynamic blockinfo stuff. */
2539 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2540 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2541 if (!dev->chunkBits) {
2542 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2543 dev->chunkBitsAlt = 1;
2545 dev->chunkBitsAlt = 0;
2548 if (dev->blockInfo && dev->chunkBits) {
2549 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2550 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2557 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2559 if (dev->blockInfoAlt && dev->blockInfo)
2560 YFREE_ALT(dev->blockInfo);
2561 else if (dev->blockInfo)
2562 YFREE(dev->blockInfo);
2564 dev->blockInfoAlt = 0;
2566 dev->blockInfo = NULL;
2568 if (dev->chunkBitsAlt && dev->chunkBits)
2569 YFREE_ALT(dev->chunkBits);
2570 else if (dev->chunkBits)
2571 YFREE(dev->chunkBits);
2572 dev->chunkBitsAlt = 0;
2573 dev->chunkBits = NULL;
2576 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
2577 yaffs_BlockInfo *bi)
2584 return 1; /* disqualification only applies to yaffs2. */
2586 if (!bi->hasShrinkHeader)
2587 return 1; /* can gc */
2589 /* Find the oldest dirty sequence number if we don't know it and save it
2590 * so we don't have to keep recomputing it.
2592 if (!dev->oldestDirtySequence) {
2593 seq = dev->sequenceNumber;
2595 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2597 b = yaffs_GetBlockInfo(dev, i);
2598 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2599 (b->pagesInUse - b->softDeletions) <
2600 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2601 seq = b->sequenceNumber;
2604 dev->oldestDirtySequence = seq;
2607 /* Can't do gc of this block if there are any blocks older than this one that have
2610 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2613 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2614 * for garbage collection.
2617 static int yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
2620 int b = dev->currentDirtyChecker;
2626 int prioritised = 0;
2627 yaffs_BlockInfo *bi;
2628 int pendingPrioritisedExist = 0;
2630 /* First let's see if we need to grab a prioritised block */
2631 if (dev->hasPendingPrioritisedGCs) {
2632 for (i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++) {
2634 bi = yaffs_GetBlockInfo(dev, i);
2635 /* yaffs_VerifyBlock(dev,bi,i); */
2637 if (bi->gcPrioritise) {
2638 pendingPrioritisedExist = 1;
2639 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2640 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2641 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2644 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2649 if (!pendingPrioritisedExist) /* None found, so we can clear this */
2650 dev->hasPendingPrioritisedGCs = 0;
2653 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2655 * else (we're doing a leasurely gc), then we only bother to do this if the
2656 * block has only a few pages in use.
2659 dev->nonAggressiveSkip--;
2661 if (!aggressive && (dev->nonAggressiveSkip > 0))
2666 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2670 dev->internalEndBlock - dev->internalStartBlock + 1;
2673 dev->internalEndBlock - dev->internalStartBlock + 1;
2674 iterations = iterations / 16;
2675 if (iterations > 200)
2679 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2681 if (b < dev->internalStartBlock || b > dev->internalEndBlock)
2682 b = dev->internalStartBlock;
2684 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2685 T(YAFFS_TRACE_ERROR,
2686 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2690 bi = yaffs_GetBlockInfo(dev, b);
2692 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2693 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2694 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2696 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2700 dev->currentDirtyChecker = b;
2704 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2705 dev->nChunksPerBlock - pagesInUse, prioritised));
2708 dev->oldestDirtySequence = 0;
2711 dev->nonAggressiveSkip = 4;
2716 static void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
2718 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2722 /* If the block is still healthy erase it and mark as clean.
2723 * If the block has had a data failure, then retire it.
2726 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2727 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2728 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2730 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2732 if (!bi->needsRetiring) {
2733 yaffs_InvalidateCheckpoint(dev);
2734 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2736 dev->nErasureFailures++;
2737 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2738 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2743 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2745 for (i = 0; i < dev->nChunksPerBlock; i++) {
2746 if (!yaffs_CheckChunkErased
2747 (dev, blockNo * dev->nChunksPerBlock + i)) {
2748 T(YAFFS_TRACE_ERROR,
2750 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2751 TENDSTR), blockNo, i));
2757 /* Clean it up... */
2758 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2759 dev->nErasedBlocks++;
2761 bi->softDeletions = 0;
2762 bi->hasShrinkHeader = 0;
2763 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2764 bi->gcPrioritise = 0;
2765 yaffs_ClearChunkBits(dev, blockNo);
2767 T(YAFFS_TRACE_ERASE,
2768 (TSTR("Erased block %d" TENDSTR), blockNo));
2770 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2772 yaffs_RetireBlock(dev, blockNo);
2773 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2774 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2778 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2782 yaffs_BlockInfo *bi;
2784 if (dev->nErasedBlocks < 1) {
2785 /* Hoosterman we've got a problem.
2786 * Can't get space to gc
2788 T(YAFFS_TRACE_ERROR,
2789 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2794 /* Find an empty block. */
2796 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2797 dev->allocationBlockFinder++;
2798 if (dev->allocationBlockFinder < dev->internalStartBlock
2799 || dev->allocationBlockFinder > dev->internalEndBlock) {
2800 dev->allocationBlockFinder = dev->internalStartBlock;
2803 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2805 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2806 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2807 dev->sequenceNumber++;
2808 bi->sequenceNumber = dev->sequenceNumber;
2809 dev->nErasedBlocks--;
2810 T(YAFFS_TRACE_ALLOCATE,
2811 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2812 dev->allocationBlockFinder, dev->sequenceNumber,
2813 dev->nErasedBlocks));
2814 return dev->allocationBlockFinder;
2818 T(YAFFS_TRACE_ALWAYS,
2820 ("yaffs tragedy: no more erased blocks, but there should have been %d"
2821 TENDSTR), dev->nErasedBlocks));
2828 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2830 if (!dev->nCheckpointBlocksRequired &&
2832 /* Not a valid value so recalculate */
2835 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2838 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2840 if (tnodeSize < sizeof(yaffs_Tnode))
2841 tnodeSize = sizeof(yaffs_Tnode);
2843 nBytes += sizeof(yaffs_CheckpointValidity);
2844 nBytes += sizeof(yaffs_CheckpointDevice);
2845 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2846 nBytes += devBlocks * dev->chunkBitmapStride;
2847 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2848 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2849 nBytes += sizeof(yaffs_CheckpointValidity);
2850 nBytes += sizeof(__u32); /* checksum*/
2852 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2854 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2856 dev->nCheckpointBlocksRequired = nBlocks;
2859 return dev->nCheckpointBlocksRequired;
2863 * Check if there's space to allocate...
2864 * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2866 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev)
2869 int reservedBlocks = dev->nReservedBlocks;
2870 int checkpointBlocks;
2872 if (dev->isYaffs2) {
2873 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
2874 dev->blocksInCheckpoint;
2875 if (checkpointBlocks < 0)
2876 checkpointBlocks = 0;
2878 checkpointBlocks = 0;
2881 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2883 return (dev->nFreeChunks > reservedChunks);
2886 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
2887 yaffs_BlockInfo **blockUsedPtr)
2890 yaffs_BlockInfo *bi;
2892 if (dev->allocationBlock < 0) {
2893 /* Get next block to allocate off */
2894 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2895 dev->allocationPage = 0;
2898 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2899 /* Not enough space to allocate unless we're allowed to use the reserve. */
2903 if (dev->nErasedBlocks < dev->nReservedBlocks
2904 && dev->allocationPage == 0) {
2905 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2908 /* Next page please.... */
2909 if (dev->allocationBlock >= 0) {
2910 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2912 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2913 dev->allocationPage;
2915 yaffs_SetChunkBit(dev, dev->allocationBlock,
2916 dev->allocationPage);
2918 dev->allocationPage++;
2922 /* If the block is full set the state to full */
2923 if (dev->allocationPage >= dev->nChunksPerBlock) {
2924 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2925 dev->allocationBlock = -1;
2934 T(YAFFS_TRACE_ERROR,
2935 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2940 static int yaffs_GetErasedChunks(yaffs_Device *dev)
2944 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2946 if (dev->allocationBlock > 0)
2947 n += (dev->nChunksPerBlock - dev->allocationPage);
2953 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
2959 int retVal = YAFFS_OK;
2962 int isCheckpointBlock;
2966 int chunksBefore = yaffs_GetErasedChunks(dev);
2969 yaffs_ExtendedTags tags;
2971 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2973 yaffs_Object *object;
2975 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2978 T(YAFFS_TRACE_TRACING,
2979 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
2982 bi->hasShrinkHeader,
2985 /*yaffs_VerifyFreeChunks(dev); */
2987 if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
2988 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2990 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2992 /* Take off the number of soft deleted entries because
2993 * they're going to get really deleted during GC.
2995 if(dev->gcChunk == 0) /* first time through for this block */
2996 dev->nFreeChunks -= bi->softDeletions;
3000 if (isCheckpointBlock ||
3001 !yaffs_StillSomeChunkBits(dev, block)) {
3002 T(YAFFS_TRACE_TRACING,
3004 ("Collecting block %d that has no chunks in use" TENDSTR),
3006 yaffs_BlockBecameDirty(dev, block);
3009 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3011 yaffs_VerifyBlock(dev, bi, block);
3013 maxCopies = (wholeBlock) ? dev->nChunksPerBlock : 10;
3014 oldChunk = block * dev->nChunksPerBlock + dev->gcChunk;
3016 for (/* init already done */;
3017 retVal == YAFFS_OK &&
3018 dev->gcChunk < dev->nChunksPerBlock &&
3019 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
3021 dev->gcChunk++, oldChunk++) {
3022 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3024 /* This page is in use and might need to be copied off */
3030 yaffs_InitialiseTags(&tags);
3032 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3036 yaffs_FindObjectByNumber(dev,
3039 T(YAFFS_TRACE_GC_DETAIL,
3041 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3042 dev->gcChunk, tags.objectId, tags.chunkId,
3045 if (object && !yaffs_SkipVerification(dev)) {
3046 if (tags.chunkId == 0)
3047 matchingChunk = object->hdrChunk;
3048 else if (object->softDeleted)
3049 matchingChunk = oldChunk; /* Defeat the test */
3051 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
3053 if (oldChunk != matchingChunk)
3054 T(YAFFS_TRACE_ERROR,
3055 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3056 oldChunk, matchingChunk, tags.objectId, tags.chunkId));
3061 T(YAFFS_TRACE_ERROR,
3063 ("page %d in gc has no object: %d %d %d "
3065 tags.objectId, tags.chunkId, tags.byteCount));
3070 object->softDeleted &&
3071 tags.chunkId != 0) {
3072 /* Data chunk in a soft deleted file, throw it away
3073 * It's a soft deleted data chunk,
3074 * No need to copy this, just forget about it and
3075 * fix up the object.
3078 object->nDataChunks--;
3080 if (object->nDataChunks <= 0) {
3081 /* remeber to clean up the object */
3082 dev->gcCleanupList[cleanups] =
3088 /* Todo object && object->deleted && object->nDataChunks == 0 */
3089 /* Deleted object header with no data chunks.
3090 * Can be discarded and the file deleted.
3092 object->hdrChunk = 0;
3093 yaffs_FreeTnode(object->myDev,
3096 object->variant.fileVariant.top = NULL;
3097 yaffs_DoGenericObjectDeletion(object);
3099 } else if (object) {
3100 /* It's either a data chunk in a live file or
3101 * an ObjectHeader, so we're interested in it.
3102 * NB Need to keep the ObjectHeaders of deleted files
3103 * until the whole file has been deleted off
3105 tags.serialNumber++;
3109 if (tags.chunkId == 0) {
3110 /* It is an object Id,
3111 * We need to nuke the shrinkheader flags first
3112 * We no longer want the shrinkHeader flag since its work is done
3113 * and if it is left in place it will mess up scanning.
3116 yaffs_ObjectHeader *oh;
3117 oh = (yaffs_ObjectHeader *)buffer;
3119 tags.extraIsShrinkHeader = 0;
3121 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
3125 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3128 retVal = YAFFS_FAIL;
3131 /* Ok, now fix up the Tnodes etc. */
3133 if (tags.chunkId == 0) {
3135 object->hdrChunk = newChunk;
3136 object->serial = tags.serialNumber;
3138 /* It's a data chunk */
3139 yaffs_PutChunkIntoFile
3147 if (retVal == YAFFS_OK)
3148 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3153 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3156 /* Do any required cleanups */
3157 for (i = 0; i < cleanups; i++) {
3158 /* Time to delete the file too */
3160 yaffs_FindObjectByNumber(dev,
3161 dev->gcCleanupList[i]);
3163 yaffs_FreeTnode(dev,
3164 object->variant.fileVariant.
3166 object->variant.fileVariant.top = NULL;
3169 ("yaffs: About to finally delete object %d"
3170 TENDSTR), object->objectId));
3171 yaffs_DoGenericObjectDeletion(object);
3172 object->myDev->nDeletedFiles--;
3179 yaffs_VerifyCollectedBlock(dev, bi, block);
3181 chunksAfter = yaffs_GetErasedChunks(dev);
3182 if (chunksBefore >= chunksAfter) {
3185 ("gc did not increase free chunks before %d after %d"
3186 TENDSTR), chunksBefore, chunksAfter));
3189 /* If the gc completed then clear the current gcBlock so that we find another. */
3190 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING) {
3200 /* New garbage collector
3201 * If we're very low on erased blocks then we do aggressive garbage collection
3202 * otherwise we do "leasurely" garbage collection.
3203 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3204 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3206 * The idea is to help clear out space in a more spread-out manner.
3207 * Dunno if it really does anything useful.
3209 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
3213 int gcOk = YAFFS_OK;
3216 int checkpointBlockAdjust;
3218 if (dev->isDoingGC) {
3219 /* Bail out so we don't get recursive gc */
3223 /* This loop should pass the first time.
3224 * We'll only see looping here if the erase of the collected block fails.
3230 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3231 if (checkpointBlockAdjust < 0)
3232 checkpointBlockAdjust = 0;
3234 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3235 /* We need a block soon...*/
3238 /* We're in no hurry */
3242 if (dev->gcBlock <= 0) {
3243 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3247 block = dev->gcBlock;
3250 dev->garbageCollections++;
3252 dev->passiveGarbageCollections++;
3256 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3257 dev->nErasedBlocks, aggressive));
3259 gcOk = yaffs_GarbageCollectBlock(dev, block, aggressive);
3262 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3265 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3266 TENDSTR), dev->nErasedBlocks, maxTries, block));
3268 } while ((dev->nErasedBlocks < dev->nReservedBlocks) &&
3272 return aggressive ? gcOk : YAFFS_OK;
3275 /*------------------------- TAGS --------------------------------*/
3277 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
3280 return (tags->chunkId == chunkInObject &&
3281 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3286 /*-------------------- Data file manipulation -----------------*/
3288 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
3289 yaffs_ExtendedTags *tags)
3291 /*Get the Tnode, then get the level 0 offset chunk offset */
3294 yaffs_ExtendedTags localTags;
3297 yaffs_Device *dev = in->myDev;
3300 /* Passed a NULL, so use our own tags space */
3304 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3307 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3310 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3316 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
3317 yaffs_ExtendedTags *tags)
3319 /* Get the Tnode, then get the level 0 offset chunk offset */
3322 yaffs_ExtendedTags localTags;
3324 yaffs_Device *dev = in->myDev;
3328 /* Passed a NULL, so use our own tags space */
3332 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3336 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3339 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3342 /* Delete the entry in the filestructure (if found) */
3344 yaffs_PutLevel0Tnode(dev, tn, chunkInInode, 0);
3350 #ifdef YAFFS_PARANOID
3352 static int yaffs_CheckFileSanity(yaffs_Object *in)
3360 yaffs_Tags localTags;
3361 yaffs_Tags *tags = &localTags;
3365 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3368 objId = in->objectId;
3369 fSize = in->variant.fileVariant.fileSize;