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.120 2010-03-15 23:10:34 charles Exp $";
18 #include "yaffs_trace.h"
20 #include "yaffsinterface.h"
21 #include "yaffs_guts.h"
22 #include "yaffs_tagsvalidity.h"
23 #include "yaffs_getblockinfo.h"
25 #include "yaffs_tagscompat.h"
26 #ifndef CONFIG_YAFFS_USE_OWN_SORT
27 #include "yaffs_qsort.h"
29 #include "yaffs_nand.h"
31 #include "yaffs_checkptrw.h"
33 #include "yaffs_nand.h"
34 #include "yaffs_packedtags2.h"
37 /* Note YAFFS_GC_GOOD_ENOUGH must be <= YAFFS_GC_PASSIVE_THRESHOLD */
38 #define YAFFS_GC_GOOD_ENOUGH 2
39 #define YAFFS_GC_PASSIVE_THRESHOLD 4
40 #define YAFFS_SMALL_HOLE_THRESHOLD 3
42 #include "yaffs_ecc.h"
45 /* Robustification (if it ever comes about...) */
46 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND);
47 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
49 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
51 const yaffs_ExtendedTags *tags);
52 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
53 const yaffs_ExtendedTags *tags);
55 /* Other local prototypes */
56 static void yaffs_UpdateParent(yaffs_Object *obj);
57 static int yaffs_UnlinkObject(yaffs_Object *obj);
58 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
60 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
62 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev,
64 yaffs_ExtendedTags *tags,
66 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
67 int chunkInNAND, int inScan);
69 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
70 yaffs_ObjectType type);
71 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
73 static int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name,
74 int force, int isShrink, int shadows);
75 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
76 static int yaffs_CheckStructures(void);
77 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
78 int chunkOffset, int *limit);
79 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
81 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev, int blockNo);
84 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
87 static int yaffs_UnlinkWorker(yaffs_Object *obj);
89 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
92 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
93 yaffs_BlockInfo **blockUsedPtr);
95 static void yaffs_VerifyFreeChunks(yaffs_Device *dev);
97 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
99 static void yaffs_VerifyDirectory(yaffs_Object *directory);
100 #ifdef YAFFS_PARANOID
101 static int yaffs_CheckFileSanity(yaffs_Object *in);
103 #define yaffs_CheckFileSanity(in)
106 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
107 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
109 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
111 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
112 yaffs_ExtendedTags *tags);
114 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
116 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
117 yaffs_FileStructure *fStruct,
120 static int yaffs_HandleHole(yaffs_Object *obj, loff_t newSize);
121 static void yaffs_SkipRestOfBlock(yaffs_Device *dev);
122 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
125 yaffs_ExtendedTags *tags);
127 /* Function to calculate chunk and offset */
129 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut,
135 chunk = (__u32)(addr >> dev->chunkShift);
137 if (dev->chunkDiv == 1) {
138 /* easy power of 2 case */
139 offset = (__u32)(addr & dev->chunkMask);
141 /* Non power-of-2 case */
145 chunk /= dev->chunkDiv;
147 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
148 offset = (__u32)(addr - chunkBase);
155 /* Function to return the number of shifts for a power of 2 greater than or
156 * equal to the given number
157 * Note we don't try to cater for all possible numbers and this does not have to
158 * be hellishly efficient.
161 static __u32 ShiftsGE(__u32 x)
166 nShifts = extraBits = 0;
181 /* Function to return the number of shifts to get a 1 in bit 0
184 static __u32 Shifts(__u32 x)
204 * Temporary buffer manipulations.
207 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
210 __u8 *buf = (__u8 *)1;
212 memset(dev->tempBuffer, 0, sizeof(dev->tempBuffer));
214 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
215 dev->tempBuffer[i].line = 0; /* not in use */
216 dev->tempBuffer[i].buffer = buf =
217 YMALLOC_DMA(dev->param.totalBytesPerChunk);
220 return buf ? YAFFS_OK : YAFFS_FAIL;
223 __u8 *yaffs_GetTempBuffer(yaffs_Device *dev, int lineNo)
228 if (dev->tempInUse > dev->maxTemp)
229 dev->maxTemp = dev->tempInUse;
231 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
232 if (dev->tempBuffer[i].line == 0) {
233 dev->tempBuffer[i].line = lineNo;
234 if ((i + 1) > dev->maxTemp) {
235 dev->maxTemp = i + 1;
236 for (j = 0; j <= i; j++)
237 dev->tempBuffer[j].maxLine =
238 dev->tempBuffer[j].line;
241 return dev->tempBuffer[i].buffer;
245 T(YAFFS_TRACE_BUFFERS,
246 (TSTR("Out of temp buffers at line %d, other held by lines:"),
248 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
249 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
251 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
254 * If we got here then we have to allocate an unmanaged one
258 dev->unmanagedTempAllocations++;
259 return YMALLOC(dev->nDataBytesPerChunk);
263 void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer,
270 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
271 if (dev->tempBuffer[i].buffer == buffer) {
272 dev->tempBuffer[i].line = 0;
278 /* assume it is an unmanaged one. */
279 T(YAFFS_TRACE_BUFFERS,
280 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
283 dev->unmanagedTempDeallocations++;
289 * Determine if we have a managed buffer.
291 int yaffs_IsManagedTempBuffer(yaffs_Device *dev, const __u8 *buffer)
295 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
296 if (dev->tempBuffer[i].buffer == buffer)
300 for (i = 0; i < dev->param.nShortOpCaches; i++) {
301 if (dev->srCache[i].data == buffer)
305 if (buffer == dev->checkpointBuffer)
308 T(YAFFS_TRACE_ALWAYS,
309 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
316 * Chunk bitmap manipulations
319 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
321 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
323 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
327 return dev->chunkBits +
328 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
331 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
333 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
334 chunk < 0 || chunk >= dev->param.nChunksPerBlock) {
336 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),
342 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device *dev, int blk)
344 __u8 *blkBits = yaffs_BlockBits(dev, blk);
346 memset(blkBits, 0, dev->chunkBitmapStride);
349 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device *dev, int blk, int chunk)
351 __u8 *blkBits = yaffs_BlockBits(dev, blk);
353 yaffs_VerifyChunkBitId(dev, blk, chunk);
355 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
358 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device *dev, int blk, int chunk)
360 __u8 *blkBits = yaffs_BlockBits(dev, blk);
362 yaffs_VerifyChunkBitId(dev, blk, chunk);
364 blkBits[chunk / 8] |= (1 << (chunk & 7));
367 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device *dev, int blk, int chunk)
369 __u8 *blkBits = yaffs_BlockBits(dev, blk);
370 yaffs_VerifyChunkBitId(dev, blk, chunk);
372 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
375 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device *dev, int blk)
377 __u8 *blkBits = yaffs_BlockBits(dev, blk);
379 for (i = 0; i < dev->chunkBitmapStride; i++) {
387 static int yaffs_CountChunkBits(yaffs_Device *dev, int blk)
389 __u8 *blkBits = yaffs_BlockBits(dev, blk);
392 for (i = 0; i < dev->chunkBitmapStride; i++) {
409 static int yaffs_SkipVerification(yaffs_Device *dev)
412 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
415 static int yaffs_SkipFullVerification(yaffs_Device *dev)
418 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
421 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
424 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
427 static const char *blockStateName[] = {
440 static void yaffs_VerifyBlock(yaffs_Device *dev, yaffs_BlockInfo *bi, int n)
445 if (yaffs_SkipVerification(dev))
448 /* Report illegal runtime states */
449 if (bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
450 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has undefined state %d"TENDSTR), n, bi->blockState));
452 switch (bi->blockState) {
453 case YAFFS_BLOCK_STATE_UNKNOWN:
454 case YAFFS_BLOCK_STATE_SCANNING:
455 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
456 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has bad run-state %s"TENDSTR),
457 n, blockStateName[bi->blockState]));
460 /* Check pages in use and soft deletions are legal */
462 actuallyUsed = bi->pagesInUse - bi->softDeletions;
464 if (bi->pagesInUse < 0 || bi->pagesInUse > dev->param.nChunksPerBlock ||
465 bi->softDeletions < 0 || bi->softDeletions > dev->param.nChunksPerBlock ||
466 actuallyUsed < 0 || actuallyUsed > dev->param.nChunksPerBlock)
467 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
468 n, bi->pagesInUse, bi->softDeletions));
471 /* Check chunk bitmap legal */
472 inUse = yaffs_CountChunkBits(dev, n);
473 if (inUse != bi->pagesInUse)
474 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
475 n, bi->pagesInUse, inUse));
477 /* Check that the sequence number is valid.
478 * Ten million is legal, but is very unlikely
480 if (dev->param.isYaffs2 &&
481 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
482 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000))
483 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has suspect sequence number of %d"TENDSTR),
484 n, bi->sequenceNumber));
487 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev, yaffs_BlockInfo *bi,
490 yaffs_VerifyBlock(dev, bi, n);
492 /* After collection the block should be in the erased state */
493 /* This will need to change if we do partial gc */
495 if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
496 bi->blockState != YAFFS_BLOCK_STATE_EMPTY) {
497 T(YAFFS_TRACE_ERROR, (TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
502 static void yaffs_VerifyBlocks(yaffs_Device *dev)
505 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
506 int nIllegalBlockStates = 0;
508 if (yaffs_SkipVerification(dev))
511 memset(nBlocksPerState, 0, sizeof(nBlocksPerState));
513 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
514 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, i);
515 yaffs_VerifyBlock(dev, bi, i);
517 if (bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
518 nBlocksPerState[bi->blockState]++;
520 nIllegalBlockStates++;
523 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
524 T(YAFFS_TRACE_VERIFY, (TSTR("Block summary"TENDSTR)));
526 T(YAFFS_TRACE_VERIFY, (TSTR("%d blocks have illegal states"TENDSTR), nIllegalBlockStates));
527 if (nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
528 T(YAFFS_TRACE_VERIFY, (TSTR("Too many allocating blocks"TENDSTR)));
530 for (i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
531 T(YAFFS_TRACE_VERIFY,
532 (TSTR("%s %d blocks"TENDSTR),
533 blockStateName[i], nBlocksPerState[i]));
535 if (dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
536 T(YAFFS_TRACE_VERIFY,
537 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
538 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
540 if (dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
541 T(YAFFS_TRACE_VERIFY,
542 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
543 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
545 if (nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
546 T(YAFFS_TRACE_VERIFY,
547 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
548 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
550 T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
555 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
556 * case those tests will not be performed.
558 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
560 if (obj && yaffs_SkipVerification(obj->myDev))
563 if (!(tags && obj && oh)) {
564 T(YAFFS_TRACE_VERIFY,
565 (TSTR("Verifying object header tags %p obj %p oh %p"TENDSTR),
570 if (oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
571 oh->type > YAFFS_OBJECT_TYPE_MAX)
572 T(YAFFS_TRACE_VERIFY,
573 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
574 tags->objectId, oh->type));
576 if (tags->objectId != obj->objectId)
577 T(YAFFS_TRACE_VERIFY,
578 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
579 tags->objectId, obj->objectId));
583 * Check that the object's parent ids match if parentCheck requested.
585 * Tests do not apply to the root object.
588 if (parentCheck && tags->objectId > 1 && !obj->parent)
589 T(YAFFS_TRACE_VERIFY,
590 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
591 tags->objectId, oh->parentObjectId));
593 if (parentCheck && obj->parent &&
594 oh->parentObjectId != obj->parent->objectId &&
595 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
596 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
597 T(YAFFS_TRACE_VERIFY,
598 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
599 tags->objectId, oh->parentObjectId, obj->parent->objectId));
601 if (tags->objectId > 1 && oh->name[0] == 0) /* Null name */
602 T(YAFFS_TRACE_VERIFY,
603 (TSTR("Obj %d header name is NULL"TENDSTR),
606 if (tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
607 T(YAFFS_TRACE_VERIFY,
608 (TSTR("Obj %d header name is 0xFF"TENDSTR),
614 static int yaffs_VerifyTnodeWorker(yaffs_Object *obj, yaffs_Tnode *tn,
615 __u32 level, int chunkOffset)
618 yaffs_Device *dev = obj->myDev;
624 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
625 if (tn->internal[i]) {
626 ok = yaffs_VerifyTnodeWorker(obj,
629 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
632 } else if (level == 0) {
633 yaffs_ExtendedTags tags;
634 __u32 objectId = obj->objectId;
636 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
638 for (i = 0; i < YAFFS_NTNODES_LEVEL0; i++) {
639 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
642 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
643 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
644 if (tags.objectId != objectId || tags.chunkId != chunkOffset) {
645 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
646 objectId, chunkOffset, theChunk,
647 tags.objectId, tags.chunkId));
660 static void yaffs_VerifyFile(yaffs_Object *obj)
662 int requiredTallness;
668 yaffs_ExtendedTags tags;
675 if (yaffs_SkipVerification(obj->myDev))
679 objectId = obj->objectId;
681 /* Check file size is consistent with tnode depth */
682 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
683 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
684 requiredTallness = 0;
686 x >>= YAFFS_TNODES_INTERNAL_BITS;
690 actualTallness = obj->variant.fileVariant.topLevel;
692 /* Check that the chunks in the tnode tree are all correct.
693 * We do this by scanning through the tnode tree and
694 * checking the tags for every chunk match.
697 if (yaffs_SkipNANDVerification(dev))
700 for (i = 1; i <= lastChunk; i++) {
701 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant, i);
704 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
706 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
707 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
708 if (tags.objectId != objectId || tags.chunkId != i) {
709 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
710 objectId, i, theChunk,
711 tags.objectId, tags.chunkId));
719 static void yaffs_VerifyHardLink(yaffs_Object *obj)
721 if (obj && yaffs_SkipVerification(obj->myDev))
724 /* Verify sane equivalent object */
727 static void yaffs_VerifySymlink(yaffs_Object *obj)
729 if (obj && yaffs_SkipVerification(obj->myDev))
732 /* Verify symlink string */
735 static void yaffs_VerifySpecial(yaffs_Object *obj)
737 if (obj && yaffs_SkipVerification(obj->myDev))
741 static void yaffs_VerifyObject(yaffs_Object *obj)
750 __u32 chunkShouldNotBeDeleted;
756 if (obj->beingCreated)
761 if (yaffs_SkipVerification(dev))
764 /* Check sane object header chunk */
766 chunkMin = dev->internalStartBlock * dev->param.nChunksPerBlock;
767 chunkMax = (dev->internalEndBlock+1) * dev->param.nChunksPerBlock - 1;
769 chunkInRange = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
770 chunkIdOk = chunkInRange || (obj->hdrChunk == 0);
771 chunkValid = chunkInRange &&
772 yaffs_CheckChunkBit(dev,
773 obj->hdrChunk / dev->param.nChunksPerBlock,
774 obj->hdrChunk % dev->param.nChunksPerBlock);
775 chunkShouldNotBeDeleted = chunkInRange && !chunkValid;
778 (!chunkIdOk || chunkShouldNotBeDeleted)) {
779 T(YAFFS_TRACE_VERIFY,
780 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
781 obj->objectId, obj->hdrChunk,
782 chunkIdOk ? "" : ",out of range",
783 chunkShouldNotBeDeleted ? ",marked as deleted" : ""));
786 if (chunkValid && !yaffs_SkipNANDVerification(dev)) {
787 yaffs_ExtendedTags tags;
788 yaffs_ObjectHeader *oh;
789 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
791 oh = (yaffs_ObjectHeader *)buffer;
793 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk, buffer,
796 yaffs_VerifyObjectHeader(obj, oh, &tags, 1);
798 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
801 /* Verify it has a parent */
802 if (obj && !obj->fake &&
803 (!obj->parent || obj->parent->myDev != dev)) {
804 T(YAFFS_TRACE_VERIFY,
805 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
806 obj->objectId, obj->parent));
809 /* Verify parent is a directory */
810 if (obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
811 T(YAFFS_TRACE_VERIFY,
812 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
813 obj->objectId, obj->parent->variantType));
816 switch (obj->variantType) {
817 case YAFFS_OBJECT_TYPE_FILE:
818 yaffs_VerifyFile(obj);
820 case YAFFS_OBJECT_TYPE_SYMLINK:
821 yaffs_VerifySymlink(obj);
823 case YAFFS_OBJECT_TYPE_DIRECTORY:
824 yaffs_VerifyDirectory(obj);
826 case YAFFS_OBJECT_TYPE_HARDLINK:
827 yaffs_VerifyHardLink(obj);
829 case YAFFS_OBJECT_TYPE_SPECIAL:
830 yaffs_VerifySpecial(obj);
832 case YAFFS_OBJECT_TYPE_UNKNOWN:
834 T(YAFFS_TRACE_VERIFY,
835 (TSTR("Obj %d has illegaltype %d"TENDSTR),
836 obj->objectId, obj->variantType));
841 static void yaffs_VerifyObjects(yaffs_Device *dev)
845 struct ylist_head *lh;
847 if (yaffs_SkipVerification(dev))
850 /* Iterate through the objects in each hash entry */
852 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
853 ylist_for_each(lh, &dev->objectBucket[i].list) {
855 obj = ylist_entry(lh, yaffs_Object, hashLink);
856 yaffs_VerifyObject(obj);
864 * Simple hash function. Needs to have a reasonable spread
867 static Y_INLINE int yaffs_HashFunction(int n)
870 return n % YAFFS_NOBJECT_BUCKETS;
874 * Access functions to useful fake objects.
875 * Note that root might have a presence in NAND if permissions are set.
878 yaffs_Object *yaffs_Root(yaffs_Device *dev)
883 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
885 return dev->lostNFoundDir;
890 * Erased NAND checking functions
893 int yaffs_CheckFF(__u8 *buffer, int nBytes)
895 /* Horrible, slow implementation */
904 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
907 int retval = YAFFS_OK;
908 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
909 yaffs_ExtendedTags tags;
912 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
914 if (tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
917 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
918 T(YAFFS_TRACE_NANDACCESS,
919 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
923 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
930 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
933 yaffs_ExtendedTags *tags)
935 int retval = YAFFS_OK;
936 yaffs_ExtendedTags tempTags;
937 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
940 result = yaffs_ReadChunkWithTagsFromNAND(dev,chunkInNAND,buffer,&tempTags);
941 if(memcmp(buffer,data,dev->nDataBytesPerChunk) ||
942 tempTags.objectId != tags->objectId ||
943 tempTags.chunkId != tags->chunkId ||
944 tempTags.byteCount != tags->byteCount)
947 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
952 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
954 yaffs_ExtendedTags *tags,
961 yaffs_InvalidateCheckpoint(dev);
964 yaffs_BlockInfo *bi = 0;
967 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
973 /* First check this chunk is erased, if it needs
974 * checking. The checking policy (unless forced
975 * always on) is as follows:
977 * Check the first page we try to write in a block.
978 * If the check passes then we don't need to check any
979 * more. If the check fails, we check again...
980 * If the block has been erased, we don't need to check.
982 * However, if the block has been prioritised for gc,
983 * then we think there might be something odd about
984 * this block and stop using it.
986 * Rationale: We should only ever see chunks that have
987 * not been erased if there was a partially written
988 * chunk due to power loss. This checking policy should
989 * catch that case with very few checks and thus save a
990 * lot of checks that are most likely not needed.
993 * If an erase check fails or the write fails we skip the
997 /* let's give it a try */
1000 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
1001 bi->skipErasedCheck = 0;
1003 if (!bi->skipErasedCheck) {
1004 erasedOk = yaffs_CheckChunkErased(dev, chunk);
1005 if (erasedOk != YAFFS_OK) {
1006 T(YAFFS_TRACE_ERROR,
1007 (TSTR("**>> yaffs chunk %d was not erased"
1010 /* If not erased, delete this one,
1011 * skip rest of block and
1012 * try another chunk */
1013 yaffs_DeleteChunk(dev,chunk,1,__LINE__);
1014 yaffs_SkipRestOfBlock(dev);
1019 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
1022 if(!bi->skipErasedCheck)
1023 writeOk = yaffs_VerifyChunkWritten(dev, chunk, data, tags);
1025 if (writeOk != YAFFS_OK) {
1026 /* Clean up aborted write, skip to next block and
1027 * try another chunk */
1028 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
1032 bi->skipErasedCheck = 1;
1034 /* Copy the data into the robustification buffer */
1035 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1037 } while (writeOk != YAFFS_OK &&
1038 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1044 T(YAFFS_TRACE_ERROR,
1045 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1048 dev->nRetriedWrites += (attempts - 1);
1056 * Oldest Dirty Sequence Number handling.
1059 /* yaffs_CalcOldestDirtySequence()
1060 * yaffs_FindOldestDirtySequence()
1061 * Calculate the oldest dirty sequence number if we don't know it.
1063 static void yaffs_CalcOldestDirtySequence(yaffs_Device *dev)
1067 unsigned blockNo = 0;
1070 if(!dev->param.isYaffs2)
1073 /* Find the oldest dirty sequence number. */
1074 seq = dev->sequenceNumber + 1;
1076 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
1077 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
1078 (b->pagesInUse - b->softDeletions) < dev->param.nChunksPerBlock &&
1079 b->sequenceNumber < seq) {
1080 seq = b->sequenceNumber;
1087 dev->oldestDirtySequence = seq;
1088 dev->oldestDirtyBlock = blockNo;
1094 static void yaffs_FindOldestDirtySequence(yaffs_Device *dev)
1096 if(dev->param.isYaffs2 && !dev->oldestDirtySequence)
1097 yaffs_CalcOldestDirtySequence(dev);
1101 * yaffs_ClearOldestDirtySequence()
1102 * Called when a block is erased or marked bad. (ie. when its sequenceNumber
1103 * becomes invalid). If the value matches the oldest then we clear
1104 * dev->oldestDirtySequence to force its recomputation.
1106 static void yaffs_ClearOldestDirtySequence(yaffs_Device *dev, yaffs_BlockInfo *bi)
1109 if(!dev->param.isYaffs2)
1112 if(!bi || bi->sequenceNumber == dev->oldestDirtySequence){
1113 dev->oldestDirtySequence = 0;
1114 dev->oldestDirtyBlock = 0;
1119 * yaffs_UpdateOldestDirtySequence()
1120 * Update the oldest dirty sequence number whenever we dirty a block.
1121 * Only do this if the oldestDirtySequence is actually being tracked.
1123 static void yaffs_UpdateOldestDirtySequence(yaffs_Device *dev, unsigned blockNo, yaffs_BlockInfo *bi)
1125 if(dev->param.isYaffs2 && dev->oldestDirtySequence){
1126 if(dev->oldestDirtySequence > bi->sequenceNumber){
1127 dev->oldestDirtySequence = bi->sequenceNumber;
1128 dev->oldestDirtyBlock = blockNo;
1134 * Block retiring for handling a broken block.
1137 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND)
1139 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1141 yaffs_InvalidateCheckpoint(dev);
1143 yaffs_ClearOldestDirtySequence(dev,bi);
1145 if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
1146 if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
1147 T(YAFFS_TRACE_ALWAYS, (TSTR(
1148 "yaffs: Failed to mark bad and erase block %d"
1149 TENDSTR), blockInNAND));
1151 yaffs_ExtendedTags tags;
1152 int chunkId = blockInNAND * dev->param.nChunksPerBlock;
1154 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
1156 memset(buffer, 0xff, dev->nDataBytesPerChunk);
1157 yaffs_InitialiseTags(&tags);
1158 tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
1159 if (dev->param.writeChunkWithTagsToNAND(dev, chunkId -
1160 dev->chunkOffset, buffer, &tags) != YAFFS_OK)
1161 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
1162 TCONT("write bad block marker to block %d")
1163 TENDSTR), blockInNAND));
1165 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
1169 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1170 bi->gcPrioritise = 0;
1171 bi->needsRetiring = 0;
1173 dev->nRetiredBlocks++;
1177 * Functions for robustisizing TODO
1181 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
1183 const yaffs_ExtendedTags *tags)
1186 chunkInNAND=chunkInNAND;
1191 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
1192 const yaffs_ExtendedTags *tags)
1195 chunkInNAND=chunkInNAND;
1199 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1201 if (!bi->gcPrioritise) {
1202 bi->gcPrioritise = 1;
1203 dev->hasPendingPrioritisedGCs = 1;
1204 bi->chunkErrorStrikes++;
1206 if (bi->chunkErrorStrikes > 3) {
1207 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1208 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1214 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
1217 int blockInNAND = chunkInNAND / dev->param.nChunksPerBlock;
1218 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1220 yaffs_HandleChunkError(dev, bi);
1223 /* Was an actual write failure, so mark the block for retirement */
1224 bi->needsRetiring = 1;
1225 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1226 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1229 /* Delete the chunk */
1230 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1231 yaffs_SkipRestOfBlock(dev);
1235 /*---------------- Name handling functions ------------*/
1237 static __u16 yaffs_CalcNameSum(const YCHAR *name)
1242 const YUCHAR *bname = (const YUCHAR *) name;
1244 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1246 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1247 sum += yaffs_toupper(*bname) * i;
1249 sum += (*bname) * i;
1258 static void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
1260 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1261 memset(obj->shortName, 0, sizeof(YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1262 if (name && yaffs_strnlen(name,YAFFS_SHORT_NAME_LENGTH+1) <= YAFFS_SHORT_NAME_LENGTH)
1263 yaffs_strcpy(obj->shortName, name);
1265 obj->shortName[0] = _Y('\0');
1267 obj->sum = yaffs_CalcNameSum(name);
1270 /*-------------------- TNODES -------------------
1272 * List of spare tnodes
1273 * The list is hooked together using the first pointer
1277 /* yaffs_CreateTnodes creates a bunch more tnodes and
1278 * adds them to the tnode free list.
1279 * Don't use this function directly
1281 static Y_INLINE int yaffs_CalcTnodeSize(yaffs_Device *dev)
1284 /* Calculate the tnode size in bytes for variable width tnode support.
1285 * Must be a multiple of 32-bits */
1286 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1288 if (tnodeSize < sizeof(yaffs_Tnode))
1289 tnodeSize = sizeof(yaffs_Tnode);
1293 static int yaffs_CreateTnodes(yaffs_Device *dev, int nTnodes)
1296 int tnodeSize = yaffs_CalcTnodeSize(dev);
1297 yaffs_Tnode *newTnodes;
1301 yaffs_TnodeList *tnl;
1307 /* make these things */
1309 newTnodes = YMALLOC(nTnodes * tnodeSize);
1310 mem = (__u8 *)newTnodes;
1313 T(YAFFS_TRACE_ERROR,
1314 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1318 /* Hook them into the free list */
1320 for (i = 0; i < nTnodes - 1; i++) {
1321 newTnodes[i].internal[0] = &newTnodes[i + 1];
1322 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1323 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1327 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1328 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1329 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1331 dev->freeTnodes = newTnodes;
1333 /* New hookup for wide tnodes */
1334 for (i = 0; i < nTnodes - 1; i++) {
1335 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1336 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1337 curr->internal[0] = next;
1340 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1341 curr->internal[0] = dev->freeTnodes;
1342 dev->freeTnodes = (yaffs_Tnode *)mem;
1347 dev->nFreeTnodes += nTnodes;
1348 dev->nTnodesCreated += nTnodes;
1350 /* Now add this bunch of tnodes to a list for freeing up.
1351 * NB If we can't add this to the management list it isn't fatal
1352 * but it just means we can't free this bunch of tnodes later.
1355 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1357 T(YAFFS_TRACE_ERROR,
1359 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1362 tnl->tnodes = newTnodes;
1363 tnl->next = dev->allocatedTnodeList;
1364 dev->allocatedTnodeList = tnl;
1367 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1372 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1374 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device *dev)
1376 yaffs_Tnode *tn = NULL;
1378 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1379 tn = YMALLOC(yaffs_CalcTnodeSize(dev));
1381 dev->nTnodesCreated++;
1383 /* If there are none left make more */
1384 if (!dev->freeTnodes)
1385 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1387 if (dev->freeTnodes) {
1388 tn = dev->freeTnodes;
1389 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1390 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1391 /* Hoosterman, this thing looks like it isn't in the list */
1392 T(YAFFS_TRACE_ALWAYS,
1393 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1396 dev->freeTnodes = dev->freeTnodes->internal[0];
1400 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1405 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
1407 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1408 int tnodeSize = yaffs_CalcTnodeSize(dev);
1411 memset(tn, 0, tnodeSize);
1416 /* FreeTnode frees up a tnode and puts it back on the free list */
1417 static void yaffs_FreeTnode(yaffs_Device *dev, yaffs_Tnode *tn)
1420 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1422 dev->nTnodesCreated--;
1424 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1425 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1426 /* Hoosterman, this thing looks like it is already in the list */
1427 T(YAFFS_TRACE_ALWAYS,
1428 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1430 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1432 tn->internal[0] = dev->freeTnodes;
1433 dev->freeTnodes = tn;
1437 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1440 static void yaffs_DeinitialiseTnodes(yaffs_Device *dev)
1442 /* Free the list of allocated tnodes */
1443 yaffs_TnodeList *tmp;
1445 while (dev->allocatedTnodeList) {
1446 tmp = dev->allocatedTnodeList->next;
1448 YFREE(dev->allocatedTnodeList->tnodes);
1449 YFREE(dev->allocatedTnodeList);
1450 dev->allocatedTnodeList = tmp;
1454 dev->freeTnodes = NULL;
1455 dev->nFreeTnodes = 0;
1456 dev->nTnodesCreated = 0;
1459 static void yaffs_InitialiseTnodes(yaffs_Device *dev)
1461 dev->allocatedTnodeList = NULL;
1462 dev->freeTnodes = NULL;
1463 dev->nFreeTnodes = 0;
1464 dev->nTnodesCreated = 0;
1468 void yaffs_LoadLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
1471 __u32 *map = (__u32 *)tn;
1477 pos &= YAFFS_TNODES_LEVEL0_MASK;
1478 val >>= dev->chunkGroupBits;
1480 bitInMap = pos * dev->tnodeWidth;
1481 wordInMap = bitInMap / 32;
1482 bitInWord = bitInMap & (32 - 1);
1484 mask = dev->tnodeMask << bitInWord;
1486 map[wordInMap] &= ~mask;
1487 map[wordInMap] |= (mask & (val << bitInWord));
1489 if (dev->tnodeWidth > (32 - bitInWord)) {
1490 bitInWord = (32 - bitInWord);
1492 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1493 map[wordInMap] &= ~mask;
1494 map[wordInMap] |= (mask & (val >> bitInWord));
1498 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
1501 __u32 *map = (__u32 *)tn;
1507 pos &= YAFFS_TNODES_LEVEL0_MASK;
1509 bitInMap = pos * dev->tnodeWidth;
1510 wordInMap = bitInMap / 32;
1511 bitInWord = bitInMap & (32 - 1);
1513 val = map[wordInMap] >> bitInWord;
1515 if (dev->tnodeWidth > (32 - bitInWord)) {
1516 bitInWord = (32 - bitInWord);
1518 val |= (map[wordInMap] << bitInWord);
1521 val &= dev->tnodeMask;
1522 val <<= dev->chunkGroupBits;
1527 /* ------------------- End of individual tnode manipulation -----------------*/
1529 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1530 * The look up tree is represented by the top tnode and the number of topLevel
1531 * in the tree. 0 means only the level 0 tnode is in the tree.
1534 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1535 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
1536 yaffs_FileStructure *fStruct,
1539 yaffs_Tnode *tn = fStruct->top;
1541 int requiredTallness;
1542 int level = fStruct->topLevel;
1546 /* Check sane level and chunk Id */
1547 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
1550 if (chunkId > YAFFS_MAX_CHUNK_ID)
1553 /* First check we're tall enough (ie enough topLevel) */
1555 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1556 requiredTallness = 0;
1558 i >>= YAFFS_TNODES_INTERNAL_BITS;
1562 if (requiredTallness > fStruct->topLevel)
1563 return NULL; /* Not tall enough, so we can't find it */
1565 /* Traverse down to level 0 */
1566 while (level > 0 && tn) {
1567 tn = tn->internal[(chunkId >>
1568 (YAFFS_TNODES_LEVEL0_BITS +
1570 YAFFS_TNODES_INTERNAL_BITS)) &
1571 YAFFS_TNODES_INTERNAL_MASK];
1578 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1579 * This happens in two steps:
1580 * 1. If the tree isn't tall enough, then make it taller.
1581 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1583 * Used when modifying the tree.
1585 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1586 * be plugged into the ttree.
1589 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
1590 yaffs_FileStructure *fStruct,
1592 yaffs_Tnode *passedTn)
1594 int requiredTallness;
1602 /* Check sane level and page Id */
1603 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
1606 if (chunkId > YAFFS_MAX_CHUNK_ID)
1609 /* First check we're tall enough (ie enough topLevel) */
1611 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1612 requiredTallness = 0;
1614 x >>= YAFFS_TNODES_INTERNAL_BITS;
1619 if (requiredTallness > fStruct->topLevel) {
1620 /* Not tall enough, gotta make the tree taller */
1621 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1623 tn = yaffs_GetTnode(dev);
1626 tn->internal[0] = fStruct->top;
1628 fStruct->topLevel++;
1630 T(YAFFS_TRACE_ERROR,
1631 (TSTR("yaffs: no more tnodes" TENDSTR)));
1637 /* Traverse down to level 0, adding anything we need */
1639 l = fStruct->topLevel;
1643 while (l > 0 && tn) {
1645 (YAFFS_TNODES_LEVEL0_BITS +
1646 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1647 YAFFS_TNODES_INTERNAL_MASK;
1650 if ((l > 1) && !tn->internal[x]) {
1651 /* Add missing non-level-zero tnode */
1652 tn->internal[x] = yaffs_GetTnode(dev);
1653 if(!tn->internal[x])
1655 } else if (l == 1) {
1656 /* Looking from level 1 at level 0 */
1658 /* If we already have one, then release it.*/
1659 if (tn->internal[x])
1660 yaffs_FreeTnode(dev, tn->internal[x]);
1661 tn->internal[x] = passedTn;
1663 } else if (!tn->internal[x]) {
1664 /* Don't have one, none passed in */
1665 tn->internal[x] = yaffs_GetTnode(dev);
1666 if(!tn->internal[x])
1671 tn = tn->internal[x];
1675 /* top is level 0 */
1677 memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1678 yaffs_FreeTnode(dev, passedTn);
1685 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
1686 yaffs_ExtendedTags *tags, int objectId,
1691 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1692 if (yaffs_CheckChunkBit(dev, theChunk / dev->param.nChunksPerBlock,
1693 theChunk % dev->param.nChunksPerBlock)) {
1695 if(dev->chunkGroupSize == 1)
1698 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1700 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1712 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1713 * chunks and tnodes in the file
1714 * Returns 1 if the tree was deleted.
1715 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1718 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
1719 int chunkOffset, int *limit)
1724 yaffs_ExtendedTags tags;
1726 yaffs_Device *dev = in->myDev;
1732 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1734 if (tn->internal[i]) {
1735 if (limit && (*limit) < 0) {
1739 yaffs_DeleteWorker(in,
1747 YAFFS_TNODES_INTERNAL_BITS)
1752 yaffs_FreeTnode(dev,
1755 tn->internal[i] = NULL;
1759 return (allDone) ? 1 : 0;
1760 } else if (level == 0) {
1763 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1765 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1768 chunkInInode = (chunkOffset <<
1769 YAFFS_TNODES_LEVEL0_BITS) + i;
1772 yaffs_FindChunkInGroup(dev,
1778 if (foundChunk > 0) {
1779 yaffs_DeleteChunk(dev,
1784 *limit = *limit - 1;
1791 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1795 return (i < 0) ? 1 : 0;
1805 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1807 yaffs_BlockInfo *theBlock;
1810 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1812 blockNo = chunk / dev->param.nChunksPerBlock;
1813 theBlock = yaffs_GetBlockInfo(dev, blockNo);
1815 theBlock->softDeletions++;
1817 yaffs_UpdateOldestDirtySequence(dev, blockNo, theBlock);
1821 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1822 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1824 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1827 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1828 __u32 level, int chunkOffset)
1833 yaffs_Device *dev = in->myDev;
1838 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1840 if (tn->internal[i]) {
1842 yaffs_SoftDeleteWorker(in,
1848 YAFFS_TNODES_INTERNAL_BITS)
1851 yaffs_FreeTnode(dev,
1854 tn->internal[i] = NULL;
1856 /* Hoosterman... how could this happen? */
1860 return (allDone) ? 1 : 0;
1861 } else if (level == 0) {
1863 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1864 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1866 /* Note this does not find the real chunk, only the chunk group.
1867 * We make an assumption that a chunk group is not larger than
1870 yaffs_SoftDeleteChunk(dev, theChunk);
1871 yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1885 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1888 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1889 if (obj->nDataChunks <= 0) {
1890 /* Empty file with no duplicate object headers, just delete it immediately */
1891 yaffs_FreeTnode(obj->myDev,
1892 obj->variant.fileVariant.top);
1893 obj->variant.fileVariant.top = NULL;
1894 T(YAFFS_TRACE_TRACING,
1895 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1897 yaffs_DoGenericObjectDeletion(obj);
1899 yaffs_SoftDeleteWorker(obj,
1900 obj->variant.fileVariant.top,
1901 obj->variant.fileVariant.
1903 obj->softDeleted = 1;
1908 /* Pruning removes any part of the file structure tree that is beyond the
1909 * bounds of the file (ie that does not point to chunks).
1911 * A file should only get pruned when its size is reduced.
1913 * Before pruning, the chunks must be pulled from the tree and the
1914 * level 0 tnode entries must be zeroed out.
1915 * Could also use this for file deletion, but that's probably better handled
1916 * by a special case.
1918 * This function is recursive. For levels > 0 the function is called again on
1919 * any sub-tree. For level == 0 we just check if the sub-tree has data.
1920 * If there is no data in a subtree then it is pruned.
1923 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1924 __u32 level, int del0)
1933 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1934 if (tn->internal[i]) {
1936 yaffs_PruneWorker(dev, tn->internal[i],
1938 (i == 0) ? del0 : 1);
1941 if (tn->internal[i])
1945 int tnodeSize_u32 = yaffs_CalcTnodeSize(dev)/sizeof(__u32);
1946 __u32 *map = (__u32 *)tn;
1948 for(i = 0; !hasData && i < tnodeSize_u32; i++){
1954 if (hasData == 0 && del0) {
1955 /* Free and return NULL */
1957 yaffs_FreeTnode(dev, tn);
1967 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1968 yaffs_FileStructure *fStruct)
1975 if (fStruct->topLevel > 0) {
1977 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1979 /* Now we have a tree with all the non-zero branches NULL but the height
1980 * is the same as it was.
1981 * Let's see if we can trim internal tnodes to shorten the tree.
1982 * We can do this if only the 0th element in the tnode is in use
1983 * (ie all the non-zero are NULL)
1986 while (fStruct->topLevel && !done) {
1990 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1991 if (tn->internal[i])
1996 fStruct->top = tn->internal[0];
1997 fStruct->topLevel--;
1998 yaffs_FreeTnode(dev, tn);
2008 /*-------------------- End of File Structure functions.-------------------*/
2010 /* yaffs_CreateFreeObjects creates a bunch more objects and
2011 * adds them to the object free list.
2013 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
2016 yaffs_Object *newObjects;
2017 yaffs_ObjectList *list;
2022 /* make these things */
2023 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
2024 list = YMALLOC(sizeof(yaffs_ObjectList));
2026 if (!newObjects || !list) {
2035 T(YAFFS_TRACE_ALLOCATE,
2036 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
2040 /* Hook them into the free list */
2041 for (i = 0; i < nObjects - 1; i++) {
2042 newObjects[i].siblings.next =
2043 (struct ylist_head *)(&newObjects[i + 1]);
2046 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
2047 dev->freeObjects = newObjects;
2048 dev->nFreeObjects += nObjects;
2049 dev->nObjectsCreated += nObjects;
2051 /* Now add this bunch of Objects to a list for freeing up. */
2053 list->objects = newObjects;
2054 list->next = dev->allocatedObjectList;
2055 dev->allocatedObjectList = list;
2061 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
2062 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
2064 yaffs_Object *tn = NULL;
2066 #ifdef CONFIG_YAFFS_VALGRIND_TEST
2067 tn = YMALLOC(sizeof(yaffs_Object));
2069 dev->nObjectsCreated++;
2071 /* If there are none left make more */
2072 if (!dev->freeObjects)
2073 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
2075 if (dev->freeObjects) {
2076 tn = dev->freeObjects;
2078 (yaffs_Object *) (dev->freeObjects->siblings.next);
2079 dev->nFreeObjects--;
2083 /* Now sweeten it up... */
2085 memset(tn, 0, sizeof(yaffs_Object));
2086 tn->beingCreated = 1;
2090 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
2091 YINIT_LIST_HEAD(&(tn->hardLinks));
2092 YINIT_LIST_HEAD(&(tn->hashLink));
2093 YINIT_LIST_HEAD(&tn->siblings);
2096 /* Now make the directory sane */
2098 tn->parent = dev->rootDir;
2099 ylist_add(&(tn->siblings), &dev->rootDir->variant.directoryVariant.children);
2102 /* Add it to the lost and found directory.
2103 * NB Can't put root or lostNFound in lostNFound so
2104 * check if lostNFound exists first
2106 if (dev->lostNFoundDir)
2107 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
2109 tn->beingCreated = 0;
2112 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2117 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
2122 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
2124 obj->fake = 1; /* it is fake so it might have no NAND presence... */
2125 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
2126 obj->unlinkAllowed = 0; /* ... or unlink it */
2129 obj->yst_mode = mode;
2131 obj->hdrChunk = 0; /* Not a valid chunk. */
2138 static void yaffs_UnhashObject(yaffs_Object *tn)
2141 yaffs_Device *dev = tn->myDev;
2143 /* If it is still linked into the bucket list, free from the list */
2144 if (!ylist_empty(&tn->hashLink)) {
2145 ylist_del_init(&tn->hashLink);
2146 bucket = yaffs_HashFunction(tn->objectId);
2147 dev->objectBucket[bucket].count--;
2151 /* FreeObject frees up a Object and puts it back on the free list */
2152 static void yaffs_FreeObject(yaffs_Object *tn)
2154 yaffs_Device *dev = tn->myDev;
2156 T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), tn, tn->myInode));
2162 if (!ylist_empty(&tn->siblings))
2167 /* We're still hooked up to a cached inode.
2168 * Don't delete now, but mark for later deletion
2170 tn->deferedFree = 1;
2174 yaffs_UnhashObject(tn);
2176 #ifdef CONFIG_YAFFS_VALGRIND_TEST
2178 dev->nObjectsCreated--;
2181 /* Link into the free list. */
2182 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2183 dev->freeObjects = tn;
2184 dev->nFreeObjects++;
2186 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2190 void yaffs_HandleDeferedFree(yaffs_Object *obj)
2192 if (obj->deferedFree)
2193 yaffs_FreeObject(obj);
2197 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
2199 /* Free the list of allocated Objects */
2201 yaffs_ObjectList *tmp;
2203 while (dev->allocatedObjectList) {
2204 tmp = dev->allocatedObjectList->next;
2205 YFREE(dev->allocatedObjectList->objects);
2206 YFREE(dev->allocatedObjectList);
2208 dev->allocatedObjectList = tmp;
2211 dev->freeObjects = NULL;
2212 dev->nFreeObjects = 0;
2213 dev->nObjectsCreated = 0;
2216 static void yaffs_InitialiseObjects(yaffs_Device *dev)
2220 dev->allocatedObjectList = NULL;
2221 dev->freeObjects = NULL;
2222 dev->nFreeObjects = 0;
2224 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2225 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2226 dev->objectBucket[i].count = 0;
2230 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
2234 int lowest = 999999;
2237 /* Search for the shortest list or one that
2241 for (i = 0; i < 10 && lowest > 4; i++) {
2242 dev->bucketFinder++;
2243 dev->bucketFinder %= YAFFS_NOBJECT_BUCKETS;
2244 if (dev->objectBucket[dev->bucketFinder].count < lowest) {
2245 lowest = dev->objectBucket[dev->bucketFinder].count;
2246 l = dev->bucketFinder;
2254 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
2256 int bucket = yaffs_FindNiceObjectBucket(dev);
2258 /* Now find an object value that has not already been taken
2259 * by scanning the list.
2263 struct ylist_head *i;
2265 __u32 n = (__u32) bucket;
2267 /* yaffs_CheckObjectHashSanity(); */
2271 n += YAFFS_NOBJECT_BUCKETS;
2272 if (1 || dev->objectBucket[bucket].count > 0) {
2273 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2274 /* If there is already one in the list */
2275 if (i && ylist_entry(i, yaffs_Object,
2276 hashLink)->objectId == n) {
2286 static void yaffs_HashObject(yaffs_Object *in)
2288 int bucket = yaffs_HashFunction(in->objectId);
2289 yaffs_Device *dev = in->myDev;
2291 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2292 dev->objectBucket[bucket].count++;
2295 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
2297 int bucket = yaffs_HashFunction(number);
2298 struct ylist_head *i;
2301 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2302 /* Look if it is in the list */
2304 in = ylist_entry(i, yaffs_Object, hashLink);
2305 if (in->objectId == number) {
2307 /* Don't tell the VFS about this one if it is defered free */
2308 if (in->deferedFree)
2319 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
2320 yaffs_ObjectType type)
2322 yaffs_Object *theObject=NULL;
2323 yaffs_Tnode *tn = NULL;
2326 number = yaffs_CreateNewObjectNumber(dev);
2328 if (type == YAFFS_OBJECT_TYPE_FILE) {
2329 tn = yaffs_GetTnode(dev);
2334 theObject = yaffs_AllocateEmptyObject(dev);
2337 yaffs_FreeTnode(dev,tn);
2343 theObject->fake = 0;
2344 theObject->renameAllowed = 1;
2345 theObject->unlinkAllowed = 1;
2346 theObject->objectId = number;
2347 yaffs_HashObject(theObject);
2348 theObject->variantType = type;
2349 #ifdef CONFIG_YAFFS_WINCE
2350 yfsd_WinFileTimeNow(theObject->win_atime);
2351 theObject->win_ctime[0] = theObject->win_mtime[0] =
2352 theObject->win_atime[0];
2353 theObject->win_ctime[1] = theObject->win_mtime[1] =
2354 theObject->win_atime[1];
2358 theObject->yst_atime = theObject->yst_mtime =
2359 theObject->yst_ctime = Y_CURRENT_TIME;
2362 case YAFFS_OBJECT_TYPE_FILE:
2363 theObject->variant.fileVariant.fileSize = 0;
2364 theObject->variant.fileVariant.scannedFileSize = 0;
2365 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2366 theObject->variant.fileVariant.topLevel = 0;
2367 theObject->variant.fileVariant.top = tn;
2369 case YAFFS_OBJECT_TYPE_DIRECTORY:
2370 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2372 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2375 case YAFFS_OBJECT_TYPE_SYMLINK:
2376 case YAFFS_OBJECT_TYPE_HARDLINK:
2377 case YAFFS_OBJECT_TYPE_SPECIAL:
2378 /* No action required */
2380 case YAFFS_OBJECT_TYPE_UNKNOWN:
2381 /* todo this should not happen */
2389 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
2391 yaffs_ObjectType type)
2393 yaffs_Object *theObject = NULL;
2396 theObject = yaffs_FindObjectByNumber(dev, number);
2399 theObject = yaffs_CreateNewObject(dev, number, type);
2406 static YCHAR *yaffs_CloneString(const YCHAR *str)
2408 YCHAR *newStr = NULL;
2414 len = yaffs_strnlen(str,YAFFS_MAX_ALIAS_LENGTH);
2415 newStr = YMALLOC((len + 1) * sizeof(YCHAR));
2417 yaffs_strncpy(newStr, str,len);
2425 * Mknod (create) a new object.
2426 * equivalentObject only has meaning for a hard link;
2427 * aliasString only has meaning for a symlink.
2428 * rdev only has meaning for devices (a subset of special objects)
2431 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2432 yaffs_Object *parent,
2437 yaffs_Object *equivalentObject,
2438 const YCHAR *aliasString, __u32 rdev)
2443 yaffs_Device *dev = parent->myDev;
2445 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2446 if (yaffs_FindObjectByName(parent, name))
2449 if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2450 str = yaffs_CloneString(aliasString);
2455 in = yaffs_CreateNewObject(dev, -1, type);
2470 in->variantType = type;
2472 in->yst_mode = mode;
2474 #ifdef CONFIG_YAFFS_WINCE
2475 yfsd_WinFileTimeNow(in->win_atime);
2476 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2477 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2480 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2482 in->yst_rdev = rdev;
2486 in->nDataChunks = 0;
2488 yaffs_SetObjectName(in, name);
2491 yaffs_AddObjectToDirectory(parent, in);
2493 in->myDev = parent->myDev;
2496 case YAFFS_OBJECT_TYPE_SYMLINK:
2497 in->variant.symLinkVariant.alias = str;
2499 case YAFFS_OBJECT_TYPE_HARDLINK:
2500 in->variant.hardLinkVariant.equivalentObject =
2502 in->variant.hardLinkVariant.equivalentObjectId =
2503 equivalentObject->objectId;
2504 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2506 case YAFFS_OBJECT_TYPE_FILE:
2507 case YAFFS_OBJECT_TYPE_DIRECTORY:
2508 case YAFFS_OBJECT_TYPE_SPECIAL:
2509 case YAFFS_OBJECT_TYPE_UNKNOWN:
2514 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2515 /* Could not create the object header, fail the creation */
2516 yaffs_DeleteObject(in);
2520 yaffs_UpdateParent(parent);
2526 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
2527 __u32 mode, __u32 uid, __u32 gid)
2529 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2530 uid, gid, NULL, NULL, 0);
2533 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
2534 __u32 mode, __u32 uid, __u32 gid)
2536 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2537 mode, uid, gid, NULL, NULL, 0);
2540 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
2541 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2543 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2544 uid, gid, NULL, NULL, rdev);
2547 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
2548 __u32 mode, __u32 uid, __u32 gid,
2551 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2552 uid, gid, NULL, alias, 0);
2555 /* yaffs_Link returns the object id of the equivalent object.*/
2556 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
2557 yaffs_Object *equivalentObject)
2559 /* Get the real object in case we were fed a hard link as an equivalent object */
2560 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2562 if (yaffs_MknodObject
2563 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2564 equivalentObject, NULL, 0)) {
2565 return equivalentObject;
2572 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
2573 const YCHAR *newName, int force, int shadows)
2578 yaffs_Object *existingTarget;
2581 newDir = obj->parent; /* use the old directory */
2583 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2584 T(YAFFS_TRACE_ALWAYS,
2586 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2591 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2592 if (obj->myDev->param.isYaffs2)
2593 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2595 unlinkOp = (newDir == obj->myDev->unlinkedDir
2596 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2598 deleteOp = (newDir == obj->myDev->deletedDir);
2600 existingTarget = yaffs_FindObjectByName(newDir, newName);
2602 /* If the object is a file going into the unlinked directory,
2603 * then it is OK to just stuff it in since duplicate names are allowed.
2604 * else only proceed if the new name does not exist and if we're putting
2605 * it into a directory.
2612 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2613 yaffs_SetObjectName(obj, newName);
2616 yaffs_AddObjectToDirectory(newDir, obj);
2621 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2622 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows) >= 0)
2629 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
2630 yaffs_Object *newDir, const YCHAR *newName)
2632 yaffs_Object *obj = NULL;
2633 yaffs_Object *existingTarget = NULL;
2639 if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2641 if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2644 dev = oldDir->myDev;
2646 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2647 /* Special case for case insemsitive systems (eg. WinCE).
2648 * While look-up is case insensitive, the name isn't.
2649 * Therefore we might want to change x.txt to X.txt
2651 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
2655 if(yaffs_strnlen(newName,YAFFS_MAX_NAME_LENGTH+1) > YAFFS_MAX_NAME_LENGTH)
2659 obj = yaffs_FindObjectByName(oldDir, oldName);
2661 if (obj && obj->renameAllowed) {
2663 /* Now do the handling for an existing target, if there is one */
2665 existingTarget = yaffs_FindObjectByName(newDir, newName);
2666 if (existingTarget &&
2667 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2668 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2669 /* There is a target that is a non-empty directory, so we fail */
2670 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2671 } else if (existingTarget && existingTarget != obj) {
2672 /* Nuke the target first, using shadowing,
2673 * but only if it isn't the same object.
2675 * Note we must disable gc otherwise it can mess up the shadowing.
2679 yaffs_ChangeObjectName(obj, newDir, newName, force,
2680 existingTarget->objectId);
2681 existingTarget->isShadowed = 1;
2682 yaffs_UnlinkObject(existingTarget);
2686 result = yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2688 yaffs_UpdateParent(oldDir);
2689 if(newDir != oldDir)
2690 yaffs_UpdateParent(newDir);
2697 /*------------------------- Block Management and Page Allocation ----------------*/
2699 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
2701 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2703 dev->blockInfo = NULL;
2704 dev->chunkBits = NULL;
2706 dev->allocationBlock = -1; /* force it to get a new one */
2708 /* If the first allocation strategy fails, thry the alternate one */
2709 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2710 if (!dev->blockInfo) {
2711 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2712 dev->blockInfoAlt = 1;
2714 dev->blockInfoAlt = 0;
2716 if (dev->blockInfo) {
2717 /* Set up dynamic blockinfo stuff. */
2718 dev->chunkBitmapStride = (dev->param.nChunksPerBlock + 7) / 8; /* round up bytes */
2719 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2720 if (!dev->chunkBits) {
2721 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2722 dev->chunkBitsAlt = 1;
2724 dev->chunkBitsAlt = 0;
2727 if (dev->blockInfo && dev->chunkBits) {
2728 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2729 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2736 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2738 if (dev->blockInfoAlt && dev->blockInfo)
2739 YFREE_ALT(dev->blockInfo);
2740 else if (dev->blockInfo)
2741 YFREE(dev->blockInfo);
2743 dev->blockInfoAlt = 0;
2745 dev->blockInfo = NULL;
2747 if (dev->chunkBitsAlt && dev->chunkBits)
2748 YFREE_ALT(dev->chunkBits);
2749 else if (dev->chunkBits)
2750 YFREE(dev->chunkBits);
2751 dev->chunkBitsAlt = 0;
2752 dev->chunkBits = NULL;
2755 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
2756 yaffs_BlockInfo *bi)
2759 if (!dev->param.isYaffs2)
2760 return 1; /* disqualification only applies to yaffs2. */
2762 if (!bi->hasShrinkHeader)
2763 return 1; /* can gc */
2765 yaffs_FindOldestDirtySequence(dev);
2767 /* Can't do gc of this block if there are any blocks older than this one that have
2770 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2774 * yaffs_FindRefreshBlock()
2775 * periodically finds the oldest full block by sequence number for refreshing.
2778 static __u32 yaffs_FindRefreshBlock(yaffs_Device *dev)
2783 __u32 oldestSequence = 0;
2785 yaffs_BlockInfo *bi;
2788 * If refresh period < 10 then refreshing is disabled.
2790 if(dev->param.refreshPeriod < 10 ||
2791 !dev->param.isYaffs2)
2795 * Fix broken values.
2797 if(dev->refreshSkip > dev->param.refreshPeriod)
2798 dev->refreshSkip = dev->param.refreshPeriod;
2800 if(dev->refreshSkip > 0)
2804 * Refresh skip is now zero.
2805 * We'll do a refresh this time around....
2806 * Update the refresh skip and find the oldest block.
2808 dev->refreshSkip = dev->param.refreshPeriod;
2809 dev->refreshCount++;
2810 bi = dev->blockInfo;
2811 for (b = dev->internalStartBlock; b <=dev->internalEndBlock; b++){
2813 if (bi->blockState == YAFFS_BLOCK_STATE_FULL){
2816 bi->sequenceNumber < oldestSequence){
2818 oldestSequence = bi->sequenceNumber;
2826 (TSTR("GC refresh count %d selected block %d with sequenceNumber %d" TENDSTR),
2827 dev->refreshCount, oldest, oldestSequence));
2834 static void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
2836 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2840 /* If the block is still healthy erase it and mark as clean.
2841 * If the block has had a data failure, then retire it.
2844 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2845 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2846 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2848 yaffs_ClearOldestDirtySequence(dev,bi);
2850 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2852 /* If this is the block being garbage collected then stop gc'ing this block */
2853 if(blockNo == dev->gcBlock)
2856 /* If this block is currently the best candidate for gc then drop as a candidate */
2857 if(blockNo == dev->gcDirtiest){
2858 dev->gcDirtiest = 0;
2859 dev->gcPagesInUse = 0;
2862 if (!bi->needsRetiring) {
2863 yaffs_InvalidateCheckpoint(dev);
2864 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2866 dev->nErasureFailures++;
2867 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2868 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2873 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2875 for (i = 0; i < dev->param.nChunksPerBlock; i++) {
2876 if (!yaffs_CheckChunkErased
2877 (dev, blockNo * dev->param.nChunksPerBlock + i)) {
2878 T(YAFFS_TRACE_ERROR,
2880 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2881 TENDSTR), blockNo, i));
2887 /* Clean it up... */
2888 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2889 bi->sequenceNumber = 0;
2890 dev->nErasedBlocks++;
2892 bi->softDeletions = 0;
2893 bi->hasShrinkHeader = 0;
2894 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2895 bi->gcPrioritise = 0;
2896 yaffs_ClearChunkBits(dev, blockNo);
2898 T(YAFFS_TRACE_ERASE,
2899 (TSTR("Erased block %d" TENDSTR), blockNo));
2901 dev->nFreeChunks -= dev->param.nChunksPerBlock; /* We lost a block of free space */
2903 yaffs_RetireBlock(dev, blockNo);
2904 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2905 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2909 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2913 yaffs_BlockInfo *bi;
2915 if (dev->nErasedBlocks < 1) {
2916 /* Hoosterman we've got a problem.
2917 * Can't get space to gc
2919 T(YAFFS_TRACE_ERROR,
2920 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2925 /* Find an empty block. */
2927 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2928 dev->allocationBlockFinder++;
2929 if (dev->allocationBlockFinder < dev->internalStartBlock
2930 || dev->allocationBlockFinder > dev->internalEndBlock) {
2931 dev->allocationBlockFinder = dev->internalStartBlock;
2934 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2936 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2937 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2938 dev->sequenceNumber++;
2939 bi->sequenceNumber = dev->sequenceNumber;
2940 dev->nErasedBlocks--;
2941 T(YAFFS_TRACE_ALLOCATE,
2942 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2943 dev->allocationBlockFinder, dev->sequenceNumber,
2944 dev->nErasedBlocks));
2945 return dev->allocationBlockFinder;
2949 T(YAFFS_TRACE_ALWAYS,
2951 ("yaffs tragedy: no more erased blocks, but there should have been %d"
2952 TENDSTR), dev->nErasedBlocks));
2959 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2961 if (!dev->nCheckpointBlocksRequired &&
2962 dev->param.isYaffs2) {
2963 /* Not a valid value so recalculate */
2966 int devBlocks = (dev->param.endBlock - dev->param.startBlock + 1);
2967 int tnodeSize = yaffs_CalcTnodeSize(dev);
2969 nBytes += sizeof(yaffs_CheckpointValidity);
2970 nBytes += sizeof(yaffs_CheckpointDevice);
2971 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2972 nBytes += devBlocks * dev->chunkBitmapStride;
2973 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2974 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2975 nBytes += sizeof(yaffs_CheckpointValidity);
2976 nBytes += sizeof(__u32); /* checksum*/
2978 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2980 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->param.nChunksPerBlock)) + 3;
2982 dev->nCheckpointBlocksRequired = nBlocks;
2985 return dev->nCheckpointBlocksRequired;
2989 * Check if there's space to allocate...
2990 * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2992 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev, int nChunks)
2995 int reservedBlocks = dev->param.nReservedBlocks;
2996 int checkpointBlocks;
2998 if (dev->param.isYaffs2) {
2999 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
3000 dev->blocksInCheckpoint;
3001 if (checkpointBlocks < 0)
3002 checkpointBlocks = 0;
3004 checkpointBlocks = 0;
3007 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->param.nChunksPerBlock);
3009 return (dev->nFreeChunks > (reservedChunks + nChunks));
3012 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
3013 yaffs_BlockInfo **blockUsedPtr)
3016 yaffs_BlockInfo *bi;
3018 if (dev->allocationBlock < 0) {
3019 /* Get next block to allocate off */
3020 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
3021 dev->allocationPage = 0;
3024 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev, 1)) {
3025 /* Not enough space to allocate unless we're allowed to use the reserve. */
3029 if (dev->nErasedBlocks < dev->param.nReservedBlocks
3030 && dev->allocationPage == 0) {
3031 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
3034 /* Next page please.... */
3035 if (dev->allocationBlock >= 0) {
3036 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3038 retVal = (dev->allocationBlock * dev->param.nChunksPerBlock) +
3039 dev->allocationPage;
3041 yaffs_SetChunkBit(dev, dev->allocationBlock,
3042 dev->allocationPage);
3044 dev->allocationPage++;
3048 /* If the block is full set the state to full */
3049 if (dev->allocationPage >= dev->param.nChunksPerBlock) {
3050 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3051 dev->allocationBlock = -1;
3060 T(YAFFS_TRACE_ERROR,
3061 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
3066 static int yaffs_GetErasedChunks(yaffs_Device *dev)
3070 n = dev->nErasedBlocks * dev->param.nChunksPerBlock;
3072 if (dev->allocationBlock > 0)
3073 n += (dev->param.nChunksPerBlock - dev->allocationPage);
3080 * yaffs_SkipRestOfBlock() skips over the rest of the allocation block
3081 * if we don't want to write to it.
3083 static void yaffs_SkipRestOfBlock(yaffs_Device *dev)
3085 if(dev->allocationBlock > 0){
3086 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3087 if(bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING){
3088 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3089 dev->allocationBlock = -1;
3095 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
3101 int retVal = YAFFS_OK;
3104 int isCheckpointBlock;
3108 int chunksBefore = yaffs_GetErasedChunks(dev);
3111 yaffs_ExtendedTags tags;
3113 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3115 yaffs_Object *object;
3117 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3120 T(YAFFS_TRACE_TRACING,
3121 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3124 bi->hasShrinkHeader,
3127 /*yaffs_VerifyFreeChunks(dev); */
3129 if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
3130 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3132 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
3136 if (isCheckpointBlock ||
3137 !yaffs_StillSomeChunkBits(dev, block)) {
3138 T(YAFFS_TRACE_TRACING,
3140 ("Collecting block %d that has no chunks in use" TENDSTR),
3142 yaffs_BlockBecameDirty(dev, block);
3145 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3147 yaffs_VerifyBlock(dev, bi, block);
3149 maxCopies = (wholeBlock) ? dev->param.nChunksPerBlock : 5;
3150 oldChunk = block * dev->param.nChunksPerBlock + dev->gcChunk;
3152 for (/* init already done */;
3153 retVal == YAFFS_OK &&
3154 dev->gcChunk < dev->param.nChunksPerBlock &&
3155 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
3157 dev->gcChunk++, oldChunk++) {
3158 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3160 /* This page is in use and might need to be copied off */
3166 yaffs_InitialiseTags(&tags);
3168 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3172 yaffs_FindObjectByNumber(dev,
3175 T(YAFFS_TRACE_GC_DETAIL,
3177 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3178 dev->gcChunk, tags.objectId, tags.chunkId,
3181 if (object && !yaffs_SkipVerification(dev)) {
3182 if (tags.chunkId == 0)
3183 matchingChunk = object->hdrChunk;
3184 else if (object->softDeleted)
3185 matchingChunk = oldChunk; /* Defeat the test */
3187 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
3189 if (oldChunk != matchingChunk)
3190 T(YAFFS_TRACE_ERROR,
3191 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3192 oldChunk, matchingChunk, tags.objectId, tags.chunkId));
3197 T(YAFFS_TRACE_ERROR,
3199 ("page %d in gc has no object: %d %d %d "
3201 tags.objectId, tags.chunkId, tags.byteCount));
3206 object->softDeleted &&
3207 tags.chunkId != 0) {
3208 /* Data chunk in a soft deleted file, throw it away
3209 * It's a soft deleted data chunk,
3210 * No need to copy this, just forget about it and
3211 * fix up the object.
3214 /* Free chunks already includes softdeleted chunks.
3215 * How ever this chunk is going to soon be really deleted
3216 * which will increment free chunks.
3217 * We have to decrement free chunks so this works out properly.
3221 object->nDataChunks--;
3223 if (object->nDataChunks <= 0) {
3224 /* remeber to clean up the object */
3225 dev->gcCleanupList[cleanups] =
3231 /* Todo object && object->deleted && object->nDataChunks == 0 */
3232 /* Deleted object header with no data chunks.
3233 * Can be discarded and the file deleted.
3235 object->hdrChunk = 0;
3236 yaffs_FreeTnode(object->myDev,
3239 object->variant.fileVariant.top = NULL;
3240 yaffs_DoGenericObjectDeletion(object);
3242 } else if (object) {
3243 /* It's either a data chunk in a live file or
3244 * an ObjectHeader, so we're interested in it.
3245 * NB Need to keep the ObjectHeaders of deleted files
3246 * until the whole file has been deleted off
3248 tags.serialNumber++;
3252 if (tags.chunkId == 0) {
3253 /* It is an object Id,
3254 * We need to nuke the shrinkheader flags first
3255 * Also need to clean up shadowing.
3256 * We no longer want the shrinkHeader flag since its work is done
3257 * and if it is left in place it will mess up scanning.
3260 yaffs_ObjectHeader *oh;
3261 oh = (yaffs_ObjectHeader *)buffer;
3264 tags.extraIsShrinkHeader = 0;
3266 oh->shadowsObject = 0;
3267 oh->inbandShadowsObject = 0;
3268 tags.extraShadows = 0;
3270 /* Update file size */
3271 if(object->variantType == YAFFS_OBJECT_TYPE_FILE){
3272 oh->fileSize = object->variant.fileVariant.fileSize;
3273 tags.extraFileLength = oh->fileSize;
3276 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
3278 yaffs_WriteNewChunkWithTagsToNAND(dev,(__u8 *) oh, &tags, 1);
3281 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3284 retVal = YAFFS_FAIL;
3287 /* Ok, now fix up the Tnodes etc. */
3289 if (tags.chunkId == 0) {
3291 object->hdrChunk = newChunk;
3292 object->serial = tags.serialNumber;
3294 /* It's a data chunk */
3296 ok = yaffs_PutChunkIntoFile
3304 if (retVal == YAFFS_OK)
3305 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3310 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3313 /* Do any required cleanups */
3314 for (i = 0; i < cleanups; i++) {
3315 /* Time to delete the file too */
3317 yaffs_FindObjectByNumber(dev,
3318 dev->gcCleanupList[i]);
3320 yaffs_FreeTnode(dev,
3321 object->variant.fileVariant.
3323 object->variant.fileVariant.top = NULL;
3326 ("yaffs: About to finally delete object %d"
3327 TENDSTR), object->objectId));
3328 yaffs_DoGenericObjectDeletion(object);
3329 object->myDev->nDeletedFiles--;
3336 yaffs_VerifyCollectedBlock(dev, bi, block);
3340 if (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3342 * The gc did not complete. Set block state back to FULL
3343 * because checkpointing does not restore gc.
3345 bi->blockState = YAFFS_BLOCK_STATE_FULL;
3347 /* The gc completed. */
3348 chunksAfter = yaffs_GetErasedChunks(dev);
3349 if (chunksBefore >= chunksAfter) {
3352 ("gc did not increase free chunks before %d after %d"
3353 TENDSTR), chunksBefore, chunksAfter));
3365 * FindBlockForgarbageCollection is used to select the dirtiest block (or close enough)
3366 * for garbage collection.
3369 static unsigned yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
3375 unsigned selected = 0;
3376 int prioritised = 0;
3377 int prioritisedExists = 0;
3378 yaffs_BlockInfo *bi;
3381 /* First let's see if we need to grab a prioritised block */
3382 if (dev->hasPendingPrioritisedGCs && !aggressive) {
3383 dev->gcDirtiest = 0;
3384 bi = dev->blockInfo;
3385 for (i = dev->internalStartBlock;
3386 i <= dev->internalEndBlock && !selected;
3389 if (bi->gcPrioritise) {
3390 prioritisedExists = 1;
3391 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
3392 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
3401 * If there is a prioritised block and none was selected then
3402 * this happened because there is at least one old dirty block gumming
3403 * up the works. Let's gc the oldest dirty block.
3406 if(prioritisedExists &&
3408 dev->oldestDirtyBlock > 0)
3409 selected = dev->oldestDirtyBlock;
3411 if (!prioritisedExists) /* None found, so we can clear this */
3412 dev->hasPendingPrioritisedGCs = 0;
3415 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
3417 * else (we're doing a leasurely gc), then we only bother to do this if the
3418 * block has only a few pages in use.
3423 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
3425 threshold = dev->param.nChunksPerBlock;
3426 iterations = nBlocks;
3428 int maxThreshold = dev->param.nChunksPerBlock/2;
3429 threshold = background ?
3430 (dev->gcNotDone + 2) * 2 : 0;
3431 if(threshold <YAFFS_GC_PASSIVE_THRESHOLD)
3432 threshold = YAFFS_GC_PASSIVE_THRESHOLD;
3433 if(threshold > maxThreshold)
3434 threshold = maxThreshold;
3436 iterations = nBlocks / 16 + 1;
3437 if (iterations > 100)
3443 (dev->gcDirtiest < 1 ||
3444 dev->gcPagesInUse > YAFFS_GC_GOOD_ENOUGH);
3446 dev->gcBlockFinder++;
3447 if (dev->gcBlockFinder < dev->internalStartBlock ||
3448 dev->gcBlockFinder > dev->internalEndBlock)
3449 dev->gcBlockFinder = dev->internalStartBlock;
3451 bi = yaffs_GetBlockInfo(dev, dev->gcBlockFinder);
3453 pagesUsed = bi->pagesInUse - bi->softDeletions;
3455 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
3456 pagesUsed < dev->param.nChunksPerBlock &&
3457 (dev->gcDirtiest < 1 || pagesUsed < dev->gcPagesInUse) &&
3458 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
3459 dev->gcDirtiest = dev->gcBlockFinder;
3460 dev->gcPagesInUse = pagesUsed;
3464 if(dev->gcDirtiest > 0 && dev->gcPagesInUse <= threshold)
3465 selected = dev->gcDirtiest;
3468 if(!selected && dev->param.isYaffs2 && dev->gcNotDone >= ( background ? 10 : 20)){
3469 yaffs_FindOldestDirtySequence(dev);
3470 if(dev->oldestDirtyBlock > 0) {
3471 selected = dev->oldestDirtyBlock;
3472 dev->gcDirtiest = selected;
3473 bi = yaffs_GetBlockInfo(dev, selected);
3474 dev->gcPagesInUse = bi->pagesInUse - bi->softDeletions;
3481 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR),
3483 dev->param.nChunksPerBlock - dev->gcPagesInUse,
3486 dev->gcDirtiest = 0;
3487 dev->gcPagesInUse = 0;
3489 if(dev->refreshSkip > 0)
3494 (TSTR("GC none: finder %d skip %d threshold %d dirtiest %d using %d oldest %d%s" TENDSTR),
3495 dev->gcBlockFinder, dev->gcNotDone,
3497 dev->gcDirtiest, dev->gcPagesInUse,
3498 dev->oldestDirtyBlock,
3499 background ? " bg" : ""));
3505 /* New garbage collector
3506 * If we're very low on erased blocks then we do aggressive garbage collection
3507 * otherwise we do "leasurely" garbage collection.
3508 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3509 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3511 * The idea is to help clear out space in a more spread-out manner.
3512 * Dunno if it really does anything useful.
3514 static int yaffs_CheckGarbageCollection(yaffs_Device *dev, int background)
3517 int gcOk = YAFFS_OK;
3523 int checkpointBlockAdjust;
3525 if(dev->param.gcControl &&
3526 (dev->param.gcControl(dev) & 1) == 0)
3529 if (dev->gcDisable) {
3530 /* Bail out so we don't get recursive gc */
3534 /* This loop should pass the first time.
3535 * We'll only see looping here if the collection does not increase space.
3541 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3542 if (checkpointBlockAdjust < 0)
3543 checkpointBlockAdjust = 0;
3545 minErased = dev->param.nReservedBlocks + checkpointBlockAdjust + 1;
3546 erasedChunks = dev->nErasedBlocks * dev->param.nChunksPerBlock;
3548 /* If we need a block soon then do aggressive gc.*/
3549 if (dev->nErasedBlocks < minErased)
3552 if(dev->gcSkip > 20)
3554 if(erasedChunks < dev->nFreeChunks/2 ||
3566 /* If we don't already have a block being gc'd then see if we should start another */
3568 if (dev->gcBlock < 1 && !aggressive) {
3569 dev->gcBlock = yaffs_FindRefreshBlock(dev);
3572 if (dev->gcBlock < 1) {
3573 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive, background);
3577 if (dev->gcBlock > 0) {
3578 dev->garbageCollections++;
3580 dev->passiveGarbageCollections++;
3584 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3585 dev->nErasedBlocks, aggressive));
3587 gcOk = yaffs_GarbageCollectBlock(dev, dev->gcBlock, aggressive);
3590 if (dev->nErasedBlocks < (dev->param.nReservedBlocks) && dev->gcBlock > 0) {
3593 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3594 TENDSTR), dev->nErasedBlocks, maxTries, dev->gcBlock));
3596 } while ((dev->nErasedBlocks < dev->param.nReservedBlocks) &&
3597 (dev->gcBlock > 0) &&
3600 return aggressive ? gcOk : YAFFS_OK;
3604 * yaffs_BackgroundGarbageCollect()
3605 * Garbage collects. Intended to be called from a background thread.
3606 * Returns non-zero if at least half the free chunks are erased.
3608 int yaffs_BackgroundGarbageCollect(yaffs_Device *dev)
3610 int erasedChunks = dev->nErasedBlocks * dev->param.nChunksPerBlock;
3612 T(YAFFS_TRACE_BACKGROUND, (TSTR("Background gc" TENDSTR)));
3614 yaffs_CheckGarbageCollection(dev, 1);
3615 return erasedChunks > dev->nFreeChunks/2;
3618 /*------------------------- TAGS --------------------------------*/
3620 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
3623 return (tags->chunkId == chunkInObject &&
3624 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3629 /*-------------------- Data file manipulation -----------------*/
3631 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
3632 yaffs_ExtendedTags *tags)
3634 /*Get the Tnode, then get the level 0 offset chunk offset */
3637 yaffs_ExtendedTags localTags;
3640 yaffs_Device *dev = in->myDev;
3643 /* Passed a NULL, so use our own tags space */
3647 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3650 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3653 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3659 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
3660 yaffs_ExtendedTags *tags)
3662 /* Get the Tnode, then get the level 0 offset chunk offset */
3665 yaffs_ExtendedTags localTags;
3667 yaffs_Device *dev = in->myDev;
3671 /* Passed a NULL, so use our own tags space */
3675 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3679 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3682 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3685 /* Delete the entry in the filestructure (if found) */
3687 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, 0);
3693 #ifdef YAFFS_PARANOID
3695 static int yaffs_CheckFileSanity(yaffs_Object *in)
3703 yaffs_Tags localTags;
3704 yaffs_Tags *tags = &localTags;
3708 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3711 objId = in->objectId;
3712 fSize = in->variant.fileVariant.fileSize;
3714 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3716 for (chunk = 1; chunk <= nChunks; chunk++) {
3717 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3722 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunk);
3724 if (yaffs_CheckChunkBits
3725 (dev, theChunk / dev->param.nChunksPerBlock,
3726 theChunk % dev->param.nChunksPerBlock)) {
3728 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3732 (tags, in->objectId, chunk, chunkDeleted)) {
3742 /* T(("No level 0 found for %d\n", chunk)); */
3746 return failed ? YAFFS_FAIL : YAFFS_OK;
3751 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
3752 int chunkInNAND, int inScan)
3754 /* NB inScan is zero unless scanning.
3755 * For forward scanning, inScan is > 0;
3756 * for backward scanning inScan is < 0
3758 * chunkInNAND = 0 is a dummy insert to make sure the tnodes are there.
3762 yaffs_Device *dev = in->myDev;
3764 yaffs_ExtendedTags existingTags;
3765 yaffs_ExtendedTags newTags;
3766 unsigned existingSerial, newSerial;
3768 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3769 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3770 * If it is not during Scanning then something went wrong!
3773 T(YAFFS_TRACE_ERROR,
3775 ("yaffs tragedy:attempt to put data chunk into a non-file"
3780 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3784 tn = yaffs_AddOrFindLevel0Tnode(dev,
3785 &in->variant.fileVariant,
3792 /* Dummy insert, bail now */
3795 existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3798 /* If we're scanning then we need to test for duplicates
3799 * NB This does not need to be efficient since it should only ever
3800 * happen when the power fails during a write, then only one
3801 * chunk should ever be affected.
3803 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3804 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3807 if (existingChunk > 0) {
3808 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3809 * thus we have to do a FindChunkInFile to get the real chunk id.
3811 * We have a duplicate now we need to decide which one to use:
3813 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3814 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3815 * YAFFS1: Get both sets of tags and compare serial numbers.
3819 /* Only do this for forward scanning */
3820 yaffs_ReadChunkWithTagsFromNAND(dev,
3824 /* Do a proper find */
3826 yaffs_FindChunkInFile(in, chunkInInode,
3830 if (existingChunk <= 0) {
3831 /*Hoosterman - how did this happen? */
3833 T(YAFFS_TRACE_ERROR,
3835 ("yaffs tragedy: existing chunk < 0 in scan"
3840 /* NB The deleted flags should be false, otherwise the chunks will
3841 * not be loaded during a scan
3845 newSerial = newTags.serialNumber;
3846 existingSerial = existingTags.serialNumber;
3850 (in->myDev->param.isYaffs2 ||
3851 existingChunk <= 0 ||
3852 ((existingSerial + 1) & 3) == newSerial)) {
3853 /* Forward scanning.
3855 * Delete the old one and drop through to update the tnode
3857 yaffs_DeleteChunk(dev, existingChunk, 1,
3860 /* Backward scanning or we want to use the existing one
3862 * Delete the new one and return early so that the tnode isn't changed
3864 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3872 if (existingChunk == 0)
3875 yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
3880 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
3883 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3885 if (chunkInNAND >= 0)
3886 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3889 T(YAFFS_TRACE_NANDACCESS,
3890 (TSTR("Chunk %d not found zero instead" TENDSTR),
3892 /* get sane (zero) data if you read a hole */
3893 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3899 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
3903 yaffs_ExtendedTags tags;
3904 yaffs_BlockInfo *bi;
3910 block = chunkId / dev->param.nChunksPerBlock;
3911 page = chunkId % dev->param.nChunksPerBlock;
3914 if (!yaffs_CheckChunkBit(dev, block, page))
3915 T(YAFFS_TRACE_VERIFY,
3916 (TSTR("Deleting invalid chunk %d"TENDSTR),
3919 bi = yaffs_GetBlockInfo(dev, block);
3921 yaffs_UpdateOldestDirtySequence(dev, block, bi);
3923 T(YAFFS_TRACE_DELETION,
3924 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3927 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->param.isYaffs2) {
3929 yaffs_InitialiseTags(&tags);
3931 tags.chunkDeleted = 1;
3933 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3934 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3936 dev->nUnmarkedDeletions++;
3939 /* Pull out of the management area.
3940 * If the whole block became dirty, this will kick off an erasure.
3942 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3943 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3944 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3945 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3948 yaffs_ClearChunkBit(dev, block, page);
3952 if (bi->pagesInUse == 0 &&
3953 !bi->hasShrinkHeader &&
3954 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3955 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3956 yaffs_BlockBecameDirty(dev, block);
3963 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
3964 const __u8 *buffer, int nBytes,
3967 /* Find old chunk Need to do this to get serial number
3968 * Write new one and patch into tree.
3969 * Invalidate old tags.
3973 yaffs_ExtendedTags prevTags;
3976 yaffs_ExtendedTags newTags;
3978 yaffs_Device *dev = in->myDev;
3980 yaffs_CheckGarbageCollection(dev,0);
3982 /* Get the previous chunk at this location in the file if it exists.
3983 * If it does not exist then put a zero into the tree. This creates
3984 * the tnode now, rather than later when it is harder to clean up.
3986 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3987 if(prevChunkId < 1 &&
3988 !yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0))
3991 /* Set up new tags */
3992 yaffs_InitialiseTags(&newTags);
3994 newTags.chunkId = chunkInInode;
3995 newTags.objectId = in->objectId;
3996 newTags.serialNumber =
3997 (prevChunkId > 0) ? prevTags.serialNumber + 1 : 1;
3998 newTags.byteCount = nBytes;
4000 if (nBytes < 1 || nBytes > dev->param.totalBytesPerChunk) {
4001 T(YAFFS_TRACE_ERROR,
4002 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
4008 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
4011 if (newChunkId > 0) {
4012 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
4014 if (prevChunkId > 0)
4015 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
4017 yaffs_CheckFileSanity(in);
4023 /* UpdateObjectHeader updates the header on NAND for an object.
4024 * If name is not NULL, then that new name is used.
4026 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
4027 int isShrink, int shadows)
4030 yaffs_BlockInfo *bi;
4032 yaffs_Device *dev = in->myDev;
4039 yaffs_ExtendedTags newTags;
4040 yaffs_ExtendedTags oldTags;
4041 YCHAR *alias = NULL;
4043 __u8 *buffer = NULL;
4044 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
4046 yaffs_ObjectHeader *oh = NULL;
4048 yaffs_strcpy(oldName, _Y("silly old name"));
4052 in == dev->rootDir || /* The rootDir should also be saved */
4055 yaffs_CheckGarbageCollection(dev,0);
4056 yaffs_CheckObjectDetailsLoaded(in);
4058 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
4059 oh = (yaffs_ObjectHeader *) buffer;
4061 prevChunkId = in->hdrChunk;
4063 if (prevChunkId > 0) {
4064 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
4067 yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
4069 memcpy(oldName, oh->name, sizeof(oh->name));
4072 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
4074 oh->type = in->variantType;
4075 oh->yst_mode = in->yst_mode;
4076 oh->shadowsObject = oh->inbandShadowsObject = shadows;
4078 #ifdef CONFIG_YAFFS_WINCE
4079 oh->win_atime[0] = in->win_atime[0];
4080 oh->win_ctime[0] = in->win_ctime[0];
4081 oh->win_mtime[0] = in->win_mtime[0];
4082 oh->win_atime[1] = in->win_atime[1];
4083 oh->win_ctime[1] = in->win_ctime[1];
4084 oh->win_mtime[1] = in->win_mtime[1];
4086 oh->yst_uid = in->yst_uid;
4087 oh->yst_gid = in->yst_gid;
4088 oh->yst_atime = in->yst_atime;
4089 oh->yst_mtime = in->yst_mtime;
4090 oh->yst_ctime = in->yst_ctime;
4091 oh->yst_rdev = in->yst_rdev;
4094 oh->parentObjectId = in->parent->objectId;
4096 oh->parentObjectId = 0;
4098 if (name && *name) {
4099 memset(oh->name, 0, sizeof(oh->name));
4100 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
4101 } else if (prevChunkId > 0)
4102 memcpy(oh->name, oldName, sizeof(oh->name));
4104 memset(oh->name, 0, sizeof(oh->name));
4106 oh->isShrink = isShrink;
4108 switch (in->variantType) {
4109 case YAFFS_OBJECT_TYPE_UNKNOWN:
4110 /* Should not happen */
4112 case YAFFS_OBJECT_TYPE_FILE:
4114 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
4115 || oh->parentObjectId ==
4116 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
4117 fileVariant.fileSize;
4119 case YAFFS_OBJECT_TYPE_HARDLINK:
4120 oh->equivalentObjectId =
4121 in->variant.hardLinkVariant.equivalentObjectId;
4123 case YAFFS_OBJECT_TYPE_SPECIAL:
4126 case YAFFS_OBJECT_TYPE_DIRECTORY:
4129 case YAFFS_OBJECT_TYPE_SYMLINK:
4130 alias = in->variant.symLinkVariant.alias;
4132 alias = _Y("no alias");
4133 yaffs_strncpy(oh->alias,
4135 YAFFS_MAX_ALIAS_LENGTH);
4136 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
4141 yaffs_InitialiseTags(&newTags);
4143 newTags.chunkId = 0;
4144 newTags.objectId = in->objectId;
4145 newTags.serialNumber = in->serial;
4147 /* Add extra info for file header */
4149 newTags.extraHeaderInfoAvailable = 1;
4150 newTags.extraParentObjectId = oh->parentObjectId;
4151 newTags.extraFileLength = oh->fileSize;
4152 newTags.extraIsShrinkHeader = oh->isShrink;
4153 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
4154 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
4155 newTags.extraObjectType = in->variantType;
4157 yaffs_VerifyObjectHeader(in, oh, &newTags, 1);
4159 /* Create new chunk in NAND */
4161 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
4162 (prevChunkId > 0) ? 1 : 0);
4164 if (newChunkId >= 0) {
4166 in->hdrChunk = newChunkId;
4168 if (prevChunkId > 0) {
4169 yaffs_DeleteChunk(dev, prevChunkId, 1,
4173 if (!yaffs_ObjectHasCachedWriteData(in))
4176 /* If this was a shrink, then mark the block that the chunk lives on */
4178 bi = yaffs_GetBlockInfo(in->myDev,
4179 newChunkId / in->myDev->param.nChunksPerBlock);
4180 bi->hasShrinkHeader = 1;
4185 retVal = newChunkId;
4190 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
4195 /*------------------------ Short Operations Cache ----------------------------------------
4196 * In many situations where there is no high level buffering (eg WinCE) a lot of
4197 * reads might be short sequential reads, and a lot of writes may be short
4198 * sequential writes. eg. scanning/writing a jpeg file.
4199 * In these cases, a short read/write cache can provide a huge perfomance benefit
4200 * with dumb-as-a-rock code.
4201 * In Linux, the page cache provides read buffering aand the short op cache provides write
4204 * There are a limited number (~10) of cache chunks per device so that we don't
4205 * need a very intelligent search.
4208 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
4210 yaffs_Device *dev = obj->myDev;
4212 yaffs_ChunkCache *cache;
4213 int nCaches = obj->myDev->param.nShortOpCaches;
4215 for (i = 0; i < nCaches; i++) {
4216 cache = &dev->srCache[i];
4217 if (cache->object == obj &&
4226 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
4228 yaffs_Device *dev = obj->myDev;
4229 int lowest = -99; /* Stop compiler whining. */
4231 yaffs_ChunkCache *cache;
4232 int chunkWritten = 0;
4233 int nCaches = obj->myDev->param.nShortOpCaches;
4239 /* Find the dirty cache for this object with the lowest chunk id. */
4240 for (i = 0; i < nCaches; i++) {
4241 if (dev->srCache[i].object == obj &&
4242 dev->srCache[i].dirty) {
4244 || dev->srCache[i].chunkId <
4246 cache = &dev->srCache[i];
4247 lowest = cache->chunkId;
4252 if (cache && !cache->locked) {
4253 /* Write it out and free it up */
4256 yaffs_WriteChunkDataToObject(cache->object,
4262 cache->object = NULL;
4265 } while (cache && chunkWritten > 0);
4268 /* Hoosterman, disk full while writing cache out. */
4269 T(YAFFS_TRACE_ERROR,
4270 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
4277 /*yaffs_FlushEntireDeviceCache(dev)
4282 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
4285 int nCaches = dev->param.nShortOpCaches;
4288 /* Find a dirty object in the cache and flush it...
4289 * until there are no further dirty objects.
4293 for (i = 0; i < nCaches && !obj; i++) {
4294 if (dev->srCache[i].object &&
4295 dev->srCache[i].dirty)
4296 obj = dev->srCache[i].object;
4300 yaffs_FlushFilesChunkCache(obj);
4307 /* Grab us a cache chunk for use.
4308 * First look for an empty one.
4309 * Then look for the least recently used non-dirty one.
4310 * Then look for the least recently used dirty one...., flush and look again.
4312 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
4316 if (dev->param.nShortOpCaches > 0) {
4317 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4318 if (!dev->srCache[i].object)
4319 return &dev->srCache[i];
4326 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
4328 yaffs_ChunkCache *cache;
4329 yaffs_Object *theObj;
4334 if (dev->param.nShortOpCaches > 0) {
4335 /* Try find a non-dirty one... */
4337 cache = yaffs_GrabChunkCacheWorker(dev);
4340 /* They were all dirty, find the last recently used object and flush
4341 * its cache, then find again.
4342 * NB what's here is not very accurate, we actually flush the object
4343 * the last recently used page.
4346 /* With locking we can't assume we can use entry zero */
4353 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4354 if (dev->srCache[i].object &&
4355 !dev->srCache[i].locked &&
4356 (dev->srCache[i].lastUse < usage || !cache)) {
4357 usage = dev->srCache[i].lastUse;
4358 theObj = dev->srCache[i].object;
4359 cache = &dev->srCache[i];
4364 if (!cache || cache->dirty) {
4365 /* Flush and try again */
4366 yaffs_FlushFilesChunkCache(theObj);
4367 cache = yaffs_GrabChunkCacheWorker(dev);
4377 /* Find a cached chunk */
4378 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj,
4381 yaffs_Device *dev = obj->myDev;
4383 if (dev->param.nShortOpCaches > 0) {
4384 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4385 if (dev->srCache[i].object == obj &&
4386 dev->srCache[i].chunkId == chunkId) {
4389 return &dev->srCache[i];
4396 /* Mark the chunk for the least recently used algorithym */
4397 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache,
4401 if (dev->param.nShortOpCaches > 0) {
4402 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4403 /* Reset the cache usages */
4405 for (i = 1; i < dev->param.nShortOpCaches; i++)
4406 dev->srCache[i].lastUse = 0;
4413 cache->lastUse = dev->srLastUse;
4420 /* Invalidate a single cache page.
4421 * Do this when a whole page gets written,
4422 * ie the short cache for this page is no longer valid.
4424 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
4426 if (object->myDev->param.nShortOpCaches > 0) {
4427 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4430 cache->object = NULL;
4434 /* Invalidate all the cache pages associated with this object
4435 * Do this whenever ther file is deleted or resized.
4437 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
4440 yaffs_Device *dev = in->myDev;
4442 if (dev->param.nShortOpCaches > 0) {
4443 /* Invalidate it. */
4444 for (i = 0; i < dev->param.nShortOpCaches; i++) {
4445 if (dev->srCache[i].object == in)
4446 dev->srCache[i].object = NULL;
4451 /*--------------------- Checkpointing --------------------*/
4454 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev, int head)
4456 yaffs_CheckpointValidity cp;
4458 memset(&cp, 0, sizeof(cp));
4460 cp.structType = sizeof(cp);
4461 cp.magic = YAFFS_MAGIC;
4462 cp.version = YAFFS_CHECKPOINT_VERSION;
4463 cp.head = (head) ? 1 : 0;
4465 return (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp)) ?
4469 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4471 yaffs_CheckpointValidity cp;
4474 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4477 ok = (cp.structType == sizeof(cp)) &&
4478 (cp.magic == YAFFS_MAGIC) &&
4479 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4480 (cp.head == ((head) ? 1 : 0));
4484 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4487 cp->nErasedBlocks = dev->nErasedBlocks;
4488 cp->allocationBlock = dev->allocationBlock;
4489 cp->allocationPage = dev->allocationPage;
4490 cp->nFreeChunks = dev->nFreeChunks;
4492 cp->nDeletedFiles = dev->nDeletedFiles;
4493 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4494 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4495 cp->sequenceNumber = dev->sequenceNumber;
4499 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4500 yaffs_CheckpointDevice *cp)
4502 dev->nErasedBlocks = cp->nErasedBlocks;
4503 dev->allocationBlock = cp->allocationBlock;
4504 dev->allocationPage = cp->allocationPage;
4505 dev->nFreeChunks = cp->nFreeChunks;
4507 dev->nDeletedFiles = cp->nDeletedFiles;
4508 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4509 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4510 dev->sequenceNumber = cp->sequenceNumber;
4514 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4516 yaffs_CheckpointDevice cp;
4518 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4522 /* Write device runtime values*/
4523 yaffs_DeviceToCheckpointDevice(&cp, dev);
4524 cp.structType = sizeof(cp);
4526 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4528 /* Write block info */
4530 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4531 ok = (yaffs_CheckpointWrite(dev, dev->blockInfo, nBytes) == nBytes);
4534 /* Write chunk bits */
4536 nBytes = nBlocks * dev->chunkBitmapStride;
4537 ok = (yaffs_CheckpointWrite(dev, dev->chunkBits, nBytes) == nBytes);
4543 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4545 yaffs_CheckpointDevice cp;
4547 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4551 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4555 if (cp.structType != sizeof(cp))
4559 yaffs_CheckpointDeviceToDevice(dev, &cp);
4561 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4563 ok = (yaffs_CheckpointRead(dev, dev->blockInfo, nBytes) == nBytes);
4567 nBytes = nBlocks * dev->chunkBitmapStride;
4569 ok = (yaffs_CheckpointRead(dev, dev->chunkBits, nBytes) == nBytes);
4574 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4578 cp->objectId = obj->objectId;
4579 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4580 cp->hdrChunk = obj->hdrChunk;
4581 cp->variantType = obj->variantType;
4582 cp->deleted = obj->deleted;
4583 cp->softDeleted = obj->softDeleted;
4584 cp->unlinked = obj->unlinked;
4585 cp->fake = obj->fake;
4586 cp->renameAllowed = obj->renameAllowed;
4587 cp->unlinkAllowed = obj->unlinkAllowed;
4588 cp->serial = obj->serial;
4589 cp->nDataChunks = obj->nDataChunks;
4591 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4592 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4593 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4594 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4597 static int yaffs_CheckpointObjectToObject(yaffs_Object *obj, yaffs_CheckpointObject *cp)
4600 yaffs_Object *parent;
4602 if (obj->variantType != cp->variantType) {
4603 T(YAFFS_TRACE_ERROR, (TSTR("Checkpoint read object %d type %d "
4604 TCONT("chunk %d does not match existing object type %d")
4605 TENDSTR), cp->objectId, cp->variantType, cp->hdrChunk,
4610 obj->objectId = cp->objectId;
4613 parent = yaffs_FindOrCreateObjectByNumber(
4616 YAFFS_OBJECT_TYPE_DIRECTORY);
4621 if (parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4622 T(YAFFS_TRACE_ALWAYS, (TSTR("Checkpoint read object %d parent %d type %d"
4623 TCONT(" chunk %d Parent type, %d, not directory")
4625 cp->objectId, cp->parentId, cp->variantType,
4626 cp->hdrChunk, parent->variantType));
4629 yaffs_AddObjectToDirectory(parent, obj);
4632 obj->hdrChunk = cp->hdrChunk;
4633 obj->variantType = cp->variantType;
4634 obj->deleted = cp->deleted;
4635 obj->softDeleted = cp->softDeleted;
4636 obj->unlinked = cp->unlinked;
4637 obj->fake = cp->fake;
4638 obj->renameAllowed = cp->renameAllowed;
4639 obj->unlinkAllowed = cp->unlinkAllowed;
4640 obj->serial = cp->serial;
4641 obj->nDataChunks = cp->nDataChunks;
4643 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4644 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4645 else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4646 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4648 if (obj->hdrChunk > 0)
4649 obj->lazyLoaded = 1;
4655 static int yaffs_CheckpointTnodeWorker(yaffs_Object *in, yaffs_Tnode *tn,
4656 __u32 level, int chunkOffset)
4659 yaffs_Device *dev = in->myDev;
4661 int tnodeSize = yaffs_CalcTnodeSize(dev);
4666 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
4667 if (tn->internal[i]) {
4668 ok = yaffs_CheckpointTnodeWorker(in,
4671 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4674 } else if (level == 0) {
4675 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4676 ok = (yaffs_CheckpointWrite(dev, &baseOffset, sizeof(baseOffset)) == sizeof(baseOffset));
4678 ok = (yaffs_CheckpointWrite(dev, tn, tnodeSize) == tnodeSize);
4686 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4688 __u32 endMarker = ~0;
4691 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4692 ok = yaffs_CheckpointTnodeWorker(obj,
4693 obj->variant.fileVariant.top,
4694 obj->variant.fileVariant.topLevel,
4697 ok = (yaffs_CheckpointWrite(obj->myDev, &endMarker, sizeof(endMarker)) ==
4704 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4708 yaffs_Device *dev = obj->myDev;
4709 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4712 int tnodeSize = yaffs_CalcTnodeSize(dev);
4714 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4716 while (ok && (~baseChunk)) {
4718 /* Read level 0 tnode */
4721 tn = yaffs_GetTnodeRaw(dev);
4723 ok = (yaffs_CheckpointRead(dev, tn, tnodeSize) == tnodeSize);
4728 ok = yaffs_AddOrFindLevel0Tnode(dev,
4734 ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4738 T(YAFFS_TRACE_CHECKPOINT, (
4739 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4740 nread, baseChunk, ok));
4746 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4749 yaffs_CheckpointObject cp;
4752 struct ylist_head *lh;
4755 /* Iterate through the objects in each hash entry,
4756 * dumping them to the checkpointing stream.
4759 for (i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++) {
4760 ylist_for_each(lh, &dev->objectBucket[i].list) {
4762 obj = ylist_entry(lh, yaffs_Object, hashLink);
4763 if (!obj->deferedFree) {
4764 yaffs_ObjectToCheckpointObject(&cp, obj);
4765 cp.structType = sizeof(cp);
4767 T(YAFFS_TRACE_CHECKPOINT, (
4768 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %p" TENDSTR),
4769 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk, obj));
4771 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4773 if (ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4774 ok = yaffs_WriteCheckpointTnodes(obj);
4780 /* Dump end of list */
4781 memset(&cp, 0xFF, sizeof(yaffs_CheckpointObject));
4782 cp.structType = sizeof(cp);
4785 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4790 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4793 yaffs_CheckpointObject cp;
4796 yaffs_Object *hardList = NULL;
4798 while (ok && !done) {
4799 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4800 if (cp.structType != sizeof(cp)) {
4801 T(YAFFS_TRACE_CHECKPOINT, (TSTR("struct size %d instead of %d ok %d"TENDSTR),
4802 cp.structType, (int)sizeof(cp), ok));
4806 T(YAFFS_TRACE_CHECKPOINT, (TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4807 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk));
4809 if (ok && cp.objectId == ~0)
4812 obj = yaffs_FindOrCreateObjectByNumber(dev, cp.objectId, cp.variantType);
4814 ok = yaffs_CheckpointObjectToObject(obj, &cp);
4817 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4818 ok = yaffs_ReadCheckpointTnodes(obj);
4819 } else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4820 obj->hardLinks.next =
4821 (struct ylist_head *) hardList;
4830 yaffs_HardlinkFixup(dev, hardList);
4835 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4837 __u32 checkpointSum;
4840 yaffs_GetCheckpointSum(dev, &checkpointSum);
4842 ok = (yaffs_CheckpointWrite(dev, &checkpointSum, sizeof(checkpointSum)) == sizeof(checkpointSum));
4850 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4852 __u32 checkpointSum0;
4853 __u32 checkpointSum1;
4856 yaffs_GetCheckpointSum(dev, &checkpointSum0);
4858 ok = (yaffs_CheckpointRead(dev, &checkpointSum1, sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4863 if (checkpointSum0 != checkpointSum1)
4870 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4874 if (dev->param.skipCheckpointWrite || !dev->param.isYaffs2) {
4875 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint write" TENDSTR)));
4880 ok = yaffs_CheckpointOpen(dev, 1);
4883 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4884 ok = yaffs_WriteCheckpointValidityMarker(dev, 1);
4887 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint device" TENDSTR)));
4888 ok = yaffs_WriteCheckpointDevice(dev);
4891 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint objects" TENDSTR)));
4892 ok = yaffs_WriteCheckpointObjects(dev);
4895 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4896 ok = yaffs_WriteCheckpointValidityMarker(dev, 0);
4900 ok = yaffs_WriteCheckpointSum(dev);
4902 if (!yaffs_CheckpointClose(dev))
4906 dev->isCheckpointed = 1;
4908 dev->isCheckpointed = 0;
4910 return dev->isCheckpointed;
4913 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4917 if (dev->param.skipCheckpointRead || !dev->param.isYaffs2) {
4918 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint read" TENDSTR)));
4923 ok = yaffs_CheckpointOpen(dev, 0); /* open for read */
4926 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4927 ok = yaffs_ReadCheckpointValidityMarker(dev, 1);
4930 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint device" TENDSTR)));
4931 ok = yaffs_ReadCheckpointDevice(dev);
4934 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint objects" TENDSTR)));
4935 ok = yaffs_ReadCheckpointObjects(dev);
4938 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4939 ok = yaffs_ReadCheckpointValidityMarker(dev, 0);
4943 ok = yaffs_ReadCheckpointSum(dev);
4944 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint checksum %d" TENDSTR), ok));
4947 if (!yaffs_CheckpointClose(dev))
4951 dev->isCheckpointed = 1;
4953 dev->isCheckpointed = 0;
4959 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4961 if (dev->isCheckpointed ||
4962 dev->blocksInCheckpoint > 0) {
4963 dev->isCheckpointed = 0;
4964 yaffs_CheckpointInvalidateStream(dev);
4966 if (dev->param.markSuperBlockDirty)
4967 dev->param.markSuperBlockDirty(dev);
4971 int yaffs_CheckpointSave(yaffs_Device *dev)
4974 T(YAFFS_TRACE_CHECKPOINT, (TSTR("save entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4976 yaffs_VerifyObjects(dev);
4977 yaffs_VerifyBlocks(dev);
4978 yaffs_VerifyFreeChunks(dev);
4980 if (!dev->isCheckpointed) {
4981 yaffs_InvalidateCheckpoint(dev);
4982 yaffs_WriteCheckpointData(dev);
4985 T(YAFFS_TRACE_ALWAYS, (TSTR("save exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4987 return dev->isCheckpointed;
4990 int yaffs_CheckpointRestore(yaffs_Device *dev)
4993 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4995 retval = yaffs_ReadCheckpointData(dev);
4997 if (dev->isCheckpointed) {
4998 yaffs_VerifyObjects(dev);
4999 yaffs_VerifyBlocks(dev);
5000 yaffs_VerifyFreeChunks(dev);
5003 T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
5008 /*--------------------- File read/write ------------------------
5009 * Read and write have very similar structures.
5010 * In general the read/write has three parts to it
5011 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
5012 * Some complete chunks
5013 * An incomplete chunk to end off with
5015 * Curve-balls: the first chunk might also be the last chunk.
5018 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 *buffer, loff_t offset,
5027 yaffs_ChunkCache *cache;
5034 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
5035 /* start = offset % dev->nDataBytesPerChunk; */
5036 yaffs_AddrToChunk(dev, offset, &chunk, &start);
5039 /* OK now check for the curveball where the start and end are in
5042 if ((start + n) < dev->nDataBytesPerChunk)
5045 nToCopy = dev->nDataBytesPerChunk - start;
5047 cache = yaffs_FindChunkCache(in, chunk);
5049 /* If the chunk is already in the cache or it is less than a whole chunk
5050 * or we're using inband tags then use the cache (if there is caching)
5051 * else bypass the cache.
5053 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
5054 if (dev->param.nShortOpCaches > 0) {
5056 /* If we can't find the data in the cache, then load it up. */
5059 cache = yaffs_GrabChunkCache(in->myDev);
5061 cache->chunkId = chunk;
5064 yaffs_ReadChunkDataFromObject(in, chunk,
5070 yaffs_UseChunkCache(dev, cache, 0);
5075 memcpy(buffer, &cache->data[start], nToCopy);
5079 /* Read into the local buffer then copy..*/
5082 yaffs_GetTempBuffer(dev, __LINE__);
5083 yaffs_ReadChunkDataFromObject(in, chunk,
5086 memcpy(buffer, &localBuffer[start], nToCopy);
5089 yaffs_ReleaseTempBuffer(dev, localBuffer,
5095 /* A full chunk. Read directly into the supplied buffer. */
5096 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
5110 int yaffs_DoWriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
5111 int nBytes, int writeThrough)
5120 int startOfWrite = offset;
5121 int chunkWritten = 0;
5129 while (n > 0 && chunkWritten >= 0) {
5130 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
5131 /* start = offset % dev->nDataBytesPerChunk; */
5132 yaffs_AddrToChunk(dev, offset, &chunk, &start);
5134 if (chunk * dev->nDataBytesPerChunk + start != offset ||
5135 start >= dev->nDataBytesPerChunk) {
5136 T(YAFFS_TRACE_ERROR, (
5137 TSTR("AddrToChunk of offset %d gives chunk %d start %d"
5139 (int)offset, chunk, start));
5143 /* OK now check for the curveball where the start and end are in
5147 if ((start + n) < dev->nDataBytesPerChunk) {
5150 /* Now folks, to calculate how many bytes to write back....
5151 * If we're overwriting and not writing to then end of file then
5152 * we need to write back as much as was there before.
5155 chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
5157 if (chunkStart > in->variant.fileVariant.fileSize)
5158 nBytesRead = 0; /* Past end of file */
5160 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
5162 if (nBytesRead > dev->nDataBytesPerChunk)
5163 nBytesRead = dev->nDataBytesPerChunk;
5167 (start + n)) ? nBytesRead : (start + n);
5169 if (nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
5173 nToCopy = dev->nDataBytesPerChunk - start;
5174 nToWriteBack = dev->nDataBytesPerChunk;
5177 if (nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
5178 /* An incomplete start or end chunk (or maybe both start and end chunk),
5179 * or we're using inband tags, so we want to use the cache buffers.
5181 if (dev->param.nShortOpCaches > 0) {
5182 yaffs_ChunkCache *cache;
5183 /* If we can't find the data in the cache, then load the cache */
5184 cache = yaffs_FindChunkCache(in, chunk);
5187 && yaffs_CheckSpaceForAllocation(dev, 1)) {
5188 cache = yaffs_GrabChunkCache(dev);
5190 cache->chunkId = chunk;
5193 yaffs_ReadChunkDataFromObject(in, chunk,
5197 !yaffs_CheckSpaceForAllocation(dev, 1)) {
5198 /* Drop the cache if it was a read cache item and
5199 * no space check has been made for it.
5205 yaffs_UseChunkCache(dev, cache, 1);
5209 memcpy(&cache->data[start], buffer,
5214 cache->nBytes = nToWriteBack;
5218 yaffs_WriteChunkDataToObject
5221 cache->data, cache->nBytes,
5227 chunkWritten = -1; /* fail the write */
5230 /* An incomplete start or end chunk (or maybe both start and end chunk)
5231 * Read into the local buffer then copy, then copy over and write back.
5235 yaffs_GetTempBuffer(dev, __LINE__);
5237 yaffs_ReadChunkDataFromObject(in, chunk,
5242 memcpy(&localBuffer[start], buffer, nToCopy);
5245 yaffs_WriteChunkDataToObject(in, chunk,
5250 yaffs_ReleaseTempBuffer(dev, localBuffer,
5256 /* A full chunk. Write directly from the supplied buffer. */
5261 yaffs_WriteChunkDataToObject(in, chunk, buffer,
5262 dev->nDataBytesPerChunk,
5265 /* Since we've overwritten the cached data, we better invalidate it. */
5266 yaffs_InvalidateChunkCache(in, chunk);
5269 if (chunkWritten >= 0) {
5278 /* Update file object */
5280 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
5281 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
5288 int yaffs_WriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
5289 int nBytes, int writeThrough)
5291 yaffs_HandleHole(in,offset);
5292 return yaffs_DoWriteDataToFile(in,buffer,offset,nBytes,writeThrough);
5297 /* ---------------------- File resizing stuff ------------------ */
5299 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
5302 yaffs_Device *dev = in->myDev;
5303 int oldFileSize = in->variant.fileVariant.fileSize;
5305 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
5307 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
5308 dev->nDataBytesPerChunk;
5312 /* Delete backwards so that we don't end up with holes if
5313 * power is lost part-way through the operation.
5315 for (i = lastDel; i >= startDel; i--) {
5316 /* NB this could be optimised somewhat,
5317 * eg. could retrieve the tags and write them without
5318 * using yaffs_DeleteChunk
5321 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5324 (dev->internalStartBlock * dev->param.nChunksPerBlock)
5326 ((dev->internalEndBlock +
5327 1) * dev->param.nChunksPerBlock)) {
5328 T(YAFFS_TRACE_ALWAYS,
5329 (TSTR("Found daft chunkId %d for %d" TENDSTR),
5333 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5341 static void yaffs_ResizeDown( yaffs_Object *obj, loff_t newSize)
5344 __u32 newSizeOfPartialChunk;
5345 yaffs_Device *dev = obj->myDev;
5347 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5349 yaffs_PruneResizedChunks(obj, newSize);
5351 if (newSizeOfPartialChunk != 0) {
5352 int lastChunk = 1 + newFullChunks;
5353 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5355 /* Got to read and rewrite the last chunk with its new size and zero pad */
5356 yaffs_ReadChunkDataFromObject(obj, lastChunk, localBuffer);
5357 memset(localBuffer + newSizeOfPartialChunk, 0,
5358 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5360 yaffs_WriteChunkDataToObject(obj, lastChunk, localBuffer,
5361 newSizeOfPartialChunk, 1);
5363 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5366 obj->variant.fileVariant.fileSize = newSize;
5368 yaffs_PruneFileStructure(dev, &obj->variant.fileVariant);
5372 static int yaffs_HandleHole(yaffs_Object *obj, loff_t newSize)
5374 /* if newsSize > oldFileSize.
5375 * We're going to be writing a hole.
5376 * If the hole is small then write zeros otherwise write a start of hole marker.
5383 int result = YAFFS_OK;
5384 yaffs_Device *dev = NULL;
5386 __u8 *localBuffer = NULL;
5388 int smallIncreaseOk = 0;
5393 if(obj->variantType != YAFFS_OBJECT_TYPE_FILE)
5398 /* Bail out if not yaffs2 mode */
5399 if(!dev->param.isYaffs2)
5402 oldFileSize = obj->variant.fileVariant.fileSize;
5404 if (newSize <= oldFileSize)
5407 increase = newSize - oldFileSize;
5409 if(increase < YAFFS_SMALL_HOLE_THRESHOLD * dev->nDataBytesPerChunk &&
5410 yaffs_CheckSpaceForAllocation(dev, YAFFS_SMALL_HOLE_THRESHOLD + 1))
5416 localBuffer= yaffs_GetTempBuffer(dev, __LINE__);
5419 /* fill hole with zero bytes */
5420 int pos = oldFileSize;
5423 memset(localBuffer,0,dev->nDataBytesPerChunk);
5424 smallIncreaseOk = 1;
5426 while(increase > 0 && smallIncreaseOk){
5427 thisWrite = increase;
5428 if(thisWrite > dev->nDataBytesPerChunk)
5429 thisWrite = dev->nDataBytesPerChunk;
5430 written = yaffs_DoWriteDataToFile(obj,localBuffer,pos,thisWrite,0);
5431 if(written == thisWrite){
5433 increase -= thisWrite;
5435 smallIncreaseOk = 0;
5438 yaffs_ReleaseTempBuffer(dev,localBuffer,__LINE__);
5440 /* If we were out of space then reverse any chunks we've added */
5441 if(!smallIncreaseOk)
5442 yaffs_ResizeDown(obj, oldFileSize);
5445 if (!smallIncreaseOk &&
5447 obj->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5448 obj->parent->objectId != YAFFS_OBJECTID_DELETED){
5449 /* Write a hole start header with the old file size */
5450 yaffs_UpdateObjectHeader(obj, NULL, 0,1,0);
5457 int yaffs_ResizeFile(yaffs_Object *in, loff_t newSize)
5459 yaffs_Device *dev = in->myDev;
5460 int oldFileSize = in->variant.fileVariant.fileSize;
5462 yaffs_FlushFilesChunkCache(in);
5463 yaffs_InvalidateWholeChunkCache(in);
5465 yaffs_CheckGarbageCollection(dev,0);
5467 if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
5470 if (newSize == oldFileSize)
5473 if(newSize > oldFileSize){
5474 yaffs_HandleHole(in,newSize);
5475 in->variant.fileVariant.fileSize = newSize;
5477 /* newSize < oldFileSize */
5478 yaffs_ResizeDown(in, newSize);
5481 /* Write a new object header to reflect the resize.
5482 * show we've shrunk the file, if need be
5483 * Do this only if the file is not in the deleted directories
5484 * and is not shadowed.
5488 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5489 in->parent->objectId != YAFFS_OBJECTID_DELETED)
5490 yaffs_UpdateObjectHeader(in, NULL, 0,0,0);
5496 loff_t yaffs_GetFileSize(yaffs_Object *obj)
5498 YCHAR *alias = NULL;
5499 obj = yaffs_GetEquivalentObject(obj);
5501 switch (obj->variantType) {
5502 case YAFFS_OBJECT_TYPE_FILE:
5503 return obj->variant.fileVariant.fileSize;
5504 case YAFFS_OBJECT_TYPE_SYMLINK:
5505 alias = obj->variant.symLinkVariant.alias;
5508 return yaffs_strnlen(alias,YAFFS_MAX_ALIAS_LENGTH);
5516 int yaffs_FlushFile(yaffs_Object *in, int updateTime, int dataSync)
5520 yaffs_FlushFilesChunkCache(in);
5521 if(dataSync) /* Only sync data */
5525 #ifdef CONFIG_YAFFS_WINCE
5526 yfsd_WinFileTimeNow(in->win_mtime);
5529 in->yst_mtime = Y_CURRENT_TIME;
5534 retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5535 0) ? YAFFS_OK : YAFFS_FAIL;
5545 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
5548 /* First off, invalidate the file's data in the cache, without flushing. */
5549 yaffs_InvalidateWholeChunkCache(in);
5551 if (in->myDev->param.isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5552 /* Move to the unlinked directory so we have a record that it was deleted. */
5553 yaffs_ChangeObjectName(in, in->myDev->deletedDir, _Y("deleted"), 0, 0);
5557 yaffs_RemoveObjectFromDirectory(in);
5558 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5561 yaffs_FreeObject(in);
5566 /* yaffs_DeleteFile deletes the whole file data
5567 * and the inode associated with the file.
5568 * It does not delete the links associated with the file.
5570 static int yaffs_UnlinkFileIfNeeded(yaffs_Object *in)
5574 int immediateDeletion = 0;
5575 yaffs_Device *dev = in->myDev;
5578 immediateDeletion = 1;
5580 if (immediateDeletion) {
5582 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5583 _Y("deleted"), 0, 0);
5584 T(YAFFS_TRACE_TRACING,
5585 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5588 in->myDev->nDeletedFiles++;
5589 if (dev->param.disableSoftDelete || dev->param.isYaffs2)
5590 yaffs_ResizeFile(in, 0);
5591 yaffs_SoftDeleteFile(in);
5594 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5595 _Y("unlinked"), 0, 0);
5602 int yaffs_DeleteFile(yaffs_Object *in)
5604 int retVal = YAFFS_OK;
5605 int deleted = in->deleted;
5606 yaffs_Device *dev = in->myDev;
5608 if (dev->param.disableSoftDelete || dev->param.isYaffs2)
5609 yaffs_ResizeFile(in, 0);
5611 if (in->nDataChunks > 0) {
5612 /* Use soft deletion if there is data in the file.
5613 * That won't be the case if it has been resized to zero.
5616 retVal = yaffs_UnlinkFileIfNeeded(in);
5618 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5621 in->myDev->nDeletedFiles++;
5622 yaffs_SoftDeleteFile(in);
5624 return deleted ? YAFFS_OK : YAFFS_FAIL;
5626 /* The file has no data chunks so we toss it immediately */
5627 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5628 in->variant.fileVariant.top = NULL;
5629 yaffs_DoGenericObjectDeletion(in);
5635 static int yaffs_IsNonEmptyDirectory(yaffs_Object *obj)
5637 return (obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) &&
5638 !(ylist_empty(&obj->variant.directoryVariant.children));
5641 static int yaffs_DeleteDirectory(yaffs_Object *obj)
5643 /* First check that the directory is empty. */
5644 if (yaffs_IsNonEmptyDirectory(obj))
5647 return yaffs_DoGenericObjectDeletion(obj);
5650 static int yaffs_DeleteSymLink(yaffs_Object *in)
5652 if(in->variant.symLinkVariant.alias)
5653 YFREE(in->variant.symLinkVariant.alias);
5654 in->variant.symLinkVariant.alias=NULL;
5656 return yaffs_DoGenericObjectDeletion(in);
5659 static int yaffs_DeleteHardLink(yaffs_Object *in)
5661 /* remove this hardlink from the list assocaited with the equivalent
5664 ylist_del_init(&in->hardLinks);
5665 return yaffs_DoGenericObjectDeletion(in);
5668 int yaffs_DeleteObject(yaffs_Object *obj)
5671 switch (obj->variantType) {
5672 case YAFFS_OBJECT_TYPE_FILE:
5673 retVal = yaffs_DeleteFile(obj);
5675 case YAFFS_OBJECT_TYPE_DIRECTORY:
5676 if(!ylist_empty(&obj->variant.directoryVariant.dirty)){
5677 T(YAFFS_TRACE_BACKGROUND, (TSTR("Remove object %d from dirty directories" TENDSTR),obj->objectId));
5678 ylist_del_init(&obj->variant.directoryVariant.dirty);
5680 return yaffs_DeleteDirectory(obj);
5682 case YAFFS_OBJECT_TYPE_SYMLINK:
5683 retVal = yaffs_DeleteSymLink(obj);
5685 case YAFFS_OBJECT_TYPE_HARDLINK:
5686 retVal = yaffs_DeleteHardLink(obj);
5688 case YAFFS_OBJECT_TYPE_SPECIAL:
5689 retVal = yaffs_DoGenericObjectDeletion(obj);
5691 case YAFFS_OBJECT_TYPE_UNKNOWN:
5693 break; /* should not happen. */
5699 static int yaffs_UnlinkWorker(yaffs_Object *obj)
5702 int immediateDeletion = 0;
5705 immediateDeletion = 1;
5708 yaffs_UpdateParent(obj->parent);
5710 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5711 return yaffs_DeleteHardLink(obj);
5712 } else if (!ylist_empty(&obj->hardLinks)) {
5713 /* Curve ball: We're unlinking an object that has a hardlink.
5715 * This problem arises because we are not strictly following
5716 * The Linux link/inode model.
5718 * We can't really delete the object.
5719 * Instead, we do the following:
5720 * - Select a hardlink.
5721 * - Unhook it from the hard links
5722 * - Move it from its parent directory (so that the rename can work)
5723 * - Rename the object to the hardlink's name.
5724 * - Delete the hardlink
5728 yaffs_Object *parent;
5730 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5732 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5734 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5735 parent = hl->parent;
5737 ylist_del_init(&hl->hardLinks);
5739 yaffs_AddObjectToDirectory(obj->myDev->unlinkedDir, hl);
5741 retVal = yaffs_ChangeObjectName(obj,parent, name, 0, 0);
5743 if (retVal == YAFFS_OK)
5744 retVal = yaffs_DoGenericObjectDeletion(hl);
5748 } else if (immediateDeletion) {
5749 switch (obj->variantType) {
5750 case YAFFS_OBJECT_TYPE_FILE:
5751 return yaffs_DeleteFile(obj);
5753 case YAFFS_OBJECT_TYPE_DIRECTORY:
5754 ylist_del_init(&obj->variant.directoryVariant.dirty);
5755 return yaffs_DeleteDirectory(obj);
5757 case YAFFS_OBJECT_TYPE_SYMLINK:
5758 return yaffs_DeleteSymLink(obj);
5760 case YAFFS_OBJECT_TYPE_SPECIAL:
5761 return yaffs_DoGenericObjectDeletion(obj);
5763 case YAFFS_OBJECT_TYPE_HARDLINK:
5764 case YAFFS_OBJECT_TYPE_UNKNOWN:
5768 } else if(yaffs_IsNonEmptyDirectory(obj))
5771 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
5772 _Y("unlinked"), 0, 0);
5776 static int yaffs_UnlinkObject(yaffs_Object *obj)
5779 if (obj && obj->unlinkAllowed)
5780 return yaffs_UnlinkWorker(obj);
5785 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
5789 obj = yaffs_FindObjectByName(dir, name);
5790 return yaffs_UnlinkObject(obj);
5793 /*----------------------- Initialisation Scanning ---------------------- */
5795 static void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
5796 int backwardScanning)
5800 if (!backwardScanning) {
5801 /* Handle YAFFS1 forward scanning case
5802 * For YAFFS1 we always do the deletion
5806 /* Handle YAFFS2 case (backward scanning)
5807 * If the shadowed object exists then ignore.
5809 obj = yaffs_FindObjectByNumber(dev, objId);
5814 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5815 * We put it in unlinked dir to be cleaned up after the scanning
5818 yaffs_FindOrCreateObjectByNumber(dev, objId,
5819 YAFFS_OBJECT_TYPE_FILE);
5822 obj->isShadowed = 1;
5823 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5824 obj->variant.fileVariant.shrinkSize = 0;
5825 obj->valid = 1; /* So that we don't read any other info for this file */
5835 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5842 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5844 in = yaffs_FindObjectByNumber(dev,
5845 hl->variant.hardLinkVariant.
5846 equivalentObjectId);
5849 /* Add the hardlink pointers */
5850 hl->variant.hardLinkVariant.equivalentObject = in;
5851 ylist_add(&hl->hardLinks, &in->hardLinks);
5853 /* Todo Need to report/handle this better.
5854 * Got a problem... hardlink to a non-existant object
5856 hl->variant.hardLinkVariant.equivalentObject = NULL;
5857 YINIT_LIST_HEAD(&hl->hardLinks);
5867 static int ybicmp(const void *a, const void *b)
5869 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5870 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5871 register int ablock = ((yaffs_BlockIndex *)a)->block;
5872 register int bblock = ((yaffs_BlockIndex *)b)->block;
5874 return ablock - bblock;
5880 struct yaffs_ShadowFixerStruct {
5883 struct yaffs_ShadowFixerStruct *next;
5887 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5890 * Sort out state of unlinked and deleted objects after scanning.
5892 struct ylist_head *i;
5893 struct ylist_head *n;
5896 /* Soft delete all the unlinked files */
5897 ylist_for_each_safe(i, n,
5898 &dev->unlinkedDir->variant.directoryVariant.children) {
5900 l = ylist_entry(i, yaffs_Object, siblings);
5901 yaffs_DeleteObject(l);
5905 ylist_for_each_safe(i, n,
5906 &dev->deletedDir->variant.directoryVariant.children) {
5908 l = ylist_entry(i, yaffs_Object, siblings);
5909 yaffs_DeleteObject(l);
5916 * This code iterates through all the objects making sure that they are rooted.
5917 * Any unrooted objects are re-rooted in lost+found.
5918 * An object needs to be in one of:
5919 * - Directly under deleted, unlinked
5920 * - Directly or indirectly under root.
5923 * This code assumes that we don't ever change the current relationships between
5925 * rootDir->parent == unlinkedDir->parent == deletedDir->parent == NULL
5926 * lostNfound->parent == rootDir
5928 * This fixes the problem where directories might have inadvertently been deleted
5929 * leaving the object "hanging" without being rooted in the directory tree.
5932 static int yaffs_HasNULLParent(yaffs_Device *dev, yaffs_Object *obj)
5934 return (obj == dev->deletedDir ||
5935 obj == dev->unlinkedDir||
5936 obj == dev->rootDir);
5939 static void yaffs_FixHangingObjects(yaffs_Device *dev)
5942 yaffs_Object *parent;
5944 struct ylist_head *lh;
5945 struct ylist_head *n;
5950 /* Iterate through the objects in each hash entry,
5951 * looking at each object.
5952 * Make sure it is rooted.
5955 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
5956 ylist_for_each_safe(lh, n, &dev->objectBucket[i].list) {
5958 obj = ylist_entry(lh, yaffs_Object, hashLink);
5959 parent= obj->parent;
5961 if(yaffs_HasNULLParent(dev,obj)){
5962 /* These directories are not hanging */
5965 else if(!parent || parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5967 else if(yaffs_HasNULLParent(dev,parent))
5971 * Need to follow the parent chain to see if it is hanging.
5976 while(parent != dev->rootDir &&
5978 parent->parent->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
5980 parent = parent->parent;
5983 if(parent != dev->rootDir)
5988 (TSTR("Hanging object %d moved to lost and found" TENDSTR),
5990 yaffs_AddObjectToDirectory(dev->lostNFoundDir,obj);
5999 * Delete directory contents for cleaning up lost and found.
6001 static void yaffs_DeleteDirectoryContents(yaffs_Object *dir)
6004 struct ylist_head *lh;
6005 struct ylist_head *n;
6007 if(dir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
6010 ylist_for_each_safe(lh, n, &dir->variant.directoryVariant.children) {
6012 obj = ylist_entry(lh, yaffs_Object, siblings);
6013 if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
6014 yaffs_DeleteDirectoryContents(obj);
6017 (TSTR("Deleting lost_found object %d" TENDSTR),
6020 /* Need to use UnlinkObject since Delete would not handle
6021 * hardlinked objects correctly.
6023 yaffs_UnlinkObject(obj);
6029 static void yaffs_EmptyLostAndFound(yaffs_Device *dev)
6031 yaffs_DeleteDirectoryContents(dev->lostNFoundDir);
6034 static int yaffs_Scan(yaffs_Device *dev)
6036 yaffs_ExtendedTags tags;
6046 yaffs_BlockState state;
6047 yaffs_Object *hardList = NULL;
6048 yaffs_BlockInfo *bi;
6049 __u32 sequenceNumber;
6050 yaffs_ObjectHeader *oh;
6052 yaffs_Object *parent;
6054 int alloc_failed = 0;
6056 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
6064 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
6065 dev->internalStartBlock, dev->internalEndBlock));
6067 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6069 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6071 /* Scan all the blocks to determine their state */
6072 bi = dev->blockInfo;
6073 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6074 yaffs_ClearChunkBits(dev, blk);
6076 bi->softDeletions = 0;
6078 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6080 bi->blockState = state;
6081 bi->sequenceNumber = sequenceNumber;
6083 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6084 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6086 T(YAFFS_TRACE_SCAN_DEBUG,
6087 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6088 state, sequenceNumber));
6090 if (state == YAFFS_BLOCK_STATE_DEAD) {
6091 T(YAFFS_TRACE_BAD_BLOCKS,
6092 (TSTR("block %d is bad" TENDSTR), blk));
6093 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6094 T(YAFFS_TRACE_SCAN_DEBUG,
6095 (TSTR("Block empty " TENDSTR)));
6096 dev->nErasedBlocks++;
6097 dev->nFreeChunks += dev->param.nChunksPerBlock;
6102 startIterator = dev->internalStartBlock;
6103 endIterator = dev->internalEndBlock;
6105 /* For each block.... */
6106 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
6113 blk = blockIterator;
6115 bi = yaffs_GetBlockInfo(dev, blk);
6116 state = bi->blockState;
6120 /* For each chunk in each block that needs scanning....*/
6121 for (c = 0; !alloc_failed && c < dev->param.nChunksPerBlock &&
6122 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
6123 /* Read the tags and decide what to do */
6124 chunk = blk * dev->param.nChunksPerBlock + c;
6126 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6129 /* Let's have a good look at this chunk... */
6131 if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
6137 /*T((" %d %d deleted\n",blk,c)); */
6138 } else if (!tags.chunkUsed) {
6139 /* An unassigned chunk in the block
6140 * This means that either the block is empty or
6141 * this is the one being allocated from
6145 /* We're looking at the first chunk in the block so the block is unused */
6146 state = YAFFS_BLOCK_STATE_EMPTY;
6147 dev->nErasedBlocks++;
6149 /* this is the block being allocated from */
6152 (" Allocating from %d %d" TENDSTR),
6154 state = YAFFS_BLOCK_STATE_ALLOCATING;
6155 dev->allocationBlock = blk;
6156 dev->allocationPage = c;
6157 dev->allocationBlockFinder = blk;
6158 /* Set block finder here to encourage the allocator to go forth from here. */
6162 dev->nFreeChunks += (dev->param.nChunksPerBlock - c);
6163 } else if (tags.chunkId > 0) {
6164 /* chunkId > 0 so it is a data chunk... */
6165 unsigned int endpos;
6167 yaffs_SetChunkBit(dev, blk, c);
6170 in = yaffs_FindOrCreateObjectByNumber(dev,
6173 YAFFS_OBJECT_TYPE_FILE);
6174 /* PutChunkIntoFile checks for a clash (two data chunks with
6175 * the same chunkId).
6182 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, 1))
6187 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
6190 in->variantType == YAFFS_OBJECT_TYPE_FILE
6191 && in->variant.fileVariant.scannedFileSize <
6193 in->variant.fileVariant.
6194 scannedFileSize = endpos;
6195 if (!dev->param.useHeaderFileSize) {
6196 in->variant.fileVariant.
6198 in->variant.fileVariant.
6203 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
6205 /* chunkId == 0, so it is an ObjectHeader.
6206 * Thus, we read in the object header and make the object
6208 yaffs_SetChunkBit(dev, blk, c);
6211 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
6215 oh = (yaffs_ObjectHeader *) chunkData;
6217 in = yaffs_FindObjectByNumber(dev,
6219 if (in && in->variantType != oh->type) {
6220 /* This should not happen, but somehow
6221 * Wev'e ended up with an objectId that has been reused but not yet
6222 * deleted, and worse still it has changed type. Delete the old object.
6225 yaffs_DeleteObject(in);
6230 in = yaffs_FindOrCreateObjectByNumber(dev,
6238 if (in && oh->shadowsObject > 0) {
6240 struct yaffs_ShadowFixerStruct *fixer;
6241 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
6243 fixer->next = shadowFixerList;
6244 shadowFixerList = fixer;
6245 fixer->objectId = tags.objectId;
6246 fixer->shadowedId = oh->shadowsObject;
6251 if (in && in->valid) {
6252 /* We have already filled this one. We have a duplicate and need to resolve it. */
6254 unsigned existingSerial = in->serial;
6255 unsigned newSerial = tags.serialNumber;
6257 if (((existingSerial + 1) & 3) == newSerial) {
6258 /* Use new one - destroy the exisiting one */
6259 yaffs_DeleteChunk(dev,
6264 /* Use existing - destroy this one. */
6265 yaffs_DeleteChunk(dev, chunk, 1,
6270 if (in && !in->valid &&
6271 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6272 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
6273 /* We only load some info, don't fiddle with directory structure */
6275 in->variantType = oh->type;
6277 in->yst_mode = oh->yst_mode;
6278 #ifdef CONFIG_YAFFS_WINCE
6279 in->win_atime[0] = oh->win_atime[0];
6280 in->win_ctime[0] = oh->win_ctime[0];
6281 in->win_mtime[0] = oh->win_mtime[0];
6282 in->win_atime[1] = oh->win_atime[1];
6283 in->win_ctime[1] = oh->win_ctime[1];
6284 in->win_mtime[1] = oh->win_mtime[1];
6286 in->yst_uid = oh->yst_uid;
6287 in->yst_gid = oh->yst_gid;
6288 in->yst_atime = oh->yst_atime;
6289 in->yst_mtime = oh->yst_mtime;
6290 in->yst_ctime = oh->yst_ctime;
6291 in->yst_rdev = oh->yst_rdev;
6293 in->hdrChunk = chunk;
6294 in->serial = tags.serialNumber;
6296 } else if (in && !in->valid) {
6297 /* we need to load this info */
6300 in->variantType = oh->type;
6302 in->yst_mode = oh->yst_mode;
6303 #ifdef CONFIG_YAFFS_WINCE
6304 in->win_atime[0] = oh->win_atime[0];
6305 in->win_ctime[0] = oh->win_ctime[0];
6306 in->win_mtime[0] = oh->win_mtime[0];
6307 in->win_atime[1] = oh->win_atime[1];
6308 in->win_ctime[1] = oh->win_ctime[1];
6309 in->win_mtime[1] = oh->win_mtime[1];
6311 in->yst_uid = oh->yst_uid;
6312 in->yst_gid = oh->yst_gid;
6313 in->yst_atime = oh->yst_atime;
6314 in->yst_mtime = oh->yst_mtime;
6315 in->yst_ctime = oh->yst_ctime;
6316 in->yst_rdev = oh->yst_rdev;
6318 in->hdrChunk = chunk;
6319 in->serial = tags.serialNumber;
6321 yaffs_SetObjectName(in, oh->name);
6324 /* directory stuff...
6329 yaffs_FindOrCreateObjectByNumber
6330 (dev, oh->parentObjectId,
6331 YAFFS_OBJECT_TYPE_DIRECTORY);
6334 if (parent && parent->variantType ==
6335 YAFFS_OBJECT_TYPE_UNKNOWN) {
6336 /* Set up as a directory */
6337 parent->variantType =
6338 YAFFS_OBJECT_TYPE_DIRECTORY;
6339 YINIT_LIST_HEAD(&parent->variant.
6342 } else if (!parent || parent->variantType !=
6343 YAFFS_OBJECT_TYPE_DIRECTORY) {
6344 /* Hoosterman, another problem....
6345 * We're trying to use a non-directory as a directory
6348 T(YAFFS_TRACE_ERROR,
6350 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6352 parent = dev->lostNFoundDir;
6355 yaffs_AddObjectToDirectory(parent, in);
6357 if (0 && (parent == dev->deletedDir ||
6358 parent == dev->unlinkedDir)) {
6359 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
6360 dev->nDeletedFiles++;
6362 /* Note re hardlinks.
6363 * Since we might scan a hardlink before its equivalent object is scanned
6364 * we put them all in a list.
6365 * After scanning is complete, we should have all the objects, so we run through this
6366 * list and fix up all the chains.
6369 switch (in->variantType) {
6370 case YAFFS_OBJECT_TYPE_UNKNOWN:
6371 /* Todo got a problem */
6373 case YAFFS_OBJECT_TYPE_FILE:
6374 if (dev->param.useHeaderFileSize)
6376 in->variant.fileVariant.
6381 case YAFFS_OBJECT_TYPE_HARDLINK:
6382 in->variant.hardLinkVariant.
6383 equivalentObjectId =
6384 oh->equivalentObjectId;
6385 in->hardLinks.next =
6386 (struct ylist_head *)
6390 case YAFFS_OBJECT_TYPE_DIRECTORY:
6393 case YAFFS_OBJECT_TYPE_SPECIAL:
6396 case YAFFS_OBJECT_TYPE_SYMLINK:
6397 in->variant.symLinkVariant.alias =
6398 yaffs_CloneString(oh->alias);
6399 if (!in->variant.symLinkVariant.alias)
6408 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6409 /* If we got this far while scanning, then the block is fully allocated.*/
6410 state = YAFFS_BLOCK_STATE_FULL;
6413 if (state == YAFFS_BLOCK_STATE_ALLOCATING) {
6414 /* If the block was partially allocated then treat it as fully allocated.*/
6415 state = YAFFS_BLOCK_STATE_FULL;
6416 dev->allocationBlock = -1;
6419 bi->blockState = state;
6421 /* Now let's see if it was dirty */
6422 if (bi->pagesInUse == 0 &&
6423 !bi->hasShrinkHeader &&
6424 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6425 yaffs_BlockBecameDirty(dev, blk);
6431 /* Ok, we've done all the scanning.
6432 * Fix up the hard link chains.
6433 * We should now have scanned all the objects, now it's time to add these
6437 yaffs_HardlinkFixup(dev, hardList);
6439 /* Fix up any shadowed objects */
6441 struct yaffs_ShadowFixerStruct *fixer;
6444 while (shadowFixerList) {
6445 fixer = shadowFixerList;
6446 shadowFixerList = fixer->next;
6447 /* Complete the rename transaction by deleting the shadowed object
6448 * then setting the object header to unshadowed.
6450 obj = yaffs_FindObjectByNumber(dev, fixer->shadowedId);
6452 yaffs_DeleteObject(obj);
6454 obj = yaffs_FindObjectByNumber(dev, fixer->objectId);
6457 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6463 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6468 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
6474 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
6477 yaffs_ObjectHeader *oh;
6479 yaffs_ExtendedTags tags;
6481 int alloc_failed = 0;
6489 T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
6491 in->lazyLoaded ? "not yet" : "already"));
6494 if (in->lazyLoaded && in->hdrChunk > 0) {
6496 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6498 result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
6499 oh = (yaffs_ObjectHeader *) chunkData;
6501 in->yst_mode = oh->yst_mode;
6502 #ifdef CONFIG_YAFFS_WINCE
6503 in->win_atime[0] = oh->win_atime[0];
6504 in->win_ctime[0] = oh->win_ctime[0];
6505 in->win_mtime[0] = oh->win_mtime[0];
6506 in->win_atime[1] = oh->win_atime[1];
6507 in->win_ctime[1] = oh->win_ctime[1];
6508 in->win_mtime[1] = oh->win_mtime[1];
6510 in->yst_uid = oh->yst_uid;
6511 in->yst_gid = oh->yst_gid;
6512 in->yst_atime = oh->yst_atime;
6513 in->yst_mtime = oh->yst_mtime;
6514 in->yst_ctime = oh->yst_ctime;
6515 in->yst_rdev = oh->yst_rdev;
6518 yaffs_SetObjectName(in, oh->name);
6520 if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6521 in->variant.symLinkVariant.alias =
6522 yaffs_CloneString(oh->alias);
6523 if (!in->variant.symLinkVariant.alias)
6524 alloc_failed = 1; /* Not returned to caller */
6527 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6531 static int yaffs_ScanBackwards(yaffs_Device *dev)
6533 yaffs_ExtendedTags tags;
6538 int nBlocksToScan = 0;
6544 yaffs_BlockState state;
6545 yaffs_Object *hardList = NULL;
6546 yaffs_BlockInfo *bi;
6547 __u32 sequenceNumber;
6548 yaffs_ObjectHeader *oh;
6550 yaffs_Object *parent;
6551 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6557 int foundChunksInBlock;
6558 int equivalentObjectId;
6559 int alloc_failed = 0;
6562 yaffs_BlockIndex *blockIndex = NULL;
6563 int altBlockIndex = 0;
6565 if (!dev->param.isYaffs2) {
6567 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6573 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
6574 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6577 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6579 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6582 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6588 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6592 dev->blocksInCheckpoint = 0;
6594 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6596 /* Scan all the blocks to determine their state */
6597 bi = dev->blockInfo;
6598 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6599 yaffs_ClearChunkBits(dev, blk);
6601 bi->softDeletions = 0;
6603 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6605 bi->blockState = state;
6606 bi->sequenceNumber = sequenceNumber;
6608 if (bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6609 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6610 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6611 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6613 T(YAFFS_TRACE_SCAN_DEBUG,
6614 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6615 state, sequenceNumber));
6618 if (state == YAFFS_BLOCK_STATE_CHECKPOINT) {
6619 dev->blocksInCheckpoint++;
6621 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6622 T(YAFFS_TRACE_BAD_BLOCKS,
6623 (TSTR("block %d is bad" TENDSTR), blk));
6624 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6625 T(YAFFS_TRACE_SCAN_DEBUG,
6626 (TSTR("Block empty " TENDSTR)));
6627 dev->nErasedBlocks++;
6628 dev->nFreeChunks += dev->param.nChunksPerBlock;
6629 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6631 /* Determine the highest sequence number */
6632 if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6633 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6635 blockIndex[nBlocksToScan].seq = sequenceNumber;
6636 blockIndex[nBlocksToScan].block = blk;
6640 if (sequenceNumber >= dev->sequenceNumber)
6641 dev->sequenceNumber = sequenceNumber;
6643 /* TODO: Nasty sequence number! */
6646 ("Block scanning block %d has bad sequence number %d"
6647 TENDSTR), blk, sequenceNumber));
6655 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6661 /* Sort the blocks */
6662 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6664 /* Use qsort now. */
6665 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6669 /* Dungy old bubble sort... */
6671 yaffs_BlockIndex temp;
6675 for (i = 0; i < nBlocksToScan; i++)
6676 for (j = i + 1; j < nBlocksToScan; j++)
6677 if (blockIndex[i].seq > blockIndex[j].seq) {
6678 temp = blockIndex[j];
6679 blockIndex[j] = blockIndex[i];
6680 blockIndex[i] = temp;
6687 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6689 /* Now scan the blocks looking at the data. */
6691 endIterator = nBlocksToScan - 1;
6692 T(YAFFS_TRACE_SCAN_DEBUG,
6693 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6695 /* For each block.... backwards */
6696 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6698 /* Cooperative multitasking! This loop can run for so
6699 long that watchdog timers expire. */
6702 /* get the block to scan in the correct order */
6703 blk = blockIndex[blockIterator].block;
6705 bi = yaffs_GetBlockInfo(dev, blk);
6708 state = bi->blockState;
6712 /* For each chunk in each block that needs scanning.... */
6713 foundChunksInBlock = 0;
6714 for (c = dev->param.nChunksPerBlock - 1;
6715 !alloc_failed && c >= 0 &&
6716 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6717 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6718 /* Scan backwards...
6719 * Read the tags and decide what to do
6722 chunk = blk * dev->param.nChunksPerBlock + c;
6724 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6727 /* Let's have a good look at this chunk... */
6729 if (!tags.chunkUsed) {
6730 /* An unassigned chunk in the block.
6731 * If there are used chunks after this one, then
6732 * it is a chunk that was skipped due to failing the erased
6733 * check. Just skip it so that it can be deleted.
6734 * But, more typically, We get here when this is an unallocated
6735 * chunk and his means that either the block is empty or
6736 * this is the one being allocated from
6739 if (foundChunksInBlock) {
6740 /* This is a chunk that was skipped due to failing the erased check */
6741 } else if (c == 0) {
6742 /* We're looking at the first chunk in the block so the block is unused */
6743 state = YAFFS_BLOCK_STATE_EMPTY;
6744 dev->nErasedBlocks++;
6746 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6747 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6748 if (dev->sequenceNumber == bi->sequenceNumber) {
6749 /* this is the block being allocated from */
6753 (" Allocating from %d %d"
6756 state = YAFFS_BLOCK_STATE_ALLOCATING;
6757 dev->allocationBlock = blk;
6758 dev->allocationPage = c;
6759 dev->allocationBlockFinder = blk;
6761 /* This is a partially written block that is not
6762 * the current allocation block.
6765 T(YAFFS_TRACE_ALWAYS,
6766 (TSTR("Partially written block %d detected" TENDSTR),
6774 } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED) {
6776 (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
6781 } else if (tags.chunkId > 0) {
6782 /* chunkId > 0 so it is a data chunk... */
6783 unsigned int endpos;
6785 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6787 foundChunksInBlock = 1;
6790 yaffs_SetChunkBit(dev, blk, c);
6793 in = yaffs_FindOrCreateObjectByNumber(dev,
6796 YAFFS_OBJECT_TYPE_FILE);
6803 in->variantType == YAFFS_OBJECT_TYPE_FILE
6804 && chunkBase < in->variant.fileVariant.shrinkSize) {
6805 /* This has not been invalidated by a resize */
6806 if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, -1)) {
6810 /* File size is calculated by looking at the data chunks if we have not
6811 * seen an object header yet. Stop this practice once we find an object header.
6813 endpos = chunkBase + tags.byteCount;
6815 if (!in->valid && /* have not got an object header yet */
6816 in->variant.fileVariant.scannedFileSize < endpos) {
6817 in->variant.fileVariant.scannedFileSize = endpos;
6818 in->variant.fileVariant.fileSize = endpos;
6822 /* This chunk has been invalidated by a resize, or a past file deletion
6823 * so delete the chunk*/
6824 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6828 /* chunkId == 0, so it is an ObjectHeader.
6829 * Thus, we read in the object header and make the object
6831 foundChunksInBlock = 1;
6833 yaffs_SetChunkBit(dev, blk, c);
6839 if (tags.extraHeaderInfoAvailable) {
6840 in = yaffs_FindOrCreateObjectByNumber(dev,
6842 tags.extraObjectType);
6848 (!in->valid && dev->param.disableLazyLoad) ||
6849 tags.extraShadows ||
6851 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6852 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))) {
6854 /* If we don't have valid info then we need to read the chunk
6855 * TODO In future we can probably defer reading the chunk and
6856 * living with invalid data until needed.
6859 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6864 oh = (yaffs_ObjectHeader *) chunkData;
6866 if (dev->param.inbandTags) {
6867 /* Fix up the header if they got corrupted by inband tags */
6868 oh->shadowsObject = oh->inbandShadowsObject;
6869 oh->isShrink = oh->inbandIsShrink;
6873 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6881 /* TODO Hoosterman we have a problem! */
6882 T(YAFFS_TRACE_ERROR,
6884 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6885 TENDSTR), tags.objectId, chunk));
6890 /* We have already filled this one.
6891 * We have a duplicate that will be discarded, but
6892 * we first have to suck out resize info if it is a file.
6895 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6897 oh->type == YAFFS_OBJECT_TYPE_FILE) ||
6898 (tags.extraHeaderInfoAvailable &&
6899 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))) {
6901 (oh) ? oh->fileSize : tags.
6903 __u32 parentObjectId =
6905 parentObjectId : tags.
6906 extraParentObjectId;
6910 (oh) ? oh->isShrink : tags.
6911 extraIsShrinkHeader;
6913 /* If it is deleted (unlinked at start also means deleted)
6914 * we treat the file size as being zeroed at this point.
6916 if (parentObjectId ==
6917 YAFFS_OBJECTID_DELETED
6918 || parentObjectId ==
6919 YAFFS_OBJECTID_UNLINKED) {
6924 if (isShrink && in->variant.fileVariant.shrinkSize > thisSize)
6925 in->variant.fileVariant.shrinkSize = thisSize;
6928 bi->hasShrinkHeader = 1;
6931 /* Use existing - destroy this one. */
6932 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6936 if (!in->valid && in->variantType !=
6937 (oh ? oh->type : tags.extraObjectType))
6938 T(YAFFS_TRACE_ERROR, (
6939 TSTR("yaffs tragedy: Bad object type, "
6940 TCONT("%d != %d, for object %d at chunk ")
6941 TCONT("%d during scan")
6943 oh->type : tags.extraObjectType,
6944 in->variantType, tags.objectId,
6948 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6950 YAFFS_OBJECTID_LOSTNFOUND)) {
6951 /* We only load some info, don't fiddle with directory structure */
6955 in->variantType = oh->type;
6957 in->yst_mode = oh->yst_mode;
6958 #ifdef CONFIG_YAFFS_WINCE
6959 in->win_atime[0] = oh->win_atime[0];
6960 in->win_ctime[0] = oh->win_ctime[0];
6961 in->win_mtime[0] = oh->win_mtime[0];
6962 in->win_atime[1] = oh->win_atime[1];
6963 in->win_ctime[1] = oh->win_ctime[1];
6964 in->win_mtime[1] = oh->win_mtime[1];
6966 in->yst_uid = oh->yst_uid;
6967 in->yst_gid = oh->yst_gid;
6968 in->yst_atime = oh->yst_atime;
6969 in->yst_mtime = oh->yst_mtime;
6970 in->yst_ctime = oh->yst_ctime;
6971 in->yst_rdev = oh->yst_rdev;
6975 in->variantType = tags.extraObjectType;
6979 in->hdrChunk = chunk;
6981 } else if (!in->valid) {
6982 /* we need to load this info */
6985 in->hdrChunk = chunk;
6988 in->variantType = oh->type;
6990 in->yst_mode = oh->yst_mode;
6991 #ifdef CONFIG_YAFFS_WINCE
6992 in->win_atime[0] = oh->win_atime[0];
6993 in->win_ctime[0] = oh->win_ctime[0];
6994 in->win_mtime[0] = oh->win_mtime[0];
6995 in->win_atime[1] = oh->win_atime[1];
6996 in->win_ctime[1] = oh->win_ctime[1];
6997 in->win_mtime[1] = oh->win_mtime[1];
6999 in->yst_uid = oh->yst_uid;
7000 in->yst_gid = oh->yst_gid;
7001 in->yst_atime = oh->yst_atime;
7002 in->yst_mtime = oh->yst_mtime;
7003 in->yst_ctime = oh->yst_ctime;
7004 in->yst_rdev = oh->yst_rdev;
7007 if (oh->shadowsObject > 0)
7008 yaffs_HandleShadowedObject(dev,
7015 yaffs_SetObjectName(in, oh->name);
7017 yaffs_FindOrCreateObjectByNumber
7018 (dev, oh->parentObjectId,
7019 YAFFS_OBJECT_TYPE_DIRECTORY);
7021 fileSize = oh->fileSize;
7022 isShrink = oh->isShrink;
7023 equivalentObjectId = oh->equivalentObjectId;
7026 in->variantType = tags.extraObjectType;
7028 yaffs_FindOrCreateObjectByNumber
7029 (dev, tags.extraParentObjectId,
7030 YAFFS_OBJECT_TYPE_DIRECTORY);
7031 fileSize = tags.extraFileLength;
7032 isShrink = tags.extraIsShrinkHeader;
7033 equivalentObjectId = tags.extraEquivalentObjectId;
7042 /* directory stuff...
7046 if (parent && parent->variantType ==
7047 YAFFS_OBJECT_TYPE_UNKNOWN) {
7048 /* Set up as a directory */
7049 parent->variantType =
7050 YAFFS_OBJECT_TYPE_DIRECTORY;
7051 YINIT_LIST_HEAD(&parent->variant.
7054 } else if (!parent || parent->variantType !=
7055 YAFFS_OBJECT_TYPE_DIRECTORY) {
7056 /* Hoosterman, another problem....
7057 * We're trying to use a non-directory as a directory
7060 T(YAFFS_TRACE_ERROR,
7062 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
7064 parent = dev->lostNFoundDir;
7067 yaffs_AddObjectToDirectory(parent, in);
7069 itsUnlinked = (parent == dev->deletedDir) ||
7070 (parent == dev->unlinkedDir);
7073 /* Mark the block as having a shrinkHeader */
7074 bi->hasShrinkHeader = 1;
7077 /* Note re hardlinks.
7078 * Since we might scan a hardlink before its equivalent object is scanned
7079 * we put them all in a list.
7080 * After scanning is complete, we should have all the objects, so we run
7081 * through this list and fix up all the chains.
7084 switch (in->variantType) {
7085 case YAFFS_OBJECT_TYPE_UNKNOWN:
7086 /* Todo got a problem */
7088 case YAFFS_OBJECT_TYPE_FILE:
7090 if (in->variant.fileVariant.
7091 scannedFileSize < fileSize) {
7092 /* This covers the case where the file size is greater
7093 * than where the data is
7094 * This will happen if the file is resized to be larger
7095 * than its current data extents.
7097 in->variant.fileVariant.fileSize = fileSize;
7098 in->variant.fileVariant.scannedFileSize = fileSize;
7101 if (in->variant.fileVariant.shrinkSize > fileSize)
7102 in->variant.fileVariant.shrinkSize = fileSize;
7106 case YAFFS_OBJECT_TYPE_HARDLINK:
7108 in->variant.hardLinkVariant.equivalentObjectId =
7110 in->hardLinks.next =
7111 (struct ylist_head *) hardList;
7115 case YAFFS_OBJECT_TYPE_DIRECTORY:
7118 case YAFFS_OBJECT_TYPE_SPECIAL:
7121 case YAFFS_OBJECT_TYPE_SYMLINK:
7123 in->variant.symLinkVariant.alias =
7124 yaffs_CloneString(oh->alias);
7125 if (!in->variant.symLinkVariant.alias)
7135 } /* End of scanning for each chunk */
7137 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
7138 /* If we got this far while scanning, then the block is fully allocated. */
7139 state = YAFFS_BLOCK_STATE_FULL;
7143 bi->blockState = state;
7145 /* Now let's see if it was dirty */
7146 if (bi->pagesInUse == 0 &&
7147 !bi->hasShrinkHeader &&
7148 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
7149 yaffs_BlockBecameDirty(dev, blk);
7154 yaffs_SkipRestOfBlock(dev);
7157 YFREE_ALT(blockIndex);
7161 /* Ok, we've done all the scanning.
7162 * Fix up the hard link chains.
7163 * We should now have scanned all the objects, now it's time to add these
7166 yaffs_HardlinkFixup(dev, hardList);
7169 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
7174 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
7179 /*------------------------------ Directory Functions ----------------------------- */
7181 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
7183 struct ylist_head *lh;
7184 yaffs_Object *listObj;
7189 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
7194 if (yaffs_SkipVerification(obj->myDev))
7198 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
7203 if (obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7204 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
7208 /* Iterate through the objects in each hash entry */
7210 ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
7212 listObj = ylist_entry(lh, yaffs_Object, siblings);
7213 yaffs_VerifyObject(listObj);
7220 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR), count));
7225 static void yaffs_VerifyDirectory(yaffs_Object *directory)
7227 struct ylist_head *lh;
7228 yaffs_Object *listObj;
7235 if (yaffs_SkipFullVerification(directory->myDev))
7238 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7239 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR), directory->variantType));
7243 /* Iterate through the objects in each hash entry */
7245 ylist_for_each(lh, &directory->variant.directoryVariant.children) {
7247 listObj = ylist_entry(lh, yaffs_Object, siblings);
7248 if (listObj->parent != directory) {
7249 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR), listObj->parent));
7252 yaffs_VerifyObjectInDirectory(listObj);
7258 *yaffs_UpdateParent() handles fixing a directories mtime and ctime when a new
7259 * link (ie. name) is created or deleted in the directory.
7262 * create dir/a : update dir's mtime/ctime
7263 * rm dir/a: update dir's mtime/ctime
7264 * modify dir/a: don't update dir's mtimme/ctime
7266 * This can be handled immediately or defered. Defering helps reduce the number
7267 * of updates when many files in a directory are changed within a brief period.
7269 * If the directory updating is defered then yaffs_UpdateDirtyDirecories must be
7270 * called periodically.
7273 static void yaffs_UpdateParent(yaffs_Object *obj)
7281 obj->yst_mtime = obj->yst_ctime = Y_CURRENT_TIME;
7282 if(dev->param.deferDirectoryUpdate){
7283 struct ylist_head *link = &obj->variant.directoryVariant.dirty;
7285 if(ylist_empty(link)){
7286 ylist_add(link,&dev->dirtyDirectories);
7287 T(YAFFS_TRACE_BACKGROUND, (TSTR("Added object %d to dirty directories" TENDSTR),obj->objectId));
7291 yaffs_UpdateObjectHeader(obj,NULL,0,0,0);
7294 void yaffs_UpdateDirtyDirectories(yaffs_Device *dev)
7296 struct ylist_head *link;
7298 yaffs_DirectoryStructure *dS;
7299 yaffs_ObjectVariant *oV;
7301 T(YAFFS_TRACE_BACKGROUND, (TSTR("Update dirty directories" TENDSTR)));
7303 while(!ylist_empty(&dev->dirtyDirectories)){
7304 link = dev->dirtyDirectories.next;
7305 ylist_del_init(link);
7307 dS=ylist_entry(link,yaffs_DirectoryStructure,dirty);
7308 oV = ylist_entry(dS,yaffs_ObjectVariant,directoryVariant);
7309 obj = ylist_entry(oV,yaffs_Object,variant);
7311 T(YAFFS_TRACE_BACKGROUND, (TSTR("Update directory %d" TENDSTR), obj->objectId));
7314 yaffs_UpdateObjectHeader(obj,NULL,0,0,0);
7318 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
7320 yaffs_Device *dev = obj->myDev;
7321 yaffs_Object *parent;
7323 yaffs_VerifyObjectInDirectory(obj);
7324 parent = obj->parent;
7326 yaffs_VerifyDirectory(parent);
7328 if (dev && dev->param.removeObjectCallback)
7329 dev->param.removeObjectCallback(obj);
7332 ylist_del_init(&obj->siblings);
7335 yaffs_VerifyDirectory(parent);
7338 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
7342 T(YAFFS_TRACE_ALWAYS,
7344 ("tragedy: Trying to add an object to a null pointer directory"
7349 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7350 T(YAFFS_TRACE_ALWAYS,
7352 ("tragedy: Trying to add an object to a non-directory"
7357 if (obj->siblings.prev == NULL) {
7358 /* Not initialised */
7363 yaffs_VerifyDirectory(directory);
7365 yaffs_RemoveObjectFromDirectory(obj);
7369 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
7370 obj->parent = directory;
7372 if (directory == obj->myDev->unlinkedDir
7373 || directory == obj->myDev->deletedDir) {
7375 obj->myDev->nUnlinkedFiles++;
7376 obj->renameAllowed = 0;
7379 yaffs_VerifyDirectory(directory);
7380 yaffs_VerifyObjectInDirectory(obj);
7383 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
7388 struct ylist_head *i;
7389 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
7397 T(YAFFS_TRACE_ALWAYS,
7399 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7404 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7405 T(YAFFS_TRACE_ALWAYS,
7407 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7411 sum = yaffs_CalcNameSum(name);
7413 ylist_for_each(i, &directory->variant.directoryVariant.children) {
7415 l = ylist_entry(i, yaffs_Object, siblings);
7417 if (l->parent != directory)
7420 yaffs_CheckObjectDetailsLoaded(l);
7422 /* Special case for lost-n-found */
7423 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7424 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
7426 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
7427 /* LostnFound chunk called Objxxx
7430 yaffs_GetObjectName(l, buffer,
7431 YAFFS_MAX_NAME_LENGTH + 1);
7432 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
7443 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
7444 int (*fn) (yaffs_Object *))
7446 struct ylist_head *i;
7450 T(YAFFS_TRACE_ALWAYS,
7452 ("tragedy: yaffs_FindObjectByName: null pointer directory"
7457 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7458 T(YAFFS_TRACE_ALWAYS,
7460 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7465 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
7467 l = ylist_entry(i, yaffs_Object, siblings);
7478 /* GetEquivalentObject dereferences any hard links to get to the
7482 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
7484 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
7485 /* We want the object id of the equivalent object, not this one */
7486 obj = obj->variant.hardLinkVariant.equivalentObject;
7487 yaffs_CheckObjectDetailsLoaded(obj);
7492 int yaffs_GetObjectName(yaffs_Object *obj, YCHAR *name, int buffSize)
7494 memset(name, 0, buffSize * sizeof(YCHAR));
7496 yaffs_CheckObjectDetailsLoaded(obj);
7498 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7499 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
7500 } else if (obj->hdrChunk <= 0) {
7502 YCHAR numString[20];
7503 YCHAR *x = &numString[19];
7504 unsigned v = obj->objectId;
7508 *x = '0' + (v % 10);
7511 /* make up a name */
7512 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
7513 yaffs_strcat(locName, x);
7514 yaffs_strncpy(name, locName, buffSize - 1);
7517 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
7518 else if (obj->shortName[0])
7519 yaffs_strncpy(name, obj->shortName,YAFFS_SHORT_NAME_LENGTH+1);
7523 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
7525 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
7527 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
7529 if (obj->hdrChunk > 0) {
7530 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
7531 obj->hdrChunk, buffer,
7534 yaffs_strncpy(name, oh->name, buffSize - 1);
7537 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
7540 return yaffs_strnlen(name,buffSize-1);
7543 int yaffs_GetObjectFileLength(yaffs_Object *obj)
7545 /* Dereference any hard linking */
7546 obj = yaffs_GetEquivalentObject(obj);
7548 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
7549 return obj->variant.fileVariant.fileSize;
7550 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
7551 if(!obj->variant.symLinkVariant.alias)
7553 return yaffs_strnlen(obj->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
7555 /* Only a directory should drop through to here */
7556 return obj->myDev->nDataBytesPerChunk;
7560 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
7563 struct ylist_head *i;
7566 count++; /* the object itself */
7568 ylist_for_each(i, &obj->hardLinks)
7569 count++; /* add the hard links; */
7574 int yaffs_GetObjectInode(yaffs_Object *obj)
7576 obj = yaffs_GetEquivalentObject(obj);
7578 return obj->objectId;
7581 unsigned yaffs_GetObjectType(yaffs_Object *obj)
7583 obj = yaffs_GetEquivalentObject(obj);
7585 switch (obj->variantType) {
7586 case YAFFS_OBJECT_TYPE_FILE:
7589 case YAFFS_OBJECT_TYPE_DIRECTORY:
7592 case YAFFS_OBJECT_TYPE_SYMLINK:
7595 case YAFFS_OBJECT_TYPE_HARDLINK:
7598 case YAFFS_OBJECT_TYPE_SPECIAL:
7599 if (S_ISFIFO(obj->yst_mode))
7601 if (S_ISCHR(obj->yst_mode))
7603 if (S_ISBLK(obj->yst_mode))
7605 if (S_ISSOCK(obj->yst_mode))
7613 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
7615 obj = yaffs_GetEquivalentObject(obj);
7616 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
7617 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7619 return yaffs_CloneString(_Y(""));
7622 #ifndef CONFIG_YAFFS_WINCE
7624 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
7626 unsigned int valid = attr->ia_valid;
7628 if (valid & ATTR_MODE)
7629 obj->yst_mode = attr->ia_mode;
7630 if (valid & ATTR_UID)
7631 obj->yst_uid = attr->ia_uid;
7632 if (valid & ATTR_GID)
7633 obj->yst_gid = attr->ia_gid;
7635 if (valid & ATTR_ATIME)
7636 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7637 if (valid & ATTR_CTIME)
7638 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7639 if (valid & ATTR_MTIME)
7640 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7642 if (valid & ATTR_SIZE)
7643 yaffs_ResizeFile(obj, attr->ia_size);
7645 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7650 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
7652 unsigned int valid = 0;
7654 attr->ia_mode = obj->yst_mode;
7656 attr->ia_uid = obj->yst_uid;
7658 attr->ia_gid = obj->yst_gid;
7661 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7662 valid |= ATTR_ATIME;
7663 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7664 valid |= ATTR_CTIME;
7665 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7666 valid |= ATTR_MTIME;
7668 attr->ia_size = yaffs_GetFileSize(obj);
7671 attr->ia_valid = valid;
7679 int yaffs_DumpObject(yaffs_Object *obj)
7683 yaffs_GetObjectName(obj, name, YAFFS_MAX_NAME_LENGTH + 1);
7685 T(YAFFS_TRACE_ALWAYS,
7687 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7688 " chunk %d type %d size %d\n"
7689 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7690 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7691 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7697 /*---------------------------- Initialisation code -------------------------------------- */
7699 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
7702 /* Common functions, gotta have */
7703 if (!dev->param.eraseBlockInNAND || !dev->param.initialiseNAND)
7706 #ifdef CONFIG_YAFFS_YAFFS2
7708 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7709 if (dev->param.writeChunkWithTagsToNAND &&
7710 dev->param.readChunkWithTagsFromNAND &&
7711 !dev->param.writeChunkToNAND &&
7712 !dev->param.readChunkFromNAND &&
7713 dev->param.markNANDBlockBad &&
7714 dev->param.queryNANDBlock)
7718 /* Can use the "spare" style interface for yaffs1 */
7719 if (!dev->param.isYaffs2 &&
7720 !dev->param.writeChunkWithTagsToNAND &&
7721 !dev->param.readChunkWithTagsFromNAND &&
7722 dev->param.writeChunkToNAND &&
7723 dev->param.readChunkFromNAND &&
7724 !dev->param.markNANDBlockBad &&
7725 !dev->param.queryNANDBlock)
7732 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7734 /* Initialise the unlinked, deleted, root and lost and found directories */
7736 dev->lostNFoundDir = dev->rootDir = NULL;
7737 dev->unlinkedDir = dev->deletedDir = NULL;
7740 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7743 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7746 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7747 YAFFS_ROOT_MODE | S_IFDIR);
7748 dev->lostNFoundDir =
7749 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7750 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7752 if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
7753 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7760 int yaffs_GutsInitialise(yaffs_Device *dev)
7762 int init_failed = 0;
7766 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7768 /* Check stuff that must be set */
7771 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7775 dev->internalStartBlock = dev->param.startBlock;
7776 dev->internalEndBlock = dev->param.endBlock;
7777 dev->blockOffset = 0;
7778 dev->chunkOffset = 0;
7779 dev->nFreeChunks = 0;
7783 if (dev->param.startBlock == 0) {
7784 dev->internalStartBlock = dev->param.startBlock + 1;
7785 dev->internalEndBlock = dev->param.endBlock + 1;
7786 dev->blockOffset = 1;
7787 dev->chunkOffset = dev->param.nChunksPerBlock;
7790 /* Check geometry parameters. */
7792 if ((!dev->param.inbandTags && dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 1024) ||
7793 (!dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 512) ||
7794 (dev->param.inbandTags && !dev->param.isYaffs2) ||
7795 dev->param.nChunksPerBlock < 2 ||
7796 dev->param.nReservedBlocks < 2 ||
7797 dev->internalStartBlock <= 0 ||
7798 dev->internalEndBlock <= 0 ||
7799 dev->internalEndBlock <= (dev->internalStartBlock + dev->param.nReservedBlocks + 2)) { /* otherwise it is too small */
7800 T(YAFFS_TRACE_ALWAYS,
7802 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7803 TENDSTR), dev->param.totalBytesPerChunk, dev->param.isYaffs2 ? "2" : "", dev->param.inbandTags));
7807 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7808 T(YAFFS_TRACE_ALWAYS,
7809 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7813 /* Sort out space for inband tags, if required */
7814 if (dev->param.inbandTags)
7815 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7817 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk;
7819 /* Got the right mix of functions? */
7820 if (!yaffs_CheckDevFunctions(dev)) {
7821 /* Function missing */
7822 T(YAFFS_TRACE_ALWAYS,
7824 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7829 /* This is really a compilation check. */
7830 if (!yaffs_CheckStructures()) {
7831 T(YAFFS_TRACE_ALWAYS,
7832 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7836 if (dev->isMounted) {
7837 T(YAFFS_TRACE_ALWAYS,
7838 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7842 /* Finished with most checks. One or two more checks happen later on too. */
7846 /* OK now calculate a few things for the device */
7849 * Calculate all the chunk size manipulation numbers:
7851 x = dev->nDataBytesPerChunk;
7852 /* We always use dev->chunkShift and dev->chunkDiv */
7853 dev->chunkShift = Shifts(x);
7854 x >>= dev->chunkShift;
7856 /* We only use chunk mask if chunkDiv is 1 */
7857 dev->chunkMask = (1<<dev->chunkShift) - 1;
7860 * Calculate chunkGroupBits.
7861 * We need to find the next power of 2 > than internalEndBlock
7864 x = dev->param.nChunksPerBlock * (dev->internalEndBlock + 1);
7868 /* Set up tnode width if wide tnodes are enabled. */
7869 if (!dev->param.wideTnodesDisabled) {
7870 /* bits must be even so that we end up with 32-bit words */
7874 dev->tnodeWidth = 16;
7876 dev->tnodeWidth = bits;
7878 dev->tnodeWidth = 16;
7880 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7882 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7883 * so if the bitwidth of the
7884 * chunk range we're using is greater than 16 we need
7885 * to figure out chunk shift and chunkGroupSize
7888 if (bits <= dev->tnodeWidth)
7889 dev->chunkGroupBits = 0;
7891 dev->chunkGroupBits = bits - dev->tnodeWidth;
7894 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7896 if (dev->param.nChunksPerBlock < dev->chunkGroupSize) {
7897 /* We have a problem because the soft delete won't work if
7898 * the chunk group size > chunks per block.
7899 * This can be remedied by using larger "virtual blocks".
7901 T(YAFFS_TRACE_ALWAYS,
7902 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7907 /* OK, we've finished verifying the device, lets continue with initialisation */
7909 /* More device initialisation */
7910 dev->garbageCollections = 0;
7911 dev->passiveGarbageCollections = 0;
7912 dev->gcBlockFinder = 0;
7913 dev->bufferedBlock = -1;
7914 dev->doingBufferedBlockRewrite = 0;
7915 dev->nDeletedFiles = 0;
7916 dev->nBackgroundDeletions = 0;
7917 dev->nUnlinkedFiles = 0;
7919 dev->eccUnfixed = 0;
7920 dev->tagsEccFixed = 0;
7921 dev->tagsEccUnfixed = 0;
7922 dev->nErasureFailures = 0;
7923 dev->nErasedBlocks = 0;
7925 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7926 YINIT_LIST_HEAD(&dev->dirtyDirectories);
7927 dev->oldestDirtySequence = 0;
7928 dev->oldestDirtyBlock = 0;
7930 /* Initialise temporary buffers and caches. */
7931 if (!yaffs_InitialiseTempBuffers(dev))
7934 dev->srCache = NULL;
7935 dev->gcCleanupList = NULL;
7939 dev->param.nShortOpCaches > 0) {
7942 int srCacheBytes = dev->param.nShortOpCaches * sizeof(yaffs_ChunkCache);
7944 if (dev->param.nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
7945 dev->param.nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7947 dev->srCache = YMALLOC(srCacheBytes);
7949 buf = (__u8 *) dev->srCache;
7952 memset(dev->srCache, 0, srCacheBytes);
7954 for (i = 0; i < dev->param.nShortOpCaches && buf; i++) {
7955 dev->srCache[i].object = NULL;
7956 dev->srCache[i].lastUse = 0;
7957 dev->srCache[i].dirty = 0;
7958 dev->srCache[i].data = buf = YMALLOC_DMA(dev->param.totalBytesPerChunk);
7969 dev->gcCleanupList = YMALLOC(dev->param.nChunksPerBlock * sizeof(__u32));
7970 if (!dev->gcCleanupList)
7974 if (dev->param.isYaffs2)
7975 dev->param.useHeaderFileSize = 1;
7977 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7980 yaffs_InitialiseTnodes(dev);
7981 yaffs_InitialiseObjects(dev);
7983 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7988 /* Now scan the flash. */
7989 if (dev->param.isYaffs2) {
7990 if (yaffs_CheckpointRestore(dev)) {
7991 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7992 T(YAFFS_TRACE_ALWAYS,
7993 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7996 /* Clean up the mess caused by an aborted checkpoint load
7997 * and scan backwards.
7999 yaffs_DeinitialiseBlocks(dev);
8000 yaffs_DeinitialiseTnodes(dev);
8001 yaffs_DeinitialiseObjects(dev);
8004 dev->nErasedBlocks = 0;
8005 dev->nFreeChunks = 0;
8006 dev->allocationBlock = -1;
8007 dev->allocationPage = -1;
8008 dev->nDeletedFiles = 0;
8009 dev->nUnlinkedFiles = 0;
8010 dev->nBackgroundDeletions = 0;
8012 if (!init_failed && !yaffs_InitialiseBlocks(dev))
8015 yaffs_InitialiseTnodes(dev);
8016 yaffs_InitialiseObjects(dev);
8018 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
8021 if (!init_failed && !yaffs_ScanBackwards(dev))
8024 } else if (!yaffs_Scan(dev))
8027 yaffs_StripDeletedObjects(dev);
8028 yaffs_FixHangingObjects(dev);
8029 if(dev->param.emptyLostAndFound)
8030 yaffs_EmptyLostAndFound(dev);
8034 /* Clean up the mess */
8035 T(YAFFS_TRACE_TRACING,
8036 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
8038 yaffs_Deinitialise(dev);
8042 /* Zero out stats */
8043 dev->nPageReads = 0;
8044 dev->nPageWrites = 0;
8045 dev->nBlockErasures = 0;
8047 dev->nRetriedWrites = 0;
8049 dev->nRetiredBlocks = 0;
8051 yaffs_VerifyFreeChunks(dev);
8052 yaffs_VerifyBlocks(dev);
8054 /* Clean up any aborted checkpoint data */
8055 if(!dev->isCheckpointed && dev->blocksInCheckpoint > 0)
8056 yaffs_InvalidateCheckpoint(dev);
8058 T(YAFFS_TRACE_TRACING,
8059 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
8064 void yaffs_Deinitialise(yaffs_Device *dev)
8066 if (dev->isMounted) {
8069 yaffs_DeinitialiseBlocks(dev);
8070 yaffs_DeinitialiseTnodes(dev);
8071 yaffs_DeinitialiseObjects(dev);
8072 if (dev->param.nShortOpCaches > 0 &&
8075 for (i = 0; i < dev->param.nShortOpCaches; i++) {
8076 if (dev->srCache[i].data)
8077 YFREE(dev->srCache[i].data);
8078 dev->srCache[i].data = NULL;
8081 YFREE(dev->srCache);
8082 dev->srCache = NULL;
8085 YFREE(dev->gcCleanupList);
8087 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
8088 YFREE(dev->tempBuffer[i].buffer);
8092 if (dev->param.deinitialiseNAND)
8093 dev->param.deinitialiseNAND(dev);
8097 static int yaffs_CountFreeChunks(yaffs_Device *dev)
8102 yaffs_BlockInfo *blk;
8104 blk = dev->blockInfo;
8105 for (b = dev->internalStartBlock; b <= dev->internalEndBlock; b++) {
8106 switch (blk->blockState) {
8107 case YAFFS_BLOCK_STATE_EMPTY:
8108 case YAFFS_BLOCK_STATE_ALLOCATING:
8109 case YAFFS_BLOCK_STATE_COLLECTING:
8110 case YAFFS_BLOCK_STATE_FULL:
8112 (dev->param.nChunksPerBlock - blk->pagesInUse +
8113 blk->softDeletions);
8124 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
8126 /* This is what we report to the outside world */
8129 int nDirtyCacheChunks;
8130 int blocksForCheckpoint;
8134 nFree = dev->nFreeChunks;
8136 nFree = yaffs_CountFreeChunks(dev);
8139 nFree += dev->nDeletedFiles;
8141 /* Now count the number of dirty chunks in the cache and subtract those */
8143 for (nDirtyCacheChunks = 0, i = 0; i < dev->param.nShortOpCaches; i++) {
8144 if (dev->srCache[i].dirty)
8145 nDirtyCacheChunks++;
8148 nFree -= nDirtyCacheChunks;
8150 nFree -= ((dev->param.nReservedBlocks + 1) * dev->param.nChunksPerBlock);
8152 /* Now we figure out how much to reserve for the checkpoint and report that... */
8153 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
8154 if (blocksForCheckpoint < 0)
8155 blocksForCheckpoint = 0;
8157 nFree -= (blocksForCheckpoint * dev->param.nChunksPerBlock);
8166 static int yaffs_freeVerificationFailures;
8168 static void yaffs_VerifyFreeChunks(yaffs_Device *dev)
8173 if (yaffs_SkipVerification(dev))
8176 counted = yaffs_CountFreeChunks(dev);
8178 difference = dev->nFreeChunks - counted;
8181 T(YAFFS_TRACE_ALWAYS,
8182 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
8183 dev->nFreeChunks, counted, difference));
8184 yaffs_freeVerificationFailures++;
8188 /*---------------------------------------- YAFFS test code ----------------------*/
8190 #define yaffs_CheckStruct(structure, syze, name) \
8192 if (sizeof(structure) != syze) { \
8193 T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
8194 name, syze, (int) sizeof(structure))); \
8195 return YAFFS_FAIL; \
8199 static int yaffs_CheckStructures(void)
8201 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
8202 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
8203 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
8204 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
8205 /* yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode"); */
8207 #ifndef CONFIG_YAFFS_WINCE
8208 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");