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.103 2010-01-01 23:54:03 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,
116 static void yaffs_SkipRestOfBlock(yaffs_Device *dev);
117 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
120 yaffs_ExtendedTags *tags);
122 /* Function to calculate chunk and offset */
124 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut,
130 chunk = (__u32)(addr >> dev->chunkShift);
132 if (dev->chunkDiv == 1) {
133 /* easy power of 2 case */
134 offset = (__u32)(addr & dev->chunkMask);
136 /* Non power-of-2 case */
140 chunk /= dev->chunkDiv;
142 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
143 offset = (__u32)(addr - chunkBase);
150 /* Function to return the number of shifts for a power of 2 greater than or
151 * equal to the given number
152 * Note we don't try to cater for all possible numbers and this does not have to
153 * be hellishly efficient.
156 static __u32 ShiftsGE(__u32 x)
161 nShifts = extraBits = 0;
176 /* Function to return the number of shifts to get a 1 in bit 0
179 static __u32 Shifts(__u32 x)
199 * Temporary buffer manipulations.
202 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
205 __u8 *buf = (__u8 *)1;
207 memset(dev->tempBuffer, 0, sizeof(dev->tempBuffer));
209 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
210 dev->tempBuffer[i].line = 0; /* not in use */
211 dev->tempBuffer[i].buffer = buf =
212 YMALLOC_DMA(dev->totalBytesPerChunk);
215 return buf ? YAFFS_OK : YAFFS_FAIL;
218 __u8 *yaffs_GetTempBuffer(yaffs_Device *dev, int lineNo)
223 if (dev->tempInUse > dev->maxTemp)
224 dev->maxTemp = dev->tempInUse;
226 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
227 if (dev->tempBuffer[i].line == 0) {
228 dev->tempBuffer[i].line = lineNo;
229 if ((i + 1) > dev->maxTemp) {
230 dev->maxTemp = i + 1;
231 for (j = 0; j <= i; j++)
232 dev->tempBuffer[j].maxLine =
233 dev->tempBuffer[j].line;
236 return dev->tempBuffer[i].buffer;
240 T(YAFFS_TRACE_BUFFERS,
241 (TSTR("Out of temp buffers at line %d, other held by lines:"),
243 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
244 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
246 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
249 * If we got here then we have to allocate an unmanaged one
253 dev->unmanagedTempAllocations++;
254 return YMALLOC(dev->nDataBytesPerChunk);
258 void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer,
265 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
266 if (dev->tempBuffer[i].buffer == buffer) {
267 dev->tempBuffer[i].line = 0;
273 /* assume it is an unmanaged one. */
274 T(YAFFS_TRACE_BUFFERS,
275 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
278 dev->unmanagedTempDeallocations++;
284 * Determine if we have a managed buffer.
286 int yaffs_IsManagedTempBuffer(yaffs_Device *dev, const __u8 *buffer)
290 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
291 if (dev->tempBuffer[i].buffer == buffer)
295 for (i = 0; i < dev->nShortOpCaches; i++) {
296 if (dev->srCache[i].data == buffer)
300 if (buffer == dev->checkpointBuffer)
303 T(YAFFS_TRACE_ALWAYS,
304 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
311 * Chunk bitmap manipulations
314 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
316 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
318 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
322 return dev->chunkBits +
323 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
326 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
328 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
329 chunk < 0 || chunk >= dev->nChunksPerBlock) {
331 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),
337 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device *dev, int blk)
339 __u8 *blkBits = yaffs_BlockBits(dev, blk);
341 memset(blkBits, 0, dev->chunkBitmapStride);
344 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device *dev, int blk, int chunk)
346 __u8 *blkBits = yaffs_BlockBits(dev, blk);
348 yaffs_VerifyChunkBitId(dev, blk, chunk);
350 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
353 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device *dev, int blk, int chunk)
355 __u8 *blkBits = yaffs_BlockBits(dev, blk);
357 yaffs_VerifyChunkBitId(dev, blk, chunk);
359 blkBits[chunk / 8] |= (1 << (chunk & 7));
362 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device *dev, int blk, int chunk)
364 __u8 *blkBits = yaffs_BlockBits(dev, blk);
365 yaffs_VerifyChunkBitId(dev, blk, chunk);
367 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
370 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device *dev, int blk)
372 __u8 *blkBits = yaffs_BlockBits(dev, blk);
374 for (i = 0; i < dev->chunkBitmapStride; i++) {
382 static int yaffs_CountChunkBits(yaffs_Device *dev, int blk)
384 __u8 *blkBits = yaffs_BlockBits(dev, blk);
387 for (i = 0; i < dev->chunkBitmapStride; i++) {
404 static int yaffs_SkipVerification(yaffs_Device *dev)
406 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
409 static int yaffs_SkipFullVerification(yaffs_Device *dev)
411 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
414 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
416 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
419 static const char *blockStateName[] = {
432 static void yaffs_VerifyBlock(yaffs_Device *dev, yaffs_BlockInfo *bi, int n)
437 if (yaffs_SkipVerification(dev))
440 /* Report illegal runtime states */
441 if (bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
442 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has undefined state %d"TENDSTR), n, bi->blockState));
444 switch (bi->blockState) {
445 case YAFFS_BLOCK_STATE_UNKNOWN:
446 case YAFFS_BLOCK_STATE_SCANNING:
447 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
448 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has bad run-state %s"TENDSTR),
449 n, blockStateName[bi->blockState]));
452 /* Check pages in use and soft deletions are legal */
454 actuallyUsed = bi->pagesInUse - bi->softDeletions;
456 if (bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
457 bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
458 actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock)
459 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
460 n, bi->pagesInUse, bi->softDeletions));
463 /* Check chunk bitmap legal */
464 inUse = yaffs_CountChunkBits(dev, n);
465 if (inUse != bi->pagesInUse)
466 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
467 n, bi->pagesInUse, inUse));
469 /* Check that the sequence number is valid.
470 * Ten million is legal, but is very unlikely
473 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
474 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000))
475 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has suspect sequence number of %d"TENDSTR),
476 n, bi->sequenceNumber));
479 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev, yaffs_BlockInfo *bi,
482 yaffs_VerifyBlock(dev, bi, n);
484 /* After collection the block should be in the erased state */
485 /* This will need to change if we do partial gc */
487 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
488 bi->blockState != YAFFS_BLOCK_STATE_EMPTY) {
489 T(YAFFS_TRACE_ERROR, (TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
494 static void yaffs_VerifyBlocks(yaffs_Device *dev)
497 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
498 int nIllegalBlockStates = 0;
500 if (yaffs_SkipVerification(dev))
503 memset(nBlocksPerState, 0, sizeof(nBlocksPerState));
505 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
506 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, i);
507 yaffs_VerifyBlock(dev, bi, i);
509 if (bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
510 nBlocksPerState[bi->blockState]++;
512 nIllegalBlockStates++;
515 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
516 T(YAFFS_TRACE_VERIFY, (TSTR("Block summary"TENDSTR)));
518 T(YAFFS_TRACE_VERIFY, (TSTR("%d blocks have illegal states"TENDSTR), nIllegalBlockStates));
519 if (nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
520 T(YAFFS_TRACE_VERIFY, (TSTR("Too many allocating blocks"TENDSTR)));
522 for (i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
523 T(YAFFS_TRACE_VERIFY,
524 (TSTR("%s %d blocks"TENDSTR),
525 blockStateName[i], nBlocksPerState[i]));
527 if (dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
528 T(YAFFS_TRACE_VERIFY,
529 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
530 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
532 if (dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
533 T(YAFFS_TRACE_VERIFY,
534 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
535 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
537 if (nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
538 T(YAFFS_TRACE_VERIFY,
539 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
540 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
542 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
547 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
548 * case those tests will not be performed.
550 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
552 if (obj && yaffs_SkipVerification(obj->myDev))
555 if (!(tags && obj && oh)) {
556 T(YAFFS_TRACE_VERIFY,
557 (TSTR("Verifying object header tags %p obj %p oh %p"TENDSTR),
562 if (oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
563 oh->type > YAFFS_OBJECT_TYPE_MAX)
564 T(YAFFS_TRACE_VERIFY,
565 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
566 tags->objectId, oh->type));
568 if (tags->objectId != obj->objectId)
569 T(YAFFS_TRACE_VERIFY,
570 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
571 tags->objectId, obj->objectId));
575 * Check that the object's parent ids match if parentCheck requested.
577 * Tests do not apply to the root object.
580 if (parentCheck && tags->objectId > 1 && !obj->parent)
581 T(YAFFS_TRACE_VERIFY,
582 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
583 tags->objectId, oh->parentObjectId));
585 if (parentCheck && obj->parent &&
586 oh->parentObjectId != obj->parent->objectId &&
587 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
588 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
589 T(YAFFS_TRACE_VERIFY,
590 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
591 tags->objectId, oh->parentObjectId, obj->parent->objectId));
593 if (tags->objectId > 1 && oh->name[0] == 0) /* Null name */
594 T(YAFFS_TRACE_VERIFY,
595 (TSTR("Obj %d header name is NULL"TENDSTR),
598 if (tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
599 T(YAFFS_TRACE_VERIFY,
600 (TSTR("Obj %d header name is 0xFF"TENDSTR),
606 static int yaffs_VerifyTnodeWorker(yaffs_Object *obj, yaffs_Tnode *tn,
607 __u32 level, int chunkOffset)
610 yaffs_Device *dev = obj->myDev;
616 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
617 if (tn->internal[i]) {
618 ok = yaffs_VerifyTnodeWorker(obj,
621 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
624 } else if (level == 0) {
625 yaffs_ExtendedTags tags;
626 __u32 objectId = obj->objectId;
628 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
630 for (i = 0; i < YAFFS_NTNODES_LEVEL0; i++) {
631 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
634 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
635 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
636 if (tags.objectId != objectId || tags.chunkId != chunkOffset) {
637 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
638 objectId, chunkOffset, theChunk,
639 tags.objectId, tags.chunkId));
652 static void yaffs_VerifyFile(yaffs_Object *obj)
654 int requiredTallness;
660 yaffs_ExtendedTags tags;
667 if (yaffs_SkipVerification(obj->myDev))
671 objectId = obj->objectId;
673 /* Check file size is consistent with tnode depth */
674 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
675 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
676 requiredTallness = 0;
678 x >>= YAFFS_TNODES_INTERNAL_BITS;
682 actualTallness = obj->variant.fileVariant.topLevel;
684 if (requiredTallness > actualTallness)
685 T(YAFFS_TRACE_VERIFY,
686 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
687 obj->objectId, actualTallness, requiredTallness));
690 /* Check that the chunks in the tnode tree are all correct.
691 * We do this by scanning through the tnode tree and
692 * checking the tags for every chunk match.
695 if (yaffs_SkipNANDVerification(dev))
698 for (i = 1; i <= lastChunk; i++) {
699 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant, i);
702 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
704 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
705 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
706 if (tags.objectId != objectId || tags.chunkId != i) {
707 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
708 objectId, i, theChunk,
709 tags.objectId, tags.chunkId));
717 static void yaffs_VerifyHardLink(yaffs_Object *obj)
719 if (obj && yaffs_SkipVerification(obj->myDev))
722 /* Verify sane equivalent object */
725 static void yaffs_VerifySymlink(yaffs_Object *obj)
727 if (obj && yaffs_SkipVerification(obj->myDev))
730 /* Verify symlink string */
733 static void yaffs_VerifySpecial(yaffs_Object *obj)
735 if (obj && yaffs_SkipVerification(obj->myDev))
739 static void yaffs_VerifyObject(yaffs_Object *obj)
748 __u32 chunkShouldNotBeDeleted;
754 if (obj->beingCreated)
759 if (yaffs_SkipVerification(dev))
762 /* Check sane object header chunk */
764 chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
765 chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
767 chunkInRange = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
768 chunkIdOk = chunkInRange || (obj->hdrChunk == 0);
769 chunkValid = chunkInRange &&
770 yaffs_CheckChunkBit(dev,
771 obj->hdrChunk / dev->nChunksPerBlock,
772 obj->hdrChunk % dev->nChunksPerBlock);
773 chunkShouldNotBeDeleted = chunkInRange && !chunkValid;
776 (!chunkIdOk || chunkShouldNotBeDeleted)) {
777 T(YAFFS_TRACE_VERIFY,
778 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
779 obj->objectId, obj->hdrChunk,
780 chunkIdOk ? "" : ",out of range",
781 chunkShouldNotBeDeleted ? ",marked as deleted" : ""));
784 if (chunkValid && !yaffs_SkipNANDVerification(dev)) {
785 yaffs_ExtendedTags tags;
786 yaffs_ObjectHeader *oh;
787 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
789 oh = (yaffs_ObjectHeader *)buffer;
791 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk, buffer,
794 yaffs_VerifyObjectHeader(obj, oh, &tags, 1);
796 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
799 /* Verify it has a parent */
800 if (obj && !obj->fake &&
801 (!obj->parent || obj->parent->myDev != dev)) {
802 T(YAFFS_TRACE_VERIFY,
803 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
804 obj->objectId, obj->parent));
807 /* Verify parent is a directory */
808 if (obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
809 T(YAFFS_TRACE_VERIFY,
810 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
811 obj->objectId, obj->parent->variantType));
814 switch (obj->variantType) {
815 case YAFFS_OBJECT_TYPE_FILE:
816 yaffs_VerifyFile(obj);
818 case YAFFS_OBJECT_TYPE_SYMLINK:
819 yaffs_VerifySymlink(obj);
821 case YAFFS_OBJECT_TYPE_DIRECTORY:
822 yaffs_VerifyDirectory(obj);
824 case YAFFS_OBJECT_TYPE_HARDLINK:
825 yaffs_VerifyHardLink(obj);
827 case YAFFS_OBJECT_TYPE_SPECIAL:
828 yaffs_VerifySpecial(obj);
830 case YAFFS_OBJECT_TYPE_UNKNOWN:
832 T(YAFFS_TRACE_VERIFY,
833 (TSTR("Obj %d has illegaltype %d"TENDSTR),
834 obj->objectId, obj->variantType));
839 static void yaffs_VerifyObjects(yaffs_Device *dev)
843 struct ylist_head *lh;
845 if (yaffs_SkipVerification(dev))
848 /* Iterate through the objects in each hash entry */
850 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
851 ylist_for_each(lh, &dev->objectBucket[i].list) {
853 obj = ylist_entry(lh, yaffs_Object, hashLink);
854 yaffs_VerifyObject(obj);
862 * Simple hash function. Needs to have a reasonable spread
865 static Y_INLINE int yaffs_HashFunction(int n)
868 return n % YAFFS_NOBJECT_BUCKETS;
872 * Access functions to useful fake objects.
873 * Note that root might have a presence in NAND if permissions are set.
876 yaffs_Object *yaffs_Root(yaffs_Device *dev)
881 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
883 return dev->lostNFoundDir;
888 * Erased NAND checking functions
891 int yaffs_CheckFF(__u8 *buffer, int nBytes)
893 /* Horrible, slow implementation */
902 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
905 int retval = YAFFS_OK;
906 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
907 yaffs_ExtendedTags tags;
910 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
912 if (tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
915 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
916 T(YAFFS_TRACE_NANDACCESS,
917 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
921 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
928 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
931 yaffs_ExtendedTags *tags)
933 int retval = YAFFS_OK;
934 yaffs_ExtendedTags tempTags;
935 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
938 result = yaffs_ReadChunkWithTagsFromNAND(dev,chunkInNAND,buffer,&tempTags);
939 if(memcmp(buffer,data,dev->nDataBytesPerChunk) ||
940 tempTags.objectId != tags->objectId ||
941 tempTags.chunkId != tags->chunkId ||
942 tempTags.byteCount != tags->byteCount)
945 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
950 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
952 yaffs_ExtendedTags *tags,
959 yaffs_InvalidateCheckpoint(dev);
962 yaffs_BlockInfo *bi = 0;
965 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
971 /* First check this chunk is erased, if it needs
972 * checking. The checking policy (unless forced
973 * always on) is as follows:
975 * Check the first page we try to write in a block.
976 * If the check passes then we don't need to check any
977 * more. If the check fails, we check again...
978 * If the block has been erased, we don't need to check.
980 * However, if the block has been prioritised for gc,
981 * then we think there might be something odd about
982 * this block and stop using it.
984 * Rationale: We should only ever see chunks that have
985 * not been erased if there was a partially written
986 * chunk due to power loss. This checking policy should
987 * catch that case with very few checks and thus save a
988 * lot of checks that are most likely not needed.
991 * If an erase check fails or the write fails we skip the
995 /* let's give it a try */
998 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
999 bi->skipErasedCheck = 0;
1001 if (!bi->skipErasedCheck) {
1002 erasedOk = yaffs_CheckChunkErased(dev, chunk);
1003 if (erasedOk != YAFFS_OK) {
1004 T(YAFFS_TRACE_ERROR,
1005 (TSTR("**>> yaffs chunk %d was not erased"
1008 /* If not erased, delete this one,
1009 * skip rest of block and
1010 * try another chunk */
1011 yaffs_DeleteChunk(dev,chunk,1,__LINE__);
1012 yaffs_SkipRestOfBlock(dev);
1017 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
1020 if(!bi->skipErasedCheck)
1021 writeOk = yaffs_VerifyChunkWritten(dev, chunk, data, tags);
1023 if (writeOk != YAFFS_OK) {
1024 /* Clean up aborted write, skip to next block and
1025 * try another chunk */
1026 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
1030 bi->skipErasedCheck = 1;
1032 /* Copy the data into the robustification buffer */
1033 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1035 } while (writeOk != YAFFS_OK &&
1036 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1042 T(YAFFS_TRACE_ERROR,
1043 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1046 dev->nRetriedWrites += (attempts - 1);
1053 * Block retiring for handling a broken block.
1056 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND)
1058 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1060 yaffs_InvalidateCheckpoint(dev);
1062 if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
1063 if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
1064 T(YAFFS_TRACE_ALWAYS, (TSTR(
1065 "yaffs: Failed to mark bad and erase block %d"
1066 TENDSTR), blockInNAND));
1068 yaffs_ExtendedTags tags;
1069 int chunkId = blockInNAND * dev->nChunksPerBlock;
1071 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
1073 memset(buffer, 0xff, dev->nDataBytesPerChunk);
1074 yaffs_InitialiseTags(&tags);
1075 tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
1076 if (dev->writeChunkWithTagsToNAND(dev, chunkId -
1077 dev->chunkOffset, buffer, &tags) != YAFFS_OK)
1078 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
1079 TCONT("write bad block marker to block %d")
1080 TENDSTR), blockInNAND));
1082 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
1086 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1087 bi->gcPrioritise = 0;
1088 bi->needsRetiring = 0;
1090 dev->nRetiredBlocks++;
1094 * Functions for robustisizing TODO
1098 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
1100 const yaffs_ExtendedTags *tags)
1104 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
1105 const yaffs_ExtendedTags *tags)
1109 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1111 if (!bi->gcPrioritise) {
1112 bi->gcPrioritise = 1;
1113 dev->hasPendingPrioritisedGCs = 1;
1114 bi->chunkErrorStrikes++;
1116 if (bi->chunkErrorStrikes > 3) {
1117 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1118 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1124 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
1127 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1128 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1130 yaffs_HandleChunkError(dev, bi);
1133 /* Was an actual write failure, so mark the block for retirement */
1134 bi->needsRetiring = 1;
1135 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1136 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1139 /* Delete the chunk */
1140 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1141 yaffs_SkipRestOfBlock(dev);
1145 /*---------------- Name handling functions ------------*/
1147 static __u16 yaffs_CalcNameSum(const YCHAR *name)
1152 const YUCHAR *bname = (const YUCHAR *) name;
1154 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1156 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1157 sum += yaffs_toupper(*bname) * i;
1159 sum += (*bname) * i;
1168 static void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
1170 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1171 memset(obj->shortName, 0, sizeof(YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1172 if (name && yaffs_strnlen(name,YAFFS_SHORT_NAME_LENGTH+1) <= YAFFS_SHORT_NAME_LENGTH)
1173 yaffs_strcpy(obj->shortName, name);
1175 obj->shortName[0] = _Y('\0');
1177 obj->sum = yaffs_CalcNameSum(name);
1180 /*-------------------- TNODES -------------------
1182 * List of spare tnodes
1183 * The list is hooked together using the first pointer
1187 /* yaffs_CreateTnodes creates a bunch more tnodes and
1188 * adds them to the tnode free list.
1189 * Don't use this function directly
1192 static int yaffs_CreateTnodes(yaffs_Device *dev, int nTnodes)
1196 yaffs_Tnode *newTnodes;
1200 yaffs_TnodeList *tnl;
1205 /* Calculate the tnode size in bytes for variable width tnode support.
1206 * Must be a multiple of 32-bits */
1207 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1209 if (tnodeSize < sizeof(yaffs_Tnode))
1210 tnodeSize = sizeof(yaffs_Tnode);
1212 /* make these things */
1214 newTnodes = YMALLOC(nTnodes * tnodeSize);
1215 mem = (__u8 *)newTnodes;
1218 T(YAFFS_TRACE_ERROR,
1219 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1223 /* Hook them into the free list */
1225 for (i = 0; i < nTnodes - 1; i++) {
1226 newTnodes[i].internal[0] = &newTnodes[i + 1];
1227 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1228 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1232 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1233 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1234 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1236 dev->freeTnodes = newTnodes;
1238 /* New hookup for wide tnodes */
1239 for (i = 0; i < nTnodes - 1; i++) {
1240 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1241 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1242 curr->internal[0] = next;
1245 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1246 curr->internal[0] = dev->freeTnodes;
1247 dev->freeTnodes = (yaffs_Tnode *)mem;
1252 dev->nFreeTnodes += nTnodes;
1253 dev->nTnodesCreated += nTnodes;
1255 /* Now add this bunch of tnodes to a list for freeing up.
1256 * NB If we can't add this to the management list it isn't fatal
1257 * but it just means we can't free this bunch of tnodes later.
1260 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1262 T(YAFFS_TRACE_ERROR,
1264 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1267 tnl->tnodes = newTnodes;
1268 tnl->next = dev->allocatedTnodeList;
1269 dev->allocatedTnodeList = tnl;
1272 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1277 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1279 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device *dev)
1281 yaffs_Tnode *tn = NULL;
1283 /* If there are none left make more */
1284 if (!dev->freeTnodes)
1285 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1287 if (dev->freeTnodes) {
1288 tn = dev->freeTnodes;
1289 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1290 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1291 /* Hoosterman, this thing looks like it isn't in the list */
1292 T(YAFFS_TRACE_ALWAYS,
1293 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1296 dev->freeTnodes = dev->freeTnodes->internal[0];
1300 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1305 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
1307 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1308 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1310 if (tnodeSize < sizeof(yaffs_Tnode))
1311 tnodeSize = sizeof(yaffs_Tnode);
1314 memset(tn, 0, tnodeSize);
1319 /* FreeTnode frees up a tnode and puts it back on the free list */
1320 static void yaffs_FreeTnode(yaffs_Device *dev, yaffs_Tnode *tn)
1323 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1324 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1325 /* Hoosterman, this thing looks like it is already in the list */
1326 T(YAFFS_TRACE_ALWAYS,
1327 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1329 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1331 tn->internal[0] = dev->freeTnodes;
1332 dev->freeTnodes = tn;
1335 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1338 static void yaffs_DeinitialiseTnodes(yaffs_Device *dev)
1340 /* Free the list of allocated tnodes */
1341 yaffs_TnodeList *tmp;
1343 while (dev->allocatedTnodeList) {
1344 tmp = dev->allocatedTnodeList->next;
1346 YFREE(dev->allocatedTnodeList->tnodes);
1347 YFREE(dev->allocatedTnodeList);
1348 dev->allocatedTnodeList = tmp;
1352 dev->freeTnodes = NULL;
1353 dev->nFreeTnodes = 0;
1354 dev->nTnodesCreated = 0;
1357 static void yaffs_InitialiseTnodes(yaffs_Device *dev)
1359 dev->allocatedTnodeList = NULL;
1360 dev->freeTnodes = NULL;
1361 dev->nFreeTnodes = 0;
1362 dev->nTnodesCreated = 0;
1366 void yaffs_LoadLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
1369 __u32 *map = (__u32 *)tn;
1375 pos &= YAFFS_TNODES_LEVEL0_MASK;
1376 val >>= dev->chunkGroupBits;
1378 bitInMap = pos * dev->tnodeWidth;
1379 wordInMap = bitInMap / 32;
1380 bitInWord = bitInMap & (32 - 1);
1382 mask = dev->tnodeMask << bitInWord;
1384 map[wordInMap] &= ~mask;
1385 map[wordInMap] |= (mask & (val << bitInWord));
1387 if (dev->tnodeWidth > (32 - bitInWord)) {
1388 bitInWord = (32 - bitInWord);
1390 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1391 map[wordInMap] &= ~mask;
1392 map[wordInMap] |= (mask & (val >> bitInWord));
1396 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
1399 __u32 *map = (__u32 *)tn;
1405 pos &= YAFFS_TNODES_LEVEL0_MASK;
1407 bitInMap = pos * dev->tnodeWidth;
1408 wordInMap = bitInMap / 32;
1409 bitInWord = bitInMap & (32 - 1);
1411 val = map[wordInMap] >> bitInWord;
1413 if (dev->tnodeWidth > (32 - bitInWord)) {
1414 bitInWord = (32 - bitInWord);
1416 val |= (map[wordInMap] << bitInWord);
1419 val &= dev->tnodeMask;
1420 val <<= dev->chunkGroupBits;
1425 /* ------------------- End of individual tnode manipulation -----------------*/
1427 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1428 * The look up tree is represented by the top tnode and the number of topLevel
1429 * in the tree. 0 means only the level 0 tnode is in the tree.
1432 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1433 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
1434 yaffs_FileStructure *fStruct,
1437 yaffs_Tnode *tn = fStruct->top;
1439 int requiredTallness;
1440 int level = fStruct->topLevel;
1442 /* Check sane level and chunk Id */
1443 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
1446 if (chunkId > YAFFS_MAX_CHUNK_ID)
1449 /* First check we're tall enough (ie enough topLevel) */
1451 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1452 requiredTallness = 0;
1454 i >>= YAFFS_TNODES_INTERNAL_BITS;
1458 if (requiredTallness > fStruct->topLevel)
1459 return NULL; /* Not tall enough, so we can't find it */
1461 /* Traverse down to level 0 */
1462 while (level > 0 && tn) {
1463 tn = tn->internal[(chunkId >>
1464 (YAFFS_TNODES_LEVEL0_BITS +
1466 YAFFS_TNODES_INTERNAL_BITS)) &
1467 YAFFS_TNODES_INTERNAL_MASK];
1474 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1475 * This happens in two steps:
1476 * 1. If the tree isn't tall enough, then make it taller.
1477 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1479 * Used when modifying the tree.
1481 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1482 * be plugged into the ttree.
1485 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
1486 yaffs_FileStructure *fStruct,
1488 yaffs_Tnode *passedTn)
1490 int requiredTallness;
1498 /* Check sane level and page Id */
1499 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
1502 if (chunkId > YAFFS_MAX_CHUNK_ID)
1505 /* First check we're tall enough (ie enough topLevel) */
1507 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1508 requiredTallness = 0;
1510 x >>= YAFFS_TNODES_INTERNAL_BITS;
1515 if (requiredTallness > fStruct->topLevel) {
1516 /* Not tall enough, gotta make the tree taller */
1517 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1519 tn = yaffs_GetTnode(dev);
1522 tn->internal[0] = fStruct->top;
1524 fStruct->topLevel++;
1526 T(YAFFS_TRACE_ERROR,
1527 (TSTR("yaffs: no more tnodes" TENDSTR)));
1533 /* Traverse down to level 0, adding anything we need */
1535 l = fStruct->topLevel;
1539 while (l > 0 && tn) {
1541 (YAFFS_TNODES_LEVEL0_BITS +
1542 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1543 YAFFS_TNODES_INTERNAL_MASK;
1546 if ((l > 1) && !tn->internal[x]) {
1547 /* Add missing non-level-zero tnode */
1548 tn->internal[x] = yaffs_GetTnode(dev);
1549 if(!tn->internal[x])
1552 } else if (l == 1) {
1553 /* Looking from level 1 at level 0 */
1555 /* If we already have one, then release it.*/
1556 if (tn->internal[x])
1557 yaffs_FreeTnode(dev, tn->internal[x]);
1558 tn->internal[x] = passedTn;
1560 } else if (!tn->internal[x]) {
1561 /* Don't have one, none passed in */
1562 tn->internal[x] = yaffs_GetTnode(dev);
1563 if(!tn->internal[x])
1568 tn = tn->internal[x];
1572 /* top is level 0 */
1574 memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1575 yaffs_FreeTnode(dev, passedTn);
1582 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
1583 yaffs_ExtendedTags *tags, int objectId,
1588 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1589 if (yaffs_CheckChunkBit(dev, theChunk / dev->nChunksPerBlock,
1590 theChunk % dev->nChunksPerBlock)) {
1592 if(dev->chunkGroupSize == 1)
1595 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1597 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1609 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1610 * chunks and tnodes in the file
1611 * Returns 1 if the tree was deleted.
1612 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1615 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
1616 int chunkOffset, int *limit)
1621 yaffs_ExtendedTags tags;
1623 yaffs_Device *dev = in->myDev;
1629 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1631 if (tn->internal[i]) {
1632 if (limit && (*limit) < 0) {
1636 yaffs_DeleteWorker(in,
1644 YAFFS_TNODES_INTERNAL_BITS)
1649 yaffs_FreeTnode(dev,
1652 tn->internal[i] = NULL;
1656 return (allDone) ? 1 : 0;
1657 } else if (level == 0) {
1660 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1662 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1665 chunkInInode = (chunkOffset <<
1666 YAFFS_TNODES_LEVEL0_BITS) + i;
1669 yaffs_FindChunkInGroup(dev,
1675 if (foundChunk > 0) {
1676 yaffs_DeleteChunk(dev,
1681 *limit = *limit - 1;
1688 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1692 return (i < 0) ? 1 : 0;
1702 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1704 yaffs_BlockInfo *theBlock;
1706 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1708 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1710 theBlock->softDeletions++;
1715 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1716 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1718 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1721 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1722 __u32 level, int chunkOffset)
1727 yaffs_Device *dev = in->myDev;
1732 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1734 if (tn->internal[i]) {
1736 yaffs_SoftDeleteWorker(in,
1742 YAFFS_TNODES_INTERNAL_BITS)
1745 yaffs_FreeTnode(dev,
1748 tn->internal[i] = NULL;
1750 /* Hoosterman... how could this happen? */
1754 return (allDone) ? 1 : 0;
1755 } else if (level == 0) {
1757 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1758 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1760 /* Note this does not find the real chunk, only the chunk group.
1761 * We make an assumption that a chunk group is not larger than
1764 yaffs_SoftDeleteChunk(dev, theChunk);
1765 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1779 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1782 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1783 if (obj->nDataChunks <= 0) {
1784 /* Empty file with no duplicate object headers, just delete it immediately */
1785 yaffs_FreeTnode(obj->myDev,
1786 obj->variant.fileVariant.top);
1787 obj->variant.fileVariant.top = NULL;
1788 T(YAFFS_TRACE_TRACING,
1789 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1791 yaffs_DoGenericObjectDeletion(obj);
1793 yaffs_SoftDeleteWorker(obj,
1794 obj->variant.fileVariant.top,
1795 obj->variant.fileVariant.
1797 obj->softDeleted = 1;
1802 /* Pruning removes any part of the file structure tree that is beyond the
1803 * bounds of the file (ie that does not point to chunks).
1805 * A file should only get pruned when its size is reduced.
1807 * Before pruning, the chunks must be pulled from the tree and the
1808 * level 0 tnode entries must be zeroed out.
1809 * Could also use this for file deletion, but that's probably better handled
1810 * by a special case.
1812 * This function is recursive. For levels > 0 the function is called again on
1813 * any sub-tree. For level == 0 we just check if the sub-tree has data.
1814 * If there is no data in a subtree then it is pruned.
1817 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1818 __u32 level, int del0)
1827 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1828 if (tn->internal[i]) {
1830 yaffs_PruneWorker(dev, tn->internal[i],
1832 (i == 0) ? del0 : 1);
1835 if (tn->internal[i])
1840 __u32 *map = (__u32 *)tn;
1841 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1843 if (tnodeSize < sizeof(yaffs_Tnode))
1844 tnodeSize = sizeof(yaffs_Tnode);
1845 tnodeSize /= sizeof(__u32);
1847 for(i = 0; !hasData && i < tnodeSize; i++){
1853 if (hasData == 0 && del0) {
1854 /* Free and return NULL */
1856 yaffs_FreeTnode(dev, tn);
1866 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1867 yaffs_FileStructure *fStruct)
1874 if (fStruct->topLevel > 0) {
1876 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1878 /* Now we have a tree with all the non-zero branches NULL but the height
1879 * is the same as it was.
1880 * Let's see if we can trim internal tnodes to shorten the tree.
1881 * We can do this if only the 0th element in the tnode is in use
1882 * (ie all the non-zero are NULL)
1885 while (fStruct->topLevel && !done) {
1889 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1890 if (tn->internal[i])
1895 fStruct->top = tn->internal[0];
1896 fStruct->topLevel--;
1897 yaffs_FreeTnode(dev, tn);
1907 /*-------------------- End of File Structure functions.-------------------*/
1909 /* yaffs_CreateFreeObjects creates a bunch more objects and
1910 * adds them to the object free list.
1912 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1915 yaffs_Object *newObjects;
1916 yaffs_ObjectList *list;
1921 /* make these things */
1922 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1923 list = YMALLOC(sizeof(yaffs_ObjectList));
1925 if (!newObjects || !list) {
1934 T(YAFFS_TRACE_ALLOCATE,
1935 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1939 /* Hook them into the free list */
1940 for (i = 0; i < nObjects - 1; i++) {
1941 newObjects[i].siblings.next =
1942 (struct ylist_head *)(&newObjects[i + 1]);
1945 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1946 dev->freeObjects = newObjects;
1947 dev->nFreeObjects += nObjects;
1948 dev->nObjectsCreated += nObjects;
1950 /* Now add this bunch of Objects to a list for freeing up. */
1952 list->objects = newObjects;
1953 list->next = dev->allocatedObjectList;
1954 dev->allocatedObjectList = list;
1960 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1961 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1963 yaffs_Object *tn = NULL;
1965 #ifdef VALGRIND_TEST
1966 tn = YMALLOC(sizeof(yaffs_Object));
1968 /* If there are none left make more */
1969 if (!dev->freeObjects)
1970 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1972 if (dev->freeObjects) {
1973 tn = dev->freeObjects;
1975 (yaffs_Object *) (dev->freeObjects->siblings.next);
1976 dev->nFreeObjects--;
1980 /* Now sweeten it up... */
1982 memset(tn, 0, sizeof(yaffs_Object));
1983 tn->beingCreated = 1;
1987 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1988 YINIT_LIST_HEAD(&(tn->hardLinks));
1989 YINIT_LIST_HEAD(&(tn->hashLink));
1990 YINIT_LIST_HEAD(&tn->siblings);
1993 /* Now make the directory sane */
1995 tn->parent = dev->rootDir;
1996 ylist_add(&(tn->siblings), &dev->rootDir->variant.directoryVariant.children);
1999 /* Add it to the lost and found directory.
2000 * NB Can't put root or lostNFound in lostNFound so
2001 * check if lostNFound exists first
2003 if (dev->lostNFoundDir)
2004 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
2006 tn->beingCreated = 0;
2009 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2014 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
2019 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
2021 obj->fake = 1; /* it is fake so it might have no NAND presence... */
2022 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
2023 obj->unlinkAllowed = 0; /* ... or unlink it */
2026 obj->yst_mode = mode;
2028 obj->hdrChunk = 0; /* Not a valid chunk. */
2035 static void yaffs_UnhashObject(yaffs_Object *tn)
2038 yaffs_Device *dev = tn->myDev;
2040 /* If it is still linked into the bucket list, free from the list */
2041 if (!ylist_empty(&tn->hashLink)) {
2042 ylist_del_init(&tn->hashLink);
2043 bucket = yaffs_HashFunction(tn->objectId);
2044 dev->objectBucket[bucket].count--;
2048 /* FreeObject frees up a Object and puts it back on the free list */
2049 static void yaffs_FreeObject(yaffs_Object *tn)
2051 yaffs_Device *dev = tn->myDev;
2054 T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), tn, tn->myInode));
2059 if (!ylist_empty(&tn->siblings))
2065 /* We're still hooked up to a cached inode.
2066 * Don't delete now, but mark for later deletion
2068 tn->deferedFree = 1;
2073 yaffs_UnhashObject(tn);
2075 #ifdef VALGRIND_TEST
2079 /* Link into the free list. */
2080 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2081 dev->freeObjects = tn;
2082 dev->nFreeObjects++;
2084 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2089 void yaffs_HandleDeferedFree(yaffs_Object *obj)
2091 if (obj->deferedFree)
2092 yaffs_FreeObject(obj);
2097 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
2099 /* Free the list of allocated Objects */
2101 yaffs_ObjectList *tmp;
2103 while (dev->allocatedObjectList) {
2104 tmp = dev->allocatedObjectList->next;
2105 YFREE(dev->allocatedObjectList->objects);
2106 YFREE(dev->allocatedObjectList);
2108 dev->allocatedObjectList = tmp;
2111 dev->freeObjects = NULL;
2112 dev->nFreeObjects = 0;
2113 dev->nObjectsCreated = 0;
2116 static void yaffs_InitialiseObjects(yaffs_Device *dev)
2120 dev->allocatedObjectList = NULL;
2121 dev->freeObjects = NULL;
2122 dev->nFreeObjects = 0;
2124 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2125 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2126 dev->objectBucket[i].count = 0;
2130 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
2135 int lowest = 999999;
2137 /* First let's see if we can find one that's empty. */
2139 for (i = 0; i < 10 && lowest > 0; i++) {
2141 x %= YAFFS_NOBJECT_BUCKETS;
2142 if (dev->objectBucket[x].count < lowest) {
2143 lowest = dev->objectBucket[x].count;
2149 /* If we didn't find an empty list, then try
2150 * looking a bit further for a short one
2153 for (i = 0; i < 10 && lowest > 3; i++) {
2155 x %= YAFFS_NOBJECT_BUCKETS;
2156 if (dev->objectBucket[x].count < lowest) {
2157 lowest = dev->objectBucket[x].count;
2166 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
2168 int bucket = yaffs_FindNiceObjectBucket(dev);
2170 /* Now find an object value that has not already been taken
2171 * by scanning the list.
2175 struct ylist_head *i;
2177 __u32 n = (__u32) bucket;
2179 /* yaffs_CheckObjectHashSanity(); */
2183 n += YAFFS_NOBJECT_BUCKETS;
2184 if (1 || dev->objectBucket[bucket].count > 0) {
2185 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2186 /* If there is already one in the list */
2187 if (i && ylist_entry(i, yaffs_Object,
2188 hashLink)->objectId == n) {
2198 static void yaffs_HashObject(yaffs_Object *in)
2200 int bucket = yaffs_HashFunction(in->objectId);
2201 yaffs_Device *dev = in->myDev;
2203 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2204 dev->objectBucket[bucket].count++;
2207 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
2209 int bucket = yaffs_HashFunction(number);
2210 struct ylist_head *i;
2213 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2214 /* Look if it is in the list */
2216 in = ylist_entry(i, yaffs_Object, hashLink);
2217 if (in->objectId == number) {
2219 /* Don't tell the VFS about this one if it is defered free */
2220 if (in->deferedFree)
2232 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
2233 yaffs_ObjectType type)
2235 yaffs_Object *theObject;
2236 yaffs_Tnode *tn = NULL;
2239 number = yaffs_CreateNewObjectNumber(dev);
2241 if (type == YAFFS_OBJECT_TYPE_FILE) {
2242 tn = yaffs_GetTnode(dev);
2247 theObject = yaffs_AllocateEmptyObject(dev);
2250 yaffs_FreeTnode(dev,tn);
2256 theObject->fake = 0;
2257 theObject->renameAllowed = 1;
2258 theObject->unlinkAllowed = 1;
2259 theObject->objectId = number;
2260 yaffs_HashObject(theObject);
2261 theObject->variantType = type;
2262 #ifdef CONFIG_YAFFS_WINCE
2263 yfsd_WinFileTimeNow(theObject->win_atime);
2264 theObject->win_ctime[0] = theObject->win_mtime[0] =
2265 theObject->win_atime[0];
2266 theObject->win_ctime[1] = theObject->win_mtime[1] =
2267 theObject->win_atime[1];
2271 theObject->yst_atime = theObject->yst_mtime =
2272 theObject->yst_ctime = Y_CURRENT_TIME;
2275 case YAFFS_OBJECT_TYPE_FILE:
2276 theObject->variant.fileVariant.fileSize = 0;
2277 theObject->variant.fileVariant.scannedFileSize = 0;
2278 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2279 theObject->variant.fileVariant.topLevel = 0;
2280 theObject->variant.fileVariant.top = tn;
2282 case YAFFS_OBJECT_TYPE_DIRECTORY:
2283 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2286 case YAFFS_OBJECT_TYPE_SYMLINK:
2287 case YAFFS_OBJECT_TYPE_HARDLINK:
2288 case YAFFS_OBJECT_TYPE_SPECIAL:
2289 /* No action required */
2291 case YAFFS_OBJECT_TYPE_UNKNOWN:
2292 /* todo this should not happen */
2300 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
2302 yaffs_ObjectType type)
2304 yaffs_Object *theObject = NULL;
2307 theObject = yaffs_FindObjectByNumber(dev, number);
2310 theObject = yaffs_CreateNewObject(dev, number, type);
2317 static YCHAR *yaffs_CloneString(const YCHAR *str)
2319 YCHAR *newStr = NULL;
2325 len = yaffs_strnlen(str,YAFFS_MAX_ALIAS_LENGTH);
2326 newStr = YMALLOC((len + 1) * sizeof(YCHAR));
2328 yaffs_strncpy(newStr, str,len);
2336 * Mknod (create) a new object.
2337 * equivalentObject only has meaning for a hard link;
2338 * aliasString only has meaning for a symlink.
2339 * rdev only has meaning for devices (a subset of special objects)
2342 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2343 yaffs_Object *parent,
2348 yaffs_Object *equivalentObject,
2349 const YCHAR *aliasString, __u32 rdev)
2354 yaffs_Device *dev = parent->myDev;
2356 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2357 if (yaffs_FindObjectByName(parent, name))
2360 if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2361 str = yaffs_CloneString(aliasString);
2366 in = yaffs_CreateNewObject(dev, -1, type);
2380 in->variantType = type;
2382 in->yst_mode = mode;
2384 #ifdef CONFIG_YAFFS_WINCE
2385 yfsd_WinFileTimeNow(in->win_atime);
2386 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2387 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2390 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2392 in->yst_rdev = rdev;
2396 in->nDataChunks = 0;
2398 yaffs_SetObjectName(in, name);
2401 yaffs_AddObjectToDirectory(parent, in);
2403 in->myDev = parent->myDev;
2406 case YAFFS_OBJECT_TYPE_SYMLINK:
2407 in->variant.symLinkVariant.alias = str;
2409 case YAFFS_OBJECT_TYPE_HARDLINK:
2410 in->variant.hardLinkVariant.equivalentObject =
2412 in->variant.hardLinkVariant.equivalentObjectId =
2413 equivalentObject->objectId;
2414 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2416 case YAFFS_OBJECT_TYPE_FILE:
2417 case YAFFS_OBJECT_TYPE_DIRECTORY:
2418 case YAFFS_OBJECT_TYPE_SPECIAL:
2419 case YAFFS_OBJECT_TYPE_UNKNOWN:
2424 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2425 /* Could not create the object header, fail the creation */
2426 yaffs_DeleteObject(in);
2430 yaffs_UpdateParent(parent);
2436 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
2437 __u32 mode, __u32 uid, __u32 gid)
2439 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2440 uid, gid, NULL, NULL, 0);
2443 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
2444 __u32 mode, __u32 uid, __u32 gid)
2446 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2447 mode, uid, gid, NULL, NULL, 0);
2450 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
2451 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2453 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2454 uid, gid, NULL, NULL, rdev);
2457 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
2458 __u32 mode, __u32 uid, __u32 gid,
2461 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2462 uid, gid, NULL, alias, 0);
2465 /* yaffs_Link returns the object id of the equivalent object.*/
2466 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
2467 yaffs_Object *equivalentObject)
2469 /* Get the real object in case we were fed a hard link as an equivalent object */
2470 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2472 if (yaffs_MknodObject
2473 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2474 equivalentObject, NULL, 0)) {
2475 return equivalentObject;
2482 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
2483 const YCHAR *newName, int force, int shadows)
2488 yaffs_Object *existingTarget;
2491 newDir = obj->parent; /* use the old directory */
2493 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2494 T(YAFFS_TRACE_ALWAYS,
2496 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2501 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2502 if (obj->myDev->isYaffs2)
2503 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2505 unlinkOp = (newDir == obj->myDev->unlinkedDir
2506 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2508 deleteOp = (newDir == obj->myDev->deletedDir);
2510 existingTarget = yaffs_FindObjectByName(newDir, newName);
2512 /* If the object is a file going into the unlinked directory,
2513 * then it is OK to just stuff it in since duplicate names are allowed.
2514 * else only proceed if the new name does not exist and if we're putting
2515 * it into a directory.
2522 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2523 yaffs_SetObjectName(obj, newName);
2526 yaffs_AddObjectToDirectory(newDir, obj);
2531 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2532 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows) >= 0)
2539 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
2540 yaffs_Object *newDir, const YCHAR *newName)
2542 yaffs_Object *obj = NULL;
2543 yaffs_Object *existingTarget = NULL;
2549 if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2551 if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2554 dev = oldDir->myDev;
2556 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2557 /* Special case for case insemsitive systems (eg. WinCE).
2558 * While look-up is case insensitive, the name isn't.
2559 * Therefore we might want to change x.txt to X.txt
2561 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
2565 if(yaffs_strnlen(newName,YAFFS_MAX_NAME_LENGTH+1) > YAFFS_MAX_NAME_LENGTH)
2569 obj = yaffs_FindObjectByName(oldDir, oldName);
2571 if (obj && obj->renameAllowed) {
2573 /* Now do the handling for an existing target, if there is one */
2575 existingTarget = yaffs_FindObjectByName(newDir, newName);
2576 if (existingTarget &&
2577 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2578 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2579 /* There is a target that is a non-empty directory, so we fail */
2580 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2581 } else if (existingTarget && existingTarget != obj) {
2582 /* Nuke the target first, using shadowing,
2583 * but only if it isn't the same object.
2585 * Note we must disable gc otherwise it can mess up the shadowing.
2589 yaffs_ChangeObjectName(obj, newDir, newName, force,
2590 existingTarget->objectId);
2591 existingTarget->isShadowed = 1;
2592 yaffs_UnlinkObject(existingTarget);
2596 result = yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2598 yaffs_UpdateParent(oldDir);
2599 if(newDir != oldDir)
2600 yaffs_UpdateParent(newDir);
2607 /*------------------------- Block Management and Page Allocation ----------------*/
2609 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
2611 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2613 dev->blockInfo = NULL;
2614 dev->chunkBits = NULL;
2616 dev->allocationBlock = -1; /* force it to get a new one */
2618 /* If the first allocation strategy fails, thry the alternate one */
2619 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2620 if (!dev->blockInfo) {
2621 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2622 dev->blockInfoAlt = 1;
2624 dev->blockInfoAlt = 0;
2626 if (dev->blockInfo) {
2627 /* Set up dynamic blockinfo stuff. */
2628 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2629 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2630 if (!dev->chunkBits) {
2631 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2632 dev->chunkBitsAlt = 1;
2634 dev->chunkBitsAlt = 0;
2637 if (dev->blockInfo && dev->chunkBits) {
2638 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2639 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2646 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2648 if (dev->blockInfoAlt && dev->blockInfo)
2649 YFREE_ALT(dev->blockInfo);
2650 else if (dev->blockInfo)
2651 YFREE(dev->blockInfo);
2653 dev->blockInfoAlt = 0;
2655 dev->blockInfo = NULL;
2657 if (dev->chunkBitsAlt && dev->chunkBits)
2658 YFREE_ALT(dev->chunkBits);
2659 else if (dev->chunkBits)
2660 YFREE(dev->chunkBits);
2661 dev->chunkBitsAlt = 0;
2662 dev->chunkBits = NULL;
2665 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
2666 yaffs_BlockInfo *bi)
2673 return 1; /* disqualification only applies to yaffs2. */
2675 if (!bi->hasShrinkHeader)
2676 return 1; /* can gc */
2678 /* Find the oldest dirty sequence number if we don't know it and save it
2679 * so we don't have to keep recomputing it.
2681 if (!dev->oldestDirtySequence) {
2682 seq = dev->sequenceNumber;
2684 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2686 b = yaffs_GetBlockInfo(dev, i);
2687 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2688 (b->pagesInUse - b->softDeletions) <
2689 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2690 seq = b->sequenceNumber;
2693 dev->oldestDirtySequence = seq;
2696 /* Can't do gc of this block if there are any blocks older than this one that have
2699 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2702 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2703 * for garbage collection.
2706 static int yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
2709 int b = dev->currentDirtyChecker;
2715 int prioritised = 0;
2716 yaffs_BlockInfo *bi;
2717 int pendingPrioritisedExist = 0;
2719 /* First let's see if we need to grab a prioritised block */
2720 if (dev->hasPendingPrioritisedGCs) {
2721 for (i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++) {
2723 bi = yaffs_GetBlockInfo(dev, i);
2724 /* yaffs_VerifyBlock(dev,bi,i); */
2726 if (bi->gcPrioritise) {
2727 pendingPrioritisedExist = 1;
2728 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2729 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2730 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2733 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2738 if (!pendingPrioritisedExist) /* None found, so we can clear this */
2739 dev->hasPendingPrioritisedGCs = 0;
2742 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2744 * else (we're doing a leasurely gc), then we only bother to do this if the
2745 * block has only a few pages in use.
2748 dev->nonAggressiveSkip--;
2750 if (!aggressive && (dev->nonAggressiveSkip > 0))
2755 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2759 dev->internalEndBlock - dev->internalStartBlock + 1;
2762 dev->internalEndBlock - dev->internalStartBlock + 1;
2763 iterations = iterations / 16;
2764 if (iterations > 200)
2768 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2770 if (b < dev->internalStartBlock || b > dev->internalEndBlock)
2771 b = dev->internalStartBlock;
2773 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2774 T(YAFFS_TRACE_ERROR,
2775 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2779 bi = yaffs_GetBlockInfo(dev, b);
2781 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2782 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2783 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2785 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2789 dev->currentDirtyChecker = b;
2793 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2794 dev->nChunksPerBlock - pagesInUse, prioritised));
2797 dev->oldestDirtySequence = 0;
2800 dev->nonAggressiveSkip = 4;
2805 static void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
2807 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2811 /* If the block is still healthy erase it and mark as clean.
2812 * If the block has had a data failure, then retire it.
2815 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2816 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2817 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2819 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2821 if (!bi->needsRetiring) {
2822 yaffs_InvalidateCheckpoint(dev);
2823 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2825 dev->nErasureFailures++;
2826 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2827 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2832 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2834 for (i = 0; i < dev->nChunksPerBlock; i++) {
2835 if (!yaffs_CheckChunkErased
2836 (dev, blockNo * dev->nChunksPerBlock + i)) {
2837 T(YAFFS_TRACE_ERROR,
2839 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2840 TENDSTR), blockNo, i));
2846 /* Clean it up... */
2847 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2848 dev->nErasedBlocks++;
2850 bi->softDeletions = 0;
2851 bi->hasShrinkHeader = 0;
2852 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2853 bi->gcPrioritise = 0;
2854 yaffs_ClearChunkBits(dev, blockNo);
2856 T(YAFFS_TRACE_ERASE,
2857 (TSTR("Erased block %d" TENDSTR), blockNo));
2859 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2861 yaffs_RetireBlock(dev, blockNo);
2862 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2863 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2867 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2871 yaffs_BlockInfo *bi;
2873 if (dev->nErasedBlocks < 1) {
2874 /* Hoosterman we've got a problem.
2875 * Can't get space to gc
2877 T(YAFFS_TRACE_ERROR,
2878 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2883 /* Find an empty block. */
2885 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2886 dev->allocationBlockFinder++;
2887 if (dev->allocationBlockFinder < dev->internalStartBlock
2888 || dev->allocationBlockFinder > dev->internalEndBlock) {
2889 dev->allocationBlockFinder = dev->internalStartBlock;
2892 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2894 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2895 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2896 dev->sequenceNumber++;
2897 bi->sequenceNumber = dev->sequenceNumber;
2898 dev->nErasedBlocks--;
2899 T(YAFFS_TRACE_ALLOCATE,
2900 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2901 dev->allocationBlockFinder, dev->sequenceNumber,
2902 dev->nErasedBlocks));
2903 return dev->allocationBlockFinder;
2907 T(YAFFS_TRACE_ALWAYS,
2909 ("yaffs tragedy: no more erased blocks, but there should have been %d"
2910 TENDSTR), dev->nErasedBlocks));
2917 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2919 if (!dev->nCheckpointBlocksRequired &&
2921 /* Not a valid value so recalculate */
2924 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2927 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2929 if (tnodeSize < sizeof(yaffs_Tnode))
2930 tnodeSize = sizeof(yaffs_Tnode);
2932 nBytes += sizeof(yaffs_CheckpointValidity);
2933 nBytes += sizeof(yaffs_CheckpointDevice);
2934 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2935 nBytes += devBlocks * dev->chunkBitmapStride;
2936 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2937 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2938 nBytes += sizeof(yaffs_CheckpointValidity);
2939 nBytes += sizeof(__u32); /* checksum*/
2941 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2943 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2945 dev->nCheckpointBlocksRequired = nBlocks;
2948 return dev->nCheckpointBlocksRequired;
2952 * Check if there's space to allocate...
2953 * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2955 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev)
2958 int reservedBlocks = dev->nReservedBlocks;
2959 int checkpointBlocks;
2961 if (dev->isYaffs2) {
2962 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
2963 dev->blocksInCheckpoint;
2964 if (checkpointBlocks < 0)
2965 checkpointBlocks = 0;
2967 checkpointBlocks = 0;
2970 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2972 return (dev->nFreeChunks > reservedChunks);
2975 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
2976 yaffs_BlockInfo **blockUsedPtr)
2979 yaffs_BlockInfo *bi;
2981 if (dev->allocationBlock < 0) {
2982 /* Get next block to allocate off */
2983 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2984 dev->allocationPage = 0;
2987 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2988 /* Not enough space to allocate unless we're allowed to use the reserve. */
2992 if (dev->nErasedBlocks < dev->nReservedBlocks
2993 && dev->allocationPage == 0) {
2994 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2997 /* Next page please.... */
2998 if (dev->allocationBlock >= 0) {
2999 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3001 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
3002 dev->allocationPage;
3004 yaffs_SetChunkBit(dev, dev->allocationBlock,
3005 dev->allocationPage);
3007 dev->allocationPage++;
3011 /* If the block is full set the state to full */
3012 if (dev->allocationPage >= dev->nChunksPerBlock) {
3013 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3014 dev->allocationBlock = -1;
3023 T(YAFFS_TRACE_ERROR,
3024 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
3029 static int yaffs_GetErasedChunks(yaffs_Device *dev)
3033 n = dev->nErasedBlocks * dev->nChunksPerBlock;
3035 if (dev->allocationBlock > 0)
3036 n += (dev->nChunksPerBlock - dev->allocationPage);
3043 * yaffs_SkipRestOfBlock() skips over the rest of the allocation block
3044 * if we don't want to write to it.
3046 static void yaffs_SkipRestOfBlock(yaffs_Device *dev)
3048 if(dev->allocationBlock > 0){
3049 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3050 if(bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING){
3051 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3052 dev->allocationBlock = -1;
3058 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
3064 int retVal = YAFFS_OK;
3067 int isCheckpointBlock;
3071 int chunksBefore = yaffs_GetErasedChunks(dev);
3074 yaffs_ExtendedTags tags;
3076 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3078 yaffs_Object *object;
3080 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3083 T(YAFFS_TRACE_TRACING,
3084 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3087 bi->hasShrinkHeader,
3090 /*yaffs_VerifyFreeChunks(dev); */
3092 if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
3093 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3095 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
3097 /* Take off the number of soft deleted entries because
3098 * they're going to get really deleted during GC.
3100 if(dev->gcChunk == 0) /* first time through for this block */
3101 dev->nFreeChunks -= bi->softDeletions;
3105 if (isCheckpointBlock ||
3106 !yaffs_StillSomeChunkBits(dev, block)) {
3107 T(YAFFS_TRACE_TRACING,
3109 ("Collecting block %d that has no chunks in use" TENDSTR),
3111 yaffs_BlockBecameDirty(dev, block);
3114 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3116 yaffs_VerifyBlock(dev, bi, block);
3118 maxCopies = (wholeBlock) ? dev->nChunksPerBlock : 10;
3119 oldChunk = block * dev->nChunksPerBlock + dev->gcChunk;
3121 for (/* init already done */;
3122 retVal == YAFFS_OK &&
3123 dev->gcChunk < dev->nChunksPerBlock &&
3124 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
3126 dev->gcChunk++, oldChunk++) {
3127 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3129 /* This page is in use and might need to be copied off */
3135 yaffs_InitialiseTags(&tags);
3137 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3141 yaffs_FindObjectByNumber(dev,
3144 T(YAFFS_TRACE_GC_DETAIL,
3146 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3147 dev->gcChunk, tags.objectId, tags.chunkId,
3150 if (object && !yaffs_SkipVerification(dev)) {
3151 if (tags.chunkId == 0)
3152 matchingChunk = object->hdrChunk;
3153 else if (object->softDeleted)
3154 matchingChunk = oldChunk; /* Defeat the test */
3156 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
3158 if (oldChunk != matchingChunk)
3159 T(YAFFS_TRACE_ERROR,
3160 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3161 oldChunk, matchingChunk, tags.objectId, tags.chunkId));
3166 T(YAFFS_TRACE_ERROR,
3168 ("page %d in gc has no object: %d %d %d "
3170 tags.objectId, tags.chunkId, tags.byteCount));
3175 object->softDeleted &&
3176 tags.chunkId != 0) {
3177 /* Data chunk in a soft deleted file, throw it away
3178 * It's a soft deleted data chunk,
3179 * No need to copy this, just forget about it and
3180 * fix up the object.
3183 object->nDataChunks--;
3185 if (object->nDataChunks <= 0) {
3186 /* remeber to clean up the object */
3187 dev->gcCleanupList[cleanups] =
3193 /* Todo object && object->deleted && object->nDataChunks == 0 */
3194 /* Deleted object header with no data chunks.
3195 * Can be discarded and the file deleted.
3197 object->hdrChunk = 0;
3198 yaffs_FreeTnode(object->myDev,
3201 object->variant.fileVariant.top = NULL;
3202 yaffs_DoGenericObjectDeletion(object);
3204 } else if (object) {
3205 /* It's either a data chunk in a live file or
3206 * an ObjectHeader, so we're interested in it.
3207 * NB Need to keep the ObjectHeaders of deleted files
3208 * until the whole file has been deleted off
3210 tags.serialNumber++;
3214 if (tags.chunkId == 0) {
3215 /* It is an object Id,
3216 * We need to nuke the shrinkheader flags first
3217 * Also need to clean up shadowing.
3218 * We no longer want the shrinkHeader flag since its work is done
3219 * and if it is left in place it will mess up scanning.
3222 yaffs_ObjectHeader *oh;
3223 oh = (yaffs_ObjectHeader *)buffer;
3225 tags.extraIsShrinkHeader = 0;
3226 oh->shadowsObject = 0;
3227 oh->inbandShadowsObject = 0;
3228 tags.extraShadows = 0;
3230 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
3234 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3237 retVal = YAFFS_FAIL;
3240 /* Ok, now fix up the Tnodes etc. */
3242 if (tags.chunkId == 0) {
3244 object->hdrChunk = newChunk;
3245 object->serial = tags.serialNumber;
3247 /* It's a data chunk */
3248 yaffs_PutChunkIntoFile
3256 if (retVal == YAFFS_OK)
3257 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3262 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3265 /* Do any required cleanups */
3266 for (i = 0; i < cleanups; i++) {
3267 /* Time to delete the file too */
3269 yaffs_FindObjectByNumber(dev,
3270 dev->gcCleanupList[i]);
3272 yaffs_FreeTnode(dev,
3273 object->variant.fileVariant.
3275 object->variant.fileVariant.top = NULL;
3278 ("yaffs: About to finally delete object %d"
3279 TENDSTR), object->objectId));
3280 yaffs_DoGenericObjectDeletion(object);
3281 object->myDev->nDeletedFiles--;
3288 yaffs_VerifyCollectedBlock(dev, bi, block);
3290 chunksAfter = yaffs_GetErasedChunks(dev);
3291 if (chunksBefore >= chunksAfter) {
3294 ("gc did not increase free chunks before %d after %d"
3295 TENDSTR), chunksBefore, chunksAfter));
3298 /* If the gc completed then clear the current gcBlock so that we find another. */
3299 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING) {
3309 /* New garbage collector
3310 * If we're very low on erased blocks then we do aggressive garbage collection
3311 * otherwise we do "leasurely" garbage collection.
3312 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3313 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3315 * The idea is to help clear out space in a more spread-out manner.
3316 * Dunno if it really does anything useful.
3318 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
3322 int gcOk = YAFFS_OK;
3325 int checkpointBlockAdjust;
3327 if (dev->isDoingGC) {
3328 /* Bail out so we don't get recursive gc */
3332 /* This loop should pass the first time.
3333 * We'll only see looping here if the erase of the collected block fails.
3339 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3340 if (checkpointBlockAdjust < 0)
3341 checkpointBlockAdjust = 0;
3343 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3344 /* We need a block soon...*/
3347 /* We're in no hurry */
3351 if (dev->gcBlock <= 0) {
3352 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3356 block = dev->gcBlock;
3359 dev->garbageCollections++;
3361 dev->passiveGarbageCollections++;
3365 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3366 dev->nErasedBlocks, aggressive));
3368 gcOk = yaffs_GarbageCollectBlock(dev, block, aggressive);
3371 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3374 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3375 TENDSTR), dev->nErasedBlocks, maxTries, block));
3377 } while ((dev->nErasedBlocks < dev->nReservedBlocks) &&
3381 return aggressive ? gcOk : YAFFS_OK;
3384 /*------------------------- TAGS --------------------------------*/
3386 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
3389 return (tags->chunkId == chunkInObject &&
3390 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3395 /*-------------------- Data file manipulation -----------------*/
3397 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
3398 yaffs_ExtendedTags *tags)
3400 /*Get the Tnode, then get the level 0 offset chunk offset */
3403 yaffs_ExtendedTags localTags;
3406 yaffs_Device *dev = in->myDev;
3409 /* Passed a NULL, so use our own tags space */
3413 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3416 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3419 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3425 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
3426 yaffs_ExtendedTags *tags)
3428 /* Get the Tnode, then get the level 0 offset chunk offset */
3431 yaffs_ExtendedTags localTags;
3433 yaffs_Device *dev = in->myDev;
3437 /* Passed a NULL, so use our own tags space */
3441 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3445 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3448 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3451 /* Delete the entry in the filestructure (if found) */
3453 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, 0);
3459 #ifdef YAFFS_PARANOID
3461 static int yaffs_CheckFileSanity(yaffs_Object *in)
3469 yaffs_Tags localTags;
3470 yaffs_Tags *tags = &localTags;
3474 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3477 objId = in->objectId;
3478 fSize = in->variant.fileVariant.fileSize;
3480 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3482 for (chunk = 1; chunk <= nChunks; chunk++) {
3483 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3488 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunk);
3490 if (yaffs_CheckChunkBits
3491 (dev, theChunk / dev->nChunksPerBlock,
3492 theChunk % dev->nChunksPerBlock)) {
3494 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3498 (tags, in->objectId, chunk, chunkDeleted)) {
3508 /* T(("No level 0 found for %d\n", chunk)); */
3512 return failed ? YAFFS_FAIL : YAFFS_OK;
3517 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
3518 int chunkInNAND, int inScan)
3520 /* NB inScan is zero unless scanning.
3521 * For forward scanning, inScan is > 0;
3522 * for backward scanning inScan is < 0
3524 * chunkInNAND = 0 is a dummy insert to make sure the tnodes are there.
3528 yaffs_Device *dev = in->myDev;
3530 yaffs_ExtendedTags existingTags;
3531 yaffs_ExtendedTags newTags;
3532 unsigned existingSerial, newSerial;
3534 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3535 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3536 * If it is not during Scanning then something went wrong!
3539 T(YAFFS_TRACE_ERROR,
3541 ("yaffs tragedy:attempt to put data chunk into a non-file"
3546 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3550 tn = yaffs_AddOrFindLevel0Tnode(dev,
3551 &in->variant.fileVariant,
3558 /* Dummy insert, bail now */
3562 existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3565 /* If we're scanning then we need to test for duplicates
3566 * NB This does not need to be efficient since it should only ever
3567 * happen when the power fails during a write, then only one
3568 * chunk should ever be affected.
3570 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3571 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3574 if (existingChunk > 0) {
3575 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3576 * thus we have to do a FindChunkInFile to get the real chunk id.
3578 * We have a duplicate now we need to decide which one to use:
3580 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3581 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3582 * YAFFS1: Get both sets of tags and compare serial numbers.
3586 /* Only do this for forward scanning */
3587 yaffs_ReadChunkWithTagsFromNAND(dev,
3591 /* Do a proper find */
3593 yaffs_FindChunkInFile(in, chunkInInode,
3597 if (existingChunk <= 0) {
3598 /*Hoosterman - how did this happen? */
3600 T(YAFFS_TRACE_ERROR,
3602 ("yaffs tragedy: existing chunk < 0 in scan"
3607 /* NB The deleted flags should be false, otherwise the chunks will
3608 * not be loaded during a scan
3612 newSerial = newTags.serialNumber;
3613 existingSerial = existingTags.serialNumber;
3617 (in->myDev->isYaffs2 ||
3618 existingChunk <= 0 ||
3619 ((existingSerial + 1) & 3) == newSerial)) {
3620 /* Forward scanning.
3622 * Delete the old one and drop through to update the tnode
3624 yaffs_DeleteChunk(dev, existingChunk, 1,
3627 /* Backward scanning or we want to use the existing one
3629 * Delete the new one and return early so that the tnode isn't changed
3631 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3639 if (existingChunk == 0)
3642 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
3647 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
3650 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3652 if (chunkInNAND >= 0)
3653 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3656 T(YAFFS_TRACE_NANDACCESS,
3657 (TSTR("Chunk %d not found zero instead" TENDSTR),
3659 /* get sane (zero) data if you read a hole */
3660 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3666 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
3670 yaffs_ExtendedTags tags;
3671 yaffs_BlockInfo *bi;
3677 block = chunkId / dev->nChunksPerBlock;
3678 page = chunkId % dev->nChunksPerBlock;
3681 if (!yaffs_CheckChunkBit(dev, block, page))
3682 T(YAFFS_TRACE_VERIFY,
3683 (TSTR("Deleting invalid chunk %d"TENDSTR),
3686 bi = yaffs_GetBlockInfo(dev, block);
3688 T(YAFFS_TRACE_DELETION,
3689 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3692 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3694 yaffs_InitialiseTags(&tags);
3696 tags.chunkDeleted = 1;
3698 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3699 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3701 dev->nUnmarkedDeletions++;
3704 /* Pull out of the management area.
3705 * If the whole block became dirty, this will kick off an erasure.
3707 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3708 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3709 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3710 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3713 yaffs_ClearChunkBit(dev, block, page);
3717 if (bi->pagesInUse == 0 &&
3718 !bi->hasShrinkHeader &&
3719 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3720 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3721 yaffs_BlockBecameDirty(dev, block);
3728 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
3729 const __u8 *buffer, int nBytes,
3732 /* Find old chunk Need to do this to get serial number
3733 * Write new one and patch into tree.
3734 * Invalidate old tags.
3738 yaffs_ExtendedTags prevTags;
3741 yaffs_ExtendedTags newTags;
3743 yaffs_Device *dev = in->myDev;
3745 yaffs_CheckGarbageCollection(dev);
3747 /* Get the previous chunk at this location in the file if it exists */
3748 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3750 /* Set up new tags */
3751 yaffs_InitialiseTags(&newTags);
3753 newTags.chunkId = chunkInInode;
3754 newTags.objectId = in->objectId;
3755 newTags.serialNumber =
3756 (prevChunkId > 0) ? prevTags.serialNumber + 1 : 1;
3757 newTags.byteCount = nBytes;
3759 if (nBytes < 1 || nBytes > dev->totalBytesPerChunk) {
3760 T(YAFFS_TRACE_ERROR,
3761 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3766 * If there isn't already a chunk there then do a dummy
3767 * insert to make sue we have the desired tnode structure.
3769 if(prevChunkId < 1 &&
3770 yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0) != YAFFS_OK)
3774 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3777 if (newChunkId > 0) {
3778 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3780 if (prevChunkId > 0)
3781 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3783 yaffs_CheckFileSanity(in);
3789 /* UpdateObjectHeader updates the header on NAND for an object.
3790 * If name is not NULL, then that new name is used.
3792 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
3793 int isShrink, int shadows)
3796 yaffs_BlockInfo *bi;
3798 yaffs_Device *dev = in->myDev;
3805 yaffs_ExtendedTags newTags;
3806 yaffs_ExtendedTags oldTags;
3807 YCHAR *alias = NULL;
3809 __u8 *buffer = NULL;
3810 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3812 yaffs_ObjectHeader *oh = NULL;
3814 yaffs_strcpy(oldName, _Y("silly old name"));
3818 in == dev->rootDir || /* The rootDir should also be saved */
3821 yaffs_CheckGarbageCollection(dev);
3822 yaffs_CheckObjectDetailsLoaded(in);
3824 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3825 oh = (yaffs_ObjectHeader *) buffer;
3827 prevChunkId = in->hdrChunk;
3829 if (prevChunkId > 0) {
3830 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3833 yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
3835 memcpy(oldName, oh->name, sizeof(oh->name));
3838 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3840 oh->type = in->variantType;
3841 oh->yst_mode = in->yst_mode;
3842 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3844 #ifdef CONFIG_YAFFS_WINCE
3845 oh->win_atime[0] = in->win_atime[0];
3846 oh->win_ctime[0] = in->win_ctime[0];
3847 oh->win_mtime[0] = in->win_mtime[0];
3848 oh->win_atime[1] = in->win_atime[1];
3849 oh->win_ctime[1] = in->win_ctime[1];
3850 oh->win_mtime[1] = in->win_mtime[1];
3852 oh->yst_uid = in->yst_uid;
3853 oh->yst_gid = in->yst_gid;
3854 oh->yst_atime = in->yst_atime;
3855 oh->yst_mtime = in->yst_mtime;
3856 oh->yst_ctime = in->yst_ctime;
3857 oh->yst_rdev = in->yst_rdev;
3860 oh->parentObjectId = in->parent->objectId;
3862 oh->parentObjectId = 0;
3864 if (name && *name) {
3865 memset(oh->name, 0, sizeof(oh->name));
3866 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3867 } else if (prevChunkId > 0)
3868 memcpy(oh->name, oldName, sizeof(oh->name));
3870 memset(oh->name, 0, sizeof(oh->name));
3872 oh->isShrink = isShrink;
3874 switch (in->variantType) {
3875 case YAFFS_OBJECT_TYPE_UNKNOWN:
3876 /* Should not happen */
3878 case YAFFS_OBJECT_TYPE_FILE:
3880 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3881 || oh->parentObjectId ==
3882 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3883 fileVariant.fileSize;
3885 case YAFFS_OBJECT_TYPE_HARDLINK:
3886 oh->equivalentObjectId =
3887 in->variant.hardLinkVariant.equivalentObjectId;
3889 case YAFFS_OBJECT_TYPE_SPECIAL:
3892 case YAFFS_OBJECT_TYPE_DIRECTORY: