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.102 2009-12-30 22:30:12 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;
1356 static void yaffs_InitialiseTnodes(yaffs_Device *dev)
1358 dev->allocatedTnodeList = NULL;
1359 dev->freeTnodes = NULL;
1360 dev->nFreeTnodes = 0;
1361 dev->nTnodesCreated = 0;
1365 void yaffs_LoadLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
1368 __u32 *map = (__u32 *)tn;
1374 pos &= YAFFS_TNODES_LEVEL0_MASK;
1375 val >>= dev->chunkGroupBits;
1377 bitInMap = pos * dev->tnodeWidth;
1378 wordInMap = bitInMap / 32;
1379 bitInWord = bitInMap & (32 - 1);
1381 mask = dev->tnodeMask << bitInWord;
1383 map[wordInMap] &= ~mask;
1384 map[wordInMap] |= (mask & (val << bitInWord));
1386 if (dev->tnodeWidth > (32 - bitInWord)) {
1387 bitInWord = (32 - bitInWord);
1389 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1390 map[wordInMap] &= ~mask;
1391 map[wordInMap] |= (mask & (val >> bitInWord));
1395 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
1398 __u32 *map = (__u32 *)tn;
1404 pos &= YAFFS_TNODES_LEVEL0_MASK;
1406 bitInMap = pos * dev->tnodeWidth;
1407 wordInMap = bitInMap / 32;
1408 bitInWord = bitInMap & (32 - 1);
1410 val = map[wordInMap] >> bitInWord;
1412 if (dev->tnodeWidth > (32 - bitInWord)) {
1413 bitInWord = (32 - bitInWord);
1415 val |= (map[wordInMap] << bitInWord);
1418 val &= dev->tnodeMask;
1419 val <<= dev->chunkGroupBits;
1424 /* ------------------- End of individual tnode manipulation -----------------*/
1426 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1427 * The look up tree is represented by the top tnode and the number of topLevel
1428 * in the tree. 0 means only the level 0 tnode is in the tree.
1431 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1432 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
1433 yaffs_FileStructure *fStruct,
1436 yaffs_Tnode *tn = fStruct->top;
1438 int requiredTallness;
1439 int level = fStruct->topLevel;
1441 /* Check sane level and chunk Id */
1442 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
1445 if (chunkId > YAFFS_MAX_CHUNK_ID)
1448 /* First check we're tall enough (ie enough topLevel) */
1450 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1451 requiredTallness = 0;
1453 i >>= YAFFS_TNODES_INTERNAL_BITS;
1457 if (requiredTallness > fStruct->topLevel)
1458 return NULL; /* Not tall enough, so we can't find it */
1460 /* Traverse down to level 0 */
1461 while (level > 0 && tn) {
1462 tn = tn->internal[(chunkId >>
1463 (YAFFS_TNODES_LEVEL0_BITS +
1465 YAFFS_TNODES_INTERNAL_BITS)) &
1466 YAFFS_TNODES_INTERNAL_MASK];
1473 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1474 * This happens in two steps:
1475 * 1. If the tree isn't tall enough, then make it taller.
1476 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1478 * Used when modifying the tree.
1480 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1481 * be plugged into the ttree.
1484 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
1485 yaffs_FileStructure *fStruct,
1487 yaffs_Tnode *passedTn)
1489 int requiredTallness;
1497 /* Check sane level and page Id */
1498 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
1501 if (chunkId > YAFFS_MAX_CHUNK_ID)
1504 /* First check we're tall enough (ie enough topLevel) */
1506 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1507 requiredTallness = 0;
1509 x >>= YAFFS_TNODES_INTERNAL_BITS;
1514 if (requiredTallness > fStruct->topLevel) {
1515 /* Not tall enough, gotta make the tree taller */
1516 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1518 tn = yaffs_GetTnode(dev);
1521 tn->internal[0] = fStruct->top;
1523 fStruct->topLevel++;
1525 T(YAFFS_TRACE_ERROR,
1526 (TSTR("yaffs: no more tnodes" TENDSTR)));
1532 /* Traverse down to level 0, adding anything we need */
1534 l = fStruct->topLevel;
1538 while (l > 0 && tn) {
1540 (YAFFS_TNODES_LEVEL0_BITS +
1541 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1542 YAFFS_TNODES_INTERNAL_MASK;
1545 if ((l > 1) && !tn->internal[x]) {
1546 /* Add missing non-level-zero tnode */
1547 tn->internal[x] = yaffs_GetTnode(dev);
1548 if(!tn->internal[x])
1551 } else if (l == 1) {
1552 /* Looking from level 1 at level 0 */
1554 /* If we already have one, then release it.*/
1555 if (tn->internal[x])
1556 yaffs_FreeTnode(dev, tn->internal[x]);
1557 tn->internal[x] = passedTn;
1559 } else if (!tn->internal[x]) {
1560 /* Don't have one, none passed in */
1561 tn->internal[x] = yaffs_GetTnode(dev);
1562 if(!tn->internal[x])
1567 tn = tn->internal[x];
1571 /* top is level 0 */
1573 memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1574 yaffs_FreeTnode(dev, passedTn);
1581 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
1582 yaffs_ExtendedTags *tags, int objectId,
1587 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1588 if (yaffs_CheckChunkBit(dev, theChunk / dev->nChunksPerBlock,
1589 theChunk % dev->nChunksPerBlock)) {
1591 if(dev->chunkGroupSize == 1)
1594 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1596 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1608 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1609 * chunks and tnodes in the file
1610 * Returns 1 if the tree was deleted.
1611 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1614 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
1615 int chunkOffset, int *limit)
1620 yaffs_ExtendedTags tags;
1622 yaffs_Device *dev = in->myDev;
1628 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1630 if (tn->internal[i]) {
1631 if (limit && (*limit) < 0) {
1635 yaffs_DeleteWorker(in,
1643 YAFFS_TNODES_INTERNAL_BITS)
1648 yaffs_FreeTnode(dev,
1651 tn->internal[i] = NULL;
1655 return (allDone) ? 1 : 0;
1656 } else if (level == 0) {
1659 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1661 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1664 chunkInInode = (chunkOffset <<
1665 YAFFS_TNODES_LEVEL0_BITS) + i;
1668 yaffs_FindChunkInGroup(dev,
1674 if (foundChunk > 0) {
1675 yaffs_DeleteChunk(dev,
1680 *limit = *limit - 1;
1687 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1691 return (i < 0) ? 1 : 0;
1701 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1703 yaffs_BlockInfo *theBlock;
1705 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1707 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1709 theBlock->softDeletions++;
1714 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1715 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1717 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1720 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1721 __u32 level, int chunkOffset)
1726 yaffs_Device *dev = in->myDev;
1731 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1733 if (tn->internal[i]) {
1735 yaffs_SoftDeleteWorker(in,
1741 YAFFS_TNODES_INTERNAL_BITS)
1744 yaffs_FreeTnode(dev,
1747 tn->internal[i] = NULL;
1749 /* Hoosterman... how could this happen? */
1753 return (allDone) ? 1 : 0;
1754 } else if (level == 0) {
1756 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1757 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1759 /* Note this does not find the real chunk, only the chunk group.
1760 * We make an assumption that a chunk group is not larger than
1763 yaffs_SoftDeleteChunk(dev, theChunk);
1764 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1778 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1781 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1782 if (obj->nDataChunks <= 0) {
1783 /* Empty file with no duplicate object headers, just delete it immediately */
1784 yaffs_FreeTnode(obj->myDev,
1785 obj->variant.fileVariant.top);
1786 obj->variant.fileVariant.top = NULL;
1787 T(YAFFS_TRACE_TRACING,
1788 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1790 yaffs_DoGenericObjectDeletion(obj);
1792 yaffs_SoftDeleteWorker(obj,
1793 obj->variant.fileVariant.top,
1794 obj->variant.fileVariant.
1796 obj->softDeleted = 1;
1801 /* Pruning removes any part of the file structure tree that is beyond the
1802 * bounds of the file (ie that does not point to chunks).
1804 * A file should only get pruned when its size is reduced.
1806 * Before pruning, the chunks must be pulled from the tree and the
1807 * level 0 tnode entries must be zeroed out.
1808 * Could also use this for file deletion, but that's probably better handled
1809 * by a special case.
1811 * This function is recursive. For levels > 0 the function is called again on
1812 * any sub-tree. For level == 0 we just check if the sub-tree has data.
1813 * If there is no data in a subtree then it is pruned.
1816 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1817 __u32 level, int del0)
1826 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1827 if (tn->internal[i]) {
1829 yaffs_PruneWorker(dev, tn->internal[i],
1831 (i == 0) ? del0 : 1);
1834 if (tn->internal[i])
1839 __u32 *map = (__u32 *)tn;
1840 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1842 if (tnodeSize < sizeof(yaffs_Tnode))
1843 tnodeSize = sizeof(yaffs_Tnode);
1844 tnodeSize /= sizeof(__u32);
1846 for(i = 0; !hasData && i < tnodeSize; i++){
1852 if (hasData == 0 && del0) {
1853 /* Free and return NULL */
1855 yaffs_FreeTnode(dev, tn);
1865 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1866 yaffs_FileStructure *fStruct)
1873 if (fStruct->topLevel > 0) {
1875 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1877 /* Now we have a tree with all the non-zero branches NULL but the height
1878 * is the same as it was.
1879 * Let's see if we can trim internal tnodes to shorten the tree.
1880 * We can do this if only the 0th element in the tnode is in use
1881 * (ie all the non-zero are NULL)
1884 while (fStruct->topLevel && !done) {
1888 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1889 if (tn->internal[i])
1894 fStruct->top = tn->internal[0];
1895 fStruct->topLevel--;
1896 yaffs_FreeTnode(dev, tn);
1906 /*-------------------- End of File Structure functions.-------------------*/
1908 /* yaffs_CreateFreeObjects creates a bunch more objects and
1909 * adds them to the object free list.
1911 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1914 yaffs_Object *newObjects;
1915 yaffs_ObjectList *list;
1920 /* make these things */
1921 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1922 list = YMALLOC(sizeof(yaffs_ObjectList));
1924 if (!newObjects || !list) {
1933 T(YAFFS_TRACE_ALLOCATE,
1934 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1938 /* Hook them into the free list */
1939 for (i = 0; i < nObjects - 1; i++) {
1940 newObjects[i].siblings.next =
1941 (struct ylist_head *)(&newObjects[i + 1]);
1944 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1945 dev->freeObjects = newObjects;
1946 dev->nFreeObjects += nObjects;
1947 dev->nObjectsCreated += nObjects;
1949 /* Now add this bunch of Objects to a list for freeing up. */
1951 list->objects = newObjects;
1952 list->next = dev->allocatedObjectList;
1953 dev->allocatedObjectList = list;
1959 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1960 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1962 yaffs_Object *tn = NULL;
1964 #ifdef VALGRIND_TEST
1965 tn = YMALLOC(sizeof(yaffs_Object));
1967 /* If there are none left make more */
1968 if (!dev->freeObjects)
1969 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1971 if (dev->freeObjects) {
1972 tn = dev->freeObjects;
1974 (yaffs_Object *) (dev->freeObjects->siblings.next);
1975 dev->nFreeObjects--;
1979 /* Now sweeten it up... */
1981 memset(tn, 0, sizeof(yaffs_Object));
1982 tn->beingCreated = 1;
1986 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1987 YINIT_LIST_HEAD(&(tn->hardLinks));
1988 YINIT_LIST_HEAD(&(tn->hashLink));
1989 YINIT_LIST_HEAD(&tn->siblings);
1992 /* Now make the directory sane */
1994 tn->parent = dev->rootDir;
1995 ylist_add(&(tn->siblings), &dev->rootDir->variant.directoryVariant.children);
1998 /* Add it to the lost and found directory.
1999 * NB Can't put root or lostNFound in lostNFound so
2000 * check if lostNFound exists first
2002 if (dev->lostNFoundDir)
2003 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
2005 tn->beingCreated = 0;
2008 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2013 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
2018 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
2020 obj->fake = 1; /* it is fake so it might have no NAND presence... */
2021 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
2022 obj->unlinkAllowed = 0; /* ... or unlink it */
2025 obj->yst_mode = mode;
2027 obj->hdrChunk = 0; /* Not a valid chunk. */
2034 static void yaffs_UnhashObject(yaffs_Object *tn)
2037 yaffs_Device *dev = tn->myDev;
2039 /* If it is still linked into the bucket list, free from the list */
2040 if (!ylist_empty(&tn->hashLink)) {
2041 ylist_del_init(&tn->hashLink);
2042 bucket = yaffs_HashFunction(tn->objectId);
2043 dev->objectBucket[bucket].count--;
2047 /* FreeObject frees up a Object and puts it back on the free list */
2048 static void yaffs_FreeObject(yaffs_Object *tn)
2050 yaffs_Device *dev = tn->myDev;
2053 T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), tn, tn->myInode));
2058 if (!ylist_empty(&tn->siblings))
2064 /* We're still hooked up to a cached inode.
2065 * Don't delete now, but mark for later deletion
2067 tn->deferedFree = 1;
2072 yaffs_UnhashObject(tn);
2074 #ifdef VALGRIND_TEST
2078 /* Link into the free list. */
2079 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2080 dev->freeObjects = tn;
2081 dev->nFreeObjects++;
2083 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2088 void yaffs_HandleDeferedFree(yaffs_Object *obj)
2090 if (obj->deferedFree)
2091 yaffs_FreeObject(obj);
2096 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
2098 /* Free the list of allocated Objects */
2100 yaffs_ObjectList *tmp;
2102 while (dev->allocatedObjectList) {
2103 tmp = dev->allocatedObjectList->next;
2104 YFREE(dev->allocatedObjectList->objects);
2105 YFREE(dev->allocatedObjectList);
2107 dev->allocatedObjectList = tmp;
2110 dev->freeObjects = NULL;
2111 dev->nFreeObjects = 0;
2114 static void yaffs_InitialiseObjects(yaffs_Device *dev)
2118 dev->allocatedObjectList = NULL;
2119 dev->freeObjects = NULL;
2120 dev->nFreeObjects = 0;
2122 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2123 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2124 dev->objectBucket[i].count = 0;
2128 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
2133 int lowest = 999999;
2135 /* First let's see if we can find one that's empty. */
2137 for (i = 0; i < 10 && lowest > 0; i++) {
2139 x %= YAFFS_NOBJECT_BUCKETS;
2140 if (dev->objectBucket[x].count < lowest) {
2141 lowest = dev->objectBucket[x].count;
2147 /* If we didn't find an empty list, then try
2148 * looking a bit further for a short one
2151 for (i = 0; i < 10 && lowest > 3; i++) {
2153 x %= YAFFS_NOBJECT_BUCKETS;
2154 if (dev->objectBucket[x].count < lowest) {
2155 lowest = dev->objectBucket[x].count;
2164 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
2166 int bucket = yaffs_FindNiceObjectBucket(dev);
2168 /* Now find an object value that has not already been taken
2169 * by scanning the list.
2173 struct ylist_head *i;
2175 __u32 n = (__u32) bucket;
2177 /* yaffs_CheckObjectHashSanity(); */
2181 n += YAFFS_NOBJECT_BUCKETS;
2182 if (1 || dev->objectBucket[bucket].count > 0) {
2183 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2184 /* If there is already one in the list */
2185 if (i && ylist_entry(i, yaffs_Object,
2186 hashLink)->objectId == n) {
2196 static void yaffs_HashObject(yaffs_Object *in)
2198 int bucket = yaffs_HashFunction(in->objectId);
2199 yaffs_Device *dev = in->myDev;
2201 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2202 dev->objectBucket[bucket].count++;
2205 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
2207 int bucket = yaffs_HashFunction(number);
2208 struct ylist_head *i;
2211 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2212 /* Look if it is in the list */
2214 in = ylist_entry(i, yaffs_Object, hashLink);
2215 if (in->objectId == number) {
2217 /* Don't tell the VFS about this one if it is defered free */
2218 if (in->deferedFree)
2230 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
2231 yaffs_ObjectType type)
2233 yaffs_Object *theObject;
2234 yaffs_Tnode *tn = NULL;
2237 number = yaffs_CreateNewObjectNumber(dev);
2239 if (type == YAFFS_OBJECT_TYPE_FILE) {
2240 tn = yaffs_GetTnode(dev);
2245 theObject = yaffs_AllocateEmptyObject(dev);
2248 yaffs_FreeTnode(dev,tn);
2254 theObject->fake = 0;
2255 theObject->renameAllowed = 1;
2256 theObject->unlinkAllowed = 1;
2257 theObject->objectId = number;
2258 yaffs_HashObject(theObject);
2259 theObject->variantType = type;
2260 #ifdef CONFIG_YAFFS_WINCE
2261 yfsd_WinFileTimeNow(theObject->win_atime);
2262 theObject->win_ctime[0] = theObject->win_mtime[0] =
2263 theObject->win_atime[0];
2264 theObject->win_ctime[1] = theObject->win_mtime[1] =
2265 theObject->win_atime[1];
2269 theObject->yst_atime = theObject->yst_mtime =
2270 theObject->yst_ctime = Y_CURRENT_TIME;
2273 case YAFFS_OBJECT_TYPE_FILE:
2274 theObject->variant.fileVariant.fileSize = 0;
2275 theObject->variant.fileVariant.scannedFileSize = 0;
2276 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2277 theObject->variant.fileVariant.topLevel = 0;
2278 theObject->variant.fileVariant.top = tn;
2280 case YAFFS_OBJECT_TYPE_DIRECTORY:
2281 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2284 case YAFFS_OBJECT_TYPE_SYMLINK:
2285 case YAFFS_OBJECT_TYPE_HARDLINK:
2286 case YAFFS_OBJECT_TYPE_SPECIAL:
2287 /* No action required */
2289 case YAFFS_OBJECT_TYPE_UNKNOWN:
2290 /* todo this should not happen */
2298 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
2300 yaffs_ObjectType type)
2302 yaffs_Object *theObject = NULL;
2305 theObject = yaffs_FindObjectByNumber(dev, number);
2308 theObject = yaffs_CreateNewObject(dev, number, type);
2315 static YCHAR *yaffs_CloneString(const YCHAR *str)
2317 YCHAR *newStr = NULL;
2323 len = yaffs_strnlen(str,YAFFS_MAX_ALIAS_LENGTH);
2324 newStr = YMALLOC((len + 1) * sizeof(YCHAR));
2326 yaffs_strncpy(newStr, str,len);
2334 * Mknod (create) a new object.
2335 * equivalentObject only has meaning for a hard link;
2336 * aliasString only has meaning for a symlink.
2337 * rdev only has meaning for devices (a subset of special objects)
2340 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2341 yaffs_Object *parent,
2346 yaffs_Object *equivalentObject,
2347 const YCHAR *aliasString, __u32 rdev)
2352 yaffs_Device *dev = parent->myDev;
2354 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2355 if (yaffs_FindObjectByName(parent, name))
2358 if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2359 str = yaffs_CloneString(aliasString);
2364 in = yaffs_CreateNewObject(dev, -1, type);
2378 in->variantType = type;
2380 in->yst_mode = mode;
2382 #ifdef CONFIG_YAFFS_WINCE
2383 yfsd_WinFileTimeNow(in->win_atime);
2384 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2385 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2388 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2390 in->yst_rdev = rdev;
2394 in->nDataChunks = 0;
2396 yaffs_SetObjectName(in, name);
2399 yaffs_AddObjectToDirectory(parent, in);
2401 in->myDev = parent->myDev;
2404 case YAFFS_OBJECT_TYPE_SYMLINK:
2405 in->variant.symLinkVariant.alias = str;
2407 case YAFFS_OBJECT_TYPE_HARDLINK:
2408 in->variant.hardLinkVariant.equivalentObject =
2410 in->variant.hardLinkVariant.equivalentObjectId =
2411 equivalentObject->objectId;
2412 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2414 case YAFFS_OBJECT_TYPE_FILE:
2415 case YAFFS_OBJECT_TYPE_DIRECTORY:
2416 case YAFFS_OBJECT_TYPE_SPECIAL:
2417 case YAFFS_OBJECT_TYPE_UNKNOWN:
2422 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2423 /* Could not create the object header, fail the creation */
2424 yaffs_DeleteObject(in);
2428 yaffs_UpdateParent(parent);
2434 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
2435 __u32 mode, __u32 uid, __u32 gid)
2437 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2438 uid, gid, NULL, NULL, 0);
2441 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
2442 __u32 mode, __u32 uid, __u32 gid)
2444 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2445 mode, uid, gid, NULL, NULL, 0);
2448 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
2449 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2451 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2452 uid, gid, NULL, NULL, rdev);
2455 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
2456 __u32 mode, __u32 uid, __u32 gid,
2459 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2460 uid, gid, NULL, alias, 0);
2463 /* yaffs_Link returns the object id of the equivalent object.*/
2464 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
2465 yaffs_Object *equivalentObject)
2467 /* Get the real object in case we were fed a hard link as an equivalent object */
2468 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2470 if (yaffs_MknodObject
2471 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2472 equivalentObject, NULL, 0)) {
2473 return equivalentObject;
2480 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
2481 const YCHAR *newName, int force, int shadows)
2486 yaffs_Object *existingTarget;
2489 newDir = obj->parent; /* use the old directory */
2491 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2492 T(YAFFS_TRACE_ALWAYS,
2494 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2499 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2500 if (obj->myDev->isYaffs2)
2501 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2503 unlinkOp = (newDir == obj->myDev->unlinkedDir
2504 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2506 deleteOp = (newDir == obj->myDev->deletedDir);
2508 existingTarget = yaffs_FindObjectByName(newDir, newName);
2510 /* If the object is a file going into the unlinked directory,
2511 * then it is OK to just stuff it in since duplicate names are allowed.
2512 * else only proceed if the new name does not exist and if we're putting
2513 * it into a directory.
2520 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2521 yaffs_SetObjectName(obj, newName);
2524 yaffs_AddObjectToDirectory(newDir, obj);
2529 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2530 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows) >= 0)
2537 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
2538 yaffs_Object *newDir, const YCHAR *newName)
2540 yaffs_Object *obj = NULL;
2541 yaffs_Object *existingTarget = NULL;
2547 if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2549 if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2552 dev = oldDir->myDev;
2554 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2555 /* Special case for case insemsitive systems (eg. WinCE).
2556 * While look-up is case insensitive, the name isn't.
2557 * Therefore we might want to change x.txt to X.txt
2559 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
2563 if(yaffs_strnlen(newName,YAFFS_MAX_NAME_LENGTH+1) > YAFFS_MAX_NAME_LENGTH)
2567 obj = yaffs_FindObjectByName(oldDir, oldName);
2569 if (obj && obj->renameAllowed) {
2571 /* Now do the handling for an existing target, if there is one */
2573 existingTarget = yaffs_FindObjectByName(newDir, newName);
2574 if (existingTarget &&
2575 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2576 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2577 /* There is a target that is a non-empty directory, so we fail */
2578 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2579 } else if (existingTarget && existingTarget != obj) {
2580 /* Nuke the target first, using shadowing,
2581 * but only if it isn't the same object.
2583 * Note we must disable gc otherwise it can mess up the shadowing.
2587 yaffs_ChangeObjectName(obj, newDir, newName, force,
2588 existingTarget->objectId);
2589 existingTarget->isShadowed = 1;
2590 yaffs_UnlinkObject(existingTarget);
2594 result = yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2596 yaffs_UpdateParent(oldDir);
2597 if(newDir != oldDir)
2598 yaffs_UpdateParent(newDir);
2605 /*------------------------- Block Management and Page Allocation ----------------*/
2607 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
2609 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2611 dev->blockInfo = NULL;
2612 dev->chunkBits = NULL;
2614 dev->allocationBlock = -1; /* force it to get a new one */
2616 /* If the first allocation strategy fails, thry the alternate one */
2617 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2618 if (!dev->blockInfo) {
2619 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2620 dev->blockInfoAlt = 1;
2622 dev->blockInfoAlt = 0;
2624 if (dev->blockInfo) {
2625 /* Set up dynamic blockinfo stuff. */
2626 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2627 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2628 if (!dev->chunkBits) {
2629 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2630 dev->chunkBitsAlt = 1;
2632 dev->chunkBitsAlt = 0;
2635 if (dev->blockInfo && dev->chunkBits) {
2636 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2637 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2644 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2646 if (dev->blockInfoAlt && dev->blockInfo)
2647 YFREE_ALT(dev->blockInfo);
2648 else if (dev->blockInfo)
2649 YFREE(dev->blockInfo);
2651 dev->blockInfoAlt = 0;
2653 dev->blockInfo = NULL;
2655 if (dev->chunkBitsAlt && dev->chunkBits)
2656 YFREE_ALT(dev->chunkBits);
2657 else if (dev->chunkBits)
2658 YFREE(dev->chunkBits);
2659 dev->chunkBitsAlt = 0;
2660 dev->chunkBits = NULL;
2663 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
2664 yaffs_BlockInfo *bi)
2671 return 1; /* disqualification only applies to yaffs2. */
2673 if (!bi->hasShrinkHeader)
2674 return 1; /* can gc */
2676 /* Find the oldest dirty sequence number if we don't know it and save it
2677 * so we don't have to keep recomputing it.
2679 if (!dev->oldestDirtySequence) {
2680 seq = dev->sequenceNumber;
2682 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2684 b = yaffs_GetBlockInfo(dev, i);
2685 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2686 (b->pagesInUse - b->softDeletions) <
2687 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2688 seq = b->sequenceNumber;
2691 dev->oldestDirtySequence = seq;
2694 /* Can't do gc of this block if there are any blocks older than this one that have
2697 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2700 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2701 * for garbage collection.
2704 static int yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
2707 int b = dev->currentDirtyChecker;
2713 int prioritised = 0;
2714 yaffs_BlockInfo *bi;
2715 int pendingPrioritisedExist = 0;
2717 /* First let's see if we need to grab a prioritised block */
2718 if (dev->hasPendingPrioritisedGCs) {
2719 for (i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++) {
2721 bi = yaffs_GetBlockInfo(dev, i);
2722 /* yaffs_VerifyBlock(dev,bi,i); */
2724 if (bi->gcPrioritise) {
2725 pendingPrioritisedExist = 1;
2726 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2727 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2728 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2731 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2736 if (!pendingPrioritisedExist) /* None found, so we can clear this */
2737 dev->hasPendingPrioritisedGCs = 0;
2740 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2742 * else (we're doing a leasurely gc), then we only bother to do this if the
2743 * block has only a few pages in use.
2746 dev->nonAggressiveSkip--;
2748 if (!aggressive && (dev->nonAggressiveSkip > 0))
2753 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2757 dev->internalEndBlock - dev->internalStartBlock + 1;
2760 dev->internalEndBlock - dev->internalStartBlock + 1;
2761 iterations = iterations / 16;
2762 if (iterations > 200)
2766 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2768 if (b < dev->internalStartBlock || b > dev->internalEndBlock)
2769 b = dev->internalStartBlock;
2771 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2772 T(YAFFS_TRACE_ERROR,
2773 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2777 bi = yaffs_GetBlockInfo(dev, b);
2779 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2780 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2781 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2783 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2787 dev->currentDirtyChecker = b;
2791 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2792 dev->nChunksPerBlock - pagesInUse, prioritised));
2795 dev->oldestDirtySequence = 0;
2798 dev->nonAggressiveSkip = 4;
2803 static void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
2805 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2809 /* If the block is still healthy erase it and mark as clean.
2810 * If the block has had a data failure, then retire it.
2813 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2814 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2815 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2817 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2819 if (!bi->needsRetiring) {
2820 yaffs_InvalidateCheckpoint(dev);
2821 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2823 dev->nErasureFailures++;
2824 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2825 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2830 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2832 for (i = 0; i < dev->nChunksPerBlock; i++) {
2833 if (!yaffs_CheckChunkErased
2834 (dev, blockNo * dev->nChunksPerBlock + i)) {
2835 T(YAFFS_TRACE_ERROR,
2837 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2838 TENDSTR), blockNo, i));
2844 /* Clean it up... */
2845 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2846 dev->nErasedBlocks++;
2848 bi->softDeletions = 0;
2849 bi->hasShrinkHeader = 0;
2850 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2851 bi->gcPrioritise = 0;
2852 yaffs_ClearChunkBits(dev, blockNo);
2854 T(YAFFS_TRACE_ERASE,
2855 (TSTR("Erased block %d" TENDSTR), blockNo));
2857 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2859 yaffs_RetireBlock(dev, blockNo);
2860 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2861 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2865 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2869 yaffs_BlockInfo *bi;
2871 if (dev->nErasedBlocks < 1) {
2872 /* Hoosterman we've got a problem.
2873 * Can't get space to gc
2875 T(YAFFS_TRACE_ERROR,
2876 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2881 /* Find an empty block. */
2883 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2884 dev->allocationBlockFinder++;
2885 if (dev->allocationBlockFinder < dev->internalStartBlock
2886 || dev->allocationBlockFinder > dev->internalEndBlock) {
2887 dev->allocationBlockFinder = dev->internalStartBlock;
2890 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2892 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2893 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2894 dev->sequenceNumber++;
2895 bi->sequenceNumber = dev->sequenceNumber;
2896 dev->nErasedBlocks--;
2897 T(YAFFS_TRACE_ALLOCATE,
2898 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2899 dev->allocationBlockFinder, dev->sequenceNumber,
2900 dev->nErasedBlocks));
2901 return dev->allocationBlockFinder;
2905 T(YAFFS_TRACE_ALWAYS,
2907 ("yaffs tragedy: no more erased blocks, but there should have been %d"
2908 TENDSTR), dev->nErasedBlocks));
2915 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2917 if (!dev->nCheckpointBlocksRequired &&
2919 /* Not a valid value so recalculate */
2922 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2925 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2927 if (tnodeSize < sizeof(yaffs_Tnode))
2928 tnodeSize = sizeof(yaffs_Tnode);
2930 nBytes += sizeof(yaffs_CheckpointValidity);
2931 nBytes += sizeof(yaffs_CheckpointDevice);
2932 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2933 nBytes += devBlocks * dev->chunkBitmapStride;
2934 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2935 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2936 nBytes += sizeof(yaffs_CheckpointValidity);
2937 nBytes += sizeof(__u32); /* checksum*/
2939 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2941 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2943 dev->nCheckpointBlocksRequired = nBlocks;
2946 return dev->nCheckpointBlocksRequired;
2950 * Check if there's space to allocate...
2951 * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2953 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev)
2956 int reservedBlocks = dev->nReservedBlocks;
2957 int checkpointBlocks;
2959 if (dev->isYaffs2) {
2960 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
2961 dev->blocksInCheckpoint;
2962 if (checkpointBlocks < 0)
2963 checkpointBlocks = 0;
2965 checkpointBlocks = 0;
2968 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2970 return (dev->nFreeChunks > reservedChunks);
2973 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
2974 yaffs_BlockInfo **blockUsedPtr)
2977 yaffs_BlockInfo *bi;
2979 if (dev->allocationBlock < 0) {
2980 /* Get next block to allocate off */
2981 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2982 dev->allocationPage = 0;
2985 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2986 /* Not enough space to allocate unless we're allowed to use the reserve. */
2990 if (dev->nErasedBlocks < dev->nReservedBlocks
2991 && dev->allocationPage == 0) {
2992 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2995 /* Next page please.... */
2996 if (dev->allocationBlock >= 0) {
2997 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2999 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
3000 dev->allocationPage;
3002 yaffs_SetChunkBit(dev, dev->allocationBlock,
3003 dev->allocationPage);
3005 dev->allocationPage++;
3009 /* If the block is full set the state to full */
3010 if (dev->allocationPage >= dev->nChunksPerBlock) {
3011 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3012 dev->allocationBlock = -1;
3021 T(YAFFS_TRACE_ERROR,
3022 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
3027 static int yaffs_GetErasedChunks(yaffs_Device *dev)
3031 n = dev->nErasedBlocks * dev->nChunksPerBlock;
3033 if (dev->allocationBlock > 0)
3034 n += (dev->nChunksPerBlock - dev->allocationPage);
3041 * yaffs_SkipRestOfBlock() skips over the rest of the allocation block
3042 * if we don't want to write to it.
3044 static void yaffs_SkipRestOfBlock(yaffs_Device *dev)
3046 if(dev->allocationBlock > 0){
3047 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3048 if(bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING){
3049 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3050 dev->allocationBlock = -1;
3056 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
3062 int retVal = YAFFS_OK;
3065 int isCheckpointBlock;
3069 int chunksBefore = yaffs_GetErasedChunks(dev);
3072 yaffs_ExtendedTags tags;
3074 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3076 yaffs_Object *object;
3078 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3081 T(YAFFS_TRACE_TRACING,
3082 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3085 bi->hasShrinkHeader,
3088 /*yaffs_VerifyFreeChunks(dev); */
3090 if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
3091 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3093 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
3095 /* Take off the number of soft deleted entries because
3096 * they're going to get really deleted during GC.
3098 if(dev->gcChunk == 0) /* first time through for this block */
3099 dev->nFreeChunks -= bi->softDeletions;
3103 if (isCheckpointBlock ||
3104 !yaffs_StillSomeChunkBits(dev, block)) {
3105 T(YAFFS_TRACE_TRACING,
3107 ("Collecting block %d that has no chunks in use" TENDSTR),
3109 yaffs_BlockBecameDirty(dev, block);
3112 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3114 yaffs_VerifyBlock(dev, bi, block);
3116 maxCopies = (wholeBlock) ? dev->nChunksPerBlock : 10;
3117 oldChunk = block * dev->nChunksPerBlock + dev->gcChunk;
3119 for (/* init already done */;
3120 retVal == YAFFS_OK &&
3121 dev->gcChunk < dev->nChunksPerBlock &&
3122 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
3124 dev->gcChunk++, oldChunk++) {
3125 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3127 /* This page is in use and might need to be copied off */
3133 yaffs_InitialiseTags(&tags);
3135 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3139 yaffs_FindObjectByNumber(dev,
3142 T(YAFFS_TRACE_GC_DETAIL,
3144 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3145 dev->gcChunk, tags.objectId, tags.chunkId,
3148 if (object && !yaffs_SkipVerification(dev)) {
3149 if (tags.chunkId == 0)
3150 matchingChunk = object->hdrChunk;
3151 else if (object->softDeleted)
3152 matchingChunk = oldChunk; /* Defeat the test */
3154 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
3156 if (oldChunk != matchingChunk)
3157 T(YAFFS_TRACE_ERROR,
3158 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3159 oldChunk, matchingChunk, tags.objectId, tags.chunkId));
3164 T(YAFFS_TRACE_ERROR,
3166 ("page %d in gc has no object: %d %d %d "
3168 tags.objectId, tags.chunkId, tags.byteCount));
3173 object->softDeleted &&
3174 tags.chunkId != 0) {
3175 /* Data chunk in a soft deleted file, throw it away
3176 * It's a soft deleted data chunk,
3177 * No need to copy this, just forget about it and
3178 * fix up the object.
3181 object->nDataChunks--;
3183 if (object->nDataChunks <= 0) {
3184 /* remeber to clean up the object */
3185 dev->gcCleanupList[cleanups] =
3191 /* Todo object && object->deleted && object->nDataChunks == 0 */
3192 /* Deleted object header with no data chunks.
3193 * Can be discarded and the file deleted.
3195 object->hdrChunk = 0;
3196 yaffs_FreeTnode(object->myDev,
3199 object->variant.fileVariant.top = NULL;
3200 yaffs_DoGenericObjectDeletion(object);
3202 } else if (object) {
3203 /* It's either a data chunk in a live file or
3204 * an ObjectHeader, so we're interested in it.
3205 * NB Need to keep the ObjectHeaders of deleted files
3206 * until the whole file has been deleted off
3208 tags.serialNumber++;
3212 if (tags.chunkId == 0) {
3213 /* It is an object Id,
3214 * We need to nuke the shrinkheader flags first
3215 * Also need to clean up shadowing.
3216 * We no longer want the shrinkHeader flag since its work is done
3217 * and if it is left in place it will mess up scanning.
3220 yaffs_ObjectHeader *oh;
3221 oh = (yaffs_ObjectHeader *)buffer;
3223 tags.extraIsShrinkHeader = 0;
3224 oh->shadowsObject = 0;
3225 oh->inbandShadowsObject = 0;
3226 tags.extraShadows = 0;
3228 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
3232 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3235 retVal = YAFFS_FAIL;
3238 /* Ok, now fix up the Tnodes etc. */
3240 if (tags.chunkId == 0) {
3242 object->hdrChunk = newChunk;
3243 object->serial = tags.serialNumber;
3245 /* It's a data chunk */
3246 yaffs_PutChunkIntoFile
3254 if (retVal == YAFFS_OK)
3255 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3260 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3263 /* Do any required cleanups */
3264 for (i = 0; i < cleanups; i++) {
3265 /* Time to delete the file too */
3267 yaffs_FindObjectByNumber(dev,
3268 dev->gcCleanupList[i]);
3270 yaffs_FreeTnode(dev,
3271 object->variant.fileVariant.
3273 object->variant.fileVariant.top = NULL;
3276 ("yaffs: About to finally delete object %d"
3277 TENDSTR), object->objectId));
3278 yaffs_DoGenericObjectDeletion(object);
3279 object->myDev->nDeletedFiles--;
3286 yaffs_VerifyCollectedBlock(dev, bi, block);
3288 chunksAfter = yaffs_GetErasedChunks(dev);
3289 if (chunksBefore >= chunksAfter) {
3292 ("gc did not increase free chunks before %d after %d"
3293 TENDSTR), chunksBefore, chunksAfter));
3296 /* If the gc completed then clear the current gcBlock so that we find another. */
3297 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING) {
3307 /* New garbage collector
3308 * If we're very low on erased blocks then we do aggressive garbage collection
3309 * otherwise we do "leasurely" garbage collection.
3310 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3311 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3313 * The idea is to help clear out space in a more spread-out manner.
3314 * Dunno if it really does anything useful.
3316 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
3320 int gcOk = YAFFS_OK;
3323 int checkpointBlockAdjust;
3325 if (dev->isDoingGC) {
3326 /* Bail out so we don't get recursive gc */
3330 /* This loop should pass the first time.
3331 * We'll only see looping here if the erase of the collected block fails.
3337 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3338 if (checkpointBlockAdjust < 0)
3339 checkpointBlockAdjust = 0;
3341 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3342 /* We need a block soon...*/
3345 /* We're in no hurry */
3349 if (dev->gcBlock <= 0) {
3350 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3354 block = dev->gcBlock;
3357 dev->garbageCollections++;
3359 dev->passiveGarbageCollections++;
3363 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3364 dev->nErasedBlocks, aggressive));
3366 gcOk = yaffs_GarbageCollectBlock(dev, block, aggressive);
3369 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3372 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3373 TENDSTR), dev->nErasedBlocks, maxTries, block));
3375 } while ((dev->nErasedBlocks < dev->nReservedBlocks) &&
3379 return aggressive ? gcOk : YAFFS_OK;
3382 /*------------------------- TAGS --------------------------------*/
3384 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
3387 return (tags->chunkId == chunkInObject &&
3388 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3393 /*-------------------- Data file manipulation -----------------*/
3395 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
3396 yaffs_ExtendedTags *tags)
3398 /*Get the Tnode, then get the level 0 offset chunk offset */
3401 yaffs_ExtendedTags localTags;
3404 yaffs_Device *dev = in->myDev;
3407 /* Passed a NULL, so use our own tags space */
3411 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3414 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3417 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3423 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
3424 yaffs_ExtendedTags *tags)
3426 /* Get the Tnode, then get the level 0 offset chunk offset */
3429 yaffs_ExtendedTags localTags;
3431 yaffs_Device *dev = in->myDev;
3435 /* Passed a NULL, so use our own tags space */
3439 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3443 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3446 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3449 /* Delete the entry in the filestructure (if found) */
3451 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, 0);
3457 #ifdef YAFFS_PARANOID
3459 static int yaffs_CheckFileSanity(yaffs_Object *in)
3467 yaffs_Tags localTags;
3468 yaffs_Tags *tags = &localTags;
3472 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3475 objId = in->objectId;
3476 fSize = in->variant.fileVariant.fileSize;
3478 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3480 for (chunk = 1; chunk <= nChunks; chunk++) {
3481 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3486 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunk);
3488 if (yaffs_CheckChunkBits
3489 (dev, theChunk / dev->nChunksPerBlock,
3490 theChunk % dev->nChunksPerBlock)) {
3492 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3496 (tags, in->objectId, chunk, chunkDeleted)) {
3506 /* T(("No level 0 found for %d\n", chunk)); */
3510 return failed ? YAFFS_FAIL : YAFFS_OK;
3515 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
3516 int chunkInNAND, int inScan)
3518 /* NB inScan is zero unless scanning.
3519 * For forward scanning, inScan is > 0;
3520 * for backward scanning inScan is < 0
3522 * chunkInNAND = 0 is a dummy insert to make sure the tnodes are there.
3526 yaffs_Device *dev = in->myDev;
3528 yaffs_ExtendedTags existingTags;
3529 yaffs_ExtendedTags newTags;
3530 unsigned existingSerial, newSerial;
3532 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3533 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3534 * If it is not during Scanning then something went wrong!
3537 T(YAFFS_TRACE_ERROR,
3539 ("yaffs tragedy:attempt to put data chunk into a non-file"
3544 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3548 tn = yaffs_AddOrFindLevel0Tnode(dev,
3549 &in->variant.fileVariant,
3556 /* Dummy insert, bail now */
3560 existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3563 /* If we're scanning then we need to test for duplicates
3564 * NB This does not need to be efficient since it should only ever
3565 * happen when the power fails during a write, then only one
3566 * chunk should ever be affected.
3568 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3569 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3572 if (existingChunk > 0) {
3573 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3574 * thus we have to do a FindChunkInFile to get the real chunk id.
3576 * We have a duplicate now we need to decide which one to use:
3578 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3579 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3580 * YAFFS1: Get both sets of tags and compare serial numbers.
3584 /* Only do this for forward scanning */
3585 yaffs_ReadChunkWithTagsFromNAND(dev,
3589 /* Do a proper find */
3591 yaffs_FindChunkInFile(in, chunkInInode,
3595 if (existingChunk <= 0) {
3596 /*Hoosterman - how did this happen? */
3598 T(YAFFS_TRACE_ERROR,
3600 ("yaffs tragedy: existing chunk < 0 in scan"
3605 /* NB The deleted flags should be false, otherwise the chunks will
3606 * not be loaded during a scan
3610 newSerial = newTags.serialNumber;
3611 existingSerial = existingTags.serialNumber;
3615 (in->myDev->isYaffs2 ||
3616 existingChunk <= 0 ||
3617 ((existingSerial + 1) & 3) == newSerial)) {
3618 /* Forward scanning.
3620 * Delete the old one and drop through to update the tnode
3622 yaffs_DeleteChunk(dev, existingChunk, 1,
3625 /* Backward scanning or we want to use the existing one
3627 * Delete the new one and return early so that the tnode isn't changed
3629 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3637 if (existingChunk == 0)
3640 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
3645 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
3648 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3650 if (chunkInNAND >= 0)
3651 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3654 T(YAFFS_TRACE_NANDACCESS,
3655 (TSTR("Chunk %d not found zero instead" TENDSTR),
3657 /* get sane (zero) data if you read a hole */
3658 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3664 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
3668 yaffs_ExtendedTags tags;
3669 yaffs_BlockInfo *bi;
3675 block = chunkId / dev->nChunksPerBlock;
3676 page = chunkId % dev->nChunksPerBlock;
3679 if (!yaffs_CheckChunkBit(dev, block, page))
3680 T(YAFFS_TRACE_VERIFY,
3681 (TSTR("Deleting invalid chunk %d"TENDSTR),
3684 bi = yaffs_GetBlockInfo(dev, block);
3686 T(YAFFS_TRACE_DELETION,
3687 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3690 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3692 yaffs_InitialiseTags(&tags);
3694 tags.chunkDeleted = 1;
3696 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3697 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3699 dev->nUnmarkedDeletions++;
3702 /* Pull out of the management area.
3703 * If the whole block became dirty, this will kick off an erasure.
3705 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3706 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3707 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3708 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3711 yaffs_ClearChunkBit(dev, block, page);
3715 if (bi->pagesInUse == 0 &&
3716 !bi->hasShrinkHeader &&
3717 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3718 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3719 yaffs_BlockBecameDirty(dev, block);
3726 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
3727 const __u8 *buffer, int nBytes,
3730 /* Find old chunk Need to do this to get serial number
3731 * Write new one and patch into tree.
3732 * Invalidate old tags.
3736 yaffs_ExtendedTags prevTags;
3739 yaffs_ExtendedTags newTags;
3741 yaffs_Device *dev = in->myDev;
3743 yaffs_CheckGarbageCollection(dev);
3745 /* Get the previous chunk at this location in the file if it exists */
3746 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3748 /* Set up new tags */
3749 yaffs_InitialiseTags(&newTags);
3751 newTags.chunkId = chunkInInode;
3752 newTags.objectId = in->objectId;
3753 newTags.serialNumber =
3754 (prevChunkId > 0) ? prevTags.serialNumber + 1 : 1;
3755 newTags.byteCount = nBytes;
3757 if (nBytes < 1 || nBytes > dev->totalBytesPerChunk) {
3758 T(YAFFS_TRACE_ERROR,
3759 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3764 * If there isn't already a chunk there then do a dummy
3765 * insert to make sue we have the desired tnode structure.
3767 if(prevChunkId < 1 &&
3768 yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0) != YAFFS_OK)
3772 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3775 if (newChunkId > 0) {
3776 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3778 if (prevChunkId > 0)
3779 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3781 yaffs_CheckFileSanity(in);
3787 /* UpdateObjectHeader updates the header on NAND for an object.
3788 * If name is not NULL, then that new name is used.
3790 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
3791 int isShrink, int shadows)
3794 yaffs_BlockInfo *bi;
3796 yaffs_Device *dev = in->myDev;
3803 yaffs_ExtendedTags newTags;
3804 yaffs_ExtendedTags oldTags;
3805 YCHAR *alias = NULL;
3807 __u8 *buffer = NULL;
3808 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3810 yaffs_ObjectHeader *oh = NULL;
3812 yaffs_strcpy(oldName, _Y("silly old name"));
3816 in == dev->rootDir || /* The rootDir should also be saved */
3819 yaffs_CheckGarbageCollection(dev);
3820 yaffs_CheckObjectDetailsLoaded(in);
3822 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3823 oh = (yaffs_ObjectHeader *) buffer;
3825 prevChunkId = in->hdrChunk;
3827 if (prevChunkId > 0) {
3828 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3831 yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
3833 memcpy(oldName, oh->name, sizeof(oh->name));
3836 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3838 oh->type = in->variantType;
3839 oh->yst_mode = in->yst_mode;
3840 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3842 #ifdef CONFIG_YAFFS_WINCE
3843 oh->win_atime[0] = in->win_atime[0];
3844 oh->win_ctime[0] = in->win_ctime[0];
3845 oh->win_mtime[0] = in->win_mtime[0];
3846 oh->win_atime[1] = in->win_atime[1];
3847 oh->win_ctime[1] = in->win_ctime[1];
3848 oh->win_mtime[1] = in->win_mtime[1];
3850 oh->yst_uid = in->yst_uid;
3851 oh->yst_gid = in->yst_gid;
3852 oh->yst_atime = in->yst_atime;
3853 oh->yst_mtime = in->yst_mtime;
3854 oh->yst_ctime = in->yst_ctime;
3855 oh->yst_rdev = in->yst_rdev;
3858 oh->parentObjectId = in->parent->objectId;
3860 oh->parentObjectId = 0;
3862 if (name && *name) {
3863 memset(oh->name, 0, sizeof(oh->name));
3864 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3865 } else if (prevChunkId > 0)
3866 memcpy(oh->name, oldName, sizeof(oh->name));
3868 memset(oh->name, 0, sizeof(oh->name));
3870 oh->isShrink = isShrink;
3872 switch (in->variantType) {
3873 case YAFFS_OBJECT_TYPE_UNKNOWN:
3874 /* Should not happen */
3876 case YAFFS_OBJECT_TYPE_FILE:
3878 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3879 || oh->parentObjectId ==
3880 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3881 fileVariant.fileSize;
3883 case YAFFS_OBJECT_TYPE_HARDLINK:
3884 oh->equivalentObjectId =
3885 in->variant.hardLinkVariant.equivalentObjectId;
3887 case YAFFS_OBJECT_TYPE_SPECIAL:
3890 case YAFFS_OBJECT_TYPE_DIRECTORY:
3893 case YAFFS_OBJECT_TYPE_SYMLINK:
3894 alias = in->variant.symLinkVariant.alias;
3896 alias = _Y("no alias");
3897 yaffs_strncpy(oh->alias,
3899 YAFFS_MAX_ALIAS_LENGTH);
3900 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3905 yaffs_InitialiseTags(&newTags);
3907 newTags.chunkId = 0;
3908 newTags.objectId = in->objectId;
3909 newTags.serialNumber = in->serial;
3911 /* Add extra info for file header */
3913 newTags.extraHeaderInfoAvailable = 1;
3914 newTags.extraParentObjectId = oh->parentObjectId;
3915 newTags.extraFileLength = oh->fileSize;
3916 newTags.extraIsShrinkHeader = oh->isShrink;
3917 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3918 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3919 newTags.extraObjectType = in->variantType;
3921 yaffs_VerifyObjectHeader(in, oh, &newTags, 1);
3923 /* Create new chunk in NAND */
3925 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3926 (prevChunkId > 0) ? 1 : 0);
3928 if (newChunkId >= 0) {
3930 in->hdrChunk = newChunkId;
3932 if (prevChunkId > 0) {
3933 yaffs_DeleteChunk(dev, prevChunkId, 1,
3937 if (!yaffs_ObjectHasCachedWriteData(in))
3940 /* If this was a shrink, then mark the block that the chunk lives on */
3942 bi = yaffs_GetBlockInfo(in->myDev,
3943 newChunkId / in->myDev->nChunksPerBlock);
3944 bi->hasShrinkHeader = 1;
3949 retVal = newChunkId;
3954 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3959 /*------------------------ Short Operations Cache ----------------------------------------
3960 * In many situations where there is no high level buffering (eg WinCE) a lot of
3961 * reads might be short sequential reads, and a lot of writes may be short
3962 * sequential writes. eg. scanning/writing a jpeg file.
3963 * In these cases, a short read/write cache can provide a huge perfomance benefit
3964 * with dumb-as-a-rock code.
3965 * In Linux, the page cache provides read buffering aand the short op cache provides write
3968 * There are a limited number (~10) of cache chunks per device so that we don't
3969 * need a very intelligent search.
3972 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3974 yaffs_Device *dev = obj->myDev;
3976 yaffs_ChunkCache *cache;
3977 int nCaches = obj->myDev->nShortOpCaches;
3979 for (i = 0; i < nCaches; i++) {
3980 cache = &dev->srCache[i];
3981 if (cache->object == obj &&
3990 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
3992 yaffs_Device *dev = obj->myDev;
3993 int lowest = -99; /* Stop compiler whining. */
3995 yaffs_ChunkCache *cache;
3996 int chunkWritten = 0;
3997 int nCaches = obj->myDev->nShortOpCaches;
4003 /* Find the dirty cache for this object with the lowest chunk id. */
4004 for (i = 0; i < nCaches; i++) {
4005 if (dev->srCache[i].object == obj &&
4006 dev->srCache[i].dirty) {
4008 || dev->srCache[i].chunkId <
4010 cache = &dev->srCache[i];
4011 lowest = cache->chunkId;
4016 if (cache && !cache->locked) {
4017 /* Write it out and free it up */
4020 yaffs_WriteChunkDataToObject(cache->object,
4026 cache->object = NULL;
4029 } while (cache && chunkWritten > 0);
4032 /* Hoosterman, disk full while writing cache out. */
4033 T(YAFFS_TRACE_ERROR,
4034 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
4041 /*yaffs_FlushEntireDeviceCache(dev)
4046 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
4049 int nCaches = dev->nShortOpCaches;
4052 /* Find a dirty object in the cache and flush it...
4053 * until there are no further dirty objects.
4057 for (i = 0; i < nCaches && !obj; i++) {
4058 if (dev->srCache[i].object &&
4059 dev->srCache[i].dirty)
4060 obj = dev->srCache[i].object;
4064 yaffs_FlushFilesChunkCache(obj);
4071 /* Grab us a cache chunk for use.
4072 * First look for an empty one.
4073 * Then look for the least recently used non-dirty one.
4074 * Then look for the least recently used dirty one...., flush and look again.
4076 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
4080 if (dev->nShortOpCaches > 0) {
4081 for (i = 0; i < dev->nShortOpCaches; i++) {
4082 if (!dev->srCache[i].object)
4083 return &dev->srCache[i];
4090 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
4092 yaffs_ChunkCache *cache;
4093 yaffs_Object *theObj;
4098 if (dev->nShortOpCaches > 0) {
4099 /* Try find a non-dirty one... */
4101 cache = yaffs_GrabChunkCacheWorker(dev);
4104 /* They were all dirty, find the last recently used object and flush
4105 * its cache, then find again.
4106 * NB what's here is not very accurate, we actually flush the object
4107 * the last recently used page.
4110 /* With locking we can't assume we can use entry zero */
4117 for (i = 0; i < dev->nShortOpCaches; i++) {
4118 if (dev->srCache[i].object &&
4119 !dev->srCache[i].locked &&
4120 (dev->srCache[i].lastUse < usage || !cache)) {
4121 usage = dev->srCache[i].lastUse;
4122 theObj = dev->srCache[i].object;
4123 cache = &dev->srCache[i];
4128 if (!cache || cache->dirty) {
4129 /* Flush and try again */
4130 yaffs_FlushFilesChunkCache(theObj);
4131 cache = yaffs_GrabChunkCacheWorker(dev);
4141 /* Find a cached chunk */
4142 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj,
4145 yaffs_Device *dev = obj->myDev;
4147 if (dev->nShortOpCaches > 0) {
4148 for (i = 0; i < dev->nShortOpCaches; i++) {
4149 if (dev->srCache[i].object == obj &&
4150 dev->srCache[i].chunkId == chunkId) {
4153 return &dev->srCache[i];
4160 /* Mark the chunk for the least recently used algorithym */
4161 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache,
4165 if (dev->nShortOpCaches > 0) {
4166 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4167 /* Reset the cache usages */
4169 for (i = 1; i < dev->nShortOpCaches; i++)
4170 dev->srCache[i].lastUse = 0;
4177 cache->lastUse = dev->srLastUse;
4184 /* Invalidate a single cache page.
4185 * Do this when a whole page gets written,
4186 * ie the short cache for this page is no longer valid.
4188 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
4190 if (object->myDev->nShortOpCaches > 0) {
4191 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4194 cache->object = NULL;
4198 /* Invalidate all the cache pages associated with this object
4199 * Do this whenever ther file is deleted or resized.
4201 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
4204 yaffs_Device *dev = in->myDev;
4206 if (dev->nShortOpCaches > 0) {
4207 /* Invalidate it. */
4208 for (i = 0; i < dev->nShortOpCaches; i++) {
4209 if (dev->srCache[i].object == in)
4210 dev->srCache[i].object = NULL;
4215 /*--------------------- Checkpointing --------------------*/
4218 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev, int head)
4220 yaffs_CheckpointValidity cp;
4222 memset(&cp, 0, sizeof(cp));
4224 cp.structType = sizeof(cp);
4225 cp.magic = YAFFS_MAGIC;
4226 cp.version = YAFFS_CHECKPOINT_VERSION;
4227 cp.head = (head) ? 1 : 0;
4229 return (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp)) ?
4233 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4235 yaffs_CheckpointValidity cp;
4238 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4241 ok = (cp.structType == sizeof(cp)) &&
4242 (cp.magic == YAFFS_MAGIC) &&
4243 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4244 (cp.head == ((head) ? 1 : 0));
4248 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4251 cp->nErasedBlocks = dev->nErasedBlocks;
4252 cp->allocationBlock = dev->allocationBlock;
4253 cp->allocationPage = dev->allocationPage;
4254 cp->nFreeChunks = dev->nFreeChunks;
4256 cp->nDeletedFiles = dev->nDeletedFiles;
4257 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4258 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4259 cp->sequenceNumber = dev->sequenceNumber;
4260 cp->oldestDirtySequence = dev->oldestDirtySequence;
4264 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4265 yaffs_CheckpointDevice *cp)
4267 dev->nErasedBlocks = cp->nErasedBlocks;
4268 dev->allocationBlock = cp->allocationBlock;
4269 dev->allocationPage = cp->allocationPage;
4270 dev->nFreeChunks = cp->nFreeChunks;
4272 dev->nDeletedFiles = cp->nDeletedFiles;
4273 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4274 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4275 dev->sequenceNumber = cp->sequenceNumber;
4276 dev->oldestDirtySequence = cp->oldestDirtySequence;
4280 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4282 yaffs_CheckpointDevice cp;
4284 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4288 /* Write device runtime values*/
4289 yaffs_DeviceToCheckpointDevice(&cp, dev);
4290 cp.structType = sizeof(cp);
4292 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4294 /* Write block info */
4296 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4297 ok = (yaffs_CheckpointWrite(dev, dev->blockInfo, nBytes) == nBytes);
4300 /* Write chunk bits */
4302 nBytes = nBlocks * dev->chunkBitmapStride;
4303 ok = (yaffs_CheckpointWrite(dev, dev->chunkBits, nBytes) == nBytes);
4309 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4311 yaffs_CheckpointDevice cp;
4313 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4317 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4321 if (cp.structType != sizeof(cp))
4325 yaffs_CheckpointDeviceToDevice(dev, &cp);
4327 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4329 ok = (yaffs_CheckpointRead(dev, dev->blockInfo, nBytes) == nBytes);
4333 nBytes = nBlocks * dev->chunkBitmapStride;
4335 ok = (yaffs_CheckpointRead(dev, dev->chunkBits, nBytes) == nBytes);
4340 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4344 cp->objectId = obj->objectId;
4345 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4346 cp->hdrChunk = obj->hdrChunk;
4347 cp->variantType = obj->variantType;
4348 cp->deleted = obj->deleted;
4349 cp->softDeleted = obj->softDeleted;
4350 cp->unlinked = obj->unlinked;
4351 cp->fake = obj->fake;
4352 cp->renameAllowed = obj->renameAllowed;
4353 cp->unlinkAllowed = obj->unlinkAllowed;
4354 cp->serial = obj->serial;
4355 cp->nDataChunks = obj->nDataChunks;
4357 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4358 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4359 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4360 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4363 static int yaffs_CheckpointObjectToObject(yaffs_Object *obj, yaffs_CheckpointObject *cp)
4366 yaffs_Object *parent;
4368 if (obj->variantType != cp->variantType) {
4369 T(YAFFS_TRACE_ERROR, (TSTR("Checkpoint read object %d type %d "
4370 TCONT("chunk %d does not match existing object type %d")
4371 TENDSTR), cp->objectId, cp->variantType, cp->hdrChunk,
4376 obj->objectId = cp->objectId;
4379 parent = yaffs_FindOrCreateObjectByNumber(
4382 YAFFS_OBJECT_TYPE_DIRECTORY);
4387 if (parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4388 T(YAFFS_TRACE_ALWAYS, (TSTR("Checkpoint read object %d parent %d type %d"
4389 TCONT(" chunk %d Parent type, %d, not directory")
4391 cp->objectId, cp->parentId, cp->variantType,
4392 cp->hdrChunk, parent->variantType));
4395 yaffs_AddObjectToDirectory(parent, obj);
4398 obj->hdrChunk = cp->hdrChunk;
4399 obj->variantType = cp->variantType;
4400 obj->deleted = cp->deleted;
4401 obj->softDeleted = cp->softDeleted;
4402 obj->unlinked = cp->unlinked;
4403 obj->fake = cp->fake;
4404 obj->renameAllowed = cp->renameAllowed;
4405 obj->unlinkAllowed = cp->unlinkAllowed;
4406 obj->serial = cp->serial;
4407 obj->nDataChunks = cp->nDataChunks;
4409 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4410 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4411 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4412 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4414 if (obj->hdrChunk > 0)
4415 obj->lazyLoaded = 1;
4421 static int yaffs_CheckpointTnodeWorker(yaffs_Object *in, yaffs_Tnode *tn,
4422 __u32 level, int chunkOffset)
4425 yaffs_Device *dev = in->myDev;
4427 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4429 if (tnodeSize < sizeof(yaffs_Tnode))
4430 tnodeSize = sizeof(yaffs_Tnode);
4436 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
4437 if (tn->internal[i]) {
4438 ok = yaffs_CheckpointTnodeWorker(in,
4441 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4444 } else if (level == 0) {
4445 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4446 ok = (yaffs_CheckpointWrite(dev, &baseOffset, sizeof(baseOffset)) == sizeof(baseOffset));
4448 ok = (yaffs_CheckpointWrite(dev, tn, tnodeSize) == tnodeSize);
4456 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4458 __u32 endMarker = ~0;
4461 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4462 ok = yaffs_CheckpointTnodeWorker(obj,
4463 obj->variant.fileVariant.top,
4464 obj->variant.fileVariant.topLevel,
4467 ok = (yaffs_CheckpointWrite(obj->myDev, &endMarker, sizeof(endMarker)) ==
4474 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4478 yaffs_Device *dev = obj->myDev;
4479 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4482 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4484 if (tnodeSize < sizeof(yaffs_Tnode))
4485 tnodeSize = sizeof(yaffs_Tnode);
4487 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4489 while (ok && (~baseChunk)) {
4491 /* Read level 0 tnode */
4494 tn = yaffs_GetTnodeRaw(dev);
4496 ok = (yaffs_CheckpointRead(dev, tn, tnodeSize) == tnodeSize);
4501 ok = yaffs_AddOrFindLevel0Tnode(dev,
4507 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4511 T(YAFFS_TRACE_CHECKPOINT, (
4512 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4513 nread, baseChunk, ok));
4519 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4522 yaffs_CheckpointObject cp;
4525 struct ylist_head *lh;
4528 /* Iterate through the objects in each hash entry,
4529 * dumping them to the checkpointing stream.
4532 for (i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++) {
4533 ylist_for_each(lh, &dev->objectBucket[i].list) {
4535 obj = ylist_entry(lh, yaffs_Object, hashLink);
4536 if (!obj->deferedFree) {
4537 yaffs_ObjectToCheckpointObject(&cp, obj);
4538 cp.structType = sizeof(cp);
4540 T(YAFFS_TRACE_CHECKPOINT, (
4541 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %p" TENDSTR),
4542 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk, obj));
4544 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4546 if (ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4547 ok = yaffs_WriteCheckpointTnodes(obj);
4553 /* Dump end of list */
4554 memset(&cp, 0xFF, sizeof(yaffs_CheckpointObject));
4555 cp.structType = sizeof(cp);
4558 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4563 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4566 yaffs_CheckpointObject cp;
4569 yaffs_Object *hardList = NULL;
4571 while (ok && !done) {
4572 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4573 if (cp.structType != sizeof(cp)) {
4574 T(YAFFS_TRACE_CHECKPOINT, (TSTR("struct size %d instead of %d ok %d"TENDSTR),
4575 cp.structType, (int)sizeof(cp), ok));
4579 T(YAFFS_TRACE_CHECKPOINT, (TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4580 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk));
4582 if (ok && cp.objectId == ~0)
4585 obj = yaffs_FindOrCreateObjectByNumber(dev, cp.objectId, cp.variantType);
4587 ok = yaffs_CheckpointObjectToObject(obj, &cp);
4590 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4591 ok = yaffs_ReadCheckpointTnodes(obj);
4592 } else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4593 obj->hardLinks.next =
4594 (struct ylist_head *) hardList;
4603 yaffs_HardlinkFixup(dev, hardList);
4608 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4610 __u32 checkpointSum;
4613 yaffs_GetCheckpointSum(dev, &checkpointSum);
4615 ok = (yaffs_CheckpointWrite(dev, &checkpointSum, sizeof(checkpointSum)) == sizeof(checkpointSum));
4623 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4625 __u32 checkpointSum0;
4626 __u32 checkpointSum1;
4629 yaffs_GetCheckpointSum(dev, &checkpointSum0);
4631 ok = (yaffs_CheckpointRead(dev, &checkpointSum1, sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4636 if (checkpointSum0 != checkpointSum1)
4643 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4647 if (dev->skipCheckpointWrite || !dev->isYaffs2) {
4648 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint write" TENDSTR)));
4653 ok = yaffs_CheckpointOpen(dev, 1);
4656 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4657 ok = yaffs_WriteCheckpointValidityMarker(dev, 1);
4660 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint device" TENDSTR)));
4661 ok = yaffs_WriteCheckpointDevice(dev);
4664 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint objects" TENDSTR)));
4665 ok = yaffs_WriteCheckpointObjects(dev);
4668 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4669 ok = yaffs_WriteCheckpointValidityMarker(dev, 0);
4673 ok = yaffs_WriteCheckpointSum(dev);
4675 if (!yaffs_CheckpointClose(dev))
4679 dev->isCheckpointed = 1;
4681 dev->isCheckpointed = 0;
4683 return dev->isCheckpointed;
4686 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4690 if (dev->skipCheckpointRead || !dev->isYaffs2) {
4691 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint read" TENDSTR)));
4696 ok = yaffs_CheckpointOpen(dev, 0); /* open for read */
4699 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4700 ok = yaffs_ReadCheckpointValidityMarker(dev, 1);
4703 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint device" TENDSTR)));
4704 ok = yaffs_ReadCheckpointDevice(dev);
4707 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint objects" TENDSTR)));
4708 ok = yaffs_ReadCheckpointObjects(dev);
4711 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4712 ok = yaffs_ReadCheckpointValidityMarker(dev, 0);
4716 ok = yaffs_ReadCheckpointSum(dev);
4717 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint checksum %d" TENDSTR), ok));
4720 if (!yaffs_CheckpointClose(dev))
4724 dev->isCheckpointed = 1;
4726 dev->isCheckpointed = 0;
4732 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4734 if (dev->isCheckpointed ||
4735 dev->blocksInCheckpoint > 0) {
4736 dev->isCheckpointed = 0;
4737 yaffs_CheckpointInvalidateStream(dev);
4738 if (dev->superBlock && dev->markSuperBlockDirty)
4739 dev->markSuperBlockDirty(dev->superBlock);
4744 int yaffs_CheckpointSave(yaffs_Device *dev)
4747 T(YAFFS_TRACE_CHECKPOINT, (TSTR("save entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4749 yaffs_VerifyObjects(dev);
4750 yaffs_VerifyBlocks(dev);
4751 yaffs_VerifyFreeChunks(dev);
4753 if (!dev->isCheckpointed) {
4754 yaffs_InvalidateCheckpoint(dev);
4755 yaffs_WriteCheckpointData(dev);
4758 T(YAFFS_TRACE_ALWAYS, (TSTR("save exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4760 return dev->isCheckpointed;
4763 int yaffs_CheckpointRestore(yaffs_Device *dev)
4766 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4768 retval = yaffs_ReadCheckpointData(dev);
4770 if (dev->isCheckpointed) {
4771 yaffs_VerifyObjects(dev);
4772 yaffs_VerifyBlocks(dev);
4773 yaffs_VerifyFreeChunks(dev);
4776 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4781 /*--------------------- File read/write ------------------------
4782 * Read and write have very similar structures.
4783 * In general the read/write has three parts to it
4784 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4785 * Some complete chunks
4786 * An incomplete chunk to end off with
4788 * Curve-balls: the first chunk might also be the last chunk.
4791 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 *buffer, loff_t offset,
4800 yaffs_ChunkCache *cache;
4807 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4808 /* start = offset % dev->nDataBytesPerChunk; */
4809 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4812 /* OK now check for the curveball where the start and end are in
4815 if ((start + n) < dev->nDataBytesPerChunk)
4818 nToCopy = dev->nDataBytesPerChunk - start;
4820 cache = yaffs_FindChunkCache(in, chunk);
4822 /* If the chunk is already in the cache or it is less than a whole chunk
4823 * or we're using inband tags then use the cache (if there is caching)
4824 * else bypass the cache.
4826 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4827 if (dev->nShortOpCaches > 0) {
4829 /* If we can't find the data in the cache, then load it up. */
4832 cache = yaffs_GrabChunkCache(in->myDev);
4834 cache->chunkId = chunk;
4837 yaffs_ReadChunkDataFromObject(in, chunk,
4843 yaffs_UseChunkCache(dev, cache, 0);
4848 memcpy(buffer, &cache->data[start], nToCopy);
4852 /* Read into the local buffer then copy..*/
4855 yaffs_GetTempBuffer(dev, __LINE__);
4856 yaffs_ReadChunkDataFromObject(in, chunk,
4859 memcpy(buffer, &localBuffer[start], nToCopy);
4862 yaffs_ReleaseTempBuffer(dev, localBuffer,
4868 /* A full chunk. Read directly into the supplied buffer. */
4869 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4883 int yaffs_WriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
4884 int nBytes, int writeThrough)
4893 int startOfWrite = offset;
4894 int chunkWritten = 0;
4902 while (n > 0 && chunkWritten >= 0) {
4903 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4904 /* start = offset % dev->nDataBytesPerChunk; */
4905 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4907 if (chunk * dev->nDataBytesPerChunk + start != offset ||
4908 start >= dev->nDataBytesPerChunk) {
4909 T(YAFFS_TRACE_ERROR, (
4910 TSTR("AddrToChunk of offset %d gives chunk %d start %d"
4912 (int)offset, chunk, start));
4916 /* OK now check for the curveball where the start and end are in
4920 if ((start + n) < dev->nDataBytesPerChunk) {
4923 /* Now folks, to calculate how many bytes to write back....
4924 * If we're overwriting and not writing to then end of file then
4925 * we need to write back as much as was there before.
4928 chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
4930 if (chunkStart > in->variant.fileVariant.fileSize)
4931 nBytesRead = 0; /* Past end of file */
4933 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
4935 if (nBytesRead > dev->nDataBytesPerChunk)
4936 nBytesRead = dev->nDataBytesPerChunk;
4940 (start + n)) ? nBytesRead : (start + n);
4942 if (nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
4946 nToCopy = dev->nDataBytesPerChunk - start;
4947 nToWriteBack = dev->nDataBytesPerChunk;
4950 if (nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4951 /* An incomplete start or end chunk (or maybe both start and end chunk),
4952 * or we're using inband tags, so we want to use the cache buffers.
4954 if (dev->nShortOpCaches > 0) {
4955 yaffs_ChunkCache *cache;
4956 /* If we can't find the data in the cache, then load the cache */
4957 cache = yaffs_FindChunkCache(in, chunk);
4960 && yaffs_CheckSpaceForAllocation(in->
4962 cache = yaffs_GrabChunkCache(in->myDev);
4964 cache->chunkId = chunk;
4967 yaffs_ReadChunkDataFromObject(in, chunk,
4972 !yaffs_CheckSpaceForAllocation(in->myDev)) {
4973 /* Drop the cache if it was a read cache item and
4974 * no space check has been made for it.
4980 yaffs_UseChunkCache(dev, cache, 1);
4984 memcpy(&cache->data[start], buffer,
4989 cache->nBytes = nToWriteBack;
4993 yaffs_WriteChunkDataToObject
4996 cache->data, cache->nBytes,
5002 chunkWritten = -1; /* fail the write */
5005 /* An incomplete start or end chunk (or maybe both start and end chunk)
5006 * Read into the local buffer then copy, then copy over and write back.
5010 yaffs_GetTempBuffer(dev, __LINE__);
5012 yaffs_ReadChunkDataFromObject(in, chunk,
5017 memcpy(&localBuffer[start], buffer, nToCopy);
5020 yaffs_WriteChunkDataToObject(in, chunk,
5025 yaffs_ReleaseTempBuffer(dev, localBuffer,
5031 /* A full chunk. Write directly from the supplied buffer. */
5036 yaffs_WriteChunkDataToObject(in, chunk, buffer,
5037 dev->nDataBytesPerChunk,
5040 /* Since we've overwritten the cached data, we better invalidate it. */
5041 yaffs_InvalidateChunkCache(in, chunk);
5044 if (chunkWritten >= 0) {
5053 /* Update file object */
5055 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
5056 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
5064 /* ---------------------- File resizing stuff ------------------ */
5066 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
5069 yaffs_Device *dev = in->myDev;
5070 int oldFileSize = in->variant.fileVariant.fileSize;
5072 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
5074 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
5075 dev->nDataBytesPerChunk;
5079 /* Delete backwards so that we don't end up with holes if
5080 * power is lost part-way through the operation.
5082 for (i = lastDel; i >= startDel; i--) {
5083 /* NB this could be optimised somewhat,
5084 * eg. could retrieve the tags and write them without
5085 * using yaffs_DeleteChunk
5088 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5091 (dev->internalStartBlock * dev->nChunksPerBlock)
5093 ((dev->internalEndBlock +
5094 1) * dev->nChunksPerBlock)) {
5095 T(YAFFS_TRACE_ALWAYS,
5096 (TSTR("Found daft chunkId %d for %d" TENDSTR),
5100 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5107 int yaffs_ResizeFile(yaffs_Object *in, loff_t newSize)
5110 int oldFileSize = in->variant.fileVariant.fileSize;
5111 __u32 newSizeOfPartialChunk;
5114 yaffs_Device *dev = in->myDev;
5116 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5118 yaffs_FlushFilesChunkCache(in);
5119 yaffs_InvalidateWholeChunkCache(in);
5121 yaffs_CheckGarbageCollection(dev);
5123 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
5126 if (newSize == oldFileSize)
5129 if (newSize < oldFileSize) {
5131 yaffs_PruneResizedChunks(in, newSize);
5133 if (newSizeOfPartialChunk != 0) {
5134 int lastChunk = 1 + newFullChunks;
5136 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5138 /* Got to read and rewrite the last chunk with its new size and zero pad */
5139 yaffs_ReadChunkDataFromObject(in, lastChunk,
5142 memset(localBuffer + newSizeOfPartialChunk, 0,
5143 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5145 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5146 newSizeOfPartialChunk, 1);
5148 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5151 in->variant.fileVariant.fileSize = newSize;
5153 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5155 /* newsSize > oldFileSize */
5156 in->variant.fileVariant.fileSize = newSize;
5160 /* Write a new object header to reflect the resize.
5161 * show we've shrunk the file, if need be
5162 * Do this only if the file is not in the deleted directories
5163 * and is not shadowed.
5167 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5168 in->parent->objectId != YAFFS_OBJECTID_DELETED)
5169 yaffs_UpdateObjectHeader(in, NULL, 0,
5170 (newSize < oldFileSize) ? 1 : 0, 0);
5175 loff_t yaffs_GetFileSize(yaffs_Object *obj)
5177 YCHAR *alias = NULL;
5178 obj = yaffs_GetEquivalentObject(obj);
5180 switch (obj->variantType) {
5181 case YAFFS_OBJECT_TYPE_FILE:
5182 return obj->variant.fileVariant.fileSize;
5183 case YAFFS_OBJECT_TYPE_SYMLINK:
5184 alias = obj->variant.symLinkVariant.alias;
5187 return yaffs_strnlen(alias,YAFFS_MAX_ALIAS_LENGTH);
5195 int yaffs_FlushFile(yaffs_Object *in, int updateTime, int dataSync)
5199 yaffs_FlushFilesChunkCache(in);
5200 if(dataSync) /* Only sync data */
5204 #ifdef CONFIG_YAFFS_WINCE
5205 yfsd_WinFileTimeNow(in->win_mtime);
5208 in->yst_mtime = Y_CURRENT_TIME;
5213 retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5214 0) ? YAFFS_OK : YAFFS_FAIL;
5224 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
5227 /* First off, invalidate the file's data in the cache, without flushing. */
5228 yaffs_InvalidateWholeChunkCache(in);
5230 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5231 /* Move to the unlinked directory so we have a record that it was deleted. */
5232 yaffs_ChangeObjectName(in, in->myDev->deletedDir, _Y("deleted"), 0, 0);
5236 yaffs_RemoveObjectFromDirectory(in);
5237 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5240 yaffs_FreeObject(in);
5245 /* yaffs_DeleteFile deletes the whole file data
5246 * and the inode associated with the file.
5247 * It does not delete the links associated with the file.
5249 static int yaffs_UnlinkFileIfNeeded(yaffs_Object *in)
5253 int immediateDeletion = 0;
5257 immediateDeletion = 1;
5260 immediateDeletion = 1;
5263 if (immediateDeletion) {
5265 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5266 _Y("deleted"), 0, 0);
5267 T(YAFFS_TRACE_TRACING,
5268 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5271 in->myDev->nDeletedFiles++;
5272 if (1 || in->myDev->isYaffs2)
5273 yaffs_ResizeFile(in, 0);
5274 yaffs_SoftDeleteFile(in);
5277 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5278 _Y("unlinked"), 0, 0);
5285 int yaffs_DeleteFile(yaffs_Object *in)
5287 int retVal = YAFFS_OK;
5288 int deleted = in->deleted;
5290 yaffs_ResizeFile(in, 0);
5292 if (in->nDataChunks > 0) {
5293 /* Use soft deletion if there is data in the file.
5294 * That won't be the case if it has been resized to zero.
5297 retVal = yaffs_UnlinkFileIfNeeded(in);
5299 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5302 in->myDev->nDeletedFiles++;
5303 yaffs_SoftDeleteFile(in);
5305 return deleted ? YAFFS_OK : YAFFS_FAIL;
5307 /* The file has no data chunks so we toss it immediately */
5308 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5309 in->variant.fileVariant.top = NULL;
5310 yaffs_DoGenericObjectDeletion(in);
5316 static int yaffs_IsNonEmptyDirectory(yaffs_Object *obj)
5318 return (obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) &&
5319 !(ylist_empty(&obj->variant.directoryVariant.children));
5322 static int yaffs_DeleteDirectory(yaffs_Object *obj)
5324 /* First check that the directory is empty. */
5325 if (yaffs_IsNonEmptyDirectory(obj))
5328 return yaffs_DoGenericObjectDeletion(obj);
5331 static int yaffs_DeleteSymLink(yaffs_Object *in)
5333 if(in->variant.symLinkVariant.alias)
5334 YFREE(in->variant.symLinkVariant.alias);
5335 in->variant.symLinkVariant.alias=NULL;
5337 return yaffs_DoGenericObjectDeletion(in);
5340 static int yaffs_DeleteHardLink(yaffs_Object *in)
5342 /* remove this hardlink from the list assocaited with the equivalent
5345 ylist_del_init(&in->hardLinks);
5346 return yaffs_DoGenericObjectDeletion(in);
5349 int yaffs_DeleteObject(yaffs_Object *obj)
5352 switch (obj->variantType) {
5353 case YAFFS_OBJECT_TYPE_FILE:
5354 retVal = yaffs_DeleteFile(obj);
5356 case YAFFS_OBJECT_TYPE_DIRECTORY:
5357 return yaffs_DeleteDirectory(obj);
5359 case YAFFS_OBJECT_TYPE_SYMLINK:
5360 retVal = yaffs_DeleteSymLink(obj);
5362 case YAFFS_OBJECT_TYPE_HARDLINK:
5363 retVal = yaffs_DeleteHardLink(obj);
5365 case YAFFS_OBJECT_TYPE_SPECIAL:
5366 retVal = yaffs_DoGenericObjectDeletion(obj);
5368 case YAFFS_OBJECT_TYPE_UNKNOWN:
5370 break; /* should not happen. */
5376 static int yaffs_UnlinkWorker(yaffs_Object *obj)
5379 int immediateDeletion = 0;
5383 immediateDeletion = 1;
5385 if (obj->inUse <= 0)
5386 immediateDeletion = 1;
5390 yaffs_UpdateParent(obj->parent);
5392 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5393 return yaffs_DeleteHardLink(obj);
5394 } else if (!ylist_empty(&obj->hardLinks)) {
5395 /* Curve ball: We're unlinking an object that has a hardlink.
5397 * This problem arises because we are not strictly following
5398 * The Linux link/inode model.
5400 * We can't really delete the object.
5401 * Instead, we do the following:
5402 * - Select a hardlink.
5403 * - Unhook it from the hard links
5404 * - Unhook it from its parent directory (so that the rename can work)
5405 * - Rename the object to the hardlink's name.
5406 * - Delete the hardlink
5411 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5413 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5415 ylist_del_init(&hl->hardLinks);
5416 ylist_del_init(&hl->siblings);
5418 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5420 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
5422 if (retVal == YAFFS_OK)
5423 retVal = yaffs_DoGenericObjectDeletion(hl);
5427 } else if (immediateDeletion) {
5428 switch (obj->variantType) {
5429 case YAFFS_OBJECT_TYPE_FILE:
5430 return yaffs_DeleteFile(obj);
5432 case YAFFS_OBJECT_TYPE_DIRECTORY:
5433 return yaffs_DeleteDirectory(obj);
5435 case YAFFS_OBJECT_TYPE_SYMLINK:
5436 return yaffs_DeleteSymLink(obj);
5438 case YAFFS_OBJECT_TYPE_SPECIAL:
5439 return yaffs_DoGenericObjectDeletion(obj);
5441 case YAFFS_OBJECT_TYPE_HARDLINK:
5442 case YAFFS_OBJECT_TYPE_UNKNOWN:
5446 } else if(yaffs_IsNonEmptyDirectory(obj))
5449 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
5450 _Y("unlinked"), 0, 0);
5454 static int yaffs_UnlinkObject(yaffs_Object *obj)
5457 if (obj && obj->unlinkAllowed)
5458 return yaffs_UnlinkWorker(obj);
5463 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
5467 obj = yaffs_FindObjectByName(dir, name);
5468 return yaffs_UnlinkObject(obj);
5471 /*----------------------- Initialisation Scanning ---------------------- */
5473 static void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
5474 int backwardScanning)
5478 if (!backwardScanning) {
5479 /* Handle YAFFS1 forward scanning case
5480 * For YAFFS1 we always do the deletion
5484 /* Handle YAFFS2 case (backward scanning)
5485 * If the shadowed object exists then ignore.
5487 obj = yaffs_FindObjectByNumber(dev, objId);
5492 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5493 * We put it in unlinked dir to be cleaned up after the scanning
5496 yaffs_FindOrCreateObjectByNumber(dev, objId,
5497 YAFFS_OBJECT_TYPE_FILE);
5500 obj->isShadowed = 1;
5501 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5502 obj->variant.fileVariant.shrinkSize = 0;
5503 obj->valid = 1; /* So that we don't read any other info for this file */
5513 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5520 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5522 in = yaffs_FindObjectByNumber(dev,
5523 hl->variant.hardLinkVariant.
5524 equivalentObjectId);
5527 /* Add the hardlink pointers */
5528 hl->variant.hardLinkVariant.equivalentObject = in;
5529 ylist_add(&hl->hardLinks, &in->hardLinks);
5531 /* Todo Need to report/handle this better.
5532 * Got a problem... hardlink to a non-existant object
5534 hl->variant.hardLinkVariant.equivalentObject = NULL;
5535 YINIT_LIST_HEAD(&hl->hardLinks);
5545 static int ybicmp(const void *a, const void *b)
5547 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5548 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5549 register int ablock = ((yaffs_BlockIndex *)a)->block;
5550 register int bblock = ((yaffs_BlockIndex *)b)->block;
5552 return ablock - bblock;
5558 struct yaffs_ShadowFixerStruct {
5561 struct yaffs_ShadowFixerStruct *next;
5565 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5568 * Sort out state of unlinked and deleted objects after scanning.
5570 struct ylist_head *i;
5571 struct ylist_head *n;
5574 /* Soft delete all the unlinked files */
5575 ylist_for_each_safe(i, n,
5576 &dev->unlinkedDir->variant.directoryVariant.children) {
5578 l = ylist_entry(i, yaffs_Object, siblings);
5579 yaffs_DeleteObject(l);
5583 ylist_for_each_safe(i, n,
5584 &dev->deletedDir->variant.directoryVariant.children) {
5586 l = ylist_entry(i, yaffs_Object, siblings);
5587 yaffs_DeleteObject(l);
5594 * This code iterates through all the objects making sure that they are rooted.
5595 * Any unrooted objects are re-rooted in lost+found.
5596 * An object needs to be in one of:
5597 * - Directly under deleted, unlinked
5598 * - Directly or indirectly under root.
5601 * This code assumes that we don't ever change the current relationships between
5603 * rootDir->parent == unlinkedDir->parent == deletedDir->parent == NULL
5604 * lostNfound->parent == rootDir
5606 * This fixes the problem where directories might have inadvertently been deleted
5607 * leaving the object "hanging" without being rooted in the directory tree.
5610 static int yaffs_HasNULLParent(yaffs_Device *dev, yaffs_Object *obj)
5612 return (obj == dev->deletedDir ||
5613 obj == dev->unlinkedDir||
5614 obj == dev->rootDir);
5617 static void yaffs_FixHangingObjects(yaffs_Device *dev)
5620 yaffs_Object *parent;
5622 struct ylist_head *lh;
5623 struct ylist_head *n;
5628 /* Iterate through the objects in each hash entry,
5629 * looking at each object.
5630 * Make sure it is rooted.
5633 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
5634 ylist_for_each_safe(lh, n, &dev->objectBucket[i].list) {
5636 obj = ylist_entry(lh, yaffs_Object, hashLink);
5637 parent= obj->parent;
5639 if(yaffs_HasNULLParent(dev,obj)){
5640 /* These directories are not hanging */
5643 else if(!parent || parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5645 else if(yaffs_HasNULLParent(dev,parent))
5649 * Need to follow the parent chain to see if it is hanging.
5654 while(parent != dev->rootDir &&
5656 parent->parent->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
5658 parent = parent->parent;
5661 if(parent != dev->rootDir)
5666 (TSTR("Hanging object %d moved to lost and found" TENDSTR),
5668 yaffs_AddObjectToDirectory(dev->lostNFoundDir,obj);
5677 * Delete directory contents for cleaning up lost and found.
5679 static void yaffs_DeleteDirectoryContents(yaffs_Object *dir)
5682 struct ylist_head *lh;
5683 struct ylist_head *n;
5685 if(dir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5688 ylist_for_each_safe(lh, n, &dir->variant.directoryVariant.children) {
5690 obj = ylist_entry(lh, yaffs_Object, siblings);
5691 if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
5692 yaffs_DeleteDirectoryContents(obj);
5695 (TSTR("Deleting lost_found object %d" TENDSTR),
5698 /* Need to use UnlinkObject since Delete would not handle
5699 * hardlinked objects correctly.
5701 yaffs_UnlinkObject(obj);
5707 static void yaffs_EmptyLostAndFound(yaffs_Device *dev)
5709 yaffs_DeleteDirectoryContents(dev->lostNFoundDir);
5712 static int yaffs_Scan(yaffs_Device *dev)
5714 yaffs_ExtendedTags tags;
5724 yaffs_BlockState state;
5725 yaffs_Object *hardList = NULL;
5726 yaffs_BlockInfo *bi;
5727 __u32 sequenceNumber;
5728 yaffs_ObjectHeader *oh;
5730 yaffs_Object *parent;
5732 int alloc_failed = 0;
5734 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5742 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5743 dev->internalStartBlock, dev->internalEndBlock));
5745 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5747 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5749 /* Scan all the blocks to determine their state */
5750 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5751 bi = yaffs_GetBlockInfo(dev, blk);
5752 yaffs_ClearChunkBits(dev, blk);
5754 bi->softDeletions = 0;
5756 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5758 bi->blockState = state;
5759 bi->sequenceNumber = sequenceNumber;
5761 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
5762 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
5764 T(YAFFS_TRACE_SCAN_DEBUG,
5765 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5766 state, sequenceNumber));
5768 if (state == YAFFS_BLOCK_STATE_DEAD) {
5769 T(YAFFS_TRACE_BAD_BLOCKS,
5770 (TSTR("block %d is bad" TENDSTR), blk));
5771 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5772 T(YAFFS_TRACE_SCAN_DEBUG,
5773 (TSTR("Block empty " TENDSTR)));
5774 dev->nErasedBlocks++;
5775 dev->nFreeChunks += dev->nChunksPerBlock;
5779 startIterator = dev->internalStartBlock;
5780 endIterator = dev->internalEndBlock;
5782 /* For each block.... */
5783 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5790 blk = blockIterator;
5792 bi = yaffs_GetBlockInfo(dev, blk);
5793 state = bi->blockState;
5797 /* For each chunk in each block that needs scanning....*/
5798 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5799 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5800 /* Read the tags and decide what to do */
5801 chunk = blk * dev->nChunksPerBlock + c;
5803 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5806 /* Let's have a good look at this chunk... */
5808 if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
5814 /*T((" %d %d deleted\n",blk,c)); */
5815 } else if (!tags.chunkUsed) {
5816 /* An unassigned chunk in the block
5817 * This means that either the block is empty or
5818 * this is the one being allocated from
5822 /* We're looking at the first chunk in the block so the block is unused */
5823 state = YAFFS_BLOCK_STATE_EMPTY;
5824 dev->nErasedBlocks++;
5826 /* this is the block being allocated from */
5829 (" Allocating from %d %d" TENDSTR),
5831 state = YAFFS_BLOCK_STATE_ALLOCATING;
5832 dev->allocationBlock = blk;
5833 dev->allocationPage = c;
5834 dev->allocationBlockFinder = blk;
5835 /* Set block finder here to encourage the allocator to go forth from here. */
5839 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5840 } else if (tags.chunkId > 0) {
5841 /* chunkId > 0 so it is a data chunk... */
5842 unsigned int endpos;
5844 yaffs_SetChunkBit(dev, blk, c);
5847 in = yaffs_FindOrCreateObjectByNumber(dev,
5850 YAFFS_OBJECT_TYPE_FILE);
5851 /* PutChunkIntoFile checks for a clash (two data chunks with
5852 * the same chunkId).
5859 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, 1))
5864 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5867 in->variantType == YAFFS_OBJECT_TYPE_FILE
5868 && in->variant.fileVariant.scannedFileSize <
5870 in->variant.fileVariant.
5871 scannedFileSize = endpos;
5872 if (!dev->useHeaderFileSize) {
5873 in->variant.fileVariant.
5875 in->variant.fileVariant.
5880 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
5882 /* chunkId == 0, so it is an ObjectHeader.
5883 * Thus, we read in the object header and make the object
5885 yaffs_SetChunkBit(dev, blk, c);
5888 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5892 oh = (yaffs_ObjectHeader *) chunkData;
5894 in = yaffs_FindObjectByNumber(dev,
5896 if (in && in->variantType != oh->type) {
5897 /* This should not happen, but somehow
5898 * Wev'e ended up with an objectId that has been reused but not yet
5899 * deleted, and worse still it has changed type. Delete the old object.
5902 yaffs_DeleteObject(in);
5907 in = yaffs_FindOrCreateObjectByNumber(dev,
5915 if (in && oh->shadowsObject > 0) {
5917 struct yaffs_ShadowFixerStruct *fixer;
5918 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
5920 fixer->next = shadowFixerList;
5921 shadowFixerList = fixer;
5922 fixer->objectId = tags.objectId;
5923 fixer->shadowedId = oh->shadowsObject;
5928 if (in && in->valid) {
5929 /* We have already filled this one. We have a duplicate and need to resolve it. */
5931 unsigned existingSerial = in->serial;
5932 unsigned newSerial = tags.serialNumber;
5934 if (((existingSerial + 1) & 3) == newSerial) {
5935 /* Use new one - destroy the exisiting one */
5936 yaffs_DeleteChunk(dev,
5941 /* Use existing - destroy this one. */
5942 yaffs_DeleteChunk(dev, chunk, 1,
5947 if (in && !in->valid &&
5948 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5949 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5950 /* We only load some info, don't fiddle with directory structure */
5952 in->variantType = oh->type;
5954 in->yst_mode = oh->yst_mode;
5955 #ifdef CONFIG_YAFFS_WINCE
5956 in->win_atime[0] = oh->win_atime[0];
5957 in->win_ctime[0] = oh->win_ctime[0];
5958 in->win_mtime[0] = oh->win_mtime[0];
5959 in->win_atime[1] = oh->win_atime[1];
5960 in->win_ctime[1] = oh->win_ctime[1];
5961 in->win_mtime[1] = oh->win_mtime[1];
5963 in->yst_uid = oh->yst_uid;
5964 in->yst_gid = oh->yst_gid;
5965 in->yst_atime = oh->yst_atime;
5966 in->yst_mtime = oh->yst_mtime;
5967 in->yst_ctime = oh->yst_ctime;
5968 in->yst_rdev = oh->yst_rdev;
5970 in->hdrChunk = chunk;
5971 in->serial = tags.serialNumber;
5973 } else if (in && !in->valid) {
5974 /* we need to load this info */
5977 in->variantType = oh->type;
5979 in->yst_mode = oh->yst_mode;
5980 #ifdef CONFIG_YAFFS_WINCE
5981 in->win_atime[0] = oh->win_atime[0];
5982 in->win_ctime[0] = oh->win_ctime[0];
5983 in->win_mtime[0] = oh->win_mtime[0];
5984 in->win_atime[1] = oh->win_atime[1];
5985 in->win_ctime[1] = oh->win_ctime[1];
5986 in->win_mtime[1] = oh->win_mtime[1];
5988 in->yst_uid = oh->yst_uid;
5989 in->yst_gid = oh->yst_gid;
5990 in->yst_atime = oh->yst_atime;
5991 in->yst_mtime = oh->yst_mtime;
5992 in->yst_ctime = oh->yst_ctime;
5993 in->yst_rdev = oh->yst_rdev;
5995 in->hdrChunk = chunk;
5996 in->serial = tags.serialNumber;
5998 yaffs_SetObjectName(in, oh->name);
6001 /* directory stuff...
6006 yaffs_FindOrCreateObjectByNumber
6007 (dev, oh->parentObjectId,
6008 YAFFS_OBJECT_TYPE_DIRECTORY);
6011 if (parent && parent->variantType ==
6012 YAFFS_OBJECT_TYPE_UNKNOWN) {
6013 /* Set up as a directory */
6014 parent->variantType =
6015 YAFFS_OBJECT_TYPE_DIRECTORY;
6016 YINIT_LIST_HEAD(&parent->variant.
6019 } else if (!parent || parent->variantType !=
6020 YAFFS_OBJECT_TYPE_DIRECTORY) {
6021 /* Hoosterman, another problem....
6022 * We're trying to use a non-directory as a directory
6025 T(YAFFS_TRACE_ERROR,
6027 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6029 parent = dev->lostNFoundDir;
6032 yaffs_AddObjectToDirectory(parent, in);
6034 if (0 && (parent == dev->deletedDir ||
6035 parent == dev->unlinkedDir)) {
6036 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
6037 dev->nDeletedFiles++;
6039 /* Note re hardlinks.
6040 * Since we might scan a hardlink before its equivalent object is scanned
6041 * we put them all in a list.
6042 * After scanning is complete, we should have all the objects, so we run through this
6043 * list and fix up all the chains.
6046 switch (in->variantType) {
6047 case YAFFS_OBJECT_TYPE_UNKNOWN:
6048 /* Todo got a problem */
6050 case YAFFS_OBJECT_TYPE_FILE:
6051 if (dev->useHeaderFileSize)
6053 in->variant.fileVariant.
6058 case YAFFS_OBJECT_TYPE_HARDLINK:
6059 in->variant.hardLinkVariant.
6060 equivalentObjectId =
6061 oh->equivalentObjectId;
6062 in->hardLinks.next =
6063 (struct ylist_head *)
6067 case YAFFS_OBJECT_TYPE_DIRECTORY:
6070 case YAFFS_OBJECT_TYPE_SPECIAL:
6073 case YAFFS_OBJECT_TYPE_SYMLINK:
6074 in->variant.symLinkVariant.alias =
6075 yaffs_CloneString(oh->alias);
6076 if (!in->variant.symLinkVariant.alias)
6085 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6086 /* If we got this far while scanning, then the block is fully allocated.*/
6087 state = YAFFS_BLOCK_STATE_FULL;
6090 if (state == YAFFS_BLOCK_STATE_ALLOCATING) {
6091 /* If the block was partially allocated then treat it as fully allocated.*/
6092 state = YAFFS_BLOCK_STATE_FULL;
6093 dev->allocationBlock = -1;
6096 bi->blockState = state;
6098 /* Now let's see if it was dirty */
6099 if (bi->pagesInUse == 0 &&
6100 !bi->hasShrinkHeader &&
6101 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6102 yaffs_BlockBecameDirty(dev, blk);
6108 /* Ok, we've done all the scanning.
6109 * Fix up the hard link chains.
6110 * We should now have scanned all the objects, now it's time to add these
6114 yaffs_HardlinkFixup(dev, hardList);
6116 /* Fix up any shadowed objects */
6118 struct yaffs_ShadowFixerStruct *fixer;
6121 while (shadowFixerList) {
6122 fixer = shadowFixerList;
6123 shadowFixerList = fixer->next;
6124 /* Complete the rename transaction by deleting the shadowed object
6125 * then setting the object header to unshadowed.
6127 obj = yaffs_FindObjectByNumber(dev, fixer->shadowedId);
6129 yaffs_DeleteObject(obj);
6131 obj = yaffs_FindObjectByNumber(dev, fixer->objectId);
6134 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6140 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6145 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
6151 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
6154 yaffs_ObjectHeader *oh;
6156 yaffs_ExtendedTags tags;
6158 int alloc_failed = 0;
6166 T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
6168 in->lazyLoaded ? "not yet" : "already"));
6171 if (in->lazyLoaded && in->hdrChunk > 0) {
6173 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6175 result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
6176 oh = (yaffs_ObjectHeader *) chunkData;
6178 in->yst_mode = oh->yst_mode;
6179 #ifdef CONFIG_YAFFS_WINCE
6180 in->win_atime[0] = oh->win_atime[0];
6181 in->win_ctime[0] = oh->win_ctime[0];
6182 in->win_mtime[0] = oh->win_mtime[0];
6183 in->win_atime[1] = oh->win_atime[1];
6184 in->win_ctime[1] = oh->win_ctime[1];
6185 in->win_mtime[1] = oh->win_mtime[1];
6187 in->yst_uid = oh->yst_uid;
6188 in->yst_gid = oh->yst_gid;
6189 in->yst_atime = oh->yst_atime;
6190 in->yst_mtime = oh->yst_mtime;
6191 in->yst_ctime = oh->yst_ctime;
6192 in->yst_rdev = oh->yst_rdev;
6195 yaffs_SetObjectName(in, oh->name);
6197 if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6198 in->variant.symLinkVariant.alias =
6199 yaffs_CloneString(oh->alias);
6200 if (!in->variant.symLinkVariant.alias)
6201 alloc_failed = 1; /* Not returned to caller */
6204 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6208 static int yaffs_ScanBackwards(yaffs_Device *dev)
6210 yaffs_ExtendedTags tags;
6215 int nBlocksToScan = 0;
6221 yaffs_BlockState state;
6222 yaffs_Object *hardList = NULL;
6223 yaffs_BlockInfo *bi;
6224 __u32 sequenceNumber;
6225 yaffs_ObjectHeader *oh;
6227 yaffs_Object *parent;
6228 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6234 int foundChunksInBlock;
6235 int equivalentObjectId;
6236 int alloc_failed = 0;
6239 yaffs_BlockIndex *blockIndex = NULL;
6240 int altBlockIndex = 0;
6242 if (!dev->isYaffs2) {
6244 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6250 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
6251 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6254 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6256 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6259 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6265 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6269 dev->blocksInCheckpoint = 0;
6271 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6273 /* Scan all the blocks to determine their state */
6274 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6275 bi = yaffs_GetBlockInfo(dev, blk);
6276 yaffs_ClearChunkBits(dev, blk);
6278 bi->softDeletions = 0;
6280 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6282 bi->blockState = state;
6283 bi->sequenceNumber = sequenceNumber;
6285 if (bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6286 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6287 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6288 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6290 T(YAFFS_TRACE_SCAN_DEBUG,
6291 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6292 state, sequenceNumber));
6295 if (state == YAFFS_BLOCK_STATE_CHECKPOINT) {
6296 dev->blocksInCheckpoint++;
6298 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6299 T(YAFFS_TRACE_BAD_BLOCKS,
6300 (TSTR("block %d is bad" TENDSTR), blk));
6301 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6302 T(YAFFS_TRACE_SCAN_DEBUG,
6303 (TSTR("Block empty " TENDSTR)));
6304 dev->nErasedBlocks++;
6305 dev->nFreeChunks += dev->nChunksPerBlock;
6306 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6308 /* Determine the highest sequence number */
6309 if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6310 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6312 blockIndex[nBlocksToScan].seq = sequenceNumber;
6313 blockIndex[nBlocksToScan].block = blk;
6317 if (sequenceNumber >= dev->sequenceNumber)
6318 dev->sequenceNumber = sequenceNumber;
6320 /* TODO: Nasty sequence number! */
6323 ("Block scanning block %d has bad sequence number %d"
6324 TENDSTR), blk, sequenceNumber));
6331 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6337 /* Sort the blocks */
6338 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6340 /* Use qsort now. */
6341 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6345 /* Dungy old bubble sort... */
6347 yaffs_BlockIndex temp;
6351 for (i = 0; i < nBlocksToScan; i++)
6352 for (j = i + 1; j < nBlocksToScan; j++)
6353 if (blockIndex[i].seq > blockIndex[j].seq) {
6354 temp = blockIndex[j];
6355 blockIndex[j] = blockIndex[i];
6356 blockIndex[i] = temp;
6363 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6365 /* Now scan the blocks looking at the data. */
6367 endIterator = nBlocksToScan - 1;
6368 T(YAFFS_TRACE_SCAN_DEBUG,
6369 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6371 /* For each block.... backwards */
6372 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6374 /* Cooperative multitasking! This loop can run for so
6375 long that watchdog timers expire. */
6378 /* get the block to scan in the correct order */
6379 blk = blockIndex[blockIterator].block;
6381 bi = yaffs_GetBlockInfo(dev, blk);
6384 state = bi->blockState;
6388 /* For each chunk in each block that needs scanning.... */
6389 foundChunksInBlock = 0;
6390 for (c = dev->nChunksPerBlock - 1;
6391 !alloc_failed && c >= 0 &&
6392 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6393 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6394 /* Scan backwards...
6395 * Read the tags and decide what to do
6398 chunk = blk * dev->nChunksPerBlock + c;
6400 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6403 /* Let's have a good look at this chunk... */
6405 if (!tags.chunkUsed) {
6406 /* An unassigned chunk in the block.
6407 * If there are used chunks after this one, then
6408 * it is a chunk that was skipped due to failing the erased
6409 * check. Just skip it so that it can be deleted.
6410 * But, more typically, We get here when this is an unallocated
6411 * chunk and his means that either the block is empty or
6412 * this is the one being allocated from
6415 if (foundChunksInBlock) {
6416 /* This is a chunk that was skipped due to failing the erased check */
6417 } else if (c == 0) {
6418 /* We're looking at the first chunk in the block so the block is unused */
6419 state = YAFFS_BLOCK_STATE_EMPTY;
6420 dev->nErasedBlocks++;
6422 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6423 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6424 if (dev->sequenceNumber == bi->sequenceNumber) {
6425 /* this is the block being allocated from */
6429 (" Allocating from %d %d"
6432 state = YAFFS_BLOCK_STATE_ALLOCATING;
6433 dev->allocationBlock = blk;
6434 dev->allocationPage = c;
6435 dev->allocationBlockFinder = blk;
6437 /* This is a partially written block that is not
6438 * the current allocation block.
6441 T(YAFFS_TRACE_ALWAYS,
6442 (TSTR("Partially written block %d detected" TENDSTR),
6450 } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED) {
6452 (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
6457 } else if (tags.chunkId > 0) {
6458 /* chunkId > 0 so it is a data chunk... */
6459 unsigned int endpos;
6461 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6463 foundChunksInBlock = 1;
6466 yaffs_SetChunkBit(dev, blk, c);
6469 in = yaffs_FindOrCreateObjectByNumber(dev,
6472 YAFFS_OBJECT_TYPE_FILE);
6479 in->variantType == YAFFS_OBJECT_TYPE_FILE
6481 in->variant.fileVariant.shrinkSize) {
6482 /* This has not been invalidated by a resize */
6483 if (!yaffs_PutChunkIntoFile(in, tags.chunkId,
6488 /* File size is calculated by looking at the data chunks if we have not
6489 * seen an object header yet. Stop this practice once we find an object header.
6493 1) * dev->nDataBytesPerChunk +
6496 if (!in->valid && /* have not got an object header yet */
6497 in->variant.fileVariant.
6498 scannedFileSize < endpos) {
6499 in->variant.fileVariant.
6500 scannedFileSize = endpos;
6501 in->variant.fileVariant.
6503 in->variant.fileVariant.
6508 /* This chunk has been invalidated by a resize, so delete */
6509 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6513 /* chunkId == 0, so it is an ObjectHeader.
6514 * Thus, we read in the object header and make the object
6516 foundChunksInBlock = 1;
6518 yaffs_SetChunkBit(dev, blk, c);
6524 if (tags.extraHeaderInfoAvailable) {
6525 in = yaffs_FindOrCreateObjectByNumber
6526 (dev, tags.objectId,
6527 tags.extraObjectType);
6533 (!in->valid && dev->disableLazyLoad) ||
6534 tags.extraShadows ||
6536 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6537 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))) {
6539 /* If we don't have valid info then we need to read the chunk
6540 * TODO In future we can probably defer reading the chunk and
6541 * living with invalid data until needed.
6544 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6549 oh = (yaffs_ObjectHeader *) chunkData;
6551 if (dev->inbandTags) {
6552 /* Fix up the header if they got corrupted by inband tags */
6553 oh->shadowsObject = oh->inbandShadowsObject;
6554 oh->isShrink = oh->inbandIsShrink;
6558 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6566 /* TODO Hoosterman we have a problem! */
6567 T(YAFFS_TRACE_ERROR,
6569 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6570 TENDSTR), tags.objectId, chunk));
6575 /* We have already filled this one.
6576 * We have a duplicate that will be discarded, but
6577 * we first have to suck out resize info if it is a file.
6580 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6582 oh->type == YAFFS_OBJECT_TYPE_FILE) ||
6583 (tags.extraHeaderInfoAvailable &&
6584 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))) {
6586 (oh) ? oh->fileSize : tags.
6588 __u32 parentObjectId =
6590 parentObjectId : tags.
6591 extraParentObjectId;
6595 (oh) ? oh->isShrink : tags.
6596 extraIsShrinkHeader;
6598 /* If it is deleted (unlinked at start also means deleted)
6599 * we treat the file size as being zeroed at this point.
6601 if (parentObjectId ==
6602 YAFFS_OBJECTID_DELETED
6603 || parentObjectId ==
6604 YAFFS_OBJECTID_UNLINKED) {
6610 in->variant.fileVariant.
6611 shrinkSize > thisSize) {
6612 in->variant.fileVariant.
6618 bi->hasShrinkHeader = 1;
6621 /* Use existing - destroy this one. */
6622 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6626 if (!in->valid && in->variantType !=
6627 (oh ? oh->type : tags.extraObjectType))
6628 T(YAFFS_TRACE_ERROR, (
6629 TSTR("yaffs tragedy: Bad object type, "
6630 TCONT("%d != %d, for object %d at chunk ")
6631 TCONT("%d during scan")
6633 oh->type : tags.extraObjectType,
6634 in->variantType, tags.objectId,
6638 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6640 YAFFS_OBJECTID_LOSTNFOUND)) {
6641 /* We only load some info, don't fiddle with directory structure */
6645 in->variantType = oh->type;
6647 in->yst_mode = oh->yst_mode;
6648 #ifdef CONFIG_YAFFS_WINCE
6649 in->win_atime[0] = oh->win_atime[0];
6650 in->win_ctime[0] = oh->win_ctime[0];
6651 in->win_mtime[0] = oh->win_mtime[0];
6652 in->win_atime[1] = oh->win_atime[1];
6653 in->win_ctime[1] = oh->win_ctime[1];
6654 in->win_mtime[1] = oh->win_mtime[1];
6656 in->yst_uid = oh->yst_uid;
6657 in->yst_gid = oh->yst_gid;
6658 in->yst_atime = oh->yst_atime;
6659 in->yst_mtime = oh->yst_mtime;
6660 in->yst_ctime = oh->yst_ctime;
6661 in->yst_rdev = oh->yst_rdev;
6665 in->variantType = tags.extraObjectType;
6669 in->hdrChunk = chunk;
6671 } else if (!in->valid) {
6672 /* we need to load this info */
6675 in->hdrChunk = chunk;
6678 in->variantType = oh->type;
6680 in->yst_mode = oh->yst_mode;
6681 #ifdef CONFIG_YAFFS_WINCE
6682 in->win_atime[0] = oh->win_atime[0];
6683 in->win_ctime[0] = oh->win_ctime[0];
6684 in->win_mtime[0] = oh->win_mtime[0];
6685 in->win_atime[1] = oh->win_atime[1];
6686 in->win_ctime[1] = oh->win_ctime[1];
6687 in->win_mtime[1] = oh->win_mtime[1];
6689 in->yst_uid = oh->yst_uid;
6690 in->yst_gid = oh->yst_gid;
6691 in->yst_atime = oh->yst_atime;
6692 in->yst_mtime = oh->yst_mtime;
6693 in->yst_ctime = oh->yst_ctime;
6694 in->yst_rdev = oh->yst_rdev;
6697 if (oh->shadowsObject > 0)
6698 yaffs_HandleShadowedObject(dev,
6705 yaffs_SetObjectName(in, oh->name);
6707 yaffs_FindOrCreateObjectByNumber
6708 (dev, oh->parentObjectId,
6709 YAFFS_OBJECT_TYPE_DIRECTORY);
6711 fileSize = oh->fileSize;
6712 isShrink = oh->isShrink;
6713 equivalentObjectId = oh->equivalentObjectId;
6716 in->variantType = tags.extraObjectType;
6718 yaffs_FindOrCreateObjectByNumber
6719 (dev, tags.extraParentObjectId,
6720 YAFFS_OBJECT_TYPE_DIRECTORY);
6721 fileSize = tags.extraFileLength;
6722 isShrink = tags.extraIsShrinkHeader;
6723 equivalentObjectId = tags.extraEquivalentObjectId;
6732 /* directory stuff...
6736 if (parent && parent->variantType ==
6737 YAFFS_OBJECT_TYPE_UNKNOWN) {
6738 /* Set up as a directory */
6739 parent->variantType =
6740 YAFFS_OBJECT_TYPE_DIRECTORY;
6741 YINIT_LIST_HEAD(&parent->variant.
6744 } else if (!parent || parent->variantType !=
6745 YAFFS_OBJECT_TYPE_DIRECTORY) {
6746 /* Hoosterman, another problem....
6747 * We're trying to use a non-directory as a directory
6750 T(YAFFS_TRACE_ERROR,
6752 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6754 parent = dev->lostNFoundDir;
6757 yaffs_AddObjectToDirectory(parent, in);
6759 itsUnlinked = (parent == dev->deletedDir) ||
6760 (parent == dev->unlinkedDir);
6763 /* Mark the block as having a shrinkHeader */
6764 bi->hasShrinkHeader = 1;
6767 /* Note re hardlinks.
6768 * Since we might scan a hardlink before its equivalent object is scanned
6769 * we put them all in a list.
6770 * After scanning is complete, we should have all the objects, so we run
6771 * through this list and fix up all the chains.
6774 switch (in->variantType) {
6775 case YAFFS_OBJECT_TYPE_UNKNOWN:
6776 /* Todo got a problem */
6778 case YAFFS_OBJECT_TYPE_FILE:
6780 if (in->variant.fileVariant.
6781 scannedFileSize < fileSize) {
6782 /* This covers the case where the file size is greater
6783 * than where the data is
6784 * This will happen if the file is resized to be larger
6785 * than its current data extents.
6787 in->variant.fileVariant.fileSize = fileSize;
6788 in->variant.fileVariant.scannedFileSize =
6789 in->variant.fileVariant.fileSize;
6793 in->variant.fileVariant.shrinkSize > fileSize) {
6794 in->variant.fileVariant.shrinkSize = fileSize;
6798 case YAFFS_OBJECT_TYPE_HARDLINK:
6800 in->variant.hardLinkVariant.equivalentObjectId =
6802 in->hardLinks.next =
6803 (struct ylist_head *) hardList;
6807 case YAFFS_OBJECT_TYPE_DIRECTORY:
6810 case YAFFS_OBJECT_TYPE_SPECIAL:
6813 case YAFFS_OBJECT_TYPE_SYMLINK:
6815 in->variant.symLinkVariant.alias =
6816 yaffs_CloneString(oh->alias);
6817 if (!in->variant.symLinkVariant.alias)
6827 } /* End of scanning for each chunk */
6829 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6830 /* If we got this far while scanning, then the block is fully allocated. */
6831 state = YAFFS_BLOCK_STATE_FULL;
6835 bi->blockState = state;
6837 /* Now let's see if it was dirty */
6838 if (bi->pagesInUse == 0 &&
6839 !bi->hasShrinkHeader &&
6840 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6841 yaffs_BlockBecameDirty(dev, blk);
6846 yaffs_SkipRestOfBlock(dev);
6849 YFREE_ALT(blockIndex);
6853 /* Ok, we've done all the scanning.
6854 * Fix up the hard link chains.
6855 * We should now have scanned all the objects, now it's time to add these
6858 yaffs_HardlinkFixup(dev, hardList);
6861 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6866 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6871 /*------------------------------ Directory Functions ----------------------------- */
6873 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
6875 struct ylist_head *lh;
6876 yaffs_Object *listObj;
6881 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
6886 if (yaffs_SkipVerification(obj->myDev))
6890 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
6895 if (obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6896 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
6900 /* Iterate through the objects in each hash entry */
6902 ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
6904 listObj = ylist_entry(lh, yaffs_Object, siblings);
6905 yaffs_VerifyObject(listObj);
6912 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR), count));
6917 static void yaffs_VerifyDirectory(yaffs_Object *directory)
6919 struct ylist_head *lh;
6920 yaffs_Object *listObj;
6927 if (yaffs_SkipFullVerification(directory->myDev))
6930 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6931 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR), directory->variantType));
6935 /* Iterate through the objects in each hash entry */
6937 ylist_for_each(lh, &directory->variant.directoryVariant.children) {
6939 listObj = ylist_entry(lh, yaffs_Object, siblings);
6940 if (listObj->parent != directory) {
6941 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR), listObj->parent));
6944 yaffs_VerifyObjectInDirectory(listObj);
6950 *yaffs_UpdateParent() handles fixing a directories mtime and ctime when a new
6951 * link (ie. name) is created or deleted in the directory.
6954 * create dir/a : update dir's mtime/ctime
6955 * rm dir/a: update dir's mtime/ctime
6956 * modify dir/a: don't update dir's mtimme/ctime
6959 static void yaffs_UpdateParent(yaffs_Object *obj)
6965 obj->yst_mtime = obj->yst_ctime = Y_CURRENT_TIME;
6967 yaffs_UpdateObjectHeader(obj,NULL,0,0,0);
6970 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
6972 yaffs_Device *dev = obj->myDev;
6973 yaffs_Object *parent;
6975 yaffs_VerifyObjectInDirectory(obj);
6976 parent = obj->parent;
6978 yaffs_VerifyDirectory(parent);
6980 if (dev && dev->removeObjectCallback)
6981 dev->removeObjectCallback(obj);
6984 ylist_del_init(&obj->siblings);
6987 yaffs_VerifyDirectory(parent);
6990 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
6994 T(YAFFS_TRACE_ALWAYS,
6996 ("tragedy: Trying to add an object to a null pointer directory"
7001 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7002 T(YAFFS_TRACE_ALWAYS,
7004 ("tragedy: Trying to add an object to a non-directory"
7009 if (obj->siblings.prev == NULL) {
7010 /* Not initialised */
7015 yaffs_VerifyDirectory(directory);
7017 yaffs_RemoveObjectFromDirectory(obj);
7021 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
7022 obj->parent = directory;
7024 if (directory == obj->myDev->unlinkedDir
7025 || directory == obj->myDev->deletedDir) {
7027 obj->myDev->nUnlinkedFiles++;
7028 obj->renameAllowed = 0;
7031 yaffs_VerifyDirectory(directory);
7032 yaffs_VerifyObjectInDirectory(obj);
7035 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
7040 struct ylist_head *i;
7041 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
7049 T(YAFFS_TRACE_ALWAYS,
7051 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7056 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7057 T(YAFFS_TRACE_ALWAYS,
7059 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7063 sum = yaffs_CalcNameSum(name);
7065 ylist_for_each(i, &directory->variant.directoryVariant.children) {
7067 l = ylist_entry(i, yaffs_Object, siblings);
7069 if (l->parent != directory)
7072 yaffs_CheckObjectDetailsLoaded(l);
7074 /* Special case for lost-n-found */
7075 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7076 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
7078 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
7079 /* LostnFound chunk called Objxxx
7082 yaffs_GetObjectName(l, buffer,
7083 YAFFS_MAX_NAME_LENGTH + 1);
7084 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
7095 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
7096 int (*fn) (yaffs_Object *))
7098 struct ylist_head *i;
7102 T(YAFFS_TRACE_ALWAYS,
7104 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7109 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7110 T(YAFFS_TRACE_ALWAYS,
7112 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7117 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
7119 l = ylist_entry(i, yaffs_Object, siblings);
7130 /* GetEquivalentObject dereferences any hard links to get to the
7134 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
7136 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
7137 /* We want the object id of the equivalent object, not this one */
7138 obj = obj->variant.hardLinkVariant.equivalentObject;
7139 yaffs_CheckObjectDetailsLoaded(obj);
7144 int yaffs_GetObjectName(yaffs_Object *obj, YCHAR *name, int buffSize)
7146 memset(name, 0, buffSize * sizeof(YCHAR));
7148 yaffs_CheckObjectDetailsLoaded(obj);
7150 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7151 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
7152 } else if (obj->hdrChunk <= 0) {
7154 YCHAR numString[20];
7155 YCHAR *x = &numString[19];
7156 unsigned v = obj->objectId;
7160 *x = '0' + (v % 10);
7163 /* make up a name */
7164 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
7165 yaffs_strcat(locName, x);
7166 yaffs_strncpy(name, locName, buffSize - 1);
7169 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
7170 else if (obj->shortName[0])
7171 yaffs_strncpy(name, obj->shortName,YAFFS_SHORT_NAME_LENGTH+1);
7175 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
7177 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
7179 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
7181 if (obj->hdrChunk > 0) {
7182 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
7183 obj->hdrChunk, buffer,
7186 yaffs_strncpy(name, oh->name, buffSize - 1);
7189 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
7192 return yaffs_strnlen(name,buffSize-1);
7195 int yaffs_GetObjectFileLength(yaffs_Object *obj)
7197 /* Dereference any hard linking */
7198 obj = yaffs_GetEquivalentObject(obj);
7200 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
7201 return obj->variant.fileVariant.fileSize;
7202 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
7203 if(!obj->variant.symLinkVariant.alias)
7205 return yaffs_strnlen(obj->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
7207 /* Only a directory should drop through to here */
7208 return obj->myDev->nDataBytesPerChunk;
7212 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
7215 struct ylist_head *i;
7218 count++; /* the object itself */
7220 ylist_for_each(i, &obj->hardLinks)
7221 count++; /* add the hard links; */
7226 int yaffs_GetObjectInode(yaffs_Object *obj)
7228 obj = yaffs_GetEquivalentObject(obj);
7230 return obj->objectId;
7233 unsigned yaffs_GetObjectType(yaffs_Object *obj)
7235 obj = yaffs_GetEquivalentObject(obj);
7237 switch (obj->variantType) {
7238 case YAFFS_OBJECT_TYPE_FILE:
7241 case YAFFS_OBJECT_TYPE_DIRECTORY:
7244 case YAFFS_OBJECT_TYPE_SYMLINK:
7247 case YAFFS_OBJECT_TYPE_HARDLINK:
7250 case YAFFS_OBJECT_TYPE_SPECIAL:
7251 if (S_ISFIFO(obj->yst_mode))
7253 if (S_ISCHR(obj->yst_mode))
7255 if (S_ISBLK(obj->yst_mode))
7257 if (S_ISSOCK(obj->yst_mode))
7265 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
7267 obj = yaffs_GetEquivalentObject(obj);
7268 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
7269 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7271 return yaffs_CloneString(_Y(""));
7274 #ifndef CONFIG_YAFFS_WINCE
7276 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
7278 unsigned int valid = attr->ia_valid;
7280 if (valid & ATTR_MODE)
7281 obj->yst_mode = attr->ia_mode;
7282 if (valid & ATTR_UID)
7283 obj->yst_uid = attr->ia_uid;
7284 if (valid & ATTR_GID)
7285 obj->yst_gid = attr->ia_gid;
7287 if (valid & ATTR_ATIME)
7288 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7289 if (valid & ATTR_CTIME)
7290 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7291 if (valid & ATTR_MTIME)
7292 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7294 if (valid & ATTR_SIZE)
7295 yaffs_ResizeFile(obj, attr->ia_size);
7297 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7302 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
7304 unsigned int valid = 0;
7306 attr->ia_mode = obj->yst_mode;
7308 attr->ia_uid = obj->yst_uid;
7310 attr->ia_gid = obj->yst_gid;
7313 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7314 valid |= ATTR_ATIME;
7315 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7316 valid |= ATTR_CTIME;
7317 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7318 valid |= ATTR_MTIME;
7320 attr->ia_size = yaffs_GetFileSize(obj);
7323 attr->ia_valid = valid;
7331 int yaffs_DumpObject(yaffs_Object *obj)
7335 yaffs_GetObjectName(obj, name, YAFFS_MAX_NAME_LENGTH + 1);
7337 T(YAFFS_TRACE_ALWAYS,
7339 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7340 " chunk %d type %d size %d\n"
7341 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7342 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7343 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7349 /*---------------------------- Initialisation code -------------------------------------- */
7351 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
7354 /* Common functions, gotta have */
7355 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
7358 #ifdef CONFIG_YAFFS_YAFFS2
7360 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7361 if (dev->writeChunkWithTagsToNAND &&
7362 dev->readChunkWithTagsFromNAND &&
7363 !dev->writeChunkToNAND &&
7364 !dev->readChunkFromNAND &&
7365 dev->markNANDBlockBad && dev->queryNANDBlock)
7369 /* Can use the "spare" style interface for yaffs1 */
7370 if (!dev->isYaffs2 &&
7371 !dev->writeChunkWithTagsToNAND &&
7372 !dev->readChunkWithTagsFromNAND &&
7373 dev->writeChunkToNAND &&
7374 dev->readChunkFromNAND &&
7375 !dev->markNANDBlockBad && !dev->queryNANDBlock)
7382 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7384 /* Initialise the unlinked, deleted, root and lost and found directories */
7386 dev->lostNFoundDir = dev->rootDir = NULL;
7387 dev->unlinkedDir = dev->deletedDir = NULL;
7390 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7393 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7396 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7397 YAFFS_ROOT_MODE | S_IFDIR);
7398 dev->lostNFoundDir =
7399 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7400 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7402 if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
7403 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7410 int yaffs_GutsInitialise(yaffs_Device *dev)
7412 int init_failed = 0;
7416 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7418 /* Check stuff that must be set */
7421 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7425 dev->internalStartBlock = dev->startBlock;
7426 dev->internalEndBlock = dev->endBlock;
7427 dev->blockOffset = 0;
7428 dev->chunkOffset = 0;
7429 dev->nFreeChunks = 0;
7433 if (dev->startBlock == 0) {
7434 dev->internalStartBlock = dev->startBlock + 1;
7435 dev->internalEndBlock = dev->endBlock + 1;
7436 dev->blockOffset = 1;
7437 dev->chunkOffset = dev->nChunksPerBlock;
7440 /* Check geometry parameters. */
7442 if ((!dev->inbandTags && dev->isYaffs2 && dev->totalBytesPerChunk < 1024) ||
7443 (!dev->isYaffs2 && dev->totalBytesPerChunk < 512) ||
7444 (dev->inbandTags && !dev->isYaffs2) ||
7445 dev->nChunksPerBlock < 2 ||
7446 dev->nReservedBlocks < 2 ||
7447 dev->internalStartBlock <= 0 ||
7448 dev->internalEndBlock <= 0 ||
7449 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2)) { /* otherwise it is too small */
7450 T(YAFFS_TRACE_ALWAYS,
7452 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7453 TENDSTR), dev->totalBytesPerChunk, dev->isYaffs2 ? "2" : "", dev->inbandTags));
7457 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7458 T(YAFFS_TRACE_ALWAYS,
7459 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7463 /* Sort out space for inband tags, if required */
7464 if (dev->inbandTags)
7465 dev->nDataBytesPerChunk = dev->totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7467 dev->nDataBytesPerChunk = dev->totalBytesPerChunk;
7469 /* Got the right mix of functions? */
7470 if (!yaffs_CheckDevFunctions(dev)) {
7471 /* Function missing */
7472 T(YAFFS_TRACE_ALWAYS,
7474 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7479 /* This is really a compilation check. */
7480 if (!yaffs_CheckStructures()) {
7481 T(YAFFS_TRACE_ALWAYS,
7482 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7486 if (dev->isMounted) {
7487 T(YAFFS_TRACE_ALWAYS,
7488 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7492 /* Finished with most checks. One or two more checks happen later on too. */
7496 /* OK now calculate a few things for the device */
7499 * Calculate all the chunk size manipulation numbers:
7501 x = dev->nDataBytesPerChunk;
7502 /* We always use dev->chunkShift and dev->chunkDiv */
7503 dev->chunkShift = Shifts(x);
7504 x >>= dev->chunkShift;
7506 /* We only use chunk mask if chunkDiv is 1 */
7507 dev->chunkMask = (1<<dev->chunkShift) - 1;
7510 * Calculate chunkGroupBits.
7511 * We need to find the next power of 2 > than internalEndBlock
7514 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7518 /* Set up tnode width if wide tnodes are enabled. */
7519 if (!dev->wideTnodesDisabled) {
7520 /* bits must be even so that we end up with 32-bit words */
7524 dev->tnodeWidth = 16;
7526 dev->tnodeWidth = bits;
7528 dev->tnodeWidth = 16;
7530 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7532 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7533 * so if the bitwidth of the
7534 * chunk range we're using is greater than 16 we need
7535 * to figure out chunk shift and chunkGroupSize
7538 if (bits <= dev->tnodeWidth)
7539 dev->chunkGroupBits = 0;
7541 dev->chunkGroupBits = bits - dev->tnodeWidth;
7544 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7546 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7547 /* We have a problem because the soft delete won't work if
7548 * the chunk group size > chunks per block.
7549 * This can be remedied by using larger "virtual blocks".
7551 T(YAFFS_TRACE_ALWAYS,
7552 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7557 /* OK, we've finished verifying the device, lets continue with initialisation */
7559 /* More device initialisation */
7560 dev->garbageCollections = 0;
7561 dev->passiveGarbageCollections = 0;
7562 dev->currentDirtyChecker = 0;
7563 dev->bufferedBlock = -1;
7564 dev->doingBufferedBlockRewrite = 0;
7565 dev->nDeletedFiles = 0;
7566 dev->nBackgroundDeletions = 0;
7567 dev->nUnlinkedFiles = 0;
7569 dev->eccUnfixed = 0;
7570 dev->tagsEccFixed = 0;
7571 dev->tagsEccUnfixed = 0;
7572 dev->nErasureFailures = 0;
7573 dev->nErasedBlocks = 0;
7575 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7577 /* Initialise temporary buffers and caches. */
7578 if (!yaffs_InitialiseTempBuffers(dev))
7581 dev->srCache = NULL;
7582 dev->gcCleanupList = NULL;
7586 dev->nShortOpCaches > 0) {
7589 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7591 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
7592 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7594 dev->srCache = YMALLOC(srCacheBytes);
7596 buf = (__u8 *) dev->srCache;
7599 memset(dev->srCache, 0, srCacheBytes);
7601 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7602 dev->srCache[i].object = NULL;
7603 dev->srCache[i].lastUse = 0;
7604 dev->srCache[i].dirty = 0;
7605 dev->srCache[i].data = buf = YMALLOC_DMA(dev->totalBytesPerChunk);
7616 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7617 if (!dev->gcCleanupList)
7622 dev->useHeaderFileSize = 1;
7624 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7627 yaffs_InitialiseTnodes(dev);
7628 yaffs_InitialiseObjects(dev);
7630 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7635 /* Now scan the flash. */
7636 if (dev->isYaffs2) {
7637 if (yaffs_CheckpointRestore(dev)) {
7638 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7639 T(YAFFS_TRACE_ALWAYS,
7640 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7643 /* Clean up the mess caused by an aborted checkpoint load
7644 * and scan backwards.
7646 yaffs_DeinitialiseBlocks(dev);
7647 yaffs_DeinitialiseTnodes(dev);
7648 yaffs_DeinitialiseObjects(dev);
7651 dev->nErasedBlocks = 0;
7652 dev->nFreeChunks = 0;
7653 dev->allocationBlock = -1;
7654 dev->allocationPage = -1;
7655 dev->nDeletedFiles = 0;
7656 dev->nUnlinkedFiles = 0;
7657 dev->nBackgroundDeletions = 0;
7658 dev->oldestDirtySequence = 0;
7660 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7663 yaffs_InitialiseTnodes(dev);
7664 yaffs_InitialiseObjects(dev);
7666 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7669 if (!init_failed && !yaffs_ScanBackwards(dev))
7672 } else if (!yaffs_Scan(dev))
7675 yaffs_StripDeletedObjects(dev);
7676 yaffs_FixHangingObjects(dev);
7677 if(dev->emptyLostAndFound)
7678 yaffs_EmptyLostAndFound(dev);
7682 /* Clean up the mess */
7683 T(YAFFS_TRACE_TRACING,
7684 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7686 yaffs_Deinitialise(dev);
7690 /* Zero out stats */
7691 dev->nPageReads = 0;
7692 dev->nPageWrites = 0;
7693 dev->nBlockErasures = 0;
7695 dev->nRetriedWrites = 0;
7697 dev->nRetiredBlocks = 0;
7699 yaffs_VerifyFreeChunks(dev);
7700 yaffs_VerifyBlocks(dev);
7702 /* Clean up any aborted checkpoint data */
7703 if(!dev->isCheckpointed && dev->blocksInCheckpoint > 0)
7704 yaffs_InvalidateCheckpoint(dev);
7706 T(YAFFS_TRACE_TRACING,
7707 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7712 void yaffs_Deinitialise(yaffs_Device *dev)
7714 if (dev->isMounted) {
7717 yaffs_DeinitialiseBlocks(dev);
7718 yaffs_DeinitialiseTnodes(dev);
7719 yaffs_DeinitialiseObjects(dev);
7720 if (dev->nShortOpCaches > 0 &&
7723 for (i = 0; i < dev->nShortOpCaches; i++) {
7724 if (dev->srCache[i].data)
7725 YFREE(dev->srCache[i].data);
7726 dev->srCache[i].data = NULL;
7729 YFREE(dev->srCache);
7730 dev->srCache = NULL;
7733 YFREE(dev->gcCleanupList);
7735 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
7736 YFREE(dev->tempBuffer[i].buffer);
7740 if (dev->deinitialiseNAND)
7741 dev->deinitialiseNAND(dev);
7745 static int yaffs_CountFreeChunks(yaffs_Device *dev)
7750 yaffs_BlockInfo *blk;
7752 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7754 blk = yaffs_GetBlockInfo(dev, b);
7756 switch (blk->blockState) {
7757 case YAFFS_BLOCK_STATE_EMPTY:
7758 case YAFFS_BLOCK_STATE_ALLOCATING:
7759 case YAFFS_BLOCK_STATE_COLLECTING:
7760 case YAFFS_BLOCK_STATE_FULL:
7762 (dev->nChunksPerBlock - blk->pagesInUse +
7763 blk->softDeletions);
7773 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
7775 /* This is what we report to the outside world */
7778 int nDirtyCacheChunks;
7779 int blocksForCheckpoint;
7783 nFree = dev->nFreeChunks;
7785 nFree = yaffs_CountFreeChunks(dev);
7788 nFree += dev->nDeletedFiles;
7790 /* Now count the number of dirty chunks in the cache and subtract those */
7792 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7793 if (dev->srCache[i].dirty)
7794 nDirtyCacheChunks++;
7797 nFree -= nDirtyCacheChunks;
7799 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7801 /* Now we figure out how much to reserve for the checkpoint and report that... */
7802 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7803 if (blocksForCheckpoint < 0)
7804 blocksForCheckpoint = 0;
7806 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7815 static int yaffs_freeVerificationFailures;
7817 static void yaffs_VerifyFreeChunks(yaffs_Device *dev)
7822 if (yaffs_SkipVerification(dev))
7825 counted = yaffs_CountFreeChunks(dev);
7827 difference = dev->nFreeChunks - counted;
7830 T(YAFFS_TRACE_ALWAYS,
7831 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7832 dev->nFreeChunks, counted, difference));
7833 yaffs_freeVerificationFailures++;
7837 /*---------------------------------------- YAFFS test code ----------------------*/
7839 #define yaffs_CheckStruct(structure, syze, name) \
7841 if (sizeof(structure) != syze) { \
7842 T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
7843 name, syze, (int) sizeof(structure))); \
7844 return YAFFS_FAIL; \
7848 static int yaffs_CheckStructures(void)
7850 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
7851 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
7852 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
7853 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7854 /* yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode"); */
7856 #ifndef CONFIG_YAFFS_WINCE
7857 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");