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.92 2009-11-03 02:41:00 charles Exp $";
19 #include "yaffsinterface.h"
20 #include "yaffs_guts.h"
21 #include "yaffs_tagsvalidity.h"
22 #include "yaffs_getblockinfo.h"
24 #include "yaffs_tagscompat.h"
25 #ifndef CONFIG_YAFFS_USE_OWN_SORT
26 #include "yaffs_qsort.h"
28 #include "yaffs_nand.h"
30 #include "yaffs_checkptrw.h"
32 #include "yaffs_nand.h"
33 #include "yaffs_packedtags2.h"
36 #define YAFFS_PASSIVE_GC_CHUNKS 2
38 #include "yaffs_ecc.h"
41 /* Robustification (if it ever comes about...) */
42 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND);
43 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
45 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
47 const yaffs_ExtendedTags *tags);
48 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
49 const yaffs_ExtendedTags *tags);
51 /* Other local prototypes */
52 static void yaffs_UpdateParent(yaffs_Object *obj);
53 static int yaffs_UnlinkObject(yaffs_Object *obj);
54 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
56 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
58 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev,
60 yaffs_ExtendedTags *tags,
62 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
63 int chunkInNAND, int inScan);
65 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
66 yaffs_ObjectType type);
67 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
69 static int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name,
70 int force, int isShrink, int shadows);
71 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
72 static int yaffs_CheckStructures(void);
73 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
74 int chunkOffset, int *limit);
75 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
77 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev, int blockNo);
80 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
83 static int yaffs_UnlinkWorker(yaffs_Object *obj);
85 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
88 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
89 yaffs_BlockInfo **blockUsedPtr);
91 static void yaffs_VerifyFreeChunks(yaffs_Device *dev);
93 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
95 static void yaffs_VerifyDirectory(yaffs_Object *directory);
97 static int yaffs_CheckFileSanity(yaffs_Object *in);
99 #define yaffs_CheckFileSanity(in)
102 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
103 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
105 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
107 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
108 yaffs_ExtendedTags *tags);
110 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
112 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
113 yaffs_FileStructure *fStruct,
117 /* Function to calculate chunk and offset */
119 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut,
125 chunk = (__u32)(addr >> dev->chunkShift);
127 if (dev->chunkDiv == 1) {
128 /* easy power of 2 case */
129 offset = (__u32)(addr & dev->chunkMask);
131 /* Non power-of-2 case */
135 chunk /= dev->chunkDiv;
137 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
138 offset = (__u32)(addr - chunkBase);
145 /* Function to return the number of shifts for a power of 2 greater than or
146 * equal to the given number
147 * Note we don't try to cater for all possible numbers and this does not have to
148 * be hellishly efficient.
151 static __u32 ShiftsGE(__u32 x)
156 nShifts = extraBits = 0;
171 /* Function to return the number of shifts to get a 1 in bit 0
174 static __u32 Shifts(__u32 x)
194 * Temporary buffer manipulations.
197 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
200 __u8 *buf = (__u8 *)1;
202 memset(dev->tempBuffer, 0, sizeof(dev->tempBuffer));
204 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
205 dev->tempBuffer[i].line = 0; /* not in use */
206 dev->tempBuffer[i].buffer = buf =
207 YMALLOC_DMA(dev->totalBytesPerChunk);
210 return buf ? YAFFS_OK : YAFFS_FAIL;
213 __u8 *yaffs_GetTempBuffer(yaffs_Device *dev, int lineNo)
218 if (dev->tempInUse > dev->maxTemp)
219 dev->maxTemp = dev->tempInUse;
221 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
222 if (dev->tempBuffer[i].line == 0) {
223 dev->tempBuffer[i].line = lineNo;
224 if ((i + 1) > dev->maxTemp) {
225 dev->maxTemp = i + 1;
226 for (j = 0; j <= i; j++)
227 dev->tempBuffer[j].maxLine =
228 dev->tempBuffer[j].line;
231 return dev->tempBuffer[i].buffer;
235 T(YAFFS_TRACE_BUFFERS,
236 (TSTR("Out of temp buffers at line %d, other held by lines:"),
238 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
239 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
241 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
244 * If we got here then we have to allocate an unmanaged one
248 dev->unmanagedTempAllocations++;
249 return YMALLOC(dev->nDataBytesPerChunk);
253 void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer,
260 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
261 if (dev->tempBuffer[i].buffer == buffer) {
262 dev->tempBuffer[i].line = 0;
268 /* assume it is an unmanaged one. */
269 T(YAFFS_TRACE_BUFFERS,
270 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
273 dev->unmanagedTempDeallocations++;
279 * Determine if we have a managed buffer.
281 int yaffs_IsManagedTempBuffer(yaffs_Device *dev, const __u8 *buffer)
285 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
286 if (dev->tempBuffer[i].buffer == buffer)
290 for (i = 0; i < dev->nShortOpCaches; i++) {
291 if (dev->srCache[i].data == buffer)
295 if (buffer == dev->checkpointBuffer)
298 T(YAFFS_TRACE_ALWAYS,
299 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
306 * Chunk bitmap manipulations
309 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
311 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
313 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
317 return dev->chunkBits +
318 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
321 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
323 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
324 chunk < 0 || chunk >= dev->nChunksPerBlock) {
326 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),
332 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device *dev, int blk)
334 __u8 *blkBits = yaffs_BlockBits(dev, blk);
336 memset(blkBits, 0, dev->chunkBitmapStride);
339 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device *dev, int blk, int chunk)
341 __u8 *blkBits = yaffs_BlockBits(dev, blk);
343 yaffs_VerifyChunkBitId(dev, blk, chunk);
345 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
348 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device *dev, int blk, int chunk)
350 __u8 *blkBits = yaffs_BlockBits(dev, blk);
352 yaffs_VerifyChunkBitId(dev, blk, chunk);
354 blkBits[chunk / 8] |= (1 << (chunk & 7));
357 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device *dev, int blk, int chunk)
359 __u8 *blkBits = yaffs_BlockBits(dev, blk);
360 yaffs_VerifyChunkBitId(dev, blk, chunk);
362 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
365 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device *dev, int blk)
367 __u8 *blkBits = yaffs_BlockBits(dev, blk);
369 for (i = 0; i < dev->chunkBitmapStride; i++) {
377 static int yaffs_CountChunkBits(yaffs_Device *dev, int blk)
379 __u8 *blkBits = yaffs_BlockBits(dev, blk);
382 for (i = 0; i < dev->chunkBitmapStride; i++) {
399 static int yaffs_SkipVerification(yaffs_Device *dev)
401 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
404 static int yaffs_SkipFullVerification(yaffs_Device *dev)
406 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
409 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
411 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
414 static const char *blockStateName[] = {
427 static void yaffs_VerifyBlock(yaffs_Device *dev, yaffs_BlockInfo *bi, int n)
432 if (yaffs_SkipVerification(dev))
435 /* Report illegal runtime states */
436 if (bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
437 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has undefined state %d"TENDSTR), n, bi->blockState));
439 switch (bi->blockState) {
440 case YAFFS_BLOCK_STATE_UNKNOWN:
441 case YAFFS_BLOCK_STATE_SCANNING:
442 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
443 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has bad run-state %s"TENDSTR),
444 n, blockStateName[bi->blockState]));
447 /* Check pages in use and soft deletions are legal */
449 actuallyUsed = bi->pagesInUse - bi->softDeletions;
451 if (bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
452 bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
453 actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock)
454 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
455 n, bi->pagesInUse, bi->softDeletions));
458 /* Check chunk bitmap legal */
459 inUse = yaffs_CountChunkBits(dev, n);
460 if (inUse != bi->pagesInUse)
461 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
462 n, bi->pagesInUse, inUse));
464 /* Check that the sequence number is valid.
465 * Ten million is legal, but is very unlikely
468 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
469 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000))
470 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has suspect sequence number of %d"TENDSTR),
471 n, bi->sequenceNumber));
474 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev, yaffs_BlockInfo *bi,
477 yaffs_VerifyBlock(dev, bi, n);
479 /* After collection the block should be in the erased state */
480 /* This will need to change if we do partial gc */
482 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
483 bi->blockState != YAFFS_BLOCK_STATE_EMPTY) {
484 T(YAFFS_TRACE_ERROR, (TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
489 static void yaffs_VerifyBlocks(yaffs_Device *dev)
492 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
493 int nIllegalBlockStates = 0;
495 if (yaffs_SkipVerification(dev))
498 memset(nBlocksPerState, 0, sizeof(nBlocksPerState));
500 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
501 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, i);
502 yaffs_VerifyBlock(dev, bi, i);
504 if (bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
505 nBlocksPerState[bi->blockState]++;
507 nIllegalBlockStates++;
510 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
511 T(YAFFS_TRACE_VERIFY, (TSTR("Block summary"TENDSTR)));
513 T(YAFFS_TRACE_VERIFY, (TSTR("%d blocks have illegal states"TENDSTR), nIllegalBlockStates));
514 if (nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
515 T(YAFFS_TRACE_VERIFY, (TSTR("Too many allocating blocks"TENDSTR)));
517 for (i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
518 T(YAFFS_TRACE_VERIFY,
519 (TSTR("%s %d blocks"TENDSTR),
520 blockStateName[i], nBlocksPerState[i]));
522 if (dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
523 T(YAFFS_TRACE_VERIFY,
524 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
525 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
527 if (dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
528 T(YAFFS_TRACE_VERIFY,
529 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
530 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
532 if (nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
533 T(YAFFS_TRACE_VERIFY,
534 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
535 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
537 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
542 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
543 * case those tests will not be performed.
545 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
547 if (obj && yaffs_SkipVerification(obj->myDev))
550 if (!(tags && obj && oh)) {
551 T(YAFFS_TRACE_VERIFY,
552 (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR),
553 (__u32)tags, (__u32)obj, (__u32)oh));
557 if (oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
558 oh->type > YAFFS_OBJECT_TYPE_MAX)
559 T(YAFFS_TRACE_VERIFY,
560 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
561 tags->objectId, oh->type));
563 if (tags->objectId != obj->objectId)
564 T(YAFFS_TRACE_VERIFY,
565 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
566 tags->objectId, obj->objectId));
570 * Check that the object's parent ids match if parentCheck requested.
572 * Tests do not apply to the root object.
575 if (parentCheck && tags->objectId > 1 && !obj->parent)
576 T(YAFFS_TRACE_VERIFY,
577 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
578 tags->objectId, oh->parentObjectId));
580 if (parentCheck && obj->parent &&
581 oh->parentObjectId != obj->parent->objectId &&
582 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
583 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
584 T(YAFFS_TRACE_VERIFY,
585 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
586 tags->objectId, oh->parentObjectId, obj->parent->objectId));
588 if (tags->objectId > 1 && oh->name[0] == 0) /* Null name */
589 T(YAFFS_TRACE_VERIFY,
590 (TSTR("Obj %d header name is NULL"TENDSTR),
593 if (tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
594 T(YAFFS_TRACE_VERIFY,
595 (TSTR("Obj %d header name is 0xFF"TENDSTR),
601 static int yaffs_VerifyTnodeWorker(yaffs_Object *obj, yaffs_Tnode *tn,
602 __u32 level, int chunkOffset)
605 yaffs_Device *dev = obj->myDev;
611 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
612 if (tn->internal[i]) {
613 ok = yaffs_VerifyTnodeWorker(obj,
616 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
619 } else if (level == 0) {
620 yaffs_ExtendedTags tags;
621 __u32 objectId = obj->objectId;
623 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
625 for (i = 0; i < YAFFS_NTNODES_LEVEL0; i++) {
626 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
629 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
630 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
631 if (tags.objectId != objectId || tags.chunkId != chunkOffset) {
632 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
633 objectId, chunkOffset, theChunk,
634 tags.objectId, tags.chunkId));
647 static void yaffs_VerifyFile(yaffs_Object *obj)
649 int requiredTallness;
655 yaffs_ExtendedTags tags;
662 if (yaffs_SkipVerification(obj->myDev))
666 objectId = obj->objectId;
668 /* Check file size is consistent with tnode depth */
669 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
670 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
671 requiredTallness = 0;
673 x >>= YAFFS_TNODES_INTERNAL_BITS;
677 actualTallness = obj->variant.fileVariant.topLevel;
679 if (requiredTallness > actualTallness)
680 T(YAFFS_TRACE_VERIFY,
681 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
682 obj->objectId, actualTallness, requiredTallness));
685 /* Check that the chunks in the tnode tree are all correct.
686 * We do this by scanning through the tnode tree and
687 * checking the tags for every chunk match.
690 if (yaffs_SkipNANDVerification(dev))
693 for (i = 1; i <= lastChunk; i++) {
694 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant, i);
697 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
699 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
700 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
701 if (tags.objectId != objectId || tags.chunkId != i) {
702 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
703 objectId, i, theChunk,
704 tags.objectId, tags.chunkId));
712 static void yaffs_VerifyHardLink(yaffs_Object *obj)
714 if (obj && yaffs_SkipVerification(obj->myDev))
717 /* Verify sane equivalent object */
720 static void yaffs_VerifySymlink(yaffs_Object *obj)
722 if (obj && yaffs_SkipVerification(obj->myDev))
725 /* Verify symlink string */
728 static void yaffs_VerifySpecial(yaffs_Object *obj)
730 if (obj && yaffs_SkipVerification(obj->myDev))
734 static void yaffs_VerifyObject(yaffs_Object *obj)
743 __u32 chunkShouldNotBeDeleted;
749 if (obj->beingCreated)
754 if (yaffs_SkipVerification(dev))
757 /* Check sane object header chunk */
759 chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
760 chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
762 chunkInRange = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
763 chunkIdOk = chunkInRange || (obj->hdrChunk == 0);
764 chunkValid = chunkInRange &&
765 yaffs_CheckChunkBit(dev,
766 obj->hdrChunk / dev->nChunksPerBlock,
767 obj->hdrChunk % dev->nChunksPerBlock);
768 chunkShouldNotBeDeleted = chunkInRange && !chunkValid;
771 (!chunkIdOk || chunkShouldNotBeDeleted)) {
772 T(YAFFS_TRACE_VERIFY,
773 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
774 obj->objectId, obj->hdrChunk,
775 chunkIdOk ? "" : ",out of range",
776 chunkShouldNotBeDeleted ? ",marked as deleted" : ""));
779 if (chunkValid && !yaffs_SkipNANDVerification(dev)) {
780 yaffs_ExtendedTags tags;
781 yaffs_ObjectHeader *oh;
782 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
784 oh = (yaffs_ObjectHeader *)buffer;
786 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk, buffer,
789 yaffs_VerifyObjectHeader(obj, oh, &tags, 1);
791 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
794 /* Verify it has a parent */
795 if (obj && !obj->fake &&
796 (!obj->parent || obj->parent->myDev != dev)) {
797 T(YAFFS_TRACE_VERIFY,
798 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
799 obj->objectId, obj->parent));
802 /* Verify parent is a directory */
803 if (obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
804 T(YAFFS_TRACE_VERIFY,
805 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
806 obj->objectId, obj->parent->variantType));
809 switch (obj->variantType) {
810 case YAFFS_OBJECT_TYPE_FILE:
811 yaffs_VerifyFile(obj);
813 case YAFFS_OBJECT_TYPE_SYMLINK:
814 yaffs_VerifySymlink(obj);
816 case YAFFS_OBJECT_TYPE_DIRECTORY:
817 yaffs_VerifyDirectory(obj);
819 case YAFFS_OBJECT_TYPE_HARDLINK:
820 yaffs_VerifyHardLink(obj);
822 case YAFFS_OBJECT_TYPE_SPECIAL:
823 yaffs_VerifySpecial(obj);
825 case YAFFS_OBJECT_TYPE_UNKNOWN:
827 T(YAFFS_TRACE_VERIFY,
828 (TSTR("Obj %d has illegaltype %d"TENDSTR),
829 obj->objectId, obj->variantType));
834 static void yaffs_VerifyObjects(yaffs_Device *dev)
838 struct ylist_head *lh;
840 if (yaffs_SkipVerification(dev))
843 /* Iterate through the objects in each hash entry */
845 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
846 ylist_for_each(lh, &dev->objectBucket[i].list) {
848 obj = ylist_entry(lh, yaffs_Object, hashLink);
849 yaffs_VerifyObject(obj);
857 * Simple hash function. Needs to have a reasonable spread
860 static Y_INLINE int yaffs_HashFunction(int n)
863 return n % YAFFS_NOBJECT_BUCKETS;
867 * Access functions to useful fake objects.
868 * Note that root might have a presence in NAND if permissions are set.
871 yaffs_Object *yaffs_Root(yaffs_Device *dev)
876 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
878 return dev->lostNFoundDir;
883 * Erased NAND checking functions
886 int yaffs_CheckFF(__u8 *buffer, int nBytes)
888 /* Horrible, slow implementation */
897 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
900 int retval = YAFFS_OK;
901 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
902 yaffs_ExtendedTags tags;
905 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
907 if (tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
910 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
911 T(YAFFS_TRACE_NANDACCESS,
912 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
916 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
922 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
924 yaffs_ExtendedTags *tags,
931 yaffs_InvalidateCheckpoint(dev);
934 yaffs_BlockInfo *bi = 0;
937 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
943 /* First check this chunk is erased, if it needs
944 * checking. The checking policy (unless forced
945 * always on) is as follows:
947 * Check the first page we try to write in a block.
948 * If the check passes then we don't need to check any
949 * more. If the check fails, we check again...
950 * If the block has been erased, we don't need to check.
952 * However, if the block has been prioritised for gc,
953 * then we think there might be something odd about
954 * this block and stop using it.
956 * Rationale: We should only ever see chunks that have
957 * not been erased if there was a partially written
958 * chunk due to power loss. This checking policy should
959 * catch that case with very few checks and thus save a
960 * lot of checks that are most likely not needed.
962 if (bi->gcPrioritise) {
963 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
964 /* try another chunk */
968 /* let's give it a try */
971 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
972 bi->skipErasedCheck = 0;
974 if (!bi->skipErasedCheck) {
975 erasedOk = yaffs_CheckChunkErased(dev, chunk);
976 if (erasedOk != YAFFS_OK) {
978 (TSTR("**>> yaffs chunk %d was not erased"
981 /* try another chunk */
984 bi->skipErasedCheck = 1;
987 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
989 if (writeOk != YAFFS_OK) {
990 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
991 /* try another chunk */
995 /* Copy the data into the robustification buffer */
996 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
998 } while (writeOk != YAFFS_OK &&
999 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1005 T(YAFFS_TRACE_ERROR,
1006 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1009 dev->nRetriedWrites += (attempts - 1);
1016 * Block retiring for handling a broken block.
1019 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND)
1021 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1023 yaffs_InvalidateCheckpoint(dev);
1025 if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
1026 if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
1027 T(YAFFS_TRACE_ALWAYS, (TSTR(
1028 "yaffs: Failed to mark bad and erase block %d"
1029 TENDSTR), blockInNAND));
1031 yaffs_ExtendedTags tags;
1032 int chunkId = blockInNAND * dev->nChunksPerBlock;
1034 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
1036 memset(buffer, 0xff, dev->nDataBytesPerChunk);
1037 yaffs_InitialiseTags(&tags);
1038 tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
1039 if (dev->writeChunkWithTagsToNAND(dev, chunkId -
1040 dev->chunkOffset, buffer, &tags) != YAFFS_OK)
1041 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
1042 TCONT("write bad block marker to block %d")
1043 TENDSTR), blockInNAND));
1045 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
1049 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1050 bi->gcPrioritise = 0;
1051 bi->needsRetiring = 0;
1053 dev->nRetiredBlocks++;
1057 * Functions for robustisizing TODO
1061 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
1063 const yaffs_ExtendedTags *tags)
1067 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
1068 const yaffs_ExtendedTags *tags)
1072 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1074 if (!bi->gcPrioritise) {
1075 bi->gcPrioritise = 1;
1076 dev->hasPendingPrioritisedGCs = 1;
1077 bi->chunkErrorStrikes++;
1079 if (bi->chunkErrorStrikes > 3) {
1080 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1081 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1087 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
1090 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1091 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1093 yaffs_HandleChunkError(dev, bi);
1096 /* Was an actual write failure, so mark the block for retirement */
1097 bi->needsRetiring = 1;
1098 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1099 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1102 /* Delete the chunk */
1103 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1107 /*---------------- Name handling functions ------------*/
1109 static __u16 yaffs_CalcNameSum(const YCHAR *name)
1114 const YUCHAR *bname = (const YUCHAR *) name;
1116 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1118 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1119 sum += yaffs_toupper(*bname) * i;
1121 sum += (*bname) * i;
1130 static void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
1132 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1133 memset(obj->shortName, 0, sizeof(YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1134 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH)
1135 yaffs_strcpy(obj->shortName, name);
1137 obj->shortName[0] = _Y('\0');
1139 obj->sum = yaffs_CalcNameSum(name);
1142 /*-------------------- TNODES -------------------
1144 * List of spare tnodes
1145 * The list is hooked together using the first pointer
1149 /* yaffs_CreateTnodes creates a bunch more tnodes and
1150 * adds them to the tnode free list.
1151 * Don't use this function directly
1154 static int yaffs_CreateTnodes(yaffs_Device *dev, int nTnodes)
1158 yaffs_Tnode *newTnodes;
1162 yaffs_TnodeList *tnl;
1167 /* Calculate the tnode size in bytes for variable width tnode support.
1168 * Must be a multiple of 32-bits */
1169 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1171 if (tnodeSize < sizeof(yaffs_Tnode))
1172 tnodeSize = sizeof(yaffs_Tnode);
1174 /* make these things */
1176 newTnodes = YMALLOC(nTnodes * tnodeSize);
1177 mem = (__u8 *)newTnodes;
1180 T(YAFFS_TRACE_ERROR,
1181 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1185 /* Hook them into the free list */
1187 for (i = 0; i < nTnodes - 1; i++) {
1188 newTnodes[i].internal[0] = &newTnodes[i + 1];
1189 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1190 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1194 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1195 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1196 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1198 dev->freeTnodes = newTnodes;
1200 /* New hookup for wide tnodes */
1201 for (i = 0; i < nTnodes - 1; i++) {
1202 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1203 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1204 curr->internal[0] = next;
1207 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1208 curr->internal[0] = dev->freeTnodes;
1209 dev->freeTnodes = (yaffs_Tnode *)mem;
1214 dev->nFreeTnodes += nTnodes;
1215 dev->nTnodesCreated += nTnodes;
1217 /* Now add this bunch of tnodes to a list for freeing up.
1218 * NB If we can't add this to the management list it isn't fatal
1219 * but it just means we can't free this bunch of tnodes later.
1222 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1224 T(YAFFS_TRACE_ERROR,
1226 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1229 tnl->tnodes = newTnodes;
1230 tnl->next = dev->allocatedTnodeList;
1231 dev->allocatedTnodeList = tnl;
1234 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1239 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1241 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device *dev)
1243 yaffs_Tnode *tn = NULL;
1245 /* If there are none left make more */
1246 if (!dev->freeTnodes)
1247 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1249 if (dev->freeTnodes) {
1250 tn = dev->freeTnodes;
1251 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1252 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1253 /* Hoosterman, this thing looks like it isn't in the list */
1254 T(YAFFS_TRACE_ALWAYS,
1255 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1258 dev->freeTnodes = dev->freeTnodes->internal[0];
1262 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1267 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
1269 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1270 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1272 if (tnodeSize < sizeof(yaffs_Tnode))
1273 tnodeSize = sizeof(yaffs_Tnode);
1276 memset(tn, 0, tnodeSize);
1281 /* FreeTnode frees up a tnode and puts it back on the free list */
1282 static void yaffs_FreeTnode(yaffs_Device *dev, yaffs_Tnode *tn)
1285 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1286 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1287 /* Hoosterman, this thing looks like it is already in the list */
1288 T(YAFFS_TRACE_ALWAYS,
1289 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1291 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1293 tn->internal[0] = dev->freeTnodes;
1294 dev->freeTnodes = tn;
1297 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1300 static void yaffs_DeinitialiseTnodes(yaffs_Device *dev)
1302 /* Free the list of allocated tnodes */
1303 yaffs_TnodeList *tmp;
1305 while (dev->allocatedTnodeList) {
1306 tmp = dev->allocatedTnodeList->next;
1308 YFREE(dev->allocatedTnodeList->tnodes);
1309 YFREE(dev->allocatedTnodeList);
1310 dev->allocatedTnodeList = tmp;
1314 dev->freeTnodes = NULL;
1315 dev->nFreeTnodes = 0;
1318 static void yaffs_InitialiseTnodes(yaffs_Device *dev)
1320 dev->allocatedTnodeList = NULL;
1321 dev->freeTnodes = NULL;
1322 dev->nFreeTnodes = 0;
1323 dev->nTnodesCreated = 0;
1327 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
1330 __u32 *map = (__u32 *)tn;
1336 pos &= YAFFS_TNODES_LEVEL0_MASK;
1337 val >>= dev->chunkGroupBits;
1339 bitInMap = pos * dev->tnodeWidth;
1340 wordInMap = bitInMap / 32;
1341 bitInWord = bitInMap & (32 - 1);
1343 mask = dev->tnodeMask << bitInWord;
1345 map[wordInMap] &= ~mask;
1346 map[wordInMap] |= (mask & (val << bitInWord));
1348 if (dev->tnodeWidth > (32 - bitInWord)) {
1349 bitInWord = (32 - bitInWord);
1351 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1352 map[wordInMap] &= ~mask;
1353 map[wordInMap] |= (mask & (val >> bitInWord));
1357 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
1360 __u32 *map = (__u32 *)tn;
1366 pos &= YAFFS_TNODES_LEVEL0_MASK;
1368 bitInMap = pos * dev->tnodeWidth;
1369 wordInMap = bitInMap / 32;
1370 bitInWord = bitInMap & (32 - 1);
1372 val = map[wordInMap] >> bitInWord;
1374 if (dev->tnodeWidth > (32 - bitInWord)) {
1375 bitInWord = (32 - bitInWord);
1377 val |= (map[wordInMap] << bitInWord);
1380 val &= dev->tnodeMask;
1381 val <<= dev->chunkGroupBits;
1386 /* ------------------- End of individual tnode manipulation -----------------*/
1388 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1389 * The look up tree is represented by the top tnode and the number of topLevel
1390 * in the tree. 0 means only the level 0 tnode is in the tree.
1393 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1394 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
1395 yaffs_FileStructure *fStruct,
1398 yaffs_Tnode *tn = fStruct->top;
1400 int requiredTallness;
1401 int level = fStruct->topLevel;
1403 /* Check sane level and chunk Id */
1404 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
1407 if (chunkId > YAFFS_MAX_CHUNK_ID)
1410 /* First check we're tall enough (ie enough topLevel) */
1412 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1413 requiredTallness = 0;
1415 i >>= YAFFS_TNODES_INTERNAL_BITS;
1419 if (requiredTallness > fStruct->topLevel)
1420 return NULL; /* Not tall enough, so we can't find it */
1422 /* Traverse down to level 0 */
1423 while (level > 0 && tn) {
1424 tn = tn->internal[(chunkId >>
1425 (YAFFS_TNODES_LEVEL0_BITS +
1427 YAFFS_TNODES_INTERNAL_BITS)) &
1428 YAFFS_TNODES_INTERNAL_MASK];
1435 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1436 * This happens in two steps:
1437 * 1. If the tree isn't tall enough, then make it taller.
1438 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1440 * Used when modifying the tree.
1442 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1443 * be plugged into the ttree.
1446 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
1447 yaffs_FileStructure *fStruct,
1449 yaffs_Tnode *passedTn)
1451 int requiredTallness;
1459 /* Check sane level and page Id */
1460 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
1463 if (chunkId > YAFFS_MAX_CHUNK_ID)
1466 /* First check we're tall enough (ie enough topLevel) */
1468 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1469 requiredTallness = 0;
1471 x >>= YAFFS_TNODES_INTERNAL_BITS;
1476 if (requiredTallness > fStruct->topLevel) {
1477 /* Not tall enough, gotta make the tree taller */
1478 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1480 tn = yaffs_GetTnode(dev);
1483 tn->internal[0] = fStruct->top;
1486 T(YAFFS_TRACE_ERROR,
1487 (TSTR("yaffs: no more tnodes" TENDSTR)));
1491 fStruct->topLevel = requiredTallness;
1494 /* Traverse down to level 0, adding anything we need */
1496 l = fStruct->topLevel;
1500 while (l > 0 && tn) {
1502 (YAFFS_TNODES_LEVEL0_BITS +
1503 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1504 YAFFS_TNODES_INTERNAL_MASK;
1507 if ((l > 1) && !tn->internal[x]) {
1508 /* Add missing non-level-zero tnode */
1509 tn->internal[x] = yaffs_GetTnode(dev);
1511 } else if (l == 1) {
1512 /* Looking from level 1 at level 0 */
1514 /* If we already have one, then release it.*/
1515 if (tn->internal[x])
1516 yaffs_FreeTnode(dev, tn->internal[x]);
1517 tn->internal[x] = passedTn;
1519 } else if (!tn->internal[x]) {
1520 /* Don't have one, none passed in */
1521 tn->internal[x] = yaffs_GetTnode(dev);
1525 tn = tn->internal[x];
1529 /* top is level 0 */
1531 memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1532 yaffs_FreeTnode(dev, passedTn);
1539 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
1540 yaffs_ExtendedTags *tags, int objectId,
1545 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1546 if (yaffs_CheckChunkBit(dev, theChunk / dev->nChunksPerBlock,
1547 theChunk % dev->nChunksPerBlock)) {
1549 if(dev->chunkGroupSize == 1)
1552 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1554 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1566 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1567 * chunks and tnodes in the file
1568 * Returns 1 if the tree was deleted.
1569 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1572 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
1573 int chunkOffset, int *limit)
1578 yaffs_ExtendedTags tags;
1580 yaffs_Device *dev = in->myDev;
1586 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1588 if (tn->internal[i]) {
1589 if (limit && (*limit) < 0) {
1593 yaffs_DeleteWorker(in,
1601 YAFFS_TNODES_INTERNAL_BITS)
1606 yaffs_FreeTnode(dev,
1609 tn->internal[i] = NULL;
1613 return (allDone) ? 1 : 0;
1614 } else if (level == 0) {
1617 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1619 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1622 chunkInInode = (chunkOffset <<
1623 YAFFS_TNODES_LEVEL0_BITS) + i;
1626 yaffs_FindChunkInGroup(dev,
1632 if (foundChunk > 0) {
1633 yaffs_DeleteChunk(dev,
1638 *limit = *limit - 1;
1645 yaffs_PutLevel0Tnode(dev, tn, i, 0);
1649 return (i < 0) ? 1 : 0;
1659 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1661 yaffs_BlockInfo *theBlock;
1663 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1665 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1667 theBlock->softDeletions++;
1672 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1673 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1675 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1678 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1679 __u32 level, int chunkOffset)
1684 yaffs_Device *dev = in->myDev;
1689 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1691 if (tn->internal[i]) {
1693 yaffs_SoftDeleteWorker(in,
1699 YAFFS_TNODES_INTERNAL_BITS)
1702 yaffs_FreeTnode(dev,
1705 tn->internal[i] = NULL;
1707 /* Hoosterman... how could this happen? */
1711 return (allDone) ? 1 : 0;
1712 } else if (level == 0) {
1714 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1715 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1717 /* Note this does not find the real chunk, only the chunk group.
1718 * We make an assumption that a chunk group is not larger than
1721 yaffs_SoftDeleteChunk(dev, theChunk);
1722 yaffs_PutLevel0Tnode(dev, tn, i, 0);
1736 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1739 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1740 if (obj->nDataChunks <= 0) {
1741 /* Empty file with no duplicate object headers, just delete it immediately */
1742 yaffs_FreeTnode(obj->myDev,
1743 obj->variant.fileVariant.top);
1744 obj->variant.fileVariant.top = NULL;
1745 T(YAFFS_TRACE_TRACING,
1746 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1748 yaffs_DoGenericObjectDeletion(obj);
1750 yaffs_SoftDeleteWorker(obj,
1751 obj->variant.fileVariant.top,
1752 obj->variant.fileVariant.
1754 obj->softDeleted = 1;
1759 /* Pruning removes any part of the file structure tree that is beyond the
1760 * bounds of the file (ie that does not point to chunks).
1762 * A file should only get pruned when its size is reduced.
1764 * Before pruning, the chunks must be pulled from the tree and the
1765 * level 0 tnode entries must be zeroed out.
1766 * Could also use this for file deletion, but that's probably better handled
1767 * by a special case.
1770 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1771 __u32 level, int del0)
1779 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1780 if (tn->internal[i] && level > 0) {
1782 yaffs_PruneWorker(dev, tn->internal[i],
1784 (i == 0) ? del0 : 1);
1787 if (tn->internal[i])
1791 if (hasData == 0 && del0) {
1792 /* Free and return NULL */
1794 yaffs_FreeTnode(dev, tn);
1804 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1805 yaffs_FileStructure *fStruct)
1812 if (fStruct->topLevel > 0) {
1814 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1816 /* Now we have a tree with all the non-zero branches NULL but the height
1817 * is the same as it was.
1818 * Let's see if we can trim internal tnodes to shorten the tree.
1819 * We can do this if only the 0th element in the tnode is in use
1820 * (ie all the non-zero are NULL)
1823 while (fStruct->topLevel && !done) {
1827 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1828 if (tn->internal[i])
1833 fStruct->top = tn->internal[0];
1834 fStruct->topLevel--;
1835 yaffs_FreeTnode(dev, tn);
1845 /*-------------------- End of File Structure functions.-------------------*/
1847 /* yaffs_CreateFreeObjects creates a bunch more objects and
1848 * adds them to the object free list.
1850 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1853 yaffs_Object *newObjects;
1854 yaffs_ObjectList *list;
1859 /* make these things */
1860 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1861 list = YMALLOC(sizeof(yaffs_ObjectList));
1863 if (!newObjects || !list) {
1868 T(YAFFS_TRACE_ALLOCATE,
1869 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1873 /* Hook them into the free list */
1874 for (i = 0; i < nObjects - 1; i++) {
1875 newObjects[i].siblings.next =
1876 (struct ylist_head *)(&newObjects[i + 1]);
1879 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1880 dev->freeObjects = newObjects;
1881 dev->nFreeObjects += nObjects;
1882 dev->nObjectsCreated += nObjects;
1884 /* Now add this bunch of Objects to a list for freeing up. */
1886 list->objects = newObjects;
1887 list->next = dev->allocatedObjectList;
1888 dev->allocatedObjectList = list;
1894 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1895 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1897 yaffs_Object *tn = NULL;
1899 #ifdef VALGRIND_TEST
1900 tn = YMALLOC(sizeof(yaffs_Object));
1902 /* If there are none left make more */
1903 if (!dev->freeObjects)
1904 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1906 if (dev->freeObjects) {
1907 tn = dev->freeObjects;
1909 (yaffs_Object *) (dev->freeObjects->siblings.next);
1910 dev->nFreeObjects--;
1914 /* Now sweeten it up... */
1916 memset(tn, 0, sizeof(yaffs_Object));
1917 tn->beingCreated = 1;
1921 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1922 YINIT_LIST_HEAD(&(tn->hardLinks));
1923 YINIT_LIST_HEAD(&(tn->hashLink));
1924 YINIT_LIST_HEAD(&tn->siblings);
1927 /* Now make the directory sane */
1929 tn->parent = dev->rootDir;
1930 ylist_add(&(tn->siblings), &dev->rootDir->variant.directoryVariant.children);
1933 /* Add it to the lost and found directory.
1934 * NB Can't put root or lostNFound in lostNFound so
1935 * check if lostNFound exists first
1937 if (dev->lostNFoundDir)
1938 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1940 tn->beingCreated = 0;
1943 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1948 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
1953 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1955 obj->fake = 1; /* it is fake so it might have no NAND presence... */
1956 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1957 obj->unlinkAllowed = 0; /* ... or unlink it */
1960 obj->yst_mode = mode;
1962 obj->hdrChunk = 0; /* Not a valid chunk. */
1969 static void yaffs_UnhashObject(yaffs_Object *tn)
1972 yaffs_Device *dev = tn->myDev;
1974 /* If it is still linked into the bucket list, free from the list */
1975 if (!ylist_empty(&tn->hashLink)) {
1976 ylist_del_init(&tn->hashLink);
1977 bucket = yaffs_HashFunction(tn->objectId);
1978 dev->objectBucket[bucket].count--;
1982 /* FreeObject frees up a Object and puts it back on the free list */
1983 static void yaffs_FreeObject(yaffs_Object *tn)
1985 yaffs_Device *dev = tn->myDev;
1988 T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), tn, tn->myInode));
1993 if (!ylist_empty(&tn->siblings))
1999 /* We're still hooked up to a cached inode.
2000 * Don't delete now, but mark for later deletion
2002 tn->deferedFree = 1;
2007 yaffs_UnhashObject(tn);
2009 #ifdef VALGRIND_TEST
2012 /* Link into the free list. */
2013 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2014 dev->freeObjects = tn;
2015 dev->nFreeObjects++;
2017 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2022 void yaffs_HandleDeferedFree(yaffs_Object *obj)
2024 if (obj->deferedFree)
2025 yaffs_FreeObject(obj);
2030 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
2032 /* Free the list of allocated Objects */
2034 yaffs_ObjectList *tmp;
2036 while (dev->allocatedObjectList) {
2037 tmp = dev->allocatedObjectList->next;
2038 YFREE(dev->allocatedObjectList->objects);
2039 YFREE(dev->allocatedObjectList);
2041 dev->allocatedObjectList = tmp;
2044 dev->freeObjects = NULL;
2045 dev->nFreeObjects = 0;
2048 static void yaffs_InitialiseObjects(yaffs_Device *dev)
2052 dev->allocatedObjectList = NULL;
2053 dev->freeObjects = NULL;
2054 dev->nFreeObjects = 0;
2056 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2057 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2058 dev->objectBucket[i].count = 0;
2062 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
2067 int lowest = 999999;
2069 /* First let's see if we can find one that's empty. */
2071 for (i = 0; i < 10 && lowest > 0; i++) {
2073 x %= YAFFS_NOBJECT_BUCKETS;
2074 if (dev->objectBucket[x].count < lowest) {
2075 lowest = dev->objectBucket[x].count;
2081 /* If we didn't find an empty list, then try
2082 * looking a bit further for a short one
2085 for (i = 0; i < 10 && lowest > 3; i++) {
2087 x %= YAFFS_NOBJECT_BUCKETS;
2088 if (dev->objectBucket[x].count < lowest) {
2089 lowest = dev->objectBucket[x].count;
2098 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
2100 int bucket = yaffs_FindNiceObjectBucket(dev);
2102 /* Now find an object value that has not already been taken
2103 * by scanning the list.
2107 struct ylist_head *i;
2109 __u32 n = (__u32) bucket;
2111 /* yaffs_CheckObjectHashSanity(); */
2115 n += YAFFS_NOBJECT_BUCKETS;
2116 if (1 || dev->objectBucket[bucket].count > 0) {
2117 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2118 /* If there is already one in the list */
2119 if (i && ylist_entry(i, yaffs_Object,
2120 hashLink)->objectId == n) {
2130 static void yaffs_HashObject(yaffs_Object *in)
2132 int bucket = yaffs_HashFunction(in->objectId);
2133 yaffs_Device *dev = in->myDev;
2135 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2136 dev->objectBucket[bucket].count++;
2139 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
2141 int bucket = yaffs_HashFunction(number);
2142 struct ylist_head *i;
2145 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2146 /* Look if it is in the list */
2148 in = ylist_entry(i, yaffs_Object, hashLink);
2149 if (in->objectId == number) {
2151 /* Don't tell the VFS about this one if it is defered free */
2152 if (in->deferedFree)
2164 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
2165 yaffs_ObjectType type)
2167 yaffs_Object *theObject;
2168 yaffs_Tnode *tn = NULL;
2171 number = yaffs_CreateNewObjectNumber(dev);
2173 theObject = yaffs_AllocateEmptyObject(dev);
2177 if (type == YAFFS_OBJECT_TYPE_FILE) {
2178 tn = yaffs_GetTnode(dev);
2180 yaffs_FreeObject(theObject);
2186 theObject->fake = 0;
2187 theObject->renameAllowed = 1;
2188 theObject->unlinkAllowed = 1;
2189 theObject->objectId = number;
2190 yaffs_HashObject(theObject);
2191 theObject->variantType = type;
2192 #ifdef CONFIG_YAFFS_WINCE
2193 yfsd_WinFileTimeNow(theObject->win_atime);
2194 theObject->win_ctime[0] = theObject->win_mtime[0] =
2195 theObject->win_atime[0];
2196 theObject->win_ctime[1] = theObject->win_mtime[1] =
2197 theObject->win_atime[1];
2201 theObject->yst_atime = theObject->yst_mtime =
2202 theObject->yst_ctime = Y_CURRENT_TIME;
2205 case YAFFS_OBJECT_TYPE_FILE:
2206 theObject->variant.fileVariant.fileSize = 0;
2207 theObject->variant.fileVariant.scannedFileSize = 0;
2208 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2209 theObject->variant.fileVariant.topLevel = 0;
2210 theObject->variant.fileVariant.top = tn;
2212 case YAFFS_OBJECT_TYPE_DIRECTORY:
2213 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2216 case YAFFS_OBJECT_TYPE_SYMLINK:
2217 case YAFFS_OBJECT_TYPE_HARDLINK:
2218 case YAFFS_OBJECT_TYPE_SPECIAL:
2219 /* No action required */
2221 case YAFFS_OBJECT_TYPE_UNKNOWN:
2222 /* todo this should not happen */
2230 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
2232 yaffs_ObjectType type)
2234 yaffs_Object *theObject = NULL;
2237 theObject = yaffs_FindObjectByNumber(dev, number);
2240 theObject = yaffs_CreateNewObject(dev, number, type);
2247 static YCHAR *yaffs_CloneString(const YCHAR *str)
2249 YCHAR *newStr = NULL;
2252 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2254 yaffs_strcpy(newStr, str);
2262 * Mknod (create) a new object.
2263 * equivalentObject only has meaning for a hard link;
2264 * aliasString only has meaning for a sumlink.
2265 * rdev only has meaning for devices (a subset of special objects)
2268 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2269 yaffs_Object *parent,
2274 yaffs_Object *equivalentObject,
2275 const YCHAR *aliasString, __u32 rdev)
2280 yaffs_Device *dev = parent->myDev;
2282 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2283 if (yaffs_FindObjectByName(parent, name))
2286 in = yaffs_CreateNewObject(dev, -1, type);
2291 if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2292 str = yaffs_CloneString(aliasString);
2294 yaffs_FreeObject(in);
2304 in->variantType = type;
2306 in->yst_mode = mode;
2308 #ifdef CONFIG_YAFFS_WINCE
2309 yfsd_WinFileTimeNow(in->win_atime);
2310 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2311 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2314 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2316 in->yst_rdev = rdev;
2320 in->nDataChunks = 0;
2322 yaffs_SetObjectName(in, name);
2325 yaffs_AddObjectToDirectory(parent, in);
2327 in->myDev = parent->myDev;
2330 case YAFFS_OBJECT_TYPE_SYMLINK:
2331 in->variant.symLinkVariant.alias = str;
2333 case YAFFS_OBJECT_TYPE_HARDLINK:
2334 in->variant.hardLinkVariant.equivalentObject =
2336 in->variant.hardLinkVariant.equivalentObjectId =
2337 equivalentObject->objectId;
2338 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2340 case YAFFS_OBJECT_TYPE_FILE:
2341 case YAFFS_OBJECT_TYPE_DIRECTORY:
2342 case YAFFS_OBJECT_TYPE_SPECIAL:
2343 case YAFFS_OBJECT_TYPE_UNKNOWN:
2348 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2349 /* Could not create the object header, fail the creation */
2350 yaffs_DeleteObject(in);
2354 yaffs_UpdateParent(parent);
2360 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
2361 __u32 mode, __u32 uid, __u32 gid)
2363 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2364 uid, gid, NULL, NULL, 0);
2367 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
2368 __u32 mode, __u32 uid, __u32 gid)
2370 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2371 mode, uid, gid, NULL, NULL, 0);
2374 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
2375 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2377 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2378 uid, gid, NULL, NULL, rdev);
2381 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
2382 __u32 mode, __u32 uid, __u32 gid,
2385 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2386 uid, gid, NULL, alias, 0);
2389 /* yaffs_Link returns the object id of the equivalent object.*/
2390 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
2391 yaffs_Object *equivalentObject)
2393 /* Get the real object in case we were fed a hard link as an equivalent object */
2394 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2396 if (yaffs_MknodObject
2397 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2398 equivalentObject, NULL, 0)) {
2399 return equivalentObject;
2406 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
2407 const YCHAR *newName, int force, int shadows)
2412 yaffs_Object *existingTarget;
2415 newDir = obj->parent; /* use the old directory */
2417 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2418 T(YAFFS_TRACE_ALWAYS,
2420 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2425 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2426 if (obj->myDev->isYaffs2)
2427 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2429 unlinkOp = (newDir == obj->myDev->unlinkedDir
2430 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2432 deleteOp = (newDir == obj->myDev->deletedDir);
2434 existingTarget = yaffs_FindObjectByName(newDir, newName);
2436 /* If the object is a file going into the unlinked directory,
2437 * then it is OK to just stuff it in since duplicate names are allowed.
2438 * else only proceed if the new name does not exist and if we're putting
2439 * it into a directory.
2446 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2447 yaffs_SetObjectName(obj, newName);
2450 yaffs_AddObjectToDirectory(newDir, obj);
2455 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2456 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows) >= 0)
2463 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
2464 yaffs_Object *newDir, const YCHAR *newName)
2466 yaffs_Object *obj = NULL;
2467 yaffs_Object *existingTarget = NULL;
2473 if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2475 if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2478 dev = oldDir->myDev;
2480 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2481 /* Special case for case insemsitive systems (eg. WinCE).
2482 * While look-up is case insensitive, the name isn't.
2483 * Therefore we might want to change x.txt to X.txt
2485 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
2489 if(yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2493 obj = yaffs_FindObjectByName(oldDir, oldName);
2495 if (obj && obj->renameAllowed) {
2497 /* Now do the handling for an existing target, if there is one */
2499 existingTarget = yaffs_FindObjectByName(newDir, newName);
2500 if (existingTarget &&
2501 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2502 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2503 /* There is a target that is a non-empty directory, so we fail */
2504 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2505 } else if (existingTarget && existingTarget != obj) {
2506 /* Nuke the target first, using shadowing,
2507 * but only if it isn't the same object.
2509 * Note we must disable gc otherwise it can mess up the shadowing.
2513 yaffs_ChangeObjectName(obj, newDir, newName, force,
2514 existingTarget->objectId);
2515 existingTarget->isShadowed = 1;
2516 yaffs_UnlinkObject(existingTarget);
2520 result = yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2522 yaffs_UpdateParent(oldDir);
2523 if(newDir != oldDir)
2524 yaffs_UpdateParent(newDir);
2531 /*------------------------- Block Management and Page Allocation ----------------*/
2533 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
2535 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2537 dev->blockInfo = NULL;
2538 dev->chunkBits = NULL;
2540 dev->allocationBlock = -1; /* force it to get a new one */
2542 /* If the first allocation strategy fails, thry the alternate one */
2543 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2544 if (!dev->blockInfo) {
2545 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2546 dev->blockInfoAlt = 1;
2548 dev->blockInfoAlt = 0;
2550 if (dev->blockInfo) {
2551 /* Set up dynamic blockinfo stuff. */
2552 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2553 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2554 if (!dev->chunkBits) {
2555 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2556 dev->chunkBitsAlt = 1;
2558 dev->chunkBitsAlt = 0;
2561 if (dev->blockInfo && dev->chunkBits) {
2562 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2563 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2570 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2572 if (dev->blockInfoAlt && dev->blockInfo)
2573 YFREE_ALT(dev->blockInfo);
2574 else if (dev->blockInfo)
2575 YFREE(dev->blockInfo);
2577 dev->blockInfoAlt = 0;
2579 dev->blockInfo = NULL;
2581 if (dev->chunkBitsAlt && dev->chunkBits)
2582 YFREE_ALT(dev->chunkBits);
2583 else if (dev->chunkBits)
2584 YFREE(dev->chunkBits);
2585 dev->chunkBitsAlt = 0;
2586 dev->chunkBits = NULL;
2589 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
2590 yaffs_BlockInfo *bi)
2597 return 1; /* disqualification only applies to yaffs2. */
2599 if (!bi->hasShrinkHeader)
2600 return 1; /* can gc */
2602 /* Find the oldest dirty sequence number if we don't know it and save it
2603 * so we don't have to keep recomputing it.
2605 if (!dev->oldestDirtySequence) {
2606 seq = dev->sequenceNumber;
2608 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2610 b = yaffs_GetBlockInfo(dev, i);
2611 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2612 (b->pagesInUse - b->softDeletions) <
2613 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2614 seq = b->sequenceNumber;
2617 dev->oldestDirtySequence = seq;
2620 /* Can't do gc of this block if there are any blocks older than this one that have
2623 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2626 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2627 * for garbage collection.
2630 static int yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
2633 int b = dev->currentDirtyChecker;
2639 int prioritised = 0;
2640 yaffs_BlockInfo *bi;
2641 int pendingPrioritisedExist = 0;
2643 /* First let's see if we need to grab a prioritised block */
2644 if (dev->hasPendingPrioritisedGCs) {
2645 for (i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++) {
2647 bi = yaffs_GetBlockInfo(dev, i);
2648 /* yaffs_VerifyBlock(dev,bi,i); */
2650 if (bi->gcPrioritise) {
2651 pendingPrioritisedExist = 1;
2652 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2653 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2654 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2657 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2662 if (!pendingPrioritisedExist) /* None found, so we can clear this */
2663 dev->hasPendingPrioritisedGCs = 0;
2666 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2668 * else (we're doing a leasurely gc), then we only bother to do this if the
2669 * block has only a few pages in use.
2672 dev->nonAggressiveSkip--;
2674 if (!aggressive && (dev->nonAggressiveSkip > 0))
2679 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2683 dev->internalEndBlock - dev->internalStartBlock + 1;
2686 dev->internalEndBlock - dev->internalStartBlock + 1;
2687 iterations = iterations / 16;
2688 if (iterations > 200)
2692 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2694 if (b < dev->internalStartBlock || b > dev->internalEndBlock)
2695 b = dev->internalStartBlock;
2697 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2698 T(YAFFS_TRACE_ERROR,
2699 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2703 bi = yaffs_GetBlockInfo(dev, b);
2705 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2706 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2707 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2709 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2713 dev->currentDirtyChecker = b;
2717 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2718 dev->nChunksPerBlock - pagesInUse, prioritised));
2721 dev->oldestDirtySequence = 0;
2724 dev->nonAggressiveSkip = 4;
2729 static void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
2731 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2735 /* If the block is still healthy erase it and mark as clean.
2736 * If the block has had a data failure, then retire it.
2739 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2740 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2741 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2743 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2745 if (!bi->needsRetiring) {
2746 yaffs_InvalidateCheckpoint(dev);
2747 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2749 dev->nErasureFailures++;
2750 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2751 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2756 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2758 for (i = 0; i < dev->nChunksPerBlock; i++) {
2759 if (!yaffs_CheckChunkErased
2760 (dev, blockNo * dev->nChunksPerBlock + i)) {
2761 T(YAFFS_TRACE_ERROR,
2763 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2764 TENDSTR), blockNo, i));
2770 /* Clean it up... */
2771 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2772 dev->nErasedBlocks++;
2774 bi->softDeletions = 0;
2775 bi->hasShrinkHeader = 0;
2776 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2777 bi->gcPrioritise = 0;
2778 yaffs_ClearChunkBits(dev, blockNo);
2780 T(YAFFS_TRACE_ERASE,
2781 (TSTR("Erased block %d" TENDSTR), blockNo));
2783 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2785 yaffs_RetireBlock(dev, blockNo);
2786 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2787 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2791 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2795 yaffs_BlockInfo *bi;
2797 if (dev->nErasedBlocks < 1) {
2798 /* Hoosterman we've got a problem.
2799 * Can't get space to gc
2801 T(YAFFS_TRACE_ERROR,
2802 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2807 /* Find an empty block. */
2809 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2810 dev->allocationBlockFinder++;
2811 if (dev->allocationBlockFinder < dev->internalStartBlock
2812 || dev->allocationBlockFinder > dev->internalEndBlock) {
2813 dev->allocationBlockFinder = dev->internalStartBlock;
2816 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2818 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2819 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2820 dev->sequenceNumber++;
2821 bi->sequenceNumber = dev->sequenceNumber;
2822 dev->nErasedBlocks--;
2823 T(YAFFS_TRACE_ALLOCATE,
2824 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2825 dev->allocationBlockFinder, dev->sequenceNumber,
2826 dev->nErasedBlocks));
2827 return dev->allocationBlockFinder;
2831 T(YAFFS_TRACE_ALWAYS,
2833 ("yaffs tragedy: no more erased blocks, but there should have been %d"
2834 TENDSTR), dev->nErasedBlocks));
2841 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2843 if (!dev->nCheckpointBlocksRequired &&
2845 /* Not a valid value so recalculate */
2848 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2851 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2853 if (tnodeSize < sizeof(yaffs_Tnode))
2854 tnodeSize = sizeof(yaffs_Tnode);
2856 nBytes += sizeof(yaffs_CheckpointValidity);
2857 nBytes += sizeof(yaffs_CheckpointDevice);
2858 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2859 nBytes += devBlocks * dev->chunkBitmapStride;
2860 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2861 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2862 nBytes += sizeof(yaffs_CheckpointValidity);
2863 nBytes += sizeof(__u32); /* checksum*/
2865 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2867 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2869 dev->nCheckpointBlocksRequired = nBlocks;
2872 return dev->nCheckpointBlocksRequired;
2876 * Check if there's space to allocate...
2877 * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2879 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev)
2882 int reservedBlocks = dev->nReservedBlocks;
2883 int checkpointBlocks;
2885 if (dev->isYaffs2) {
2886 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
2887 dev->blocksInCheckpoint;
2888 if (checkpointBlocks < 0)
2889 checkpointBlocks = 0;
2891 checkpointBlocks = 0;
2894 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2896 return (dev->nFreeChunks > reservedChunks);
2899 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
2900 yaffs_BlockInfo **blockUsedPtr)
2903 yaffs_BlockInfo *bi;
2905 if (dev->allocationBlock < 0) {
2906 /* Get next block to allocate off */
2907 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2908 dev->allocationPage = 0;
2911 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2912 /* Not enough space to allocate unless we're allowed to use the reserve. */
2916 if (dev->nErasedBlocks < dev->nReservedBlocks
2917 && dev->allocationPage == 0) {
2918 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2921 /* Next page please.... */
2922 if (dev->allocationBlock >= 0) {
2923 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2925 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2926 dev->allocationPage;
2928 yaffs_SetChunkBit(dev, dev->allocationBlock,
2929 dev->allocationPage);
2931 dev->allocationPage++;
2935 /* If the block is full set the state to full */
2936 if (dev->allocationPage >= dev->nChunksPerBlock) {
2937 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2938 dev->allocationBlock = -1;
2947 T(YAFFS_TRACE_ERROR,
2948 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2953 static int yaffs_GetErasedChunks(yaffs_Device *dev)
2957 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2959 if (dev->allocationBlock > 0)
2960 n += (dev->nChunksPerBlock - dev->allocationPage);
2966 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
2972 int retVal = YAFFS_OK;
2975 int isCheckpointBlock;
2979 int chunksBefore = yaffs_GetErasedChunks(dev);
2982 yaffs_ExtendedTags tags;
2984 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2986 yaffs_Object *object;
2988 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2991 T(YAFFS_TRACE_TRACING,
2992 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
2995 bi->hasShrinkHeader,
2998 /*yaffs_VerifyFreeChunks(dev); */
3000 if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
3001 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3003 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
3005 /* Take off the number of soft deleted entries because
3006 * they're going to get really deleted during GC.
3008 if(dev->gcChunk == 0) /* first time through for this block */
3009 dev->nFreeChunks -= bi->softDeletions;
3013 if (isCheckpointBlock ||
3014 !yaffs_StillSomeChunkBits(dev, block)) {
3015 T(YAFFS_TRACE_TRACING,
3017 ("Collecting block %d that has no chunks in use" TENDSTR),
3019 yaffs_BlockBecameDirty(dev, block);
3022 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3024 yaffs_VerifyBlock(dev, bi, block);
3026 maxCopies = (wholeBlock) ? dev->nChunksPerBlock : 10;
3027 oldChunk = block * dev->nChunksPerBlock + dev->gcChunk;
3029 for (/* init already done */;
3030 retVal == YAFFS_OK &&
3031 dev->gcChunk < dev->nChunksPerBlock &&
3032 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
3034 dev->gcChunk++, oldChunk++) {
3035 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3037 /* This page is in use and might need to be copied off */
3043 yaffs_InitialiseTags(&tags);
3045 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3049 yaffs_FindObjectByNumber(dev,
3052 T(YAFFS_TRACE_GC_DETAIL,
3054 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3055 dev->gcChunk, tags.objectId, tags.chunkId,
3058 if (object && !yaffs_SkipVerification(dev)) {
3059 if (tags.chunkId == 0)
3060 matchingChunk = object->hdrChunk;
3061 else if (object->softDeleted)
3062 matchingChunk = oldChunk; /* Defeat the test */
3064 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
3066 if (oldChunk != matchingChunk)
3067 T(YAFFS_TRACE_ERROR,
3068 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3069 oldChunk, matchingChunk, tags.objectId, tags.chunkId));
3074 T(YAFFS_TRACE_ERROR,
3076 ("page %d in gc has no object: %d %d %d "
3078 tags.objectId, tags.chunkId, tags.byteCount));
3083 object->softDeleted &&
3084 tags.chunkId != 0) {
3085 /* Data chunk in a soft deleted file, throw it away
3086 * It's a soft deleted data chunk,
3087 * No need to copy this, just forget about it and
3088 * fix up the object.
3091 object->nDataChunks--;
3093 if (object->nDataChunks <= 0) {
3094 /* remeber to clean up the object */
3095 dev->gcCleanupList[cleanups] =
3101 /* Todo object && object->deleted && object->nDataChunks == 0 */
3102 /* Deleted object header with no data chunks.
3103 * Can be discarded and the file deleted.
3105 object->hdrChunk = 0;
3106 yaffs_FreeTnode(object->myDev,
3109 object->variant.fileVariant.top = NULL;
3110 yaffs_DoGenericObjectDeletion(object);
3112 } else if (object) {
3113 /* It's either a data chunk in a live file or
3114 * an ObjectHeader, so we're interested in it.
3115 * NB Need to keep the ObjectHeaders of deleted files
3116 * until the whole file has been deleted off
3118 tags.serialNumber++;
3122 if (tags.chunkId == 0) {
3123 /* It is an object Id,
3124 * We need to nuke the shrinkheader flags first
3125 * We no longer want the shrinkHeader flag since its work is done
3126 * and if it is left in place it will mess up scanning.
3129 yaffs_ObjectHeader *oh;
3130 oh = (yaffs_ObjectHeader *)buffer;
3132 tags.extraIsShrinkHeader = 0;
3134 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
3138 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3141 retVal = YAFFS_FAIL;
3144 /* Ok, now fix up the Tnodes etc. */
3146 if (tags.chunkId == 0) {
3148 object->hdrChunk = newChunk;
3149 object->serial = tags.serialNumber;
3151 /* It's a data chunk */
3152 yaffs_PutChunkIntoFile
3160 if (retVal == YAFFS_OK)
3161 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3166 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3169 /* Do any required cleanups */
3170 for (i = 0; i < cleanups; i++) {
3171 /* Time to delete the file too */
3173 yaffs_FindObjectByNumber(dev,
3174 dev->gcCleanupList[i]);
3176 yaffs_FreeTnode(dev,
3177 object->variant.fileVariant.
3179 object->variant.fileVariant.top = NULL;
3182 ("yaffs: About to finally delete object %d"
3183 TENDSTR), object->objectId));
3184 yaffs_DoGenericObjectDeletion(object);
3185 object->myDev->nDeletedFiles--;
3192 yaffs_VerifyCollectedBlock(dev, bi, block);
3194 chunksAfter = yaffs_GetErasedChunks(dev);
3195 if (chunksBefore >= chunksAfter) {
3198 ("gc did not increase free chunks before %d after %d"
3199 TENDSTR), chunksBefore, chunksAfter));
3202 /* If the gc completed then clear the current gcBlock so that we find another. */
3203 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING) {
3213 /* New garbage collector
3214 * If we're very low on erased blocks then we do aggressive garbage collection
3215 * otherwise we do "leasurely" garbage collection.
3216 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3217 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3219 * The idea is to help clear out space in a more spread-out manner.
3220 * Dunno if it really does anything useful.
3222 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
3226 int gcOk = YAFFS_OK;
3229 int checkpointBlockAdjust;
3231 if (dev->isDoingGC) {
3232 /* Bail out so we don't get recursive gc */
3236 /* This loop should pass the first time.
3237 * We'll only see looping here if the erase of the collected block fails.
3243 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3244 if (checkpointBlockAdjust < 0)
3245 checkpointBlockAdjust = 0;
3247 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3248 /* We need a block soon...*/
3251 /* We're in no hurry */
3255 if (dev->gcBlock <= 0) {
3256 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3260 block = dev->gcBlock;
3263 dev->garbageCollections++;
3265 dev->passiveGarbageCollections++;
3269 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3270 dev->nErasedBlocks, aggressive));
3272 gcOk = yaffs_GarbageCollectBlock(dev, block, aggressive);
3275 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3278 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3279 TENDSTR), dev->nErasedBlocks, maxTries, block));
3281 } while ((dev->nErasedBlocks < dev->nReservedBlocks) &&
3285 return aggressive ? gcOk : YAFFS_OK;
3288 /*------------------------- TAGS --------------------------------*/
3290 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
3293 return (tags->chunkId == chunkInObject &&
3294 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3299 /*-------------------- Data file manipulation -----------------*/
3301 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
3302 yaffs_ExtendedTags *tags)
3304 /*Get the Tnode, then get the level 0 offset chunk offset */
3307 yaffs_ExtendedTags localTags;
3310 yaffs_Device *dev = in->myDev;
3313 /* Passed a NULL, so use our own tags space */
3317 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3320 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3323 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3329 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
3330 yaffs_ExtendedTags *tags)
3332 /* Get the Tnode, then get the level 0 offset chunk offset */
3335 yaffs_ExtendedTags localTags;
3337 yaffs_Device *dev = in->myDev;
3341 /* Passed a NULL, so use our own tags space */
3345 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3349 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3352 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3355 /* Delete the entry in the filestructure (if found) */
3357 yaffs_PutLevel0Tnode(dev, tn, chunkInInode, 0);
3363 #ifdef YAFFS_PARANOID
3365 static int yaffs_CheckFileSanity(yaffs_Object *in)
3373 yaffs_Tags localTags;
3374 yaffs_Tags *tags = &localTags;
3378 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3381 objId = in->objectId;
3382 fSize = in->variant.fileVariant.fileSize;
3384 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3386 for (chunk = 1; chunk <= nChunks; chunk++) {
3387 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3392 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunk);
3394 if (yaffs_CheckChunkBits
3395 (dev, theChunk / dev->nChunksPerBlock,
3396 theChunk % dev->nChunksPerBlock)) {
3398 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3402 (tags, in->objectId, chunk, chunkDeleted)) {
3412 /* T(("No level 0 found for %d\n", chunk)); */
3416 return failed ? YAFFS_FAIL : YAFFS_OK;
3421 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
3422 int chunkInNAND, int inScan)
3424 /* NB inScan is zero unless scanning.
3425 * For forward scanning, inScan is > 0;
3426 * for backward scanning inScan is < 0
3430 yaffs_Device *dev = in->myDev;
3432 yaffs_ExtendedTags existingTags;
3433 yaffs_ExtendedTags newTags;
3434 unsigned existingSerial, newSerial;
3436 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3437 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3438 * If it is not during Scanning then something went wrong!
3441 T(YAFFS_TRACE_ERROR,
3443 ("yaffs tragedy:attempt to put data chunk into a non-file"
3448 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3452 tn = yaffs_AddOrFindLevel0Tnode(dev,
3453 &in->variant.fileVariant,
3459 existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3462 /* If we're scanning then we need to test for duplicates
3463 * NB This does not need to be efficient since it should only ever
3464 * happen when the power fails during a write, then only one
3465 * chunk should ever be affected.
3467 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3468 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3471 if (existingChunk > 0) {
3472 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3473 * thus we have to do a FindChunkInFile to get the real chunk id.
3475 * We have a duplicate now we need to decide which one to use:
3477 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3478 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3479 * YAFFS1: Get both sets of tags and compare serial numbers.
3483 /* Only do this for forward scanning */
3484 yaffs_ReadChunkWithTagsFromNAND(dev,
3488 /* Do a proper find */
3490 yaffs_FindChunkInFile(in, chunkInInode,
3494 if (existingChunk <= 0) {
3495 /*Hoosterman - how did this happen? */
3497 T(YAFFS_TRACE_ERROR,
3499 ("yaffs tragedy: existing chunk < 0 in scan"
3504 /* NB The deleted flags should be false, otherwise the chunks will
3505 * not be loaded during a scan
3509 newSerial = newTags.serialNumber;
3510 existingSerial = existingTags.serialNumber;
3514 (in->myDev->isYaffs2 ||
3515 existingChunk <= 0 ||
3516 ((existingSerial + 1) & 3) == newSerial)) {
3517 /* Forward scanning.
3519 * Delete the old one and drop through to update the tnode
3521 yaffs_DeleteChunk(dev, existingChunk, 1,
3524 /* Backward scanning or we want to use the existing one
3526 * Delete the new one and return early so that the tnode isn't changed
3528 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3536 if (existingChunk == 0)
3539 yaffs_PutLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
3544 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
3547 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3549 if (chunkInNAND >= 0)
3550 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3553 T(YAFFS_TRACE_NANDACCESS,
3554 (TSTR("Chunk %d not found zero instead" TENDSTR),
3556 /* get sane (zero) data if you read a hole */
3557 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3563 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
3567 yaffs_ExtendedTags tags;
3568 yaffs_BlockInfo *bi;
3574 block = chunkId / dev->nChunksPerBlock;
3575 page = chunkId % dev->nChunksPerBlock;
3578 if (!yaffs_CheckChunkBit(dev, block, page))
3579 T(YAFFS_TRACE_VERIFY,
3580 (TSTR("Deleting invalid chunk %d"TENDSTR),
3583 bi = yaffs_GetBlockInfo(dev, block);
3585 T(YAFFS_TRACE_DELETION,
3586 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3589 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3591 yaffs_InitialiseTags(&tags);
3593 tags.chunkDeleted = 1;
3595 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3596 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3598 dev->nUnmarkedDeletions++;
3601 /* Pull out of the management area.
3602 * If the whole block became dirty, this will kick off an erasure.
3604 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3605 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3606 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3607 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3610 yaffs_ClearChunkBit(dev, block, page);
3614 if (bi->pagesInUse == 0 &&
3615 !bi->hasShrinkHeader &&
3616 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3617 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3618 yaffs_BlockBecameDirty(dev, block);
3625 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
3626 const __u8 *buffer, int nBytes,
3629 /* Find old chunk Need to do this to get serial number
3630 * Write new one and patch into tree.
3631 * Invalidate old tags.
3635 yaffs_ExtendedTags prevTags;
3638 yaffs_ExtendedTags newTags;
3640 yaffs_Device *dev = in->myDev;
3642 yaffs_CheckGarbageCollection(dev);
3644 /* Get the previous chunk at this location in the file if it exists */
3645 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3647 /* Set up new tags */
3648 yaffs_InitialiseTags(&newTags);
3650 newTags.chunkId = chunkInInode;
3651 newTags.objectId = in->objectId;
3652 newTags.serialNumber =
3653 (prevChunkId > 0) ? prevTags.serialNumber + 1 : 1;
3654 newTags.byteCount = nBytes;
3656 if (nBytes < 1 || nBytes > dev->totalBytesPerChunk) {
3657 T(YAFFS_TRACE_ERROR,
3658 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3663 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3666 if (newChunkId >= 0) {
3667 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3669 if (prevChunkId > 0)
3670 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3672 yaffs_CheckFileSanity(in);
3678 /* UpdateObjectHeader updates the header on NAND for an object.
3679 * If name is not NULL, then that new name is used.
3681 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
3682 int isShrink, int shadows)
3685 yaffs_BlockInfo *bi;
3687 yaffs_Device *dev = in->myDev;
3694 yaffs_ExtendedTags newTags;
3695 yaffs_ExtendedTags oldTags;
3697 __u8 *buffer = NULL;
3698 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3700 yaffs_ObjectHeader *oh = NULL;
3702 yaffs_strcpy(oldName, _Y("silly old name"));
3706 in == dev->rootDir || /* The rootDir should also be saved */
3709 yaffs_CheckGarbageCollection(dev);
3710 yaffs_CheckObjectDetailsLoaded(in);
3712 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3713 oh = (yaffs_ObjectHeader *) buffer;
3715 prevChunkId = in->hdrChunk;
3717 if (prevChunkId > 0) {
3718 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3721 yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
3723 memcpy(oldName, oh->name, sizeof(oh->name));
3726 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3728 oh->type = in->variantType;
3729 oh->yst_mode = in->yst_mode;
3730 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3732 #ifdef CONFIG_YAFFS_WINCE
3733 oh->win_atime[0] = in->win_atime[0];
3734 oh->win_ctime[0] = in->win_ctime[0];
3735 oh->win_mtime[0] = in->win_mtime[0];
3736 oh->win_atime[1] = in->win_atime[1];
3737 oh->win_ctime[1] = in->win_ctime[1];
3738 oh->win_mtime[1] = in->win_mtime[1];
3740 oh->yst_uid = in->yst_uid;
3741 oh->yst_gid = in->yst_gid;
3742 oh->yst_atime = in->yst_atime;
3743 oh->yst_mtime = in->yst_mtime;
3744 oh->yst_ctime = in->yst_ctime;
3745 oh->yst_rdev = in->yst_rdev;
3748 oh->parentObjectId = in->parent->objectId;
3750 oh->parentObjectId = 0;
3752 if (name && *name) {
3753 memset(oh->name, 0, sizeof(oh->name));
3754 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3755 } else if (prevChunkId > 0)
3756 memcpy(oh->name, oldName, sizeof(oh->name));
3758 memset(oh->name, 0, sizeof(oh->name));
3760 oh->isShrink = isShrink;
3762 switch (in->variantType) {
3763 case YAFFS_OBJECT_TYPE_UNKNOWN:
3764 /* Should not happen */
3766 case YAFFS_OBJECT_TYPE_FILE:
3768 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3769 || oh->parentObjectId ==
3770 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3771 fileVariant.fileSize;
3773 case YAFFS_OBJECT_TYPE_HARDLINK:
3774 oh->equivalentObjectId =
3775 in->variant.hardLinkVariant.equivalentObjectId;
3777 case YAFFS_OBJECT_TYPE_SPECIAL:
3780 case YAFFS_OBJECT_TYPE_DIRECTORY:
3783 case YAFFS_OBJECT_TYPE_SYMLINK:
3784 yaffs_strncpy(oh->alias,
3785 in->variant.symLinkVariant.alias,
3786 YAFFS_MAX_ALIAS_LENGTH);
3787 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3792 yaffs_InitialiseTags(&newTags);
3794 newTags.chunkId = 0;
3795 newTags.objectId = in->objectId;
3796 newTags.serialNumber = in->serial;
3798 /* Add extra info for file header */
3800 newTags.extraHeaderInfoAvailable = 1;
3801 newTags.extraParentObjectId = oh->parentObjectId;
3802 newTags.extraFileLength = oh->fileSize;
3803 newTags.extraIsShrinkHeader = oh->isShrink;
3804 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3805 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3806 newTags.extraObjectType = in->variantType;
3808 yaffs_VerifyObjectHeader(in, oh, &newTags, 1);
3810 /* Create new chunk in NAND */
3812 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3813 (prevChunkId > 0) ? 1 : 0);
3815 if (newChunkId >= 0) {
3817 in->hdrChunk = newChunkId;
3819 if (prevChunkId > 0) {
3820 yaffs_DeleteChunk(dev, prevChunkId, 1,
3824 if (!yaffs_ObjectHasCachedWriteData(in))
3827 /* If this was a shrink, then mark the block that the chunk lives on */
3829 bi = yaffs_GetBlockInfo(in->myDev,
3830 newChunkId / in->myDev->nChunksPerBlock);
3831 bi->hasShrinkHeader = 1;
3836 retVal = newChunkId;
3841 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3846 /*------------------------ Short Operations Cache ----------------------------------------
3847 * In many situations where there is no high level buffering (eg WinCE) a lot of
3848 * reads might be short sequential reads, and a lot of writes may be short
3849 * sequential writes. eg. scanning/writing a jpeg file.
3850 * In these cases, a short read/write cache can provide a huge perfomance benefit
3851 * with dumb-as-a-rock code.
3852 * In Linux, the page cache provides read buffering aand the short op cache provides write
3855 * There are a limited number (~10) of cache chunks per device so that we don't
3856 * need a very intelligent search.
3859 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3861 yaffs_Device *dev = obj->myDev;
3863 yaffs_ChunkCache *cache;
3864 int nCaches = obj->myDev->nShortOpCaches;
3866 for (i = 0; i < nCaches; i++) {
3867 cache = &dev->srCache[i];
3868 if (cache->object == obj &&
3877 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
3879 yaffs_Device *dev = obj->myDev;
3880 int lowest = -99; /* Stop compiler whining. */
3882 yaffs_ChunkCache *cache;
3883 int chunkWritten = 0;
3884 int nCaches = obj->myDev->nShortOpCaches;
3890 /* Find the dirty cache for this object with the lowest chunk id. */
3891 for (i = 0; i < nCaches; i++) {
3892 if (dev->srCache[i].object == obj &&
3893 dev->srCache[i].dirty) {
3895 || dev->srCache[i].chunkId <
3897 cache = &dev->srCache[i];
3898 lowest = cache->chunkId;
3903 if (cache && !cache->locked) {
3904 /* Write it out and free it up */
3907 yaffs_WriteChunkDataToObject(cache->object,
3913 cache->object = NULL;
3916 } while (cache && chunkWritten > 0);
3919 /* Hoosterman, disk full while writing cache out. */
3920 T(YAFFS_TRACE_ERROR,
3921 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3928 /*yaffs_FlushEntireDeviceCache(dev)
3933 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3936 int nCaches = dev->nShortOpCaches;
3939 /* Find a dirty object in the cache and flush it...
3940 * until there are no further dirty objects.
3944 for (i = 0; i < nCaches && !obj; i++) {
3945 if (dev->srCache[i].object &&
3946 dev->srCache[i].dirty)
3947 obj = dev->srCache[i].object;
3951 yaffs_FlushFilesChunkCache(obj);
3958 /* Grab us a cache chunk for use.
3959 * First look for an empty one.
3960 * Then look for the least recently used non-dirty one.
3961 * Then look for the least recently used dirty one...., flush and look again.
3963 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
3967 if (dev->nShortOpCaches > 0) {
3968 for (i = 0; i < dev->nShortOpCaches; i++) {
3969 if (!dev->srCache[i].object)
3970 return &dev->srCache[i];
3977 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
3979 yaffs_ChunkCache *cache;
3980 yaffs_Object *theObj;
3985 if (dev->nShortOpCaches > 0) {
3986 /* Try find a non-dirty one... */
3988 cache = yaffs_GrabChunkCacheWorker(dev);
3991 /* They were all dirty, find the last recently used object and flush
3992 * its cache, then find again.
3993 * NB what's here is not very accurate, we actually flush the object
3994 * the last recently used page.
3997 /* With locking we can't assume we can use entry zero */
4004 for (i = 0; i < dev->nShortOpCaches; i++) {
4005 if (dev->srCache[i].object &&
4006 !dev->srCache[i].locked &&
4007 (dev->srCache[i].lastUse < usage || !cache)) {
4008 usage = dev->srCache[i].lastUse;
4009 theObj = dev->srCache[i].object;
4010 cache = &dev->srCache[i];
4015 if (!cache || cache->dirty) {
4016 /* Flush and try again */
4017 yaffs_FlushFilesChunkCache(theObj);
4018 cache = yaffs_GrabChunkCacheWorker(dev);
4028 /* Find a cached chunk */
4029 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj,
4032 yaffs_Device *dev = obj->myDev;
4034 if (dev->nShortOpCaches > 0) {
4035 for (i = 0; i < dev->nShortOpCaches; i++) {
4036 if (dev->srCache[i].object == obj &&
4037 dev->srCache[i].chunkId == chunkId) {
4040 return &dev->srCache[i];
4047 /* Mark the chunk for the least recently used algorithym */
4048 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache,
4052 if (dev->nShortOpCaches > 0) {
4053 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4054 /* Reset the cache usages */
4056 for (i = 1; i < dev->nShortOpCaches; i++)
4057 dev->srCache[i].lastUse = 0;
4064 cache->lastUse = dev->srLastUse;
4071 /* Invalidate a single cache page.
4072 * Do this when a whole page gets written,
4073 * ie the short cache for this page is no longer valid.
4075 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
4077 if (object->myDev->nShortOpCaches > 0) {
4078 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4081 cache->object = NULL;
4085 /* Invalidate all the cache pages associated with this object
4086 * Do this whenever ther file is deleted or resized.
4088 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
4091 yaffs_Device *dev = in->myDev;
4093 if (dev->nShortOpCaches > 0) {
4094 /* Invalidate it. */
4095 for (i = 0; i < dev->nShortOpCaches; i++) {
4096 if (dev->srCache[i].object == in)
4097 dev->srCache[i].object = NULL;
4102 /*--------------------- Checkpointing --------------------*/
4105 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev, int head)
4107 yaffs_CheckpointValidity cp;
4109 memset(&cp, 0, sizeof(cp));
4111 cp.structType = sizeof(cp);
4112 cp.magic = YAFFS_MAGIC;
4113 cp.version = YAFFS_CHECKPOINT_VERSION;
4114 cp.head = (head) ? 1 : 0;
4116 return (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp)) ?
4120 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4122 yaffs_CheckpointValidity cp;
4125 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4128 ok = (cp.structType == sizeof(cp)) &&
4129 (cp.magic == YAFFS_MAGIC) &&
4130 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4131 (cp.head == ((head) ? 1 : 0));
4135 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4138 cp->nErasedBlocks = dev->nErasedBlocks;
4139 cp->allocationBlock = dev->allocationBlock;
4140 cp->allocationPage = dev->allocationPage;
4141 cp->nFreeChunks = dev->nFreeChunks;
4143 cp->nDeletedFiles = dev->nDeletedFiles;
4144 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4145 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4146 cp->sequenceNumber = dev->sequenceNumber;
4147 cp->oldestDirtySequence = dev->oldestDirtySequence;
4151 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4152 yaffs_CheckpointDevice *cp)
4154 dev->nErasedBlocks = cp->nErasedBlocks;
4155 dev->allocationBlock = cp->allocationBlock;
4156 dev->allocationPage = cp->allocationPage;
4157 dev->nFreeChunks = cp->nFreeChunks;
4159 dev->nDeletedFiles = cp->nDeletedFiles;
4160 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4161 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4162 dev->sequenceNumber = cp->sequenceNumber;
4163 dev->oldestDirtySequence = cp->oldestDirtySequence;
4167 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4169 yaffs_CheckpointDevice cp;
4171 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4175 /* Write device runtime values*/
4176 yaffs_DeviceToCheckpointDevice(&cp, dev);
4177 cp.structType = sizeof(cp);
4179 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4181 /* Write block info */
4183 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4184 ok = (yaffs_CheckpointWrite(dev, dev->blockInfo, nBytes) == nBytes);
4187 /* Write chunk bits */
4189 nBytes = nBlocks * dev->chunkBitmapStride;
4190 ok = (yaffs_CheckpointWrite(dev, dev->chunkBits, nBytes) == nBytes);
4196 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4198 yaffs_CheckpointDevice cp;
4200 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4204 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4208 if (cp.structType != sizeof(cp))
4212 yaffs_CheckpointDeviceToDevice(dev, &cp);
4214 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4216 ok = (yaffs_CheckpointRead(dev, dev->blockInfo, nBytes) == nBytes);
4220 nBytes = nBlocks * dev->chunkBitmapStride;
4222 ok = (yaffs_CheckpointRead(dev, dev->chunkBits, nBytes) == nBytes);
4227 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4231 cp->objectId = obj->objectId;
4232 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4233 cp->hdrChunk = obj->hdrChunk;
4234 cp->variantType = obj->variantType;
4235 cp->deleted = obj->deleted;
4236 cp->softDeleted = obj->softDeleted;
4237 cp->unlinked = obj->unlinked;
4238 cp->fake = obj->fake;
4239 cp->renameAllowed = obj->renameAllowed;
4240 cp->unlinkAllowed = obj->unlinkAllowed;
4241 cp->serial = obj->serial;
4242 cp->nDataChunks = obj->nDataChunks;
4244 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4245 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4246 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4247 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4250 static int yaffs_CheckpointObjectToObject(yaffs_Object *obj, yaffs_CheckpointObject *cp)
4253 yaffs_Object *parent;
4255 if (obj->variantType != cp->variantType) {
4256 T(YAFFS_TRACE_ERROR, (TSTR("Checkpoint read object %d type %d "
4257 TCONT("chunk %d does not match existing object type %d")
4258 TENDSTR), cp->objectId, cp->variantType, cp->hdrChunk,
4263 obj->objectId = cp->objectId;
4266 parent = yaffs_FindOrCreateObjectByNumber(
4269 YAFFS_OBJECT_TYPE_DIRECTORY);
4274 if (parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4275 T(YAFFS_TRACE_ALWAYS, (TSTR("Checkpoint read object %d parent %d type %d"
4276 TCONT(" chunk %d Parent type, %d, not directory")
4278 cp->objectId, cp->parentId, cp->variantType,
4279 cp->hdrChunk, parent->variantType));
4282 yaffs_AddObjectToDirectory(parent, obj);
4285 obj->hdrChunk = cp->hdrChunk;
4286 obj->variantType = cp->variantType;
4287 obj->deleted = cp->deleted;
4288 obj->softDeleted = cp->softDeleted;
4289 obj->unlinked = cp->unlinked;
4290 obj->fake = cp->fake;
4291 obj->renameAllowed = cp->renameAllowed;
4292 obj->unlinkAllowed = cp->unlinkAllowed;
4293 obj->serial = cp->serial;
4294 obj->nDataChunks = cp->nDataChunks;
4296 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4297 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4298 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4299 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4301 if (obj->hdrChunk > 0)
4302 obj->lazyLoaded = 1;
4308 static int yaffs_CheckpointTnodeWorker(yaffs_Object *in, yaffs_Tnode *tn,
4309 __u32 level, int chunkOffset)
4312 yaffs_Device *dev = in->myDev;
4314 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4316 if (tnodeSize < sizeof(yaffs_Tnode))
4317 tnodeSize = sizeof(yaffs_Tnode);
4323 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
4324 if (tn->internal[i]) {
4325 ok = yaffs_CheckpointTnodeWorker(in,
4328 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4331 } else if (level == 0) {
4332 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4333 ok = (yaffs_CheckpointWrite(dev, &baseOffset, sizeof(baseOffset)) == sizeof(baseOffset));
4335 ok = (yaffs_CheckpointWrite(dev, tn, tnodeSize) == tnodeSize);
4343 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4345 __u32 endMarker = ~0;
4348 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4349 ok = yaffs_CheckpointTnodeWorker(obj,
4350 obj->variant.fileVariant.top,
4351 obj->variant.fileVariant.topLevel,
4354 ok = (yaffs_CheckpointWrite(obj->myDev, &endMarker, sizeof(endMarker)) ==
4361 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4365 yaffs_Device *dev = obj->myDev;
4366 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4369 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4371 if (tnodeSize < sizeof(yaffs_Tnode))
4372 tnodeSize = sizeof(yaffs_Tnode);
4374 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4376 while (ok && (~baseChunk)) {
4378 /* Read level 0 tnode */
4381 tn = yaffs_GetTnodeRaw(dev);
4383 ok = (yaffs_CheckpointRead(dev, tn, tnodeSize) == tnodeSize);
4388 ok = yaffs_AddOrFindLevel0Tnode(dev,
4394 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4398 T(YAFFS_TRACE_CHECKPOINT, (
4399 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4400 nread, baseChunk, ok));
4406 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4409 yaffs_CheckpointObject cp;
4412 struct ylist_head *lh;
4415 /* Iterate through the objects in each hash entry,
4416 * dumping them to the checkpointing stream.
4419 for (i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++) {
4420 ylist_for_each(lh, &dev->objectBucket[i].list) {
4422 obj = ylist_entry(lh, yaffs_Object, hashLink);
4423 if (!obj->deferedFree) {
4424 yaffs_ObjectToCheckpointObject(&cp, obj);
4425 cp.structType = sizeof(cp);
4427 T(YAFFS_TRACE_CHECKPOINT, (
4428 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
4429 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk, (unsigned) obj));
4431 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4433 if (ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4434 ok = yaffs_WriteCheckpointTnodes(obj);
4440 /* Dump end of list */
4441 memset(&cp, 0xFF, sizeof(yaffs_CheckpointObject));
4442 cp.structType = sizeof(cp);
4445 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4450 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4453 yaffs_CheckpointObject cp;
4456 yaffs_Object *hardList = NULL;
4458 while (ok && !done) {
4459 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4460 if (cp.structType != sizeof(cp)) {
4461 T(YAFFS_TRACE_CHECKPOINT, (TSTR("struct size %d instead of %d ok %d"TENDSTR),
4462 cp.structType, sizeof(cp), ok));
4466 T(YAFFS_TRACE_CHECKPOINT, (TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4467 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk));
4469 if (ok && cp.objectId == ~0)
4472 obj = yaffs_FindOrCreateObjectByNumber(dev, cp.objectId, cp.variantType);
4474 ok = yaffs_CheckpointObjectToObject(obj, &cp);
4477 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4478 ok = yaffs_ReadCheckpointTnodes(obj);
4479 } else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4480 obj->hardLinks.next =
4481 (struct ylist_head *) hardList;
4490 yaffs_HardlinkFixup(dev, hardList);
4495 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4497 __u32 checkpointSum;
4500 yaffs_GetCheckpointSum(dev, &checkpointSum);
4502 ok = (yaffs_CheckpointWrite(dev, &checkpointSum, sizeof(checkpointSum)) == sizeof(checkpointSum));
4510 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4512 __u32 checkpointSum0;
4513 __u32 checkpointSum1;
4516 yaffs_GetCheckpointSum(dev, &checkpointSum0);
4518 ok = (yaffs_CheckpointRead(dev, &checkpointSum1, sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4523 if (checkpointSum0 != checkpointSum1)
4530 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4534 if (dev->skipCheckpointWrite || !dev->isYaffs2) {
4535 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint write" TENDSTR)));
4540 ok = yaffs_CheckpointOpen(dev, 1);
4543 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4544 ok = yaffs_WriteCheckpointValidityMarker(dev, 1);
4547 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint device" TENDSTR)));
4548 ok = yaffs_WriteCheckpointDevice(dev);
4551 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint objects" TENDSTR)));
4552 ok = yaffs_WriteCheckpointObjects(dev);
4555 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4556 ok = yaffs_WriteCheckpointValidityMarker(dev, 0);
4560 ok = yaffs_WriteCheckpointSum(dev);
4562 if (!yaffs_CheckpointClose(dev))
4566 dev->isCheckpointed = 1;
4568 dev->isCheckpointed = 0;
4570 return dev->isCheckpointed;
4573 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4577 if (dev->skipCheckpointRead || !dev->isYaffs2) {
4578 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint read" TENDSTR)));
4583 ok = yaffs_CheckpointOpen(dev, 0); /* open for read */
4586 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4587 ok = yaffs_ReadCheckpointValidityMarker(dev, 1);
4590 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint device" TENDSTR)));
4591 ok = yaffs_ReadCheckpointDevice(dev);
4594 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint objects" TENDSTR)));
4595 ok = yaffs_ReadCheckpointObjects(dev);
4598 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4599 ok = yaffs_ReadCheckpointValidityMarker(dev, 0);
4603 ok = yaffs_ReadCheckpointSum(dev);
4604 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint checksum %d" TENDSTR), ok));
4607 if (!yaffs_CheckpointClose(dev))
4611 dev->isCheckpointed = 1;
4613 dev->isCheckpointed = 0;
4619 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4621 if (dev->isCheckpointed ||
4622 dev->blocksInCheckpoint > 0) {
4623 dev->isCheckpointed = 0;
4624 yaffs_CheckpointInvalidateStream(dev);
4625 if (dev->superBlock && dev->markSuperBlockDirty)
4626 dev->markSuperBlockDirty(dev->superBlock);
4631 int yaffs_CheckpointSave(yaffs_Device *dev)
4634 T(YAFFS_TRACE_CHECKPOINT, (TSTR("save entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4636 yaffs_VerifyObjects(dev);
4637 yaffs_VerifyBlocks(dev);
4638 yaffs_VerifyFreeChunks(dev);
4640 if (!dev->isCheckpointed) {
4641 yaffs_InvalidateCheckpoint(dev);
4642 yaffs_WriteCheckpointData(dev);
4645 T(YAFFS_TRACE_ALWAYS, (TSTR("save exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4647 return dev->isCheckpointed;
4650 int yaffs_CheckpointRestore(yaffs_Device *dev)
4653 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4655 retval = yaffs_ReadCheckpointData(dev);
4657 if (dev->isCheckpointed) {
4658 yaffs_VerifyObjects(dev);
4659 yaffs_VerifyBlocks(dev);
4660 yaffs_VerifyFreeChunks(dev);
4663 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4668 /*--------------------- File read/write ------------------------
4669 * Read and write have very similar structures.
4670 * In general the read/write has three parts to it
4671 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4672 * Some complete chunks
4673 * An incomplete chunk to end off with
4675 * Curve-balls: the first chunk might also be the last chunk.
4678 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 *buffer, loff_t offset,
4687 yaffs_ChunkCache *cache;
4694 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4695 /* start = offset % dev->nDataBytesPerChunk; */
4696 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4699 /* OK now check for the curveball where the start and end are in
4702 if ((start + n) < dev->nDataBytesPerChunk)
4705 nToCopy = dev->nDataBytesPerChunk - start;
4707 cache = yaffs_FindChunkCache(in, chunk);
4709 /* If the chunk is already in the cache or it is less than a whole chunk
4710 * or we're using inband tags then use the cache (if there is caching)
4711 * else bypass the cache.
4713 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4714 if (dev->nShortOpCaches > 0) {
4716 /* If we can't find the data in the cache, then load it up. */
4719 cache = yaffs_GrabChunkCache(in->myDev);
4721 cache->chunkId = chunk;
4724 yaffs_ReadChunkDataFromObject(in, chunk,
4730 yaffs_UseChunkCache(dev, cache, 0);
4735 memcpy(buffer, &cache->data[start], nToCopy);
4739 /* Read into the local buffer then copy..*/
4742 yaffs_GetTempBuffer(dev, __LINE__);
4743 yaffs_ReadChunkDataFromObject(in, chunk,
4746 memcpy(buffer, &localBuffer[start], nToCopy);
4749 yaffs_ReleaseTempBuffer(dev, localBuffer,
4755 /* A full chunk. Read directly into the supplied buffer. */
4756 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4770 int yaffs_WriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
4771 int nBytes, int writeThrough)
4780 int startOfWrite = offset;
4781 int chunkWritten = 0;
4789 while (n > 0 && chunkWritten >= 0) {
4790 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4791 /* start = offset % dev->nDataBytesPerChunk; */
4792 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4794 if (chunk * dev->nDataBytesPerChunk + start != offset ||
4795 start >= dev->nDataBytesPerChunk) {
4796 T(YAFFS_TRACE_ERROR, (
4797 TSTR("AddrToChunk of offset %d gives chunk %d start %d"
4799 (int)offset, chunk, start));
4803 /* OK now check for the curveball where the start and end are in
4807 if ((start + n) < dev->nDataBytesPerChunk) {
4810 /* Now folks, to calculate how many bytes to write back....
4811 * If we're overwriting and not writing to then end of file then
4812 * we need to write back as much as was there before.
4815 chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
4817 if (chunkStart > in->variant.fileVariant.fileSize)
4818 nBytesRead = 0; /* Past end of file */
4820 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
4822 if (nBytesRead > dev->nDataBytesPerChunk)
4823 nBytesRead = dev->nDataBytesPerChunk;
4827 (start + n)) ? nBytesRead : (start + n);
4829 if (nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
4833 nToCopy = dev->nDataBytesPerChunk - start;
4834 nToWriteBack = dev->nDataBytesPerChunk;
4837 if (nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4838 /* An incomplete start or end chunk (or maybe both start and end chunk),
4839 * or we're using inband tags, so we want to use the cache buffers.
4841 if (dev->nShortOpCaches > 0) {
4842 yaffs_ChunkCache *cache;
4843 /* If we can't find the data in the cache, then load the cache */
4844 cache = yaffs_FindChunkCache(in, chunk);
4847 && yaffs_CheckSpaceForAllocation(in->
4849 cache = yaffs_GrabChunkCache(in->myDev);
4851 cache->chunkId = chunk;
4854 yaffs_ReadChunkDataFromObject(in, chunk,
4859 !yaffs_CheckSpaceForAllocation(in->myDev)) {
4860 /* Drop the cache if it was a read cache item and
4861 * no space check has been made for it.
4867 yaffs_UseChunkCache(dev, cache, 1);
4871 memcpy(&cache->data[start], buffer,
4876 cache->nBytes = nToWriteBack;
4880 yaffs_WriteChunkDataToObject
4883 cache->data, cache->nBytes,
4889 chunkWritten = -1; /* fail the write */
4892 /* An incomplete start or end chunk (or maybe both start and end chunk)
4893 * Read into the local buffer then copy, then copy over and write back.
4897 yaffs_GetTempBuffer(dev, __LINE__);
4899 yaffs_ReadChunkDataFromObject(in, chunk,
4904 memcpy(&localBuffer[start], buffer, nToCopy);
4907 yaffs_WriteChunkDataToObject(in, chunk,
4912 yaffs_ReleaseTempBuffer(dev, localBuffer,
4918 /* A full chunk. Write directly from the supplied buffer. */
4923 yaffs_WriteChunkDataToObject(in, chunk, buffer,
4924 dev->nDataBytesPerChunk,
4927 /* Since we've overwritten the cached data, we better invalidate it. */
4928 yaffs_InvalidateChunkCache(in, chunk);
4931 if (chunkWritten >= 0) {
4940 /* Update file object */
4942 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
4943 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4951 /* ---------------------- File resizing stuff ------------------ */
4953 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
4956 yaffs_Device *dev = in->myDev;
4957 int oldFileSize = in->variant.fileVariant.fileSize;
4959 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
4961 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
4962 dev->nDataBytesPerChunk;
4966 /* Delete backwards so that we don't end up with holes if
4967 * power is lost part-way through the operation.
4969 for (i = lastDel; i >= startDel; i--) {
4970 /* NB this could be optimised somewhat,
4971 * eg. could retrieve the tags and write them without
4972 * using yaffs_DeleteChunk
4975 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
4978 (dev->internalStartBlock * dev->nChunksPerBlock)
4980 ((dev->internalEndBlock +
4981 1) * dev->nChunksPerBlock)) {
4982 T(YAFFS_TRACE_ALWAYS,
4983 (TSTR("Found daft chunkId %d for %d" TENDSTR),
4987 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
4994 int yaffs_ResizeFile(yaffs_Object *in, loff_t newSize)
4997 int oldFileSize = in->variant.fileVariant.fileSize;
4998 __u32 newSizeOfPartialChunk;
5001 yaffs_Device *dev = in->myDev;
5003 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5005 yaffs_FlushFilesChunkCache(in);
5006 yaffs_InvalidateWholeChunkCache(in);
5008 yaffs_CheckGarbageCollection(dev);
5010 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
5013 if (newSize == oldFileSize)
5016 if (newSize < oldFileSize) {
5018 yaffs_PruneResizedChunks(in, newSize);
5020 if (newSizeOfPartialChunk != 0) {
5021 int lastChunk = 1 + newFullChunks;
5023 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5025 /* Got to read and rewrite the last chunk with its new size and zero pad */
5026 yaffs_ReadChunkDataFromObject(in, lastChunk,
5029 memset(localBuffer + newSizeOfPartialChunk, 0,
5030 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5032 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5033 newSizeOfPartialChunk, 1);
5035 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5038 in->variant.fileVariant.fileSize = newSize;
5040 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5042 /* newsSize > oldFileSize */
5043 in->variant.fileVariant.fileSize = newSize;
5047 /* Write a new object header to reflect the resize.
5048 * show we've shrunk the file, if need be
5049 * Do this only if the file is not in the deleted directories
5050 * and is not shadowed.
5054 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5055 in->parent->objectId != YAFFS_OBJECTID_DELETED)
5056 yaffs_UpdateObjectHeader(in, NULL, 0,
5057 (newSize < oldFileSize) ? 1 : 0, 0);
5062 loff_t yaffs_GetFileSize(yaffs_Object *obj)
5064 obj = yaffs_GetEquivalentObject(obj);
5066 switch (obj->variantType) {
5067 case YAFFS_OBJECT_TYPE_FILE:
5068 return obj->variant.fileVariant.fileSize;
5069 case YAFFS_OBJECT_TYPE_SYMLINK:
5070 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5078 int yaffs_FlushFile(yaffs_Object *in, int updateTime, int dataSync)
5082 yaffs_FlushFilesChunkCache(in);
5083 if(dataSync) /* Only sync data */
5087 #ifdef CONFIG_YAFFS_WINCE
5088 yfsd_WinFileTimeNow(in->win_mtime);
5091 in->yst_mtime = Y_CURRENT_TIME;
5096 retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5097 0) ? YAFFS_OK : YAFFS_FAIL;
5107 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
5110 /* First off, invalidate the file's data in the cache, without flushing. */
5111 yaffs_InvalidateWholeChunkCache(in);
5113 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5114 /* Move to the unlinked directory so we have a record that it was deleted. */
5115 yaffs_ChangeObjectName(in, in->myDev->deletedDir, _Y("deleted"), 0, 0);
5119 yaffs_RemoveObjectFromDirectory(in);
5120 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5123 yaffs_FreeObject(in);
5128 /* yaffs_DeleteFile deletes the whole file data
5129 * and the inode associated with the file.
5130 * It does not delete the links associated with the file.
5132 static int yaffs_UnlinkFileIfNeeded(yaffs_Object *in)
5136 int immediateDeletion = 0;
5140 immediateDeletion = 1;
5143 immediateDeletion = 1;
5146 if (immediateDeletion) {
5148 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5149 _Y("deleted"), 0, 0);
5150 T(YAFFS_TRACE_TRACING,
5151 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5154 in->myDev->nDeletedFiles++;
5155 if (1 || in->myDev->isYaffs2)
5156 yaffs_ResizeFile(in, 0);
5157 yaffs_SoftDeleteFile(in);
5160 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5161 _Y("unlinked"), 0, 0);
5168 int yaffs_DeleteFile(yaffs_Object *in)
5170 int retVal = YAFFS_OK;
5171 int deleted = in->deleted;
5173 yaffs_ResizeFile(in, 0);
5175 if (in->nDataChunks > 0) {
5176 /* Use soft deletion if there is data in the file.
5177 * That won't be the case if it has been resized to zero.
5180 retVal = yaffs_UnlinkFileIfNeeded(in);
5182 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5185 in->myDev->nDeletedFiles++;
5186 yaffs_SoftDeleteFile(in);
5188 return deleted ? YAFFS_OK : YAFFS_FAIL;
5190 /* The file has no data chunks so we toss it immediately */
5191 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5192 in->variant.fileVariant.top = NULL;
5193 yaffs_DoGenericObjectDeletion(in);
5199 static int yaffs_IsNonEmptyDirectory(yaffs_Object *obj)
5201 return (obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) &&
5202 !(ylist_empty(&obj->variant.directoryVariant.children));
5205 static int yaffs_DeleteDirectory(yaffs_Object *obj)
5207 /* First check that the directory is empty. */
5208 if (yaffs_IsNonEmptyDirectory(obj))
5211 return yaffs_DoGenericObjectDeletion(obj);
5214 static int yaffs_DeleteSymLink(yaffs_Object *in)
5216 YFREE(in->variant.symLinkVariant.alias);
5218 return yaffs_DoGenericObjectDeletion(in);
5221 static int yaffs_DeleteHardLink(yaffs_Object *in)
5223 /* remove this hardlink from the list assocaited with the equivalent
5226 ylist_del_init(&in->hardLinks);
5227 return yaffs_DoGenericObjectDeletion(in);
5230 int yaffs_DeleteObject(yaffs_Object *obj)
5233 switch (obj->variantType) {
5234 case YAFFS_OBJECT_TYPE_FILE:
5235 retVal = yaffs_DeleteFile(obj);
5237 case YAFFS_OBJECT_TYPE_DIRECTORY:
5238 return yaffs_DeleteDirectory(obj);
5240 case YAFFS_OBJECT_TYPE_SYMLINK:
5241 retVal = yaffs_DeleteSymLink(obj);
5243 case YAFFS_OBJECT_TYPE_HARDLINK:
5244 retVal = yaffs_DeleteHardLink(obj);
5246 case YAFFS_OBJECT_TYPE_SPECIAL:
5247 retVal = yaffs_DoGenericObjectDeletion(obj);
5249 case YAFFS_OBJECT_TYPE_UNKNOWN:
5251 break; /* should not happen. */
5257 static int yaffs_UnlinkWorker(yaffs_Object *obj)
5260 int immediateDeletion = 0;
5264 immediateDeletion = 1;
5266 if (obj->inUse <= 0)
5267 immediateDeletion = 1;
5271 yaffs_UpdateParent(obj->parent);
5273 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5274 return yaffs_DeleteHardLink(obj);
5275 } else if (!ylist_empty(&obj->hardLinks)) {
5276 /* Curve ball: We're unlinking an object that has a hardlink.
5278 * This problem arises because we are not strictly following
5279 * The Linux link/inode model.
5281 * We can't really delete the object.
5282 * Instead, we do the following:
5283 * - Select a hardlink.
5284 * - Unhook it from the hard links
5285 * - Unhook it from its parent directory (so that the rename can work)
5286 * - Rename the object to the hardlink's name.
5287 * - Delete the hardlink
5292 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5294 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5296 ylist_del_init(&hl->hardLinks);
5297 ylist_del_init(&hl->siblings);
5299 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5301 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
5303 if (retVal == YAFFS_OK)
5304 retVal = yaffs_DoGenericObjectDeletion(hl);
5308 } else if (immediateDeletion) {
5309 switch (obj->variantType) {
5310 case YAFFS_OBJECT_TYPE_FILE:
5311 return yaffs_DeleteFile(obj);
5313 case YAFFS_OBJECT_TYPE_DIRECTORY:
5314 return yaffs_DeleteDirectory(obj);
5316 case YAFFS_OBJECT_TYPE_SYMLINK:
5317 return yaffs_DeleteSymLink(obj);
5319 case YAFFS_OBJECT_TYPE_SPECIAL:
5320 return yaffs_DoGenericObjectDeletion(obj);
5322 case YAFFS_OBJECT_TYPE_HARDLINK:
5323 case YAFFS_OBJECT_TYPE_UNKNOWN:
5327 } else if(yaffs_IsNonEmptyDirectory(obj))
5330 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
5331 _Y("unlinked"), 0, 0);
5335 static int yaffs_UnlinkObject(yaffs_Object *obj)
5338 if (obj && obj->unlinkAllowed)
5339 return yaffs_UnlinkWorker(obj);
5344 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
5348 obj = yaffs_FindObjectByName(dir, name);
5349 return yaffs_UnlinkObject(obj);
5352 /*----------------------- Initialisation Scanning ---------------------- */
5354 static void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
5355 int backwardScanning)
5359 if (!backwardScanning) {
5360 /* Handle YAFFS1 forward scanning case
5361 * For YAFFS1 we always do the deletion
5365 /* Handle YAFFS2 case (backward scanning)
5366 * If the shadowed object exists then ignore.
5368 obj = yaffs_FindObjectByNumber(dev, objId);
5373 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5374 * We put it in unlinked dir to be cleaned up after the scanning
5377 yaffs_FindOrCreateObjectByNumber(dev, objId,
5378 YAFFS_OBJECT_TYPE_FILE);
5381 obj->isShadowed = 1;
5382 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5383 obj->variant.fileVariant.shrinkSize = 0;
5384 obj->valid = 1; /* So that we don't read any other info for this file */
5394 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5401 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5403 in = yaffs_FindObjectByNumber(dev,
5404 hl->variant.hardLinkVariant.
5405 equivalentObjectId);
5408 /* Add the hardlink pointers */
5409 hl->variant.hardLinkVariant.equivalentObject = in;
5410 ylist_add(&hl->hardLinks, &in->hardLinks);
5412 /* Todo Need to report/handle this better.
5413 * Got a problem... hardlink to a non-existant object
5415 hl->variant.hardLinkVariant.equivalentObject = NULL;
5416 YINIT_LIST_HEAD(&hl->hardLinks);
5426 static int ybicmp(const void *a, const void *b)
5428 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5429 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5430 register int ablock = ((yaffs_BlockIndex *)a)->block;
5431 register int bblock = ((yaffs_BlockIndex *)b)->block;
5433 return ablock - bblock;
5439 struct yaffs_ShadowFixerStruct {
5442 struct yaffs_ShadowFixerStruct *next;
5446 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5449 * Sort out state of unlinked and deleted objects after scanning.
5451 struct ylist_head *i;
5452 struct ylist_head *n;
5455 /* Soft delete all the unlinked files */
5456 ylist_for_each_safe(i, n,
5457 &dev->unlinkedDir->variant.directoryVariant.children) {
5459 l = ylist_entry(i, yaffs_Object, siblings);
5460 yaffs_DeleteObject(l);
5464 ylist_for_each_safe(i, n,
5465 &dev->deletedDir->variant.directoryVariant.children) {
5467 l = ylist_entry(i, yaffs_Object, siblings);
5468 yaffs_DeleteObject(l);
5474 static int yaffs_Scan(yaffs_Device *dev)
5476 yaffs_ExtendedTags tags;
5486 yaffs_BlockState state;
5487 yaffs_Object *hardList = NULL;
5488 yaffs_BlockInfo *bi;
5489 __u32 sequenceNumber;
5490 yaffs_ObjectHeader *oh;
5492 yaffs_Object *parent;
5494 int alloc_failed = 0;
5496 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5504 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5505 dev->internalStartBlock, dev->internalEndBlock));
5507 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5509 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5511 /* Scan all the blocks to determine their state */
5512 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5513 bi = yaffs_GetBlockInfo(dev, blk);
5514 yaffs_ClearChunkBits(dev, blk);
5516 bi->softDeletions = 0;
5518 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5520 bi->blockState = state;
5521 bi->sequenceNumber = sequenceNumber;
5523 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
5524 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
5526 T(YAFFS_TRACE_SCAN_DEBUG,
5527 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5528 state, sequenceNumber));
5530 if (state == YAFFS_BLOCK_STATE_DEAD) {
5531 T(YAFFS_TRACE_BAD_BLOCKS,
5532 (TSTR("block %d is bad" TENDSTR), blk));
5533 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5534 T(YAFFS_TRACE_SCAN_DEBUG,
5535 (TSTR("Block empty " TENDSTR)));
5536 dev->nErasedBlocks++;
5537 dev->nFreeChunks += dev->nChunksPerBlock;
5541 startIterator = dev->internalStartBlock;
5542 endIterator = dev->internalEndBlock;
5544 /* For each block.... */
5545 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5552 blk = blockIterator;
5554 bi = yaffs_GetBlockInfo(dev, blk);
5555 state = bi->blockState;
5559 /* For each chunk in each block that needs scanning....*/
5560 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5561 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5562 /* Read the tags and decide what to do */
5563 chunk = blk * dev->nChunksPerBlock + c;
5565 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5568 /* Let's have a good look at this chunk... */
5570 if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
5576 /*T((" %d %d deleted\n",blk,c)); */
5577 } else if (!tags.chunkUsed) {
5578 /* An unassigned chunk in the block
5579 * This means that either the block is empty or
5580 * this is the one being allocated from
5584 /* We're looking at the first chunk in the block so the block is unused */
5585 state = YAFFS_BLOCK_STATE_EMPTY;
5586 dev->nErasedBlocks++;
5588 /* this is the block being allocated from */
5591 (" Allocating from %d %d" TENDSTR),
5593 state = YAFFS_BLOCK_STATE_ALLOCATING;
5594 dev->allocationBlock = blk;
5595 dev->allocationPage = c;
5596 dev->allocationBlockFinder = blk;
5597 /* Set it to here to encourage the allocator to go forth from here. */
5601 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5602 } else if (tags.chunkId > 0) {
5603 /* chunkId > 0 so it is a data chunk... */
5604 unsigned int endpos;
5606 yaffs_SetChunkBit(dev, blk, c);
5609 in = yaffs_FindOrCreateObjectByNumber(dev,
5612 YAFFS_OBJECT_TYPE_FILE);
5613 /* PutChunkIntoFile checks for a clash (two data chunks with
5614 * the same chunkId).
5621 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, 1))
5626 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5629 in->variantType == YAFFS_OBJECT_TYPE_FILE
5630 && in->variant.fileVariant.scannedFileSize <
5632 in->variant.fileVariant.
5633 scannedFileSize = endpos;
5634 if (!dev->useHeaderFileSize) {
5635 in->variant.fileVariant.
5637 in->variant.fileVariant.
5642 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
5644 /* chunkId == 0, so it is an ObjectHeader.
5645 * Thus, we read in the object header and make the object
5647 yaffs_SetChunkBit(dev, blk, c);
5650 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5654 oh = (yaffs_ObjectHeader *) chunkData;
5656 in = yaffs_FindObjectByNumber(dev,
5658 if (in && in->variantType != oh->type) {
5659 /* This should not happen, but somehow
5660 * Wev'e ended up with an objectId that has been reused but not yet
5661 * deleted, and worse still it has changed type. Delete the old object.
5664 yaffs_DeleteObject(in);
5669 in = yaffs_FindOrCreateObjectByNumber(dev,
5677 if (in && oh->shadowsObject > 0) {
5679 struct yaffs_ShadowFixerStruct *fixer;
5680 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
5682 fixer->next = shadowFixerList;
5683 shadowFixerList = fixer;
5684 fixer->objectId = tags.objectId;
5685 fixer->shadowedId = oh->shadowsObject;
5690 if (in && in->valid) {
5691 /* We have already filled this one. We have a duplicate and need to resolve it. */
5693 unsigned existingSerial = in->serial;
5694 unsigned newSerial = tags.serialNumber;
5696 if (((existingSerial + 1) & 3) == newSerial) {
5697 /* Use new one - destroy the exisiting one */
5698 yaffs_DeleteChunk(dev,
5703 /* Use existing - destroy this one. */
5704 yaffs_DeleteChunk(dev, chunk, 1,
5709 if (in && !in->valid &&
5710 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5711 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5712 /* We only load some info, don't fiddle with directory structure */
5714 in->variantType = oh->type;
5716 in->yst_mode = oh->yst_mode;
5717 #ifdef CONFIG_YAFFS_WINCE
5718 in->win_atime[0] = oh->win_atime[0];
5719 in->win_ctime[0] = oh->win_ctime[0];
5720 in->win_mtime[0] = oh->win_mtime[0];
5721 in->win_atime[1] = oh->win_atime[1];
5722 in->win_ctime[1] = oh->win_ctime[1];
5723 in->win_mtime[1] = oh->win_mtime[1];
5725 in->yst_uid = oh->yst_uid;
5726 in->yst_gid = oh->yst_gid;
5727 in->yst_atime = oh->yst_atime;
5728 in->yst_mtime = oh->yst_mtime;
5729 in->yst_ctime = oh->yst_ctime;
5730 in->yst_rdev = oh->yst_rdev;
5732 in->hdrChunk = chunk;
5733 in->serial = tags.serialNumber;
5735 } else if (in && !in->valid) {
5736 /* we need to load this info */
5739 in->variantType = oh->type;
5741 in->yst_mode = oh->yst_mode;
5742 #ifdef CONFIG_YAFFS_WINCE
5743 in->win_atime[0] = oh->win_atime[0];
5744 in->win_ctime[0] = oh->win_ctime[0];
5745 in->win_mtime[0] = oh->win_mtime[0];
5746 in->win_atime[1] = oh->win_atime[1];
5747 in->win_ctime[1] = oh->win_ctime[1];
5748 in->win_mtime[1] = oh->win_mtime[1];
5750 in->yst_uid = oh->yst_uid;
5751 in->yst_gid = oh->yst_gid;
5752 in->yst_atime = oh->yst_atime;
5753 in->yst_mtime = oh->yst_mtime;
5754 in->yst_ctime = oh->yst_ctime;
5755 in->yst_rdev = oh->yst_rdev;
5757 in->hdrChunk = chunk;
5758 in->serial = tags.serialNumber;
5760 yaffs_SetObjectName(in, oh->name);
5763 /* directory stuff...
5768 yaffs_FindOrCreateObjectByNumber
5769 (dev, oh->parentObjectId,
5770 YAFFS_OBJECT_TYPE_DIRECTORY);
5773 if (parent && parent->variantType ==
5774 YAFFS_OBJECT_TYPE_UNKNOWN) {
5775 /* Set up as a directory */
5776 parent->variantType =
5777 YAFFS_OBJECT_TYPE_DIRECTORY;
5778 YINIT_LIST_HEAD(&parent->variant.
5781 } else if (!parent || parent->variantType !=
5782 YAFFS_OBJECT_TYPE_DIRECTORY) {
5783 /* Hoosterman, another problem....
5784 * We're trying to use a non-directory as a directory
5787 T(YAFFS_TRACE_ERROR,
5789 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
5791 parent = dev->lostNFoundDir;
5794 yaffs_AddObjectToDirectory(parent, in);
5796 if (0 && (parent == dev->deletedDir ||
5797 parent == dev->unlinkedDir)) {
5798 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
5799 dev->nDeletedFiles++;
5801 /* Note re hardlinks.
5802 * Since we might scan a hardlink before its equivalent object is scanned
5803 * we put them all in a list.
5804 * After scanning is complete, we should have all the objects, so we run through this
5805 * list and fix up all the chains.
5808 switch (in->variantType) {
5809 case YAFFS_OBJECT_TYPE_UNKNOWN:
5810 /* Todo got a problem */
5812 case YAFFS_OBJECT_TYPE_FILE:
5813 if (dev->useHeaderFileSize)
5815 in->variant.fileVariant.
5820 case YAFFS_OBJECT_TYPE_HARDLINK:
5821 in->variant.hardLinkVariant.
5822 equivalentObjectId =
5823 oh->equivalentObjectId;
5824 in->hardLinks.next =
5825 (struct ylist_head *)
5829 case YAFFS_OBJECT_TYPE_DIRECTORY:
5832 case YAFFS_OBJECT_TYPE_SPECIAL:
5835 case YAFFS_OBJECT_TYPE_SYMLINK:
5836 in->variant.symLinkVariant.alias =
5837 yaffs_CloneString(oh->alias);
5838 if (!in->variant.symLinkVariant.alias)
5844 if (parent == dev->deletedDir) {
5845 yaffs_DestroyObject(in);
5846 bi->hasShrinkHeader = 1;
5853 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5854 /* If we got this far while scanning, then the block is fully allocated.*/
5855 state = YAFFS_BLOCK_STATE_FULL;
5858 bi->blockState = state;
5860 /* Now let's see if it was dirty */
5861 if (bi->pagesInUse == 0 &&
5862 !bi->hasShrinkHeader &&
5863 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5864 yaffs_BlockBecameDirty(dev, blk);
5870 /* Ok, we've done all the scanning.
5871 * Fix up the hard link chains.
5872 * We should now have scanned all the objects, now it's time to add these
5876 yaffs_HardlinkFixup(dev, hardList);
5878 /* Fix up any shadowed objects */
5880 struct yaffs_ShadowFixerStruct *fixer;
5883 while (shadowFixerList) {
5884 fixer = shadowFixerList;
5885 shadowFixerList = fixer->next;
5886 /* Complete the rename transaction by deleting the shadowed object
5887 * then setting the object header to unshadowed.
5889 obj = yaffs_FindObjectByNumber(dev, fixer->shadowedId);
5891 yaffs_DeleteObject(obj);
5893 obj = yaffs_FindObjectByNumber(dev, fixer->objectId);
5896 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
5902 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5907 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5913 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5916 yaffs_ObjectHeader *oh;
5918 yaffs_ExtendedTags tags;
5920 int alloc_failed = 0;
5928 T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
5930 in->lazyLoaded ? "not yet" : "already"));
5933 if (in->lazyLoaded && in->hdrChunk > 0) {
5935 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5937 result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
5938 oh = (yaffs_ObjectHeader *) chunkData;
5940 in->yst_mode = oh->yst_mode;
5941 #ifdef CONFIG_YAFFS_WINCE
5942 in->win_atime[0] = oh->win_atime[0];
5943 in->win_ctime[0] = oh->win_ctime[0];
5944 in->win_mtime[0] = oh->win_mtime[0];
5945 in->win_atime[1] = oh->win_atime[1];
5946 in->win_ctime[1] = oh->win_ctime[1];
5947 in->win_mtime[1] = oh->win_mtime[1];
5949 in->yst_uid = oh->yst_uid;
5950 in->yst_gid = oh->yst_gid;
5951 in->yst_atime = oh->yst_atime;
5952 in->yst_mtime = oh->yst_mtime;
5953 in->yst_ctime = oh->yst_ctime;
5954 in->yst_rdev = oh->yst_rdev;
5957 yaffs_SetObjectName(in, oh->name);
5959 if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
5960 in->variant.symLinkVariant.alias =
5961 yaffs_CloneString(oh->alias);
5962 if (!in->variant.symLinkVariant.alias)
5963 alloc_failed = 1; /* Not returned to caller */
5966 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5970 static int yaffs_ScanBackwards(yaffs_Device *dev)
5972 yaffs_ExtendedTags tags;
5977 int nBlocksToScan = 0;
5983 yaffs_BlockState state;
5984 yaffs_Object *hardList = NULL;
5985 yaffs_BlockInfo *bi;
5986 __u32 sequenceNumber;
5987 yaffs_ObjectHeader *oh;
5989 yaffs_Object *parent;
5990 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5996 int foundChunksInBlock;
5997 int equivalentObjectId;
5998 int alloc_failed = 0;
6001 yaffs_BlockIndex *blockIndex = NULL;
6002 int altBlockIndex = 0;
6004 if (!dev->isYaffs2) {
6006 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6012 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
6013 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6016 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6018 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6021 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6027 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6031 dev->blocksInCheckpoint = 0;
6033 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6035 /* Scan all the blocks to determine their state */
6036 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6037 bi = yaffs_GetBlockInfo(dev, blk);
6038 yaffs_ClearChunkBits(dev, blk);
6040 bi->softDeletions = 0;
6042 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6044 bi->blockState = state;
6045 bi->sequenceNumber = sequenceNumber;
6047 if (bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6048 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6049 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6050 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6052 T(YAFFS_TRACE_SCAN_DEBUG,
6053 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6054 state, sequenceNumber));
6057 if (state == YAFFS_BLOCK_STATE_CHECKPOINT) {
6058 dev->blocksInCheckpoint++;
6060 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6061 T(YAFFS_TRACE_BAD_BLOCKS,
6062 (TSTR("block %d is bad" TENDSTR), blk));
6063 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6064 T(YAFFS_TRACE_SCAN_DEBUG,
6065 (TSTR("Block empty " TENDSTR)));
6066 dev->nErasedBlocks++;
6067 dev->nFreeChunks += dev->nChunksPerBlock;
6068 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6070 /* Determine the highest sequence number */
6071 if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6072 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6074 blockIndex[nBlocksToScan].seq = sequenceNumber;
6075 blockIndex[nBlocksToScan].block = blk;
6079 if (sequenceNumber >= dev->sequenceNumber)
6080 dev->sequenceNumber = sequenceNumber;
6082 /* TODO: Nasty sequence number! */
6085 ("Block scanning block %d has bad sequence number %d"
6086 TENDSTR), blk, sequenceNumber));
6093 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6099 /* Sort the blocks */
6100 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6102 /* Use qsort now. */
6103 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6107 /* Dungy old bubble sort... */
6109 yaffs_BlockIndex temp;
6113 for (i = 0; i < nBlocksToScan; i++)
6114 for (j = i + 1; j < nBlocksToScan; j++)
6115 if (blockIndex[i].seq > blockIndex[j].seq) {
6116 temp = blockIndex[j];
6117 blockIndex[j] = blockIndex[i];
6118 blockIndex[i] = temp;
6125 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6127 /* Now scan the blocks looking at the data. */
6129 endIterator = nBlocksToScan - 1;
6130 T(YAFFS_TRACE_SCAN_DEBUG,
6131 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6133 /* For each block.... backwards */
6134 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6136 /* Cooperative multitasking! This loop can run for so
6137 long that watchdog timers expire. */
6140 /* get the block to scan in the correct order */
6141 blk = blockIndex[blockIterator].block;
6143 bi = yaffs_GetBlockInfo(dev, blk);
6146 state = bi->blockState;
6150 /* For each chunk in each block that needs scanning.... */
6151 foundChunksInBlock = 0;
6152 for (c = dev->nChunksPerBlock - 1;
6153 !alloc_failed && c >= 0 &&
6154 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6155 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6156 /* Scan backwards...
6157 * Read the tags and decide what to do
6160 chunk = blk * dev->nChunksPerBlock + c;
6162 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6165 /* Let's have a good look at this chunk... */
6167 if (!tags.chunkUsed) {
6168 /* An unassigned chunk in the block.
6169 * If there are used chunks after this one, then
6170 * it is a chunk that was skipped due to failing the erased
6171 * check. Just skip it so that it can be deleted.
6172 * But, more typically, We get here when this is an unallocated
6173 * chunk and his means that either the block is empty or
6174 * this is the one being allocated from
6177 if (foundChunksInBlock) {
6178 /* This is a chunk that was skipped due to failing the erased check */
6179 } else if (c == 0) {
6180 /* We're looking at the first chunk in the block so the block is unused */
6181 state = YAFFS_BLOCK_STATE_EMPTY;
6182 dev->nErasedBlocks++;
6184 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6185 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6186 if (dev->sequenceNumber == bi->sequenceNumber) {
6187 /* this is the block being allocated from */
6191 (" Allocating from %d %d"
6194 state = YAFFS_BLOCK_STATE_ALLOCATING;
6195 dev->allocationBlock = blk;
6196 dev->allocationPage = c;
6197 dev->allocationBlockFinder = blk;
6199 /* This is a partially written block that is not
6200 * the current allocation block. This block must have
6201 * had a write failure, so set up for retirement.
6204 /* bi->needsRetiring = 1; ??? TODO */
6205 bi->gcPrioritise = 1;
6207 T(YAFFS_TRACE_ALWAYS,
6208 (TSTR("Partially written block %d detected" TENDSTR),
6216 } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED) {
6218 (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
6223 } else if (tags.chunkId > 0) {
6224 /* chunkId > 0 so it is a data chunk... */
6225 unsigned int endpos;
6227 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6229 foundChunksInBlock = 1;
6232 yaffs_SetChunkBit(dev, blk, c);
6235 in = yaffs_FindOrCreateObjectByNumber(dev,
6238 YAFFS_OBJECT_TYPE_FILE);
6245 in->variantType == YAFFS_OBJECT_TYPE_FILE
6247 in->variant.fileVariant.shrinkSize) {
6248 /* This has not been invalidated by a resize */
6249 if (!yaffs_PutChunkIntoFile(in, tags.chunkId,
6254 /* File size is calculated by looking at the data chunks if we have not
6255 * seen an object header yet. Stop this practice once we find an object header.
6259 1) * dev->nDataBytesPerChunk +
6262 if (!in->valid && /* have not got an object header yet */
6263 in->variant.fileVariant.
6264 scannedFileSize < endpos) {
6265 in->variant.fileVariant.
6266 scannedFileSize = endpos;
6267 in->variant.fileVariant.
6269 in->variant.fileVariant.
6274 /* This chunk has been invalidated by a resize, so delete */
6275 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6279 /* chunkId == 0, so it is an ObjectHeader.
6280 * Thus, we read in the object header and make the object
6282 foundChunksInBlock = 1;
6284 yaffs_SetChunkBit(dev, blk, c);
6290 if (tags.extraHeaderInfoAvailable) {
6291 in = yaffs_FindOrCreateObjectByNumber
6292 (dev, tags.objectId,
6293 tags.extraObjectType);
6299 (!in->valid && dev->disableLazyLoad) ||
6300 tags.extraShadows ||
6302 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6303 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))) {
6305 /* If we don't have valid info then we need to read the chunk
6306 * TODO In future we can probably defer reading the chunk and
6307 * living with invalid data until needed.
6310 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6315 oh = (yaffs_ObjectHeader *) chunkData;
6317 if (dev->inbandTags) {
6318 /* Fix up the header if they got corrupted by inband tags */
6319 oh->shadowsObject = oh->inbandShadowsObject;
6320 oh->isShrink = oh->inbandIsShrink;
6324 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6332 /* TODO Hoosterman we have a problem! */
6333 T(YAFFS_TRACE_ERROR,
6335 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6336 TENDSTR), tags.objectId, chunk));
6341 /* We have already filled this one.
6342 * We have a duplicate that will be discarded, but
6343 * we first have to suck out resize info if it is a file.
6346 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6348 oh->type == YAFFS_OBJECT_TYPE_FILE) ||
6349 (tags.extraHeaderInfoAvailable &&
6350 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))) {
6352 (oh) ? oh->fileSize : tags.
6354 __u32 parentObjectId =
6356 parentObjectId : tags.
6357 extraParentObjectId;
6361 (oh) ? oh->isShrink : tags.
6362 extraIsShrinkHeader;
6364 /* If it is deleted (unlinked at start also means deleted)
6365 * we treat the file size as being zeroed at this point.
6367 if (parentObjectId ==
6368 YAFFS_OBJECTID_DELETED
6369 || parentObjectId ==
6370 YAFFS_OBJECTID_UNLINKED) {
6376 in->variant.fileVariant.
6377 shrinkSize > thisSize) {
6378 in->variant.fileVariant.
6384 bi->hasShrinkHeader = 1;
6387 /* Use existing - destroy this one. */
6388 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6392 if (!in->valid && in->variantType !=
6393 (oh ? oh->type : tags.extraObjectType))
6394 T(YAFFS_TRACE_ERROR, (
6395 TSTR("yaffs tragedy: Bad object type, "
6396 TCONT("%d != %d, for object %d at chunk ")
6397 TCONT("%d during scan")
6399 oh->type : tags.extraObjectType,
6400 in->variantType, tags.objectId,
6404 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6406 YAFFS_OBJECTID_LOSTNFOUND)) {
6407 /* We only load some info, don't fiddle with directory structure */
6411 in->variantType = oh->type;
6413 in->yst_mode = oh->yst_mode;
6414 #ifdef CONFIG_YAFFS_WINCE
6415 in->win_atime[0] = oh->win_atime[0];
6416 in->win_ctime[0] = oh->win_ctime[0];
6417 in->win_mtime[0] = oh->win_mtime[0];
6418 in->win_atime[1] = oh->win_atime[1];
6419 in->win_ctime[1] = oh->win_ctime[1];
6420 in->win_mtime[1] = oh->win_mtime[1];
6422 in->yst_uid = oh->yst_uid;
6423 in->yst_gid = oh->yst_gid;
6424 in->yst_atime = oh->yst_atime;
6425 in->yst_mtime = oh->yst_mtime;
6426 in->yst_ctime = oh->yst_ctime;
6427 in->yst_rdev = oh->yst_rdev;
6431 in->variantType = tags.extraObjectType;
6435 in->hdrChunk = chunk;
6437 } else if (!in->valid) {
6438 /* we need to load this info */
6441 in->hdrChunk = chunk;
6444 in->variantType = oh->type;
6446 in->yst_mode = oh->yst_mode;
6447 #ifdef CONFIG_YAFFS_WINCE
6448 in->win_atime[0] = oh->win_atime[0];
6449 in->win_ctime[0] = oh->win_ctime[0];
6450 in->win_mtime[0] = oh->win_mtime[0];
6451 in->win_atime[1] = oh->win_atime[1];
6452 in->win_ctime[1] = oh->win_ctime[1];
6453 in->win_mtime[1] = oh->win_mtime[1];
6455 in->yst_uid = oh->yst_uid;
6456 in->yst_gid = oh->yst_gid;
6457 in->yst_atime = oh->yst_atime;
6458 in->yst_mtime = oh->yst_mtime;
6459 in->yst_ctime = oh->yst_ctime;
6460 in->yst_rdev = oh->yst_rdev;
6463 if (oh->shadowsObject > 0)
6464 yaffs_HandleShadowedObject(dev,
6470 yaffs_SetObjectName(in, oh->name);
6472 yaffs_FindOrCreateObjectByNumber
6473 (dev, oh->parentObjectId,
6474 YAFFS_OBJECT_TYPE_DIRECTORY);
6476 fileSize = oh->fileSize;
6477 isShrink = oh->isShrink;
6478 equivalentObjectId = oh->equivalentObjectId;
6481 in->variantType = tags.extraObjectType;
6483 yaffs_FindOrCreateObjectByNumber
6484 (dev, tags.extraParentObjectId,
6485 YAFFS_OBJECT_TYPE_DIRECTORY);
6486 fileSize = tags.extraFileLength;
6487 isShrink = tags.extraIsShrinkHeader;
6488 equivalentObjectId = tags.extraEquivalentObjectId;
6497 /* directory stuff...
6501 if (parent && parent->variantType ==
6502 YAFFS_OBJECT_TYPE_UNKNOWN) {
6503 /* Set up as a directory */
6504 parent->variantType =
6505 YAFFS_OBJECT_TYPE_DIRECTORY;
6506 YINIT_LIST_HEAD(&parent->variant.
6509 } else if (!parent || parent->variantType !=
6510 YAFFS_OBJECT_TYPE_DIRECTORY) {
6511 /* Hoosterman, another problem....
6512 * We're trying to use a non-directory as a directory
6515 T(YAFFS_TRACE_ERROR,
6517 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6519 parent = dev->lostNFoundDir;
6522 yaffs_AddObjectToDirectory(parent, in);
6524 itsUnlinked = (parent == dev->deletedDir) ||
6525 (parent == dev->unlinkedDir);
6528 /* Mark the block as having a shrinkHeader */
6529 bi->hasShrinkHeader = 1;
6532 /* Note re hardlinks.
6533 * Since we might scan a hardlink before its equivalent object is scanned
6534 * we put them all in a list.
6535 * After scanning is complete, we should have all the objects, so we run
6536 * through this list and fix up all the chains.
6539 switch (in->variantType) {
6540 case YAFFS_OBJECT_TYPE_UNKNOWN:
6541 /* Todo got a problem */
6543 case YAFFS_OBJECT_TYPE_FILE:
6545 if (in->variant.fileVariant.
6546 scannedFileSize < fileSize) {
6547 /* This covers the case where the file size is greater
6548 * than where the data is
6549 * This will happen if the file is resized to be larger
6550 * than its current data extents.
6552 in->variant.fileVariant.fileSize = fileSize;
6553 in->variant.fileVariant.scannedFileSize =
6554 in->variant.fileVariant.fileSize;
6558 in->variant.fileVariant.shrinkSize > fileSize) {
6559 in->variant.fileVariant.shrinkSize = fileSize;
6563 case YAFFS_OBJECT_TYPE_HARDLINK:
6565 in->variant.hardLinkVariant.equivalentObjectId =
6567 in->hardLinks.next =
6568 (struct ylist_head *) hardList;
6572 case YAFFS_OBJECT_TYPE_DIRECTORY:
6575 case YAFFS_OBJECT_TYPE_SPECIAL:
6578 case YAFFS_OBJECT_TYPE_SYMLINK:
6580 in->variant.symLinkVariant.alias =
6581 yaffs_CloneString(oh->alias);
6582 if (!in->variant.symLinkVariant.alias)
6592 } /* End of scanning for each chunk */
6594 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6595 /* If we got this far while scanning, then the block is fully allocated. */
6596 state = YAFFS_BLOCK_STATE_FULL;
6599 bi->blockState = state;
6601 /* Now let's see if it was dirty */
6602 if (bi->pagesInUse == 0 &&
6603 !bi->hasShrinkHeader &&
6604 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6605 yaffs_BlockBecameDirty(dev, blk);
6611 YFREE_ALT(blockIndex);
6615 /* Ok, we've done all the scanning.
6616 * Fix up the hard link chains.
6617 * We should now have scanned all the objects, now it's time to add these
6620 yaffs_HardlinkFixup(dev, hardList);
6623 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6628 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6633 /*------------------------------ Directory Functions ----------------------------- */
6635 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
6637 struct ylist_head *lh;
6638 yaffs_Object *listObj;
6643 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
6648 if (yaffs_SkipVerification(obj->myDev))
6652 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
6657 if (obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6658 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
6662 /* Iterate through the objects in each hash entry */
6664 ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
6666 listObj = ylist_entry(lh, yaffs_Object, siblings);
6667 yaffs_VerifyObject(listObj);
6674 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR), count));
6679 static void yaffs_VerifyDirectory(yaffs_Object *directory)
6681 struct ylist_head *lh;
6682 yaffs_Object *listObj;
6689 if (yaffs_SkipFullVerification(directory->myDev))
6692 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6693 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR), directory->variantType));
6697 /* Iterate through the objects in each hash entry */
6699 ylist_for_each(lh, &directory->variant.directoryVariant.children) {
6701 listObj = ylist_entry(lh, yaffs_Object, siblings);
6702 if (listObj->parent != directory) {
6703 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR), listObj->parent));
6706 yaffs_VerifyObjectInDirectory(listObj);
6712 *yaffs_UpdateParent() handles fixing a directories mtime and ctime when a new
6713 * link (ie. name) is created or deleted in the directory.
6716 * create dir/a : update dir's mtime/ctime
6717 * rm dir/a: update dir's mtime/ctime
6718 * modify dir/a: don't update dir's mtimme/ctime
6721 static void yaffs_UpdateParent(yaffs_Object *obj)
6727 obj->yst_mtime = obj->yst_ctime = Y_CURRENT_TIME;
6729 yaffs_UpdateObjectHeader(obj,NULL,0,0,0);
6732 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
6734 yaffs_Device *dev = obj->myDev;
6735 yaffs_Object *parent;
6737 yaffs_VerifyObjectInDirectory(obj);
6738 parent = obj->parent;
6740 yaffs_VerifyDirectory(parent);
6742 if (dev && dev->removeObjectCallback)
6743 dev->removeObjectCallback(obj);
6746 ylist_del_init(&obj->siblings);
6749 yaffs_VerifyDirectory(parent);
6752 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
6756 T(YAFFS_TRACE_ALWAYS,
6758 ("tragedy: Trying to add an object to a null pointer directory"
6763 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6764 T(YAFFS_TRACE_ALWAYS,
6766 ("tragedy: Trying to add an object to a non-directory"
6771 if (obj->siblings.prev == NULL) {
6772 /* Not initialised */
6777 yaffs_VerifyDirectory(directory);
6779 yaffs_RemoveObjectFromDirectory(obj);
6783 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
6784 obj->parent = directory;
6786 if (directory == obj->myDev->unlinkedDir
6787 || directory == obj->myDev->deletedDir) {
6789 obj->myDev->nUnlinkedFiles++;
6790 obj->renameAllowed = 0;
6793 yaffs_VerifyDirectory(directory);
6794 yaffs_VerifyObjectInDirectory(obj);
6797 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
6802 struct ylist_head *i;
6803 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
6811 T(YAFFS_TRACE_ALWAYS,
6813 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6818 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6819 T(YAFFS_TRACE_ALWAYS,
6821 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6825 sum = yaffs_CalcNameSum(name);
6827 ylist_for_each(i, &directory->variant.directoryVariant.children) {
6829 l = ylist_entry(i, yaffs_Object, siblings);
6831 if (l->parent != directory)
6834 yaffs_CheckObjectDetailsLoaded(l);
6836 /* Special case for lost-n-found */
6837 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6838 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
6840 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
6841 /* LostnFound chunk called Objxxx
6844 yaffs_GetObjectName(l, buffer,
6845 YAFFS_MAX_NAME_LENGTH + 1);
6846 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
6857 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
6858 int (*fn) (yaffs_Object *))
6860 struct ylist_head *i;
6864 T(YAFFS_TRACE_ALWAYS,
6866 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6871 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6872 T(YAFFS_TRACE_ALWAYS,
6874 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6879 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
6881 l = ylist_entry(i, yaffs_Object, siblings);
6892 /* GetEquivalentObject dereferences any hard links to get to the
6896 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
6898 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
6899 /* We want the object id of the equivalent object, not this one */
6900 obj = obj->variant.hardLinkVariant.equivalentObject;
6901 yaffs_CheckObjectDetailsLoaded(obj);
6906 int yaffs_GetObjectName(yaffs_Object *obj, YCHAR *name, int buffSize)
6908 memset(name, 0, buffSize * sizeof(YCHAR));
6910 yaffs_CheckObjectDetailsLoaded(obj);
6912 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6913 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
6914 } else if (obj->hdrChunk <= 0) {
6916 YCHAR numString[20];
6917 YCHAR *x = &numString[19];
6918 unsigned v = obj->objectId;
6922 *x = '0' + (v % 10);
6925 /* make up a name */
6926 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
6927 yaffs_strcat(locName, x);
6928 yaffs_strncpy(name, locName, buffSize - 1);
6931 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
6932 else if (obj->shortName[0])
6933 yaffs_strcpy(name, obj->shortName);
6937 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
6939 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
6941 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
6943 if (obj->hdrChunk > 0) {
6944 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
6945 obj->hdrChunk, buffer,
6948 yaffs_strncpy(name, oh->name, buffSize - 1);
6950 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
6953 return yaffs_strlen(name);
6956 int yaffs_GetObjectFileLength(yaffs_Object *obj)
6958 /* Dereference any hard linking */
6959 obj = yaffs_GetEquivalentObject(obj);
6961 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
6962 return obj->variant.fileVariant.fileSize;
6963 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
6964 return yaffs_strlen(obj->variant.symLinkVariant.alias);
6966 /* Only a directory should drop through to here */
6967 return obj->myDev->nDataBytesPerChunk;
6971 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
6974 struct ylist_head *i;
6977 count++; /* the object itself */
6979 ylist_for_each(i, &obj->hardLinks)
6980 count++; /* add the hard links; */
6985 int yaffs_GetObjectInode(yaffs_Object *obj)
6987 obj = yaffs_GetEquivalentObject(obj);
6989 return obj->objectId;
6992 unsigned yaffs_GetObjectType(yaffs_Object *obj)
6994 obj = yaffs_GetEquivalentObject(obj);
6996 switch (obj->variantType) {
6997 case YAFFS_OBJECT_TYPE_FILE:
7000 case YAFFS_OBJECT_TYPE_DIRECTORY:
7003 case YAFFS_OBJECT_TYPE_SYMLINK:
7006 case YAFFS_OBJECT_TYPE_HARDLINK:
7009 case YAFFS_OBJECT_TYPE_SPECIAL:
7010 if (S_ISFIFO(obj->yst_mode))
7012 if (S_ISCHR(obj->yst_mode))
7014 if (S_ISBLK(obj->yst_mode))
7016 if (S_ISSOCK(obj->yst_mode))
7024 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
7026 obj = yaffs_GetEquivalentObject(obj);
7027 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
7028 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7030 return yaffs_CloneString(_Y(""));
7033 #ifndef CONFIG_YAFFS_WINCE
7035 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
7037 unsigned int valid = attr->ia_valid;
7039 if (valid & ATTR_MODE)
7040 obj->yst_mode = attr->ia_mode;
7041 if (valid & ATTR_UID)
7042 obj->yst_uid = attr->ia_uid;
7043 if (valid & ATTR_GID)
7044 obj->yst_gid = attr->ia_gid;
7046 if (valid & ATTR_ATIME)
7047 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7048 if (valid & ATTR_CTIME)
7049 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7050 if (valid & ATTR_MTIME)
7051 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7053 if (valid & ATTR_SIZE)
7054 yaffs_ResizeFile(obj, attr->ia_size);
7056 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7061 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
7063 unsigned int valid = 0;
7065 attr->ia_mode = obj->yst_mode;
7067 attr->ia_uid = obj->yst_uid;
7069 attr->ia_gid = obj->yst_gid;
7072 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7073 valid |= ATTR_ATIME;
7074 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7075 valid |= ATTR_CTIME;
7076 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7077 valid |= ATTR_MTIME;
7079 attr->ia_size = yaffs_GetFileSize(obj);
7082 attr->ia_valid = valid;
7090 int yaffs_DumpObject(yaffs_Object *obj)
7094 yaffs_GetObjectName(obj, name, YAFFS_MAX_NAME_LENGTH + 1);
7096 T(YAFFS_TRACE_ALWAYS,
7098 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7099 " chunk %d type %d size %d\n"
7100 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7101 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7102 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7108 /*---------------------------- Initialisation code -------------------------------------- */
7110 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
7113 /* Common functions, gotta have */
7114 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
7117 #ifdef CONFIG_YAFFS_YAFFS2
7119 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7120 if (dev->writeChunkWithTagsToNAND &&
7121 dev->readChunkWithTagsFromNAND &&
7122 !dev->writeChunkToNAND &&
7123 !dev->readChunkFromNAND &&
7124 dev->markNANDBlockBad && dev->queryNANDBlock)
7128 /* Can use the "spare" style interface for yaffs1 */
7129 if (!dev->isYaffs2 &&
7130 !dev->writeChunkWithTagsToNAND &&
7131 !dev->readChunkWithTagsFromNAND &&
7132 dev->writeChunkToNAND &&
7133 dev->readChunkFromNAND &&
7134 !dev->markNANDBlockBad && !dev->queryNANDBlock)
7141 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7143 /* Initialise the unlinked, deleted, root and lost and found directories */
7145 dev->lostNFoundDir = dev->rootDir = NULL;
7146 dev->unlinkedDir = dev->deletedDir = NULL;
7149 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7152 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7155 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7156 YAFFS_ROOT_MODE | S_IFDIR);
7157 dev->lostNFoundDir =
7158 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7159 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7161 if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
7162 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7169 int yaffs_GutsInitialise(yaffs_Device *dev)
7171 int init_failed = 0;
7175 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7177 /* Check stuff that must be set */
7180 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7184 dev->internalStartBlock = dev->startBlock;
7185 dev->internalEndBlock = dev->endBlock;
7186 dev->blockOffset = 0;
7187 dev->chunkOffset = 0;
7188 dev->nFreeChunks = 0;
7192 if (dev->startBlock == 0) {
7193 dev->internalStartBlock = dev->startBlock + 1;
7194 dev->internalEndBlock = dev->endBlock + 1;
7195 dev->blockOffset = 1;
7196 dev->chunkOffset = dev->nChunksPerBlock;
7199 /* Check geometry parameters. */
7201 if ((!dev->inbandTags && dev->isYaffs2 && dev->totalBytesPerChunk < 1024) ||
7202 (!dev->isYaffs2 && dev->totalBytesPerChunk < 512) ||
7203 (dev->inbandTags && !dev->isYaffs2) ||
7204 dev->nChunksPerBlock < 2 ||
7205 dev->nReservedBlocks < 2 ||
7206 dev->internalStartBlock <= 0 ||
7207 dev->internalEndBlock <= 0 ||
7208 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2)) { /* otherwise it is too small */
7209 T(YAFFS_TRACE_ALWAYS,
7211 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7212 TENDSTR), dev->totalBytesPerChunk, dev->isYaffs2 ? "2" : "", dev->inbandTags));
7216 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7217 T(YAFFS_TRACE_ALWAYS,
7218 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7222 /* Sort out space for inband tags, if required */
7223 if (dev->inbandTags)
7224 dev->nDataBytesPerChunk = dev->totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7226 dev->nDataBytesPerChunk = dev->totalBytesPerChunk;
7228 /* Got the right mix of functions? */
7229 if (!yaffs_CheckDevFunctions(dev)) {
7230 /* Function missing */
7231 T(YAFFS_TRACE_ALWAYS,
7233 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7238 /* This is really a compilation check. */
7239 if (!yaffs_CheckStructures()) {
7240 T(YAFFS_TRACE_ALWAYS,
7241 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7245 if (dev->isMounted) {
7246 T(YAFFS_TRACE_ALWAYS,
7247 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7251 /* Finished with most checks. One or two more checks happen later on too. */
7255 /* OK now calculate a few things for the device */
7258 * Calculate all the chunk size manipulation numbers:
7260 x = dev->nDataBytesPerChunk;
7261 /* We always use dev->chunkShift and dev->chunkDiv */
7262 dev->chunkShift = Shifts(x);
7263 x >>= dev->chunkShift;
7265 /* We only use chunk mask if chunkDiv is 1 */
7266 dev->chunkMask = (1<<dev->chunkShift) - 1;
7269 * Calculate chunkGroupBits.
7270 * We need to find the next power of 2 > than internalEndBlock
7273 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7277 /* Set up tnode width if wide tnodes are enabled. */
7278 if (!dev->wideTnodesDisabled) {
7279 /* bits must be even so that we end up with 32-bit words */
7283 dev->tnodeWidth = 16;
7285 dev->tnodeWidth = bits;
7287 dev->tnodeWidth = 16;
7289 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7291 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7292 * so if the bitwidth of the
7293 * chunk range we're using is greater than 16 we need
7294 * to figure out chunk shift and chunkGroupSize
7297 if (bits <= dev->tnodeWidth)
7298 dev->chunkGroupBits = 0;
7300 dev->chunkGroupBits = bits - dev->tnodeWidth;
7303 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7305 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7306 /* We have a problem because the soft delete won't work if
7307 * the chunk group size > chunks per block.
7308 * This can be remedied by using larger "virtual blocks".
7310 T(YAFFS_TRACE_ALWAYS,
7311 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7316 /* OK, we've finished verifying the device, lets continue with initialisation */
7318 /* More device initialisation */
7319 dev->garbageCollections = 0;
7320 dev->passiveGarbageCollections = 0;
7321 dev->currentDirtyChecker = 0;
7322 dev->bufferedBlock = -1;
7323 dev->doingBufferedBlockRewrite = 0;
7324 dev->nDeletedFiles = 0;
7325 dev->nBackgroundDeletions = 0;
7326 dev->nUnlinkedFiles = 0;
7328 dev->eccUnfixed = 0;
7329 dev->tagsEccFixed = 0;
7330 dev->tagsEccUnfixed = 0;
7331 dev->nErasureFailures = 0;
7332 dev->nErasedBlocks = 0;
7334 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7336 /* Initialise temporary buffers and caches. */
7337 if (!yaffs_InitialiseTempBuffers(dev))
7340 dev->srCache = NULL;
7341 dev->gcCleanupList = NULL;
7345 dev->nShortOpCaches > 0) {
7348 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7350 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
7351 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7353 dev->srCache = YMALLOC(srCacheBytes);
7355 buf = (__u8 *) dev->srCache;
7358 memset(dev->srCache, 0, srCacheBytes);
7360 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7361 dev->srCache[i].object = NULL;
7362 dev->srCache[i].lastUse = 0;
7363 dev->srCache[i].dirty = 0;
7364 dev->srCache[i].data = buf = YMALLOC_DMA(dev->totalBytesPerChunk);
7375 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7376 if (!dev->gcCleanupList)
7381 dev->useHeaderFileSize = 1;
7383 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7386 yaffs_InitialiseTnodes(dev);
7387 yaffs_InitialiseObjects(dev);
7389 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7394 /* Now scan the flash. */
7395 if (dev->isYaffs2) {
7396 if (yaffs_CheckpointRestore(dev)) {
7397 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7398 T(YAFFS_TRACE_ALWAYS,
7399 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7402 /* Clean up the mess caused by an aborted checkpoint load
7403 * and scan backwards.
7405 yaffs_DeinitialiseBlocks(dev);
7406 yaffs_DeinitialiseTnodes(dev);
7407 yaffs_DeinitialiseObjects(dev);
7410 dev->nErasedBlocks = 0;
7411 dev->nFreeChunks = 0;
7412 dev->allocationBlock = -1;
7413 dev->allocationPage = -1;
7414 dev->nDeletedFiles = 0;
7415 dev->nUnlinkedFiles = 0;
7416 dev->nBackgroundDeletions = 0;
7417 dev->oldestDirtySequence = 0;
7419 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7422 yaffs_InitialiseTnodes(dev);
7423 yaffs_InitialiseObjects(dev);
7425 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7428 if (!init_failed && !yaffs_ScanBackwards(dev))
7431 } else if (!yaffs_Scan(dev))
7434 yaffs_StripDeletedObjects(dev);
7438 /* Clean up the mess */
7439 T(YAFFS_TRACE_TRACING,
7440 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7442 yaffs_Deinitialise(dev);
7446 /* Zero out stats */
7447 dev->nPageReads = 0;
7448 dev->nPageWrites = 0;
7449 dev->nBlockErasures = 0;
7451 dev->nRetriedWrites = 0;
7453 dev->nRetiredBlocks = 0;
7455 yaffs_VerifyFreeChunks(dev);
7456 yaffs_VerifyBlocks(dev);
7459 /* Clean up any aborted checkpoint data */
7460 if(!dev->isCheckpointed && dev->blocksInCheckpoint > 0)
7461 yaffs_InvalidateCheckpoint(dev);
7463 T(YAFFS_TRACE_TRACING,
7464 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7469 void yaffs_Deinitialise(yaffs_Device *dev)
7471 if (dev->isMounted) {
7474 yaffs_DeinitialiseBlocks(dev);
7475 yaffs_DeinitialiseTnodes(dev);
7476 yaffs_DeinitialiseObjects(dev);
7477 if (dev->nShortOpCaches > 0 &&
7480 for (i = 0; i < dev->nShortOpCaches; i++) {
7481 if (dev->srCache[i].data)
7482 YFREE(dev->srCache[i].data);
7483 dev->srCache[i].data = NULL;
7486 YFREE(dev->srCache);
7487 dev->srCache = NULL;
7490 YFREE(dev->gcCleanupList);
7492 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
7493 YFREE(dev->tempBuffer[i].buffer);
7497 if (dev->deinitialiseNAND)
7498 dev->deinitialiseNAND(dev);
7502 static int yaffs_CountFreeChunks(yaffs_Device *dev)
7507 yaffs_BlockInfo *blk;
7509 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7511 blk = yaffs_GetBlockInfo(dev, b);
7513 switch (blk->blockState) {
7514 case YAFFS_BLOCK_STATE_EMPTY:
7515 case YAFFS_BLOCK_STATE_ALLOCATING:
7516 case YAFFS_BLOCK_STATE_COLLECTING:
7517 case YAFFS_BLOCK_STATE_FULL:
7519 (dev->nChunksPerBlock - blk->pagesInUse +
7520 blk->softDeletions);
7530 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
7532 /* This is what we report to the outside world */
7535 int nDirtyCacheChunks;
7536 int blocksForCheckpoint;
7540 nFree = dev->nFreeChunks;
7542 nFree = yaffs_CountFreeChunks(dev);
7545 nFree += dev->nDeletedFiles;
7547 /* Now count the number of dirty chunks in the cache and subtract those */
7549 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7550 if (dev->srCache[i].dirty)
7551 nDirtyCacheChunks++;
7554 nFree -= nDirtyCacheChunks;
7556 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7558 /* Now we figure out how much to reserve for the checkpoint and report that... */
7559 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7560 if (blocksForCheckpoint < 0)
7561 blocksForCheckpoint = 0;
7563 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7572 static int yaffs_freeVerificationFailures;
7574 static void yaffs_VerifyFreeChunks(yaffs_Device *dev)
7579 if (yaffs_SkipVerification(dev))
7582 counted = yaffs_CountFreeChunks(dev);
7584 difference = dev->nFreeChunks - counted;
7587 T(YAFFS_TRACE_ALWAYS,
7588 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7589 dev->nFreeChunks, counted, difference));
7590 yaffs_freeVerificationFailures++;
7594 /*---------------------------------------- YAFFS test code ----------------------*/
7596 #define yaffs_CheckStruct(structure, syze, name) \
7598 if (sizeof(structure) != syze) { \
7599 T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
7600 name, syze, sizeof(structure))); \
7601 return YAFFS_FAIL; \
7605 static int yaffs_CheckStructures(void)
7607 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
7608 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
7609 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
7610 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7611 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode");
7613 #ifndef CONFIG_YAFFS_WINCE
7614 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");