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.52 2007-10-16 00:45:05 charles Exp $";
19 #include "yaffsinterface.h"
20 #include "yaffs_guts.h"
21 #include "yaffs_tagsvalidity.h"
23 #include "yaffs_tagscompat.h"
24 #ifndef CONFIG_YAFFS_USE_OWN_SORT
25 #include "yaffs_qsort.h"
27 #include "yaffs_nand.h"
29 #include "yaffs_checkptrw.h"
31 #include "yaffs_nand.h"
32 #include "yaffs_packedtags2.h"
35 #ifdef CONFIG_YAFFS_WINCE
36 void yfsd_LockYAFFS(BOOL fsLockOnly);
37 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
40 #define YAFFS_PASSIVE_GC_CHUNKS 2
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, int erasedOk);
48 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
50 const yaffs_ExtendedTags * tags);
51 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
52 const yaffs_ExtendedTags * tags);
54 /* Other local prototypes */
55 static int yaffs_UnlinkObject( yaffs_Object *obj);
56 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
58 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
60 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
62 yaffs_ExtendedTags * tags,
64 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
65 int chunkInNAND, int inScan);
67 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
68 yaffs_ObjectType type);
69 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
71 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
72 int force, int isShrink, int shadows);
73 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
74 static int yaffs_CheckStructures(void);
75 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
76 int chunkOffset, int *limit);
77 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
79 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
81 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo);
82 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
85 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
88 static int yaffs_UnlinkWorker(yaffs_Object * obj);
89 static void yaffs_DestroyObject(yaffs_Object * obj);
91 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
94 loff_t yaffs_GetFileSize(yaffs_Object * obj);
96 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr);
98 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
100 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
102 #ifdef YAFFS_PARANOID
103 static int yaffs_CheckFileSanity(yaffs_Object * in);
105 #define yaffs_CheckFileSanity(in)
108 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
109 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
111 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
113 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
114 yaffs_ExtendedTags * tags);
116 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos);
117 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
118 yaffs_FileStructure * fStruct,
122 /* Function to calculate chunk and offset */
124 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, __u32 *chunk, __u32 *offset)
127 /* Easy-peasy power of 2 case */
128 *chunk = (__u32)(addr >> dev->chunkShift);
129 *offset = (__u32)(addr & dev->chunkMask);
131 else if(dev->crumbsPerChunk)
133 /* Case where we're using "crumbs" */
134 *offset = (__u32)(addr & dev->crumbMask);
135 addr >>= dev->crumbShift;
136 *chunk = ((__u32)addr)/dev->crumbsPerChunk;
137 *offset += ((addr - (*chunk * dev->crumbsPerChunk)) << dev->crumbShift);
143 /* Function to return the number of shifts for a power of 2 greater than or equal
144 * to the given number
145 * Note we don't try to cater for all possible numbers and this does not have to
146 * be hellishly efficient.
149 static __u32 ShiftsGE(__u32 x)
154 nShifts = extraBits = 0;
157 if(x & 1) extraBits++;
168 /* Function to return the number of shifts to get a 1 in bit 0
171 static __u32 ShiftDiv(__u32 x)
190 * Temporary buffer manipulations.
193 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
196 __u8 *buf = (__u8 *)1;
198 memset(dev->tempBuffer,0,sizeof(dev->tempBuffer));
200 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
201 dev->tempBuffer[i].line = 0; /* not in use */
202 dev->tempBuffer[i].buffer = buf =
203 YMALLOC_DMA(dev->nDataBytesPerChunk);
206 return buf ? YAFFS_OK : YAFFS_FAIL;
210 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
213 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
214 if (dev->tempBuffer[i].line == 0) {
215 dev->tempBuffer[i].line = lineNo;
216 if ((i + 1) > dev->maxTemp) {
217 dev->maxTemp = i + 1;
218 for (j = 0; j <= i; j++)
219 dev->tempBuffer[j].maxLine =
220 dev->tempBuffer[j].line;
223 return dev->tempBuffer[i].buffer;
227 T(YAFFS_TRACE_BUFFERS,
228 (TSTR("Out of temp buffers at line %d, other held by lines:"),
230 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
231 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
233 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
236 * If we got here then we have to allocate an unmanaged one
240 dev->unmanagedTempAllocations++;
241 return YMALLOC(dev->nDataBytesPerChunk);
245 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
249 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
250 if (dev->tempBuffer[i].buffer == buffer) {
251 dev->tempBuffer[i].line = 0;
257 /* assume it is an unmanaged one. */
258 T(YAFFS_TRACE_BUFFERS,
259 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
262 dev->unmanagedTempDeallocations++;
268 * Determine if we have a managed buffer.
270 int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
273 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
274 if (dev->tempBuffer[i].buffer == buffer)
279 for (i = 0; i < dev->nShortOpCaches; i++) {
280 if( dev->srCache[i].data == buffer )
285 if (buffer == dev->checkpointBuffer)
288 T(YAFFS_TRACE_ALWAYS,
289 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
296 * Chunk bitmap manipulations
299 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
301 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
303 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
307 return dev->chunkBits +
308 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
311 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
313 if(blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
314 chunk < 0 || chunk >= dev->nChunksPerBlock) {
316 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),blk,chunk));
321 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
323 __u8 *blkBits = yaffs_BlockBits(dev, blk);
325 memset(blkBits, 0, dev->chunkBitmapStride);
328 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
330 __u8 *blkBits = yaffs_BlockBits(dev, blk);
332 yaffs_VerifyChunkBitId(dev,blk,chunk);
334 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
337 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
339 __u8 *blkBits = yaffs_BlockBits(dev, blk);
341 yaffs_VerifyChunkBitId(dev,blk,chunk);
343 blkBits[chunk / 8] |= (1 << (chunk & 7));
346 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
348 __u8 *blkBits = yaffs_BlockBits(dev, blk);
349 yaffs_VerifyChunkBitId(dev,blk,chunk);
351 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
354 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
356 __u8 *blkBits = yaffs_BlockBits(dev, blk);
358 for (i = 0; i < dev->chunkBitmapStride; i++) {
366 static int yaffs_CountChunkBits(yaffs_Device * dev, int blk)
368 __u8 *blkBits = yaffs_BlockBits(dev, blk);
371 for (i = 0; i < dev->chunkBitmapStride; i++) {
388 static int yaffs_SkipVerification(yaffs_Device *dev)
390 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
393 static int yaffs_SkipFullVerification(yaffs_Device *dev)
395 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
398 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
400 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
403 static const char * blockStateName[] = {
416 static void yaffs_VerifyBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
421 if(yaffs_SkipVerification(dev))
424 /* Report illegal runtime states */
425 if(bi->blockState <0 || bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
426 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has undefined state %d"TENDSTR),n,bi->blockState));
428 switch(bi->blockState){
429 case YAFFS_BLOCK_STATE_UNKNOWN:
430 case YAFFS_BLOCK_STATE_SCANNING:
431 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
432 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has bad run-state %s"TENDSTR),
433 n,blockStateName[bi->blockState]));
436 /* Check pages in use and soft deletions are legal */
438 actuallyUsed = bi->pagesInUse - bi->softDeletions;
440 if(bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
441 bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
442 actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock)
443 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
444 n,bi->pagesInUse,bi->softDeletions));
447 /* Check chunk bitmap legal */
448 inUse = yaffs_CountChunkBits(dev,n);
449 if(inUse != bi->pagesInUse)
450 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
451 n,bi->pagesInUse,inUse));
453 /* Check that the sequence number is valid.
454 * Ten million is legal, but is very unlikely
457 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
458 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000 ))
459 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has suspect sequence number of %d"TENDSTR),
460 n,bi->sequenceNumber));
464 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
466 yaffs_VerifyBlock(dev,bi,n);
468 /* After collection the block should be in the erased state */
469 /* TODO: This will need to change if we do partial gc */
471 if(bi->blockState != YAFFS_BLOCK_STATE_EMPTY){
472 T(YAFFS_TRACE_ERROR,(TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
477 static void yaffs_VerifyBlocks(yaffs_Device *dev)
480 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
481 int nIllegalBlockStates = 0;
484 if(yaffs_SkipVerification(dev))
487 memset(nBlocksPerState,0,sizeof(nBlocksPerState));
490 for(i = dev->internalStartBlock; i <= dev->internalEndBlock; i++){
491 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
492 yaffs_VerifyBlock(dev,bi,i);
494 if(bi->blockState >=0 && bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
495 nBlocksPerState[bi->blockState]++;
497 nIllegalBlockStates++;
501 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
502 T(YAFFS_TRACE_VERIFY,(TSTR("Block summary"TENDSTR)));
504 T(YAFFS_TRACE_VERIFY,(TSTR("%d blocks have illegal states"TENDSTR),nIllegalBlockStates));
505 if(nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
506 T(YAFFS_TRACE_VERIFY,(TSTR("Too many allocating blocks"TENDSTR)));
508 for(i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
509 T(YAFFS_TRACE_VERIFY,
510 (TSTR("%s %d blocks"TENDSTR),
511 blockStateName[i],nBlocksPerState[i]));
513 if(dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
514 T(YAFFS_TRACE_VERIFY,
515 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
516 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
518 if(dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
519 T(YAFFS_TRACE_VERIFY,
520 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
521 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
523 if(nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
524 T(YAFFS_TRACE_VERIFY,
525 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
526 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
528 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
533 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
534 * case those tests will not be performed.
536 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
538 if(yaffs_SkipVerification(obj->myDev))
541 if(!(tags && obj && oh)){
542 T(YAFFS_TRACE_VERIFY,
543 (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR),
544 (__u32)tags,(__u32)obj,(__u32)oh));
548 if(oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
549 oh->type > YAFFS_OBJECT_TYPE_MAX)
550 T(YAFFS_TRACE_VERIFY,
551 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
552 tags->objectId, oh->type));
554 if(tags->objectId != obj->objectId)
555 T(YAFFS_TRACE_VERIFY,
556 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
557 tags->objectId, obj->objectId));
561 * Check that the object's parent ids match if parentCheck requested.
563 * Tests do not apply to the root object.
566 if(parentCheck && tags->objectId > 1 && !obj->parent)
567 T(YAFFS_TRACE_VERIFY,
568 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
569 tags->objectId, oh->parentObjectId));
572 if(parentCheck && obj->parent &&
573 oh->parentObjectId != obj->parent->objectId &&
574 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
575 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
576 T(YAFFS_TRACE_VERIFY,
577 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
578 tags->objectId, oh->parentObjectId, obj->parent->objectId));
581 if(tags->objectId > 1 && oh->name[0] == 0) /* Null name */
582 T(YAFFS_TRACE_VERIFY,
583 (TSTR("Obj %d header name is NULL"TENDSTR),
586 if(tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
587 T(YAFFS_TRACE_VERIFY,
588 (TSTR("Obj %d header name is 0xFF"TENDSTR),
594 static int yaffs_VerifyTnodeWorker(yaffs_Object * obj, yaffs_Tnode * tn,
595 __u32 level, int chunkOffset)
598 yaffs_Device *dev = obj->myDev;
600 int nTnodeBytes = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
605 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
606 if (tn->internal[i]) {
607 ok = yaffs_VerifyTnodeWorker(obj,
610 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
613 } else if (level == 0) {
615 yaffs_ExtendedTags tags;
616 __u32 objectId = obj->objectId;
618 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
620 for(i = 0; i < YAFFS_NTNODES_LEVEL0; i++){
621 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
624 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
625 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
626 if(tags.objectId != objectId || tags.chunkId != chunkOffset){
627 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
628 objectId, chunkOffset, theChunk,
629 tags.objectId, tags.chunkId));
642 static void yaffs_VerifyFile(yaffs_Object *obj)
644 int requiredTallness;
651 yaffs_ExtendedTags tags;
655 if(obj && yaffs_SkipVerification(obj->myDev))
659 objectId = obj->objectId;
661 /* Check file size is consistent with tnode depth */
662 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
663 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
664 requiredTallness = 0;
666 x >>= YAFFS_TNODES_INTERNAL_BITS;
670 actualTallness = obj->variant.fileVariant.topLevel;
672 if(requiredTallness > actualTallness )
673 T(YAFFS_TRACE_VERIFY,
674 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
675 obj->objectId,actualTallness, requiredTallness));
678 /* Check that the chunks in the tnode tree are all correct.
679 * We do this by scanning through the tnode tree and
680 * checking the tags for every chunk match.
683 if(yaffs_SkipNANDVerification(dev))
686 for(i = 1; i <= lastChunk; i++){
687 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant,i);
690 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
692 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
693 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
694 if(tags.objectId != objectId || tags.chunkId != i){
695 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
696 objectId, i, theChunk,
697 tags.objectId, tags.chunkId));
706 static void yaffs_VerifyDirectory(yaffs_Object *obj)
708 if(obj && yaffs_SkipVerification(obj->myDev))
713 static void yaffs_VerifyHardLink(yaffs_Object *obj)
715 if(obj && yaffs_SkipVerification(obj->myDev))
718 /* Verify sane equivalent object */
721 static void yaffs_VerifySymlink(yaffs_Object *obj)
723 if(obj && yaffs_SkipVerification(obj->myDev))
726 /* Verify symlink string */
729 static void yaffs_VerifySpecial(yaffs_Object *obj)
731 if(obj && yaffs_SkipVerification(obj->myDev))
735 static void yaffs_VerifyObject(yaffs_Object *obj)
750 if(yaffs_SkipVerification(dev))
753 /* Check sane object header chunk */
755 chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
756 chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
758 chunkIdOk = (obj->chunkId >= chunkMin && obj->chunkId <= chunkMax);
759 chunkIsLive = chunkIdOk &&
760 yaffs_CheckChunkBit(dev,
761 obj->chunkId / dev->nChunksPerBlock,
762 obj->chunkId % dev->nChunksPerBlock);
764 (!chunkIdOk || !chunkIsLive)) {
765 T(YAFFS_TRACE_VERIFY,
766 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
767 obj->objectId,obj->chunkId,
768 chunkIdOk ? "" : ",out of range",
769 chunkIsLive || !chunkIdOk ? "" : ",marked as deleted"));
772 if(chunkIdOk && chunkIsLive &&!yaffs_SkipNANDVerification(dev)) {
773 yaffs_ExtendedTags tags;
774 yaffs_ObjectHeader *oh;
775 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
777 oh = (yaffs_ObjectHeader *)buffer;
779 yaffs_ReadChunkWithTagsFromNAND(dev, obj->chunkId,buffer, &tags);
781 yaffs_VerifyObjectHeader(obj,oh,&tags,1);
783 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
786 /* Verify it has a parent */
787 if(obj && !obj->fake &&
788 (!obj->parent || obj->parent->myDev != dev)){
789 T(YAFFS_TRACE_VERIFY,
790 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
791 obj->objectId,obj->parent));
794 /* Verify parent is a directory */
795 if(obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
796 T(YAFFS_TRACE_VERIFY,
797 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
798 obj->objectId,obj->parent->variantType));
801 switch(obj->variantType){
802 case YAFFS_OBJECT_TYPE_FILE:
803 yaffs_VerifyFile(obj);
805 case YAFFS_OBJECT_TYPE_SYMLINK:
806 yaffs_VerifySymlink(obj);
808 case YAFFS_OBJECT_TYPE_DIRECTORY:
809 yaffs_VerifyDirectory(obj);
811 case YAFFS_OBJECT_TYPE_HARDLINK:
812 yaffs_VerifyHardLink(obj);
814 case YAFFS_OBJECT_TYPE_SPECIAL:
815 yaffs_VerifySpecial(obj);
817 case YAFFS_OBJECT_TYPE_UNKNOWN:
819 T(YAFFS_TRACE_VERIFY,
820 (TSTR("Obj %d has illegaltype %d"TENDSTR),
821 obj->objectId,obj->variantType));
828 static void yaffs_VerifyObjects(yaffs_Device *dev)
832 struct list_head *lh;
834 if(yaffs_SkipVerification(dev))
837 /* Iterate through the objects in each hash entry */
839 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++){
840 list_for_each(lh, &dev->objectBucket[i].list) {
842 obj = list_entry(lh, yaffs_Object, hashLink);
843 yaffs_VerifyObject(obj);
852 * Simple hash function. Needs to have a reasonable spread
855 static Y_INLINE int yaffs_HashFunction(int n)
858 return (n % YAFFS_NOBJECT_BUCKETS);
862 * Access functions to useful fake objects
865 yaffs_Object *yaffs_Root(yaffs_Device * dev)
870 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
872 return dev->lostNFoundDir;
877 * Erased NAND checking functions
880 int yaffs_CheckFF(__u8 * buffer, int nBytes)
882 /* Horrible, slow implementation */
891 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
895 int retval = YAFFS_OK;
896 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
897 yaffs_ExtendedTags tags;
900 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
902 if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
906 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
907 T(YAFFS_TRACE_NANDACCESS,
908 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
912 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
918 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
920 yaffs_ExtendedTags * tags,
927 yaffs_InvalidateCheckpoint(dev);
930 yaffs_BlockInfo *bi = 0;
933 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
939 /* First check this chunk is erased, if it needs
940 * checking. The checking policy (unless forced
941 * always on) is as follows:
943 * Check the first page we try to write in a block.
944 * If the check passes then we don't need to check any
945 * more. If the check fails, we check again...
946 * If the block has been erased, we don't need to check.
948 * However, if the block has been prioritised for gc,
949 * then we think there might be something odd about
950 * this block and stop using it.
952 * Rationale: We should only ever see chunks that have
953 * not been erased if there was a partially written
954 * chunk due to power loss. This checking policy should
955 * catch that case with very few checks and thus save a
956 * lot of checks that are most likely not needed.
958 if (bi->gcPrioritise) {
959 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
960 /* try another chunk */
964 /* let's give it a try */
967 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
968 bi->skipErasedCheck = 0;
970 if (!bi->skipErasedCheck) {
971 erasedOk = yaffs_CheckChunkErased(dev, chunk);
972 if (erasedOk != YAFFS_OK) {
974 (TSTR ("**>> yaffs chunk %d was not erased"
977 /* try another chunk */
980 bi->skipErasedCheck = 1;
983 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
985 if (writeOk != YAFFS_OK) {
986 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
987 /* try another chunk */
991 /* Copy the data into the robustification buffer */
992 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
994 } while (writeOk != YAFFS_OK &&
995 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1001 T(YAFFS_TRACE_ERROR,
1002 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1005 dev->nRetriedWrites += (attempts - 1);
1012 * Block retiring for handling a broken block.
1015 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
1017 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1019 yaffs_InvalidateCheckpoint(dev);
1021 yaffs_MarkBlockBad(dev, blockInNAND);
1023 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1024 bi->gcPrioritise = 0;
1025 bi->needsRetiring = 0;
1027 dev->nRetiredBlocks++;
1031 * Functions for robustisizing TODO
1035 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
1037 const yaffs_ExtendedTags * tags)
1041 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
1042 const yaffs_ExtendedTags * tags)
1046 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1048 if(!bi->gcPrioritise){
1049 bi->gcPrioritise = 1;
1050 dev->hasPendingPrioritisedGCs = 1;
1051 bi->chunkErrorStrikes ++;
1053 if(bi->chunkErrorStrikes > 3){
1054 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1055 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1062 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
1065 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1066 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1068 yaffs_HandleChunkError(dev,bi);
1072 /* Was an actual write failure, so mark the block for retirement */
1073 bi->needsRetiring = 1;
1074 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1075 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1080 /* Delete the chunk */
1081 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1085 /*---------------- Name handling functions ------------*/
1087 static __u16 yaffs_CalcNameSum(const YCHAR * name)
1092 YUCHAR *bname = (YUCHAR *) name;
1094 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1096 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1097 sum += yaffs_toupper(*bname) * i;
1099 sum += (*bname) * i;
1108 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
1110 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1111 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
1112 yaffs_strcpy(obj->shortName, name);
1114 obj->shortName[0] = _Y('\0');
1117 obj->sum = yaffs_CalcNameSum(name);
1120 /*-------------------- TNODES -------------------
1122 * List of spare tnodes
1123 * The list is hooked together using the first pointer
1127 /* yaffs_CreateTnodes creates a bunch more tnodes and
1128 * adds them to the tnode free list.
1129 * Don't use this function directly
1132 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
1136 yaffs_Tnode *newTnodes;
1140 yaffs_TnodeList *tnl;
1145 /* Calculate the tnode size in bytes for variable width tnode support.
1146 * Must be a multiple of 32-bits */
1147 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1149 /* make these things */
1151 newTnodes = YMALLOC(nTnodes * tnodeSize);
1152 mem = (__u8 *)newTnodes;
1155 T(YAFFS_TRACE_ERROR,
1156 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1160 /* Hook them into the free list */
1162 for (i = 0; i < nTnodes - 1; i++) {
1163 newTnodes[i].internal[0] = &newTnodes[i + 1];
1164 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1165 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1169 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1170 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1171 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1173 dev->freeTnodes = newTnodes;
1175 /* New hookup for wide tnodes */
1176 for(i = 0; i < nTnodes -1; i++) {
1177 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1178 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1179 curr->internal[0] = next;
1182 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1183 curr->internal[0] = dev->freeTnodes;
1184 dev->freeTnodes = (yaffs_Tnode *)mem;
1189 dev->nFreeTnodes += nTnodes;
1190 dev->nTnodesCreated += nTnodes;
1192 /* Now add this bunch of tnodes to a list for freeing up.
1193 * NB If we can't add this to the management list it isn't fatal
1194 * but it just means we can't free this bunch of tnodes later.
1197 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1199 T(YAFFS_TRACE_ERROR,
1201 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1205 tnl->tnodes = newTnodes;
1206 tnl->next = dev->allocatedTnodeList;
1207 dev->allocatedTnodeList = tnl;
1210 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1215 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1217 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
1219 yaffs_Tnode *tn = NULL;
1221 /* If there are none left make more */
1222 if (!dev->freeTnodes) {
1223 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1226 if (dev->freeTnodes) {
1227 tn = dev->freeTnodes;
1228 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1229 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1230 /* Hoosterman, this thing looks like it isn't in the list */
1231 T(YAFFS_TRACE_ALWAYS,
1232 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1235 dev->freeTnodes = dev->freeTnodes->internal[0];
1242 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
1244 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1247 memset(tn, 0, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1252 /* FreeTnode frees up a tnode and puts it back on the free list */
1253 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
1256 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1257 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1258 /* Hoosterman, this thing looks like it is already in the list */
1259 T(YAFFS_TRACE_ALWAYS,
1260 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1262 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1264 tn->internal[0] = dev->freeTnodes;
1265 dev->freeTnodes = tn;
1270 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
1272 /* Free the list of allocated tnodes */
1273 yaffs_TnodeList *tmp;
1275 while (dev->allocatedTnodeList) {
1276 tmp = dev->allocatedTnodeList->next;
1278 YFREE(dev->allocatedTnodeList->tnodes);
1279 YFREE(dev->allocatedTnodeList);
1280 dev->allocatedTnodeList = tmp;
1284 dev->freeTnodes = NULL;
1285 dev->nFreeTnodes = 0;
1288 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
1290 dev->allocatedTnodeList = NULL;
1291 dev->freeTnodes = NULL;
1292 dev->nFreeTnodes = 0;
1293 dev->nTnodesCreated = 0;
1298 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
1300 __u32 *map = (__u32 *)tn;
1306 pos &= YAFFS_TNODES_LEVEL0_MASK;
1307 val >>= dev->chunkGroupBits;
1309 bitInMap = pos * dev->tnodeWidth;
1310 wordInMap = bitInMap /32;
1311 bitInWord = bitInMap & (32 -1);
1313 mask = dev->tnodeMask << bitInWord;
1315 map[wordInMap] &= ~mask;
1316 map[wordInMap] |= (mask & (val << bitInWord));
1318 if(dev->tnodeWidth > (32-bitInWord)) {
1319 bitInWord = (32 - bitInWord);
1321 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1322 map[wordInMap] &= ~mask;
1323 map[wordInMap] |= (mask & (val >> bitInWord));
1327 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
1329 __u32 *map = (__u32 *)tn;
1335 pos &= YAFFS_TNODES_LEVEL0_MASK;
1337 bitInMap = pos * dev->tnodeWidth;
1338 wordInMap = bitInMap /32;
1339 bitInWord = bitInMap & (32 -1);
1341 val = map[wordInMap] >> bitInWord;
1343 if(dev->tnodeWidth > (32-bitInWord)) {
1344 bitInWord = (32 - bitInWord);
1346 val |= (map[wordInMap] << bitInWord);
1349 val &= dev->tnodeMask;
1350 val <<= dev->chunkGroupBits;
1355 /* ------------------- End of individual tnode manipulation -----------------*/
1357 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1358 * The look up tree is represented by the top tnode and the number of topLevel
1359 * in the tree. 0 means only the level 0 tnode is in the tree.
1362 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1363 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
1364 yaffs_FileStructure * fStruct,
1368 yaffs_Tnode *tn = fStruct->top;
1370 int requiredTallness;
1371 int level = fStruct->topLevel;
1373 /* Check sane level and chunk Id */
1374 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
1378 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1382 /* First check we're tall enough (ie enough topLevel) */
1384 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1385 requiredTallness = 0;
1387 i >>= YAFFS_TNODES_INTERNAL_BITS;
1391 if (requiredTallness > fStruct->topLevel) {
1392 /* Not tall enough, so we can't find it, return NULL. */
1396 /* Traverse down to level 0 */
1397 while (level > 0 && tn) {
1399 internal[(chunkId >>
1400 ( YAFFS_TNODES_LEVEL0_BITS +
1402 YAFFS_TNODES_INTERNAL_BITS)
1404 YAFFS_TNODES_INTERNAL_MASK];
1412 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1413 * This happens in two steps:
1414 * 1. If the tree isn't tall enough, then make it taller.
1415 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1417 * Used when modifying the tree.
1419 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1420 * be plugged into the ttree.
1423 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
1424 yaffs_FileStructure * fStruct,
1426 yaffs_Tnode *passedTn)
1429 int requiredTallness;
1437 /* Check sane level and page Id */
1438 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
1442 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1446 /* First check we're tall enough (ie enough topLevel) */
1448 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1449 requiredTallness = 0;
1451 x >>= YAFFS_TNODES_INTERNAL_BITS;
1456 if (requiredTallness > fStruct->topLevel) {
1457 /* Not tall enough,gotta make the tree taller */
1458 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1460 tn = yaffs_GetTnode(dev);
1463 tn->internal[0] = fStruct->top;
1466 T(YAFFS_TRACE_ERROR,
1467 (TSTR("yaffs: no more tnodes" TENDSTR)));
1471 fStruct->topLevel = requiredTallness;
1474 /* Traverse down to level 0, adding anything we need */
1476 l = fStruct->topLevel;
1480 while (l > 0 && tn) {
1482 ( YAFFS_TNODES_LEVEL0_BITS +
1483 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1484 YAFFS_TNODES_INTERNAL_MASK;
1487 if((l>1) && !tn->internal[x]){
1488 /* Add missing non-level-zero tnode */
1489 tn->internal[x] = yaffs_GetTnode(dev);
1492 /* Looking from level 1 at level 0 */
1494 /* If we already have one, then release it.*/
1496 yaffs_FreeTnode(dev,tn->internal[x]);
1497 tn->internal[x] = passedTn;
1499 } else if(!tn->internal[x]) {
1500 /* Don't have one, none passed in */
1501 tn->internal[x] = yaffs_GetTnode(dev);
1505 tn = tn->internal[x];
1509 /* top is level 0 */
1511 memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1512 yaffs_FreeTnode(dev,passedTn);
1519 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1520 yaffs_ExtendedTags * tags, int objectId,
1525 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1526 if (yaffs_CheckChunkBit
1527 (dev, theChunk / dev->nChunksPerBlock,
1528 theChunk % dev->nChunksPerBlock)) {
1529 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1531 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1543 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1544 * chunks and tnodes in the file
1545 * Returns 1 if the tree was deleted.
1546 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1549 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1550 int chunkOffset, int *limit)
1555 yaffs_ExtendedTags tags;
1557 yaffs_Device *dev = in->myDev;
1564 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1566 if (tn->internal[i]) {
1567 if (limit && (*limit) < 0) {
1571 yaffs_DeleteWorker(in,
1579 YAFFS_TNODES_INTERNAL_BITS)
1584 yaffs_FreeTnode(dev,
1587 tn->internal[i] = NULL;
1592 return (allDone) ? 1 : 0;
1593 } else if (level == 0) {
1596 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1598 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1603 YAFFS_TNODES_LEVEL0_BITS) + i;
1606 yaffs_FindChunkInGroup(dev,
1612 if (foundChunk > 0) {
1613 yaffs_DeleteChunk(dev,
1618 *limit = *limit - 1;
1626 yaffs_PutLevel0Tnode(dev,tn,i,0);
1630 return (i < 0) ? 1 : 0;
1640 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1643 yaffs_BlockInfo *theBlock;
1645 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1647 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1649 theBlock->softDeletions++;
1654 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1655 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1657 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1660 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1661 __u32 level, int chunkOffset)
1666 yaffs_Device *dev = in->myDev;
1671 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1673 if (tn->internal[i]) {
1675 yaffs_SoftDeleteWorker(in,
1681 YAFFS_TNODES_INTERNAL_BITS)
1684 yaffs_FreeTnode(dev,
1687 tn->internal[i] = NULL;
1689 /* Hoosterman... how could this happen? */
1693 return (allDone) ? 1 : 0;
1694 } else if (level == 0) {
1696 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1697 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1699 /* Note this does not find the real chunk, only the chunk group.
1700 * We make an assumption that a chunk group is not larger than
1703 yaffs_SoftDeleteChunk(dev, theChunk);
1704 yaffs_PutLevel0Tnode(dev,tn,i,0);
1718 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1721 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1722 if (obj->nDataChunks <= 0) {
1723 /* Empty file with no duplicate object headers, just delete it immediately */
1724 yaffs_FreeTnode(obj->myDev,
1725 obj->variant.fileVariant.top);
1726 obj->variant.fileVariant.top = NULL;
1727 T(YAFFS_TRACE_TRACING,
1728 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1730 yaffs_DoGenericObjectDeletion(obj);
1732 yaffs_SoftDeleteWorker(obj,
1733 obj->variant.fileVariant.top,
1734 obj->variant.fileVariant.
1736 obj->softDeleted = 1;
1741 /* Pruning removes any part of the file structure tree that is beyond the
1742 * bounds of the file (ie that does not point to chunks).
1744 * A file should only get pruned when its size is reduced.
1746 * Before pruning, the chunks must be pulled from the tree and the
1747 * level 0 tnode entries must be zeroed out.
1748 * Could also use this for file deletion, but that's probably better handled
1749 * by a special case.
1752 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1753 __u32 level, int del0)
1761 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1762 if (tn->internal[i] && level > 0) {
1764 yaffs_PruneWorker(dev, tn->internal[i],
1766 (i == 0) ? del0 : 1);
1769 if (tn->internal[i]) {
1774 if (hasData == 0 && del0) {
1775 /* Free and return NULL */
1777 yaffs_FreeTnode(dev, tn);
1787 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1788 yaffs_FileStructure * fStruct)
1795 if (fStruct->topLevel > 0) {
1797 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1799 /* Now we have a tree with all the non-zero branches NULL but the height
1800 * is the same as it was.
1801 * Let's see if we can trim internal tnodes to shorten the tree.
1802 * We can do this if only the 0th element in the tnode is in use
1803 * (ie all the non-zero are NULL)
1806 while (fStruct->topLevel && !done) {
1810 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1811 if (tn->internal[i]) {
1817 fStruct->top = tn->internal[0];
1818 fStruct->topLevel--;
1819 yaffs_FreeTnode(dev, tn);
1829 /*-------------------- End of File Structure functions.-------------------*/
1831 /* yaffs_CreateFreeObjects creates a bunch more objects and
1832 * adds them to the object free list.
1834 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1837 yaffs_Object *newObjects;
1838 yaffs_ObjectList *list;
1843 /* make these things */
1844 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1845 list = YMALLOC(sizeof(yaffs_ObjectList));
1847 if (!newObjects || !list) {
1852 T(YAFFS_TRACE_ALLOCATE,
1853 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1857 /* Hook them into the free list */
1858 for (i = 0; i < nObjects - 1; i++) {
1859 newObjects[i].siblings.next =
1860 (struct list_head *)(&newObjects[i + 1]);
1863 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1864 dev->freeObjects = newObjects;
1865 dev->nFreeObjects += nObjects;
1866 dev->nObjectsCreated += nObjects;
1868 /* Now add this bunch of Objects to a list for freeing up. */
1870 list->objects = newObjects;
1871 list->next = dev->allocatedObjectList;
1872 dev->allocatedObjectList = list;
1878 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1879 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1881 yaffs_Object *tn = NULL;
1883 /* If there are none left make more */
1884 if (!dev->freeObjects) {
1885 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1888 if (dev->freeObjects) {
1889 tn = dev->freeObjects;
1891 (yaffs_Object *) (dev->freeObjects->siblings.next);
1892 dev->nFreeObjects--;
1894 /* Now sweeten it up... */
1896 memset(tn, 0, sizeof(yaffs_Object));
1899 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1900 INIT_LIST_HEAD(&(tn->hardLinks));
1901 INIT_LIST_HEAD(&(tn->hashLink));
1902 INIT_LIST_HEAD(&tn->siblings);
1904 /* Add it to the lost and found directory.
1905 * NB Can't put root or lostNFound in lostNFound so
1906 * check if lostNFound exists first
1908 if (dev->lostNFoundDir) {
1909 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1916 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1921 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1923 obj->fake = 1; /* it is fake so it has no NAND presence... */
1924 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1925 obj->unlinkAllowed = 0; /* ... or unlink it */
1928 obj->yst_mode = mode;
1930 obj->chunkId = 0; /* Not a valid chunk. */
1937 static void yaffs_UnhashObject(yaffs_Object * tn)
1940 yaffs_Device *dev = tn->myDev;
1942 /* If it is still linked into the bucket list, free from the list */
1943 if (!list_empty(&tn->hashLink)) {
1944 list_del_init(&tn->hashLink);
1945 bucket = yaffs_HashFunction(tn->objectId);
1946 dev->objectBucket[bucket].count--;
1951 /* FreeObject frees up a Object and puts it back on the free list */
1952 static void yaffs_FreeObject(yaffs_Object * tn)
1955 yaffs_Device *dev = tn->myDev;
1959 /* We're still hooked up to a cached inode.
1960 * Don't delete now, but mark for later deletion
1962 tn->deferedFree = 1;
1967 yaffs_UnhashObject(tn);
1969 /* Link into the free list. */
1970 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1971 dev->freeObjects = tn;
1972 dev->nFreeObjects++;
1977 void yaffs_HandleDeferedFree(yaffs_Object * obj)
1979 if (obj->deferedFree) {
1980 yaffs_FreeObject(obj);
1986 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
1988 /* Free the list of allocated Objects */
1990 yaffs_ObjectList *tmp;
1992 while (dev->allocatedObjectList) {
1993 tmp = dev->allocatedObjectList->next;
1994 YFREE(dev->allocatedObjectList->objects);
1995 YFREE(dev->allocatedObjectList);
1997 dev->allocatedObjectList = tmp;
2000 dev->freeObjects = NULL;
2001 dev->nFreeObjects = 0;
2004 static void yaffs_InitialiseObjects(yaffs_Device * dev)
2008 dev->allocatedObjectList = NULL;
2009 dev->freeObjects = NULL;
2010 dev->nFreeObjects = 0;
2012 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2013 INIT_LIST_HEAD(&dev->objectBucket[i].list);
2014 dev->objectBucket[i].count = 0;
2019 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
2024 int lowest = 999999;
2026 /* First let's see if we can find one that's empty. */
2028 for (i = 0; i < 10 && lowest > 0; i++) {
2030 x %= YAFFS_NOBJECT_BUCKETS;
2031 if (dev->objectBucket[x].count < lowest) {
2032 lowest = dev->objectBucket[x].count;
2038 /* If we didn't find an empty list, then try
2039 * looking a bit further for a short one
2042 for (i = 0; i < 10 && lowest > 3; i++) {
2044 x %= YAFFS_NOBJECT_BUCKETS;
2045 if (dev->objectBucket[x].count < lowest) {
2046 lowest = dev->objectBucket[x].count;
2055 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
2057 int bucket = yaffs_FindNiceObjectBucket(dev);
2059 /* Now find an object value that has not already been taken
2060 * by scanning the list.
2064 struct list_head *i;
2066 __u32 n = (__u32) bucket;
2068 /* yaffs_CheckObjectHashSanity(); */
2072 n += YAFFS_NOBJECT_BUCKETS;
2073 if (1 || dev->objectBucket[bucket].count > 0) {
2074 list_for_each(i, &dev->objectBucket[bucket].list) {
2075 /* If there is already one in the list */
2077 && list_entry(i, yaffs_Object,
2078 hashLink)->objectId == n) {
2089 static void yaffs_HashObject(yaffs_Object * in)
2091 int bucket = yaffs_HashFunction(in->objectId);
2092 yaffs_Device *dev = in->myDev;
2094 list_add(&in->hashLink, &dev->objectBucket[bucket].list);
2095 dev->objectBucket[bucket].count++;
2099 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
2101 int bucket = yaffs_HashFunction(number);
2102 struct list_head *i;
2105 list_for_each(i, &dev->objectBucket[bucket].list) {
2106 /* Look if it is in the list */
2108 in = list_entry(i, yaffs_Object, hashLink);
2109 if (in->objectId == number) {
2111 /* Don't tell the VFS about this one if it is defered free */
2112 if (in->deferedFree)
2124 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
2125 yaffs_ObjectType type)
2128 yaffs_Object *theObject;
2132 number = yaffs_CreateNewObjectNumber(dev);
2135 theObject = yaffs_AllocateEmptyObject(dev);
2139 if(type == YAFFS_OBJECT_TYPE_FILE){
2140 tn = yaffs_GetTnode(dev);
2142 yaffs_FreeObject(theObject);
2150 theObject->fake = 0;
2151 theObject->renameAllowed = 1;
2152 theObject->unlinkAllowed = 1;
2153 theObject->objectId = number;
2154 yaffs_HashObject(theObject);
2155 theObject->variantType = type;
2156 #ifdef CONFIG_YAFFS_WINCE
2157 yfsd_WinFileTimeNow(theObject->win_atime);
2158 theObject->win_ctime[0] = theObject->win_mtime[0] =
2159 theObject->win_atime[0];
2160 theObject->win_ctime[1] = theObject->win_mtime[1] =
2161 theObject->win_atime[1];
2165 theObject->yst_atime = theObject->yst_mtime =
2166 theObject->yst_ctime = Y_CURRENT_TIME;
2169 case YAFFS_OBJECT_TYPE_FILE:
2170 theObject->variant.fileVariant.fileSize = 0;
2171 theObject->variant.fileVariant.scannedFileSize = 0;
2172 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2173 theObject->variant.fileVariant.topLevel = 0;
2174 theObject->variant.fileVariant.top = tn;
2176 case YAFFS_OBJECT_TYPE_DIRECTORY:
2177 INIT_LIST_HEAD(&theObject->variant.directoryVariant.
2180 case YAFFS_OBJECT_TYPE_SYMLINK:
2181 case YAFFS_OBJECT_TYPE_HARDLINK:
2182 case YAFFS_OBJECT_TYPE_SPECIAL:
2183 /* No action required */
2185 case YAFFS_OBJECT_TYPE_UNKNOWN:
2186 /* todo this should not happen */
2194 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
2196 yaffs_ObjectType type)
2198 yaffs_Object *theObject = NULL;
2201 theObject = yaffs_FindObjectByNumber(dev, number);
2205 theObject = yaffs_CreateNewObject(dev, number, type);
2213 static YCHAR *yaffs_CloneString(const YCHAR * str)
2215 YCHAR *newStr = NULL;
2218 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2220 yaffs_strcpy(newStr, str);
2228 * Mknod (create) a new object.
2229 * equivalentObject only has meaning for a hard link;
2230 * aliasString only has meaning for a sumlink.
2231 * rdev only has meaning for devices (a subset of special objects)
2234 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2235 yaffs_Object * parent,
2240 yaffs_Object * equivalentObject,
2241 const YCHAR * aliasString, __u32 rdev)
2246 yaffs_Device *dev = parent->myDev;
2248 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2249 if (yaffs_FindObjectByName(parent, name)) {
2253 in = yaffs_CreateNewObject(dev, -1, type);
2255 if(type == YAFFS_OBJECT_TYPE_SYMLINK){
2256 str = yaffs_CloneString(aliasString);
2258 yaffs_FreeObject(in);
2268 in->variantType = type;
2270 in->yst_mode = mode;
2272 #ifdef CONFIG_YAFFS_WINCE
2273 yfsd_WinFileTimeNow(in->win_atime);
2274 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2275 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2278 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2280 in->yst_rdev = rdev;
2284 in->nDataChunks = 0;
2286 yaffs_SetObjectName(in, name);
2289 yaffs_AddObjectToDirectory(parent, in);
2291 in->myDev = parent->myDev;
2294 case YAFFS_OBJECT_TYPE_SYMLINK:
2295 in->variant.symLinkVariant.alias = str;
2297 case YAFFS_OBJECT_TYPE_HARDLINK:
2298 in->variant.hardLinkVariant.equivalentObject =
2300 in->variant.hardLinkVariant.equivalentObjectId =
2301 equivalentObject->objectId;
2302 list_add(&in->hardLinks, &equivalentObject->hardLinks);
2304 case YAFFS_OBJECT_TYPE_FILE:
2305 case YAFFS_OBJECT_TYPE_DIRECTORY:
2306 case YAFFS_OBJECT_TYPE_SPECIAL:
2307 case YAFFS_OBJECT_TYPE_UNKNOWN:
2312 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2313 /* Could not create the object header, fail the creation */
2314 yaffs_DestroyObject(in);
2323 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
2324 __u32 mode, __u32 uid, __u32 gid)
2326 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2327 uid, gid, NULL, NULL, 0);
2330 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
2331 __u32 mode, __u32 uid, __u32 gid)
2333 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2334 mode, uid, gid, NULL, NULL, 0);
2337 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
2338 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2340 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2341 uid, gid, NULL, NULL, rdev);
2344 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
2345 __u32 mode, __u32 uid, __u32 gid,
2346 const YCHAR * alias)
2348 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2349 uid, gid, NULL, alias, 0);
2352 /* yaffs_Link returns the object id of the equivalent object.*/
2353 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
2354 yaffs_Object * equivalentObject)
2356 /* Get the real object in case we were fed a hard link as an equivalent object */
2357 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2359 if (yaffs_MknodObject
2360 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2361 equivalentObject, NULL, 0)) {
2362 return equivalentObject;
2369 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
2370 const YCHAR * newName, int force, int shadows)
2375 yaffs_Object *existingTarget;
2377 if (newDir == NULL) {
2378 newDir = obj->parent; /* use the old directory */
2381 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2382 T(YAFFS_TRACE_ALWAYS,
2384 ("tragendy: yaffs_ChangeObjectName: newDir is not a directory"
2389 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2390 if (obj->myDev->isYaffs2) {
2391 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2393 unlinkOp = (newDir == obj->myDev->unlinkedDir
2394 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2397 deleteOp = (newDir == obj->myDev->deletedDir);
2399 existingTarget = yaffs_FindObjectByName(newDir, newName);
2401 /* If the object is a file going into the unlinked directory,
2402 * then it is OK to just stuff it in since duplicate names are allowed.
2403 * else only proceed if the new name does not exist and if we're putting
2404 * it into a directory.
2411 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2412 yaffs_SetObjectName(obj, newName);
2415 yaffs_AddObjectToDirectory(newDir, obj);
2420 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2421 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
2428 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
2429 yaffs_Object * newDir, const YCHAR * newName)
2432 yaffs_Object *existingTarget;
2435 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2436 /* Special case for case insemsitive systems (eg. WinCE).
2437 * While look-up is case insensitive, the name isn't.
2438 * Therefore we might want to change x.txt to X.txt
2440 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
2445 obj = yaffs_FindObjectByName(oldDir, oldName);
2446 /* Check new name to long. */
2447 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK &&
2448 yaffs_strlen(newName) > YAFFS_MAX_ALIAS_LENGTH)
2451 else if (obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK &&
2452 yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2456 if (obj && obj->renameAllowed) {
2458 /* Now do the handling for an existing target, if there is one */
2460 existingTarget = yaffs_FindObjectByName(newDir, newName);
2461 if (existingTarget &&
2462 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2463 !list_empty(&existingTarget->variant.directoryVariant.children)) {
2464 /* There is a target that is a non-empty directory, so we fail */
2465 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2466 } else if (existingTarget && existingTarget != obj) {
2467 /* Nuke the target first, using shadowing,
2468 * but only if it isn't the same object
2470 yaffs_ChangeObjectName(obj, newDir, newName, force,
2471 existingTarget->objectId);
2472 yaffs_UnlinkObject(existingTarget);
2475 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2480 /*------------------------- Block Management and Page Allocation ----------------*/
2482 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
2484 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2486 dev->blockInfo = NULL;
2487 dev->chunkBits = NULL;
2489 dev->allocationBlock = -1; /* force it to get a new one */
2491 /* If the first allocation strategy fails, thry the alternate one */
2492 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2493 if(!dev->blockInfo){
2494 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2495 dev->blockInfoAlt = 1;
2498 dev->blockInfoAlt = 0;
2502 /* Set up dynamic blockinfo stuff. */
2503 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2504 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2505 if(!dev->chunkBits){
2506 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2507 dev->chunkBitsAlt = 1;
2510 dev->chunkBitsAlt = 0;
2513 if (dev->blockInfo && dev->chunkBits) {
2514 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2515 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2523 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
2525 if(dev->blockInfoAlt && dev->blockInfo)
2526 YFREE_ALT(dev->blockInfo);
2527 else if(dev->blockInfo)
2528 YFREE(dev->blockInfo);
2530 dev->blockInfoAlt = 0;
2532 dev->blockInfo = NULL;
2534 if(dev->chunkBitsAlt && dev->chunkBits)
2535 YFREE_ALT(dev->chunkBits);
2536 else if(dev->chunkBits)
2537 YFREE(dev->chunkBits);
2538 dev->chunkBitsAlt = 0;
2539 dev->chunkBits = NULL;
2542 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
2543 yaffs_BlockInfo * bi)
2550 return 1; /* disqualification only applies to yaffs2. */
2552 if (!bi->hasShrinkHeader)
2553 return 1; /* can gc */
2555 /* Find the oldest dirty sequence number if we don't know it and save it
2556 * so we don't have to keep recomputing it.
2558 if (!dev->oldestDirtySequence) {
2559 seq = dev->sequenceNumber;
2561 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2563 b = yaffs_GetBlockInfo(dev, i);
2564 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2565 (b->pagesInUse - b->softDeletions) <
2566 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2567 seq = b->sequenceNumber;
2570 dev->oldestDirtySequence = seq;
2573 /* Can't do gc of this block if there are any blocks older than this one that have
2576 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2580 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2581 * for garbage collection.
2584 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2588 int b = dev->currentDirtyChecker;
2595 yaffs_BlockInfo *bi;
2596 int pendingPrioritisedExist = 0;
2598 /* First let's see if we need to grab a prioritised block */
2599 if(dev->hasPendingPrioritisedGCs){
2600 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2602 bi = yaffs_GetBlockInfo(dev, i);
2603 //yaffs_VerifyBlock(dev,bi,i);
2605 if(bi->gcPrioritise) {
2606 pendingPrioritisedExist = 1;
2607 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2608 yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2609 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2612 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2617 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2618 dev->hasPendingPrioritisedGCs = 0;
2621 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2623 * else (we're doing a leasurely gc), then we only bother to do this if the
2624 * block has only a few pages in use.
2627 dev->nonAggressiveSkip--;
2629 if (!aggressive && (dev->nonAggressiveSkip > 0)) {
2635 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2639 dev->internalEndBlock - dev->internalStartBlock + 1;
2642 dev->internalEndBlock - dev->internalStartBlock + 1;
2643 iterations = iterations / 16;
2644 if (iterations > 200) {
2649 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2651 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2652 b = dev->internalStartBlock;
2655 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2656 T(YAFFS_TRACE_ERROR,
2657 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2661 bi = yaffs_GetBlockInfo(dev, b);
2664 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2671 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2672 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2673 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2675 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2679 dev->currentDirtyChecker = b;
2683 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2684 dev->nChunksPerBlock - pagesInUse,prioritised));
2687 dev->oldestDirtySequence = 0;
2690 dev->nonAggressiveSkip = 4;
2696 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2698 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2702 /* If the block is still healthy erase it and mark as clean.
2703 * If the block has had a data failure, then retire it.
2706 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2707 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2708 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2710 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2712 if (!bi->needsRetiring) {
2713 yaffs_InvalidateCheckpoint(dev);
2714 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2716 dev->nErasureFailures++;
2717 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2718 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2723 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2725 for (i = 0; i < dev->nChunksPerBlock; i++) {
2726 if (!yaffs_CheckChunkErased
2727 (dev, blockNo * dev->nChunksPerBlock + i)) {
2728 T(YAFFS_TRACE_ERROR,
2730 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2731 TENDSTR), blockNo, i));
2737 /* Clean it up... */
2738 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2739 dev->nErasedBlocks++;
2741 bi->softDeletions = 0;
2742 bi->hasShrinkHeader = 0;
2743 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2744 bi->gcPrioritise = 0;
2745 yaffs_ClearChunkBits(dev, blockNo);
2747 T(YAFFS_TRACE_ERASE,
2748 (TSTR("Erased block %d" TENDSTR), blockNo));
2750 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2752 yaffs_RetireBlock(dev, blockNo);
2753 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2754 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2758 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2762 yaffs_BlockInfo *bi;
2764 if (dev->nErasedBlocks < 1) {
2765 /* Hoosterman we've got a problem.
2766 * Can't get space to gc
2768 T(YAFFS_TRACE_ERROR,
2769 (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2774 /* Find an empty block. */
2776 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2777 dev->allocationBlockFinder++;
2778 if (dev->allocationBlockFinder < dev->internalStartBlock
2779 || dev->allocationBlockFinder > dev->internalEndBlock) {
2780 dev->allocationBlockFinder = dev->internalStartBlock;
2783 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2785 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2786 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2787 dev->sequenceNumber++;
2788 bi->sequenceNumber = dev->sequenceNumber;
2789 dev->nErasedBlocks--;
2790 T(YAFFS_TRACE_ALLOCATE,
2791 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2792 dev->allocationBlockFinder, dev->sequenceNumber,
2793 dev->nErasedBlocks));
2794 return dev->allocationBlockFinder;
2798 T(YAFFS_TRACE_ALWAYS,
2800 ("yaffs tragedy: no more eraased blocks, but there should have been %d"
2801 TENDSTR), dev->nErasedBlocks));
2807 // Check if there's space to allocate...
2808 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2809 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2812 int reservedBlocks = dev->nReservedBlocks;
2813 int checkpointBlocks;
2815 checkpointBlocks = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
2816 if(checkpointBlocks < 0)
2817 checkpointBlocks = 0;
2819 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2821 return (dev->nFreeChunks > reservedChunks);
2824 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2827 yaffs_BlockInfo *bi;
2829 if (dev->allocationBlock < 0) {
2830 /* Get next block to allocate off */
2831 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2832 dev->allocationPage = 0;
2835 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2836 /* Not enough space to allocate unless we're allowed to use the reserve. */
2840 if (dev->nErasedBlocks < dev->nReservedBlocks
2841 && dev->allocationPage == 0) {
2842 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2845 /* Next page please.... */
2846 if (dev->allocationBlock >= 0) {
2847 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2849 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2850 dev->allocationPage;
2852 yaffs_SetChunkBit(dev, dev->allocationBlock,
2853 dev->allocationPage);
2855 dev->allocationPage++;
2859 /* If the block is full set the state to full */
2860 if (dev->allocationPage >= dev->nChunksPerBlock) {
2861 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2862 dev->allocationBlock = -1;
2871 T(YAFFS_TRACE_ERROR,
2872 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2877 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2881 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2883 if (dev->allocationBlock > 0) {
2884 n += (dev->nChunksPerBlock - dev->allocationPage);
2891 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2897 int retVal = YAFFS_OK;
2900 int isCheckpointBlock;
2903 int chunksBefore = yaffs_GetErasedChunks(dev);
2906 yaffs_ExtendedTags tags;
2908 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2910 yaffs_Object *object;
2912 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2914 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2916 T(YAFFS_TRACE_TRACING,
2917 (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2918 bi->pagesInUse, bi->hasShrinkHeader));
2920 /*yaffs_VerifyFreeChunks(dev); */
2922 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2924 /* Take off the number of soft deleted entries because
2925 * they're going to get really deleted during GC.
2927 dev->nFreeChunks -= bi->softDeletions;
2931 if (isCheckpointBlock ||
2932 !yaffs_StillSomeChunkBits(dev, block)) {
2933 T(YAFFS_TRACE_TRACING,
2935 ("Collecting block %d that has no chunks in use" TENDSTR),
2937 yaffs_BlockBecameDirty(dev, block);
2940 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2942 yaffs_VerifyBlock(dev,bi,block);
2944 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
2945 chunkInBlock < dev->nChunksPerBlock
2946 && yaffs_StillSomeChunkBits(dev, block);
2947 chunkInBlock++, oldChunk++) {
2948 if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
2950 /* This page is in use and might need to be copied off */
2954 yaffs_InitialiseTags(&tags);
2956 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2960 yaffs_FindObjectByNumber(dev,
2963 T(YAFFS_TRACE_GC_DETAIL,
2965 ("Collecting page %d, %d %d %d " TENDSTR),
2966 chunkInBlock, tags.objectId, tags.chunkId,
2969 if(object && !yaffs_SkipVerification(dev)){
2970 if(tags.chunkId == 0)
2971 matchingChunk = object->chunkId;
2972 else if(object->softDeleted)
2973 matchingChunk = oldChunk; /* Defeat the test */
2975 matchingChunk = yaffs_FindChunkInFile(object,tags.chunkId,NULL);
2977 if(oldChunk != matchingChunk)
2978 T(YAFFS_TRACE_ERROR,
2979 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
2980 oldChunk,matchingChunk,tags.objectId, tags.chunkId));
2985 T(YAFFS_TRACE_ERROR,
2987 ("page %d in gc has no object: %d %d %d "
2989 tags.objectId, tags.chunkId, tags.byteCount));
2992 if (object && object->deleted
2993 && tags.chunkId != 0) {
2994 /* Data chunk in a deleted file, throw it away
2995 * It's a soft deleted data chunk,
2996 * No need to copy this, just forget about it and
2997 * fix up the object.
3000 object->nDataChunks--;
3002 if (object->nDataChunks <= 0) {
3003 /* remeber to clean up the object */
3004 dev->gcCleanupList[cleanups] =
3010 /* Todo object && object->deleted && object->nDataChunks == 0 */
3012 /* Deleted object header with no data chunks.
3013 * Can be discarded and the file deleted.
3015 object->chunkId = 0;
3016 yaffs_FreeTnode(object->myDev,
3019 object->variant.fileVariant.top = NULL;
3020 yaffs_DoGenericObjectDeletion(object);
3022 } else if (object) {
3023 /* It's either a data chunk in a live file or
3024 * an ObjectHeader, so we're interested in it.
3025 * NB Need to keep the ObjectHeaders of deleted files
3026 * until the whole file has been deleted off
3028 tags.serialNumber++;
3032 if (tags.chunkId == 0) {
3033 /* It is an object Id,
3034 * We need to nuke the shrinkheader flags first
3035 * We no longer want the shrinkHeader flag since its work is done
3036 * and if it is left in place it will mess up scanning.
3037 * Also, clear out any shadowing stuff
3040 yaffs_ObjectHeader *oh;
3041 oh = (yaffs_ObjectHeader *)buffer;
3043 oh->shadowsObject = -1;
3044 tags.extraShadows = 0;
3045 tags.extraIsShrinkHeader = 0;
3047 yaffs_VerifyObjectHeader(object,oh,&tags,1);
3051 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3054 retVal = YAFFS_FAIL;
3057 /* Ok, now fix up the Tnodes etc. */
3059 if (tags.chunkId == 0) {
3061 object->chunkId = newChunk;
3062 object->serial = tags.serialNumber;
3064 /* It's a data chunk */
3065 yaffs_PutChunkIntoFile
3073 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3078 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3081 /* Do any required cleanups */
3082 for (i = 0; i < cleanups; i++) {
3083 /* Time to delete the file too */
3085 yaffs_FindObjectByNumber(dev,
3086 dev->gcCleanupList[i]);
3088 yaffs_FreeTnode(dev,
3089 object->variant.fileVariant.
3091 object->variant.fileVariant.top = NULL;
3094 ("yaffs: About to finally delete object %d"
3095 TENDSTR), object->objectId));
3096 yaffs_DoGenericObjectDeletion(object);
3097 object->myDev->nDeletedFiles--;
3104 yaffs_VerifyCollectedBlock(dev,bi,block);
3106 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
3109 ("gc did not increase free chunks before %d after %d"
3110 TENDSTR), chunksBefore, chunksAfter));
3118 /* New garbage collector
3119 * If we're very low on erased blocks then we do aggressive garbage collection
3120 * otherwise we do "leasurely" garbage collection.
3121 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3122 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3124 * The idea is to help clear out space in a more spread-out manner.
3125 * Dunno if it really does anything useful.
3127 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
3131 int gcOk = YAFFS_OK;
3134 int checkpointBlockAdjust;
3136 if (dev->isDoingGC) {
3137 /* Bail out so we don't get recursive gc */
3141 /* This loop should pass the first time.
3142 * We'll only see looping here if the erase of the collected block fails.
3148 checkpointBlockAdjust = (dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint);
3149 if(checkpointBlockAdjust < 0)
3150 checkpointBlockAdjust = 0;
3152 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3153 /* We need a block soon...*/
3156 /* We're in no hurry */
3160 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3163 dev->garbageCollections++;
3165 dev->passiveGarbageCollections++;
3170 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3171 dev->nErasedBlocks, aggressive));
3173 gcOk = yaffs_GarbageCollectBlock(dev, block);
3176 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3179 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3180 TENDSTR), dev->nErasedBlocks, maxTries, block));
3182 } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
3185 return aggressive ? gcOk : YAFFS_OK;
3188 /*------------------------- TAGS --------------------------------*/
3190 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
3193 return (tags->chunkId == chunkInObject &&
3194 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3199 /*-------------------- Data file manipulation -----------------*/
3201 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
3202 yaffs_ExtendedTags * tags)
3204 /*Get the Tnode, then get the level 0 offset chunk offset */
3207 yaffs_ExtendedTags localTags;
3210 yaffs_Device *dev = in->myDev;
3213 /* Passed a NULL, so use our own tags space */
3217 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3220 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3223 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3229 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
3230 yaffs_ExtendedTags * tags)
3232 /* Get the Tnode, then get the level 0 offset chunk offset */
3235 yaffs_ExtendedTags localTags;
3237 yaffs_Device *dev = in->myDev;
3241 /* Passed a NULL, so use our own tags space */
3245 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3249 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3252 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3255 /* Delete the entry in the filestructure (if found) */
3257 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
3260 /*T(("No level 0 found for %d\n", chunkInInode)); */
3264 /* T(("Could not find %d to delete\n",chunkInInode)); */
3269 #ifdef YAFFS_PARANOID
3271 static int yaffs_CheckFileSanity(yaffs_Object * in)
3279 yaffs_Tags localTags;
3280 yaffs_Tags *tags = &localTags;
3284 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3285 /* T(("Object not a file\n")); */
3289 objId = in->objectId;
3290 fSize = in->variant.fileVariant.fileSize;
3292 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3294 for (chunk = 1; chunk <= nChunks; chunk++) {
3295 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3300 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
3302 if (yaffs_CheckChunkBits
3303 (dev, theChunk / dev->nChunksPerBlock,
3304 theChunk % dev->nChunksPerBlock)) {
3306 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3310 (tags, in->objectId, chunk, chunkDeleted)) {
3320 /* T(("No level 0 found for %d\n", chunk)); */
3324 return failed ? YAFFS_FAIL : YAFFS_OK;
3329 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
3330 int chunkInNAND, int inScan)
3332 /* NB inScan is zero unless scanning.
3333 * For forward scanning, inScan is > 0;
3334 * for backward scanning inScan is < 0
3338 yaffs_Device *dev = in->myDev;
3340 yaffs_ExtendedTags existingTags;
3341 yaffs_ExtendedTags newTags;
3342 unsigned existingSerial, newSerial;
3344 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3345 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3346 * If it is not during Scanning then something went wrong!
3349 T(YAFFS_TRACE_ERROR,
3351 ("yaffs tragedy:attempt to put data chunk into a non-file"