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.68 2008-11-27 20:32:52 charles Exp $";
19 #include "yaffsinterface.h"
20 #include "yaffs_guts.h"
21 #include "yaffs_tagsvalidity.h"
22 #include "yaffs_getblockinfo.h"
24 #include "yaffs_tagscompat.h"
25 #ifndef CONFIG_YAFFS_USE_OWN_SORT
26 #include "yaffs_qsort.h"
28 #include "yaffs_nand.h"
30 #include "yaffs_checkptrw.h"
32 #include "yaffs_nand.h"
33 #include "yaffs_packedtags2.h"
36 #ifdef CONFIG_YAFFS_WINCE
37 void yfsd_LockYAFFS(BOOL fsLockOnly);
38 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
41 #define YAFFS_PASSIVE_GC_CHUNKS 2
43 #include "yaffs_ecc.h"
46 /* Robustification (if it ever comes about...) */
47 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
48 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk);
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 int yaffs_UnlinkObject( yaffs_Object *obj);
57 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
59 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
61 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
63 yaffs_ExtendedTags * tags,
65 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
66 int chunkInNAND, int inScan);
68 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
69 yaffs_ObjectType type);
70 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
72 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
73 int force, int isShrink, int shadows);
74 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
75 static int yaffs_CheckStructures(void);
76 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
77 int chunkOffset, int *limit);
78 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
80 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
83 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
86 static int yaffs_UnlinkWorker(yaffs_Object * obj);
87 static void yaffs_DestroyObject(yaffs_Object * obj);
89 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
92 loff_t yaffs_GetFileSize(yaffs_Object * obj);
94 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr);
96 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
98 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
100 static void yaffs_VerifyDirectory(yaffs_Object *directory);
101 #ifdef YAFFS_PARANOID
102 static int yaffs_CheckFileSanity(yaffs_Object * in);
104 #define yaffs_CheckFileSanity(in)
107 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
108 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
110 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
112 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
113 yaffs_ExtendedTags * tags);
115 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos);
116 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
117 yaffs_FileStructure * fStruct,
121 /* Function to calculate chunk and offset */
123 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut, __u32 *offsetOut)
128 chunk = (__u32)(addr >> dev->chunkShift);
130 if(dev->chunkDiv == 1)
132 /* easy power of 2 case */
133 offset = (__u32)(addr & dev->chunkMask);
137 /* Non power-of-2 case */
141 chunk /= dev->chunkDiv;
143 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
144 offset = (__u32)(addr - chunkBase);
151 /* Function to return the number of shifts for a power of 2 greater than or equal
152 * to the given number
153 * Note we don't try to cater for all possible numbers and this does not have to
154 * be hellishly efficient.
157 static __u32 ShiftsGE(__u32 x)
162 nShifts = extraBits = 0;
165 if(x & 1) extraBits++;
176 /* Function to return the number of shifts to get a 1 in bit 0
179 static __u32 Shifts(__u32 x)
198 * Temporary buffer manipulations.
201 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
204 __u8 *buf = (__u8 *)1;
206 memset(dev->tempBuffer,0,sizeof(dev->tempBuffer));
208 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
209 dev->tempBuffer[i].line = 0; /* not in use */
210 dev->tempBuffer[i].buffer = buf =
211 YMALLOC_DMA(dev->totalBytesPerChunk);
214 return buf ? YAFFS_OK : YAFFS_FAIL;
218 __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
223 if(dev->tempInUse > dev->maxTemp)
224 dev->maxTemp = dev->tempInUse;
226 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
227 if (dev->tempBuffer[i].line == 0) {
228 dev->tempBuffer[i].line = lineNo;
229 if ((i + 1) > dev->maxTemp) {
230 dev->maxTemp = i + 1;
231 for (j = 0; j <= i; j++)
232 dev->tempBuffer[j].maxLine =
233 dev->tempBuffer[j].line;
236 return dev->tempBuffer[i].buffer;
240 T(YAFFS_TRACE_BUFFERS,
241 (TSTR("Out of temp buffers at line %d, other held by lines:"),
243 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
244 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
246 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
249 * If we got here then we have to allocate an unmanaged one
253 dev->unmanagedTempAllocations++;
254 return YMALLOC(dev->nDataBytesPerChunk);
258 void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
265 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
266 if (dev->tempBuffer[i].buffer == buffer) {
267 dev->tempBuffer[i].line = 0;
273 /* assume it is an unmanaged one. */
274 T(YAFFS_TRACE_BUFFERS,
275 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
278 dev->unmanagedTempDeallocations++;
284 * Determine if we have a managed buffer.
286 int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
289 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
290 if (dev->tempBuffer[i].buffer == buffer)
295 for (i = 0; i < dev->nShortOpCaches; i++) {
296 if( dev->srCache[i].data == buffer )
301 if (buffer == dev->checkpointBuffer)
304 T(YAFFS_TRACE_ALWAYS,
305 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
312 * Chunk bitmap manipulations
315 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
317 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
319 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
323 return dev->chunkBits +
324 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
327 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
329 if(blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
330 chunk < 0 || chunk >= dev->nChunksPerBlock) {
332 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),blk,chunk));
337 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
339 __u8 *blkBits = yaffs_BlockBits(dev, blk);
341 memset(blkBits, 0, dev->chunkBitmapStride);
344 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
346 __u8 *blkBits = yaffs_BlockBits(dev, blk);
348 yaffs_VerifyChunkBitId(dev,blk,chunk);
350 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
353 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
355 __u8 *blkBits = yaffs_BlockBits(dev, blk);
357 yaffs_VerifyChunkBitId(dev,blk,chunk);
359 blkBits[chunk / 8] |= (1 << (chunk & 7));
362 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
364 __u8 *blkBits = yaffs_BlockBits(dev, blk);
365 yaffs_VerifyChunkBitId(dev,blk,chunk);
367 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
370 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
372 __u8 *blkBits = yaffs_BlockBits(dev, blk);
374 for (i = 0; i < dev->chunkBitmapStride; i++) {
382 static int yaffs_CountChunkBits(yaffs_Device * dev, int blk)
384 __u8 *blkBits = yaffs_BlockBits(dev, blk);
387 for (i = 0; i < dev->chunkBitmapStride; i++) {
404 static int yaffs_SkipVerification(yaffs_Device *dev)
406 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
409 static int yaffs_SkipFullVerification(yaffs_Device *dev)
411 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
414 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
416 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
419 static const char * blockStateName[] = {
432 static void yaffs_VerifyBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
437 if(yaffs_SkipVerification(dev))
440 /* Report illegal runtime states */
441 if(bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
442 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has undefined state %d"TENDSTR),n,bi->blockState));
444 switch(bi->blockState){
445 case YAFFS_BLOCK_STATE_UNKNOWN:
446 case YAFFS_BLOCK_STATE_SCANNING:
447 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
448 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has bad run-state %s"TENDSTR),
449 n,blockStateName[bi->blockState]));
452 /* Check pages in use and soft deletions are legal */
454 actuallyUsed = bi->pagesInUse - bi->softDeletions;
456 if(bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
457 bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
458 actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock)
459 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
460 n,bi->pagesInUse,bi->softDeletions));
463 /* Check chunk bitmap legal */
464 inUse = yaffs_CountChunkBits(dev,n);
465 if(inUse != bi->pagesInUse)
466 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
467 n,bi->pagesInUse,inUse));
469 /* Check that the sequence number is valid.
470 * Ten million is legal, but is very unlikely
473 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
474 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000 ))
475 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has suspect sequence number of %d"TENDSTR),
476 n,bi->sequenceNumber));
480 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
482 yaffs_VerifyBlock(dev,bi,n);
484 /* After collection the block should be in the erased state */
485 /* TODO: This will need to change if we do partial gc */
487 if(bi->blockState != YAFFS_BLOCK_STATE_EMPTY){
488 T(YAFFS_TRACE_ERROR,(TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
493 static void yaffs_VerifyBlocks(yaffs_Device *dev)
496 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
497 int nIllegalBlockStates = 0;
500 if(yaffs_SkipVerification(dev))
503 memset(nBlocksPerState,0,sizeof(nBlocksPerState));
506 for(i = dev->internalStartBlock; i <= dev->internalEndBlock; i++){
507 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
508 yaffs_VerifyBlock(dev,bi,i);
510 if(bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
511 nBlocksPerState[bi->blockState]++;
513 nIllegalBlockStates++;
517 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
518 T(YAFFS_TRACE_VERIFY,(TSTR("Block summary"TENDSTR)));
520 T(YAFFS_TRACE_VERIFY,(TSTR("%d blocks have illegal states"TENDSTR),nIllegalBlockStates));
521 if(nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
522 T(YAFFS_TRACE_VERIFY,(TSTR("Too many allocating blocks"TENDSTR)));
524 for(i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
525 T(YAFFS_TRACE_VERIFY,
526 (TSTR("%s %d blocks"TENDSTR),
527 blockStateName[i],nBlocksPerState[i]));
529 if(dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
530 T(YAFFS_TRACE_VERIFY,
531 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
532 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
534 if(dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
535 T(YAFFS_TRACE_VERIFY,
536 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
537 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
539 if(nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
540 T(YAFFS_TRACE_VERIFY,
541 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
542 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
544 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
549 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
550 * case those tests will not be performed.
552 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
554 if(obj && yaffs_SkipVerification(obj->myDev))
557 if(!(tags && obj && oh)){
558 T(YAFFS_TRACE_VERIFY,
559 (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR),
560 (__u32)tags,(__u32)obj,(__u32)oh));
564 if(oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
565 oh->type > YAFFS_OBJECT_TYPE_MAX)
566 T(YAFFS_TRACE_VERIFY,
567 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
568 tags->objectId, oh->type));
570 if(tags->objectId != obj->objectId)
571 T(YAFFS_TRACE_VERIFY,
572 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
573 tags->objectId, obj->objectId));
577 * Check that the object's parent ids match if parentCheck requested.
579 * Tests do not apply to the root object.
582 if(parentCheck && tags->objectId > 1 && !obj->parent)
583 T(YAFFS_TRACE_VERIFY,
584 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
585 tags->objectId, oh->parentObjectId));
588 if(parentCheck && obj->parent &&
589 oh->parentObjectId != obj->parent->objectId &&
590 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
591 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
592 T(YAFFS_TRACE_VERIFY,
593 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
594 tags->objectId, oh->parentObjectId, obj->parent->objectId));
597 if(tags->objectId > 1 && oh->name[0] == 0) /* Null name */
598 T(YAFFS_TRACE_VERIFY,
599 (TSTR("Obj %d header name is NULL"TENDSTR),
602 if(tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
603 T(YAFFS_TRACE_VERIFY,
604 (TSTR("Obj %d header name is 0xFF"TENDSTR),
610 static int yaffs_VerifyTnodeWorker(yaffs_Object * obj, yaffs_Tnode * tn,
611 __u32 level, int chunkOffset)
614 yaffs_Device *dev = obj->myDev;
620 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
621 if (tn->internal[i]) {
622 ok = yaffs_VerifyTnodeWorker(obj,
625 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
628 } else if (level == 0) {
629 yaffs_ExtendedTags tags;
630 __u32 objectId = obj->objectId;
632 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
634 for(i = 0; i < YAFFS_NTNODES_LEVEL0; i++){
635 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
638 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
639 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
640 if(tags.objectId != objectId || tags.chunkId != chunkOffset){
641 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
642 objectId, chunkOffset, theChunk,
643 tags.objectId, tags.chunkId));
656 static void yaffs_VerifyFile(yaffs_Object *obj)
658 int requiredTallness;
664 yaffs_ExtendedTags tags;
671 if(yaffs_SkipVerification(obj->myDev))
675 objectId = obj->objectId;
677 /* Check file size is consistent with tnode depth */
678 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
679 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
680 requiredTallness = 0;
682 x >>= YAFFS_TNODES_INTERNAL_BITS;
686 actualTallness = obj->variant.fileVariant.topLevel;
688 if(requiredTallness > actualTallness )
689 T(YAFFS_TRACE_VERIFY,
690 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
691 obj->objectId,actualTallness, requiredTallness));
694 /* Check that the chunks in the tnode tree are all correct.
695 * We do this by scanning through the tnode tree and
696 * checking the tags for every chunk match.
699 if(yaffs_SkipNANDVerification(dev))
702 for(i = 1; i <= lastChunk; i++){
703 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant,i);
706 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
708 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
709 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
710 if(tags.objectId != objectId || tags.chunkId != i){
711 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
712 objectId, i, theChunk,
713 tags.objectId, tags.chunkId));
723 static void yaffs_VerifyHardLink(yaffs_Object *obj)
725 if(obj && yaffs_SkipVerification(obj->myDev))
728 /* Verify sane equivalent object */
731 static void yaffs_VerifySymlink(yaffs_Object *obj)
733 if(obj && yaffs_SkipVerification(obj->myDev))
736 /* Verify symlink string */
739 static void yaffs_VerifySpecial(yaffs_Object *obj)
741 if(obj && yaffs_SkipVerification(obj->myDev))
745 static void yaffs_VerifyObject(yaffs_Object *obj)
760 if(yaffs_SkipVerification(dev))
763 /* Check sane object header chunk */
765 chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
766 chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
768 chunkIdOk = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
769 chunkIsLive = chunkIdOk &&
770 yaffs_CheckChunkBit(dev,
771 obj->hdrChunk / dev->nChunksPerBlock,
772 obj->hdrChunk % dev->nChunksPerBlock);
774 (!chunkIdOk || !chunkIsLive)) {
775 T(YAFFS_TRACE_VERIFY,
776 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
777 obj->objectId,obj->hdrChunk,
778 chunkIdOk ? "" : ",out of range",
779 chunkIsLive || !chunkIdOk ? "" : ",marked as deleted"));
782 if(chunkIdOk && chunkIsLive &&!yaffs_SkipNANDVerification(dev)) {
783 yaffs_ExtendedTags tags;
784 yaffs_ObjectHeader *oh;
785 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
787 oh = (yaffs_ObjectHeader *)buffer;
789 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk,buffer, &tags);
791 yaffs_VerifyObjectHeader(obj,oh,&tags,1);
793 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
796 /* Verify it has a parent */
797 if(obj && !obj->fake &&
798 (!obj->parent || obj->parent->myDev != dev)){
799 T(YAFFS_TRACE_VERIFY,
800 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
801 obj->objectId,obj->parent));
804 /* Verify parent is a directory */
805 if(obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
806 T(YAFFS_TRACE_VERIFY,
807 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
808 obj->objectId,obj->parent->variantType));
811 switch(obj->variantType){
812 case YAFFS_OBJECT_TYPE_FILE:
813 yaffs_VerifyFile(obj);
815 case YAFFS_OBJECT_TYPE_SYMLINK:
816 yaffs_VerifySymlink(obj);
818 case YAFFS_OBJECT_TYPE_DIRECTORY:
819 yaffs_VerifyDirectory(obj);
821 case YAFFS_OBJECT_TYPE_HARDLINK:
822 yaffs_VerifyHardLink(obj);
824 case YAFFS_OBJECT_TYPE_SPECIAL:
825 yaffs_VerifySpecial(obj);
827 case YAFFS_OBJECT_TYPE_UNKNOWN:
829 T(YAFFS_TRACE_VERIFY,
830 (TSTR("Obj %d has illegaltype %d"TENDSTR),
831 obj->objectId,obj->variantType));
838 static void yaffs_VerifyObjects(yaffs_Device *dev)
842 struct ylist_head *lh;
844 if(yaffs_SkipVerification(dev))
847 /* Iterate through the objects in each hash entry */
849 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++){
850 ylist_for_each(lh, &dev->objectBucket[i].list) {
852 obj = ylist_entry(lh, yaffs_Object, hashLink);
853 yaffs_VerifyObject(obj);
862 * Simple hash function. Needs to have a reasonable spread
865 static Y_INLINE int yaffs_HashFunction(int n)
868 return (n % YAFFS_NOBJECT_BUCKETS);
872 * Access functions to useful fake objects.
873 * Note that root might have a presence in NAND if permissions are set.
876 yaffs_Object *yaffs_Root(yaffs_Device * dev)
881 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
883 return dev->lostNFoundDir;
888 * Erased NAND checking functions
891 int yaffs_CheckFF(__u8 * buffer, int nBytes)
893 /* Horrible, slow implementation */
902 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
906 int retval = YAFFS_OK;
907 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
908 yaffs_ExtendedTags tags;
911 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
913 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__);
929 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
931 yaffs_ExtendedTags * tags,
938 yaffs_InvalidateCheckpoint(dev);
941 yaffs_BlockInfo *bi = 0;
944 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
950 /* First check this chunk is erased, if it needs
951 * checking. The checking policy (unless forced
952 * always on) is as follows:
954 * Check the first page we try to write in a block.
955 * If the check passes then we don't need to check any
956 * more. If the check fails, we check again...
957 * If the block has been erased, we don't need to check.
959 * However, if the block has been prioritised for gc,
960 * then we think there might be something odd about
961 * this block and stop using it.
963 * Rationale: We should only ever see chunks that have
964 * not been erased if there was a partially written
965 * chunk due to power loss. This checking policy should
966 * catch that case with very few checks and thus save a
967 * lot of checks that are most likely not needed.
969 if (bi->gcPrioritise) {
970 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
971 /* try another chunk */
975 /* let's give it a try */
978 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
979 bi->skipErasedCheck = 0;
981 if (!bi->skipErasedCheck) {
982 erasedOk = yaffs_CheckChunkErased(dev, chunk);
983 if (erasedOk != YAFFS_OK) {
985 (TSTR ("**>> yaffs chunk %d was not erased"
988 /* try another chunk */
991 bi->skipErasedCheck = 1;
994 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
996 if (writeOk != YAFFS_OK) {
997 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
998 /* try another chunk */
1002 /* Copy the data into the robustification buffer */
1003 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1005 } while (writeOk != YAFFS_OK &&
1006 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1012 T(YAFFS_TRACE_ERROR,
1013 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1016 dev->nRetriedWrites += (attempts - 1);
1023 * Block retiring for handling a broken block.
1026 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
1028 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1030 yaffs_InvalidateCheckpoint(dev);
1032 yaffs_MarkBlockBad(dev, blockInNAND);
1034 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1035 bi->gcPrioritise = 0;
1036 bi->needsRetiring = 0;
1038 dev->nRetiredBlocks++;
1042 * Functions for robustisizing TODO
1046 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
1048 const yaffs_ExtendedTags * tags)
1052 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
1053 const yaffs_ExtendedTags * tags)
1057 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1059 if(!bi->gcPrioritise){
1060 bi->gcPrioritise = 1;
1061 dev->hasPendingPrioritisedGCs = 1;
1062 bi->chunkErrorStrikes ++;
1064 if(bi->chunkErrorStrikes > 3){
1065 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1066 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1073 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
1076 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1077 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1079 yaffs_HandleChunkError(dev,bi);
1083 /* Was an actual write failure, so mark the block for retirement */
1084 bi->needsRetiring = 1;
1085 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1086 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1091 /* Delete the chunk */
1092 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1096 /*---------------- Name handling functions ------------*/
1098 static __u16 yaffs_CalcNameSum(const YCHAR * name)
1103 const YUCHAR *bname = (const YUCHAR *) name;
1105 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1107 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1108 sum += yaffs_toupper(*bname) * i;
1110 sum += (*bname) * i;
1120 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
1122 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1123 memset(obj->shortName,0,sizeof (YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1124 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
1125 yaffs_strcpy(obj->shortName, name);
1127 obj->shortName[0] = _Y('\0');
1130 obj->sum = yaffs_CalcNameSum(name);
1133 /*-------------------- TNODES -------------------
1135 * List of spare tnodes
1136 * The list is hooked together using the first pointer
1140 /* yaffs_CreateTnodes creates a bunch more tnodes and
1141 * adds them to the tnode free list.
1142 * Don't use this function directly
1145 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
1149 yaffs_Tnode *newTnodes;
1153 yaffs_TnodeList *tnl;
1158 /* Calculate the tnode size in bytes for variable width tnode support.
1159 * Must be a multiple of 32-bits */
1160 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1162 if(tnodeSize < sizeof(yaffs_Tnode))
1163 tnodeSize = sizeof(yaffs_Tnode);
1166 /* make these things */
1168 newTnodes = YMALLOC(nTnodes * tnodeSize);
1169 mem = (__u8 *)newTnodes;
1172 T(YAFFS_TRACE_ERROR,
1173 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1177 /* Hook them into the free list */
1179 for (i = 0; i < nTnodes - 1; i++) {
1180 newTnodes[i].internal[0] = &newTnodes[i + 1];
1181 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1182 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1186 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1187 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1188 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1190 dev->freeTnodes = newTnodes;
1192 /* New hookup for wide tnodes */
1193 for(i = 0; i < nTnodes -1; i++) {
1194 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1195 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1196 curr->internal[0] = next;
1199 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1200 curr->internal[0] = dev->freeTnodes;
1201 dev->freeTnodes = (yaffs_Tnode *)mem;
1206 dev->nFreeTnodes += nTnodes;
1207 dev->nTnodesCreated += nTnodes;
1209 /* Now add this bunch of tnodes to a list for freeing up.
1210 * NB If we can't add this to the management list it isn't fatal
1211 * but it just means we can't free this bunch of tnodes later.
1214 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1216 T(YAFFS_TRACE_ERROR,
1218 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1222 tnl->tnodes = newTnodes;
1223 tnl->next = dev->allocatedTnodeList;
1224 dev->allocatedTnodeList = tnl;
1227 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1232 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1234 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
1236 yaffs_Tnode *tn = NULL;
1238 /* If there are none left make more */
1239 if (!dev->freeTnodes) {
1240 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1243 if (dev->freeTnodes) {
1244 tn = dev->freeTnodes;
1245 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1246 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1247 /* Hoosterman, this thing looks like it isn't in the list */
1248 T(YAFFS_TRACE_ALWAYS,
1249 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1252 dev->freeTnodes = dev->freeTnodes->internal[0];
1256 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1261 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
1263 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1264 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1266 if(tnodeSize < sizeof(yaffs_Tnode))
1267 tnodeSize = sizeof(yaffs_Tnode);
1270 memset(tn, 0, tnodeSize);
1275 /* FreeTnode frees up a tnode and puts it back on the free list */
1276 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
1279 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1280 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1281 /* Hoosterman, this thing looks like it is already in the list */
1282 T(YAFFS_TRACE_ALWAYS,
1283 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1285 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1287 tn->internal[0] = dev->freeTnodes;
1288 dev->freeTnodes = tn;
1291 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1295 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
1297 /* Free the list of allocated tnodes */
1298 yaffs_TnodeList *tmp;
1300 while (dev->allocatedTnodeList) {
1301 tmp = dev->allocatedTnodeList->next;
1303 YFREE(dev->allocatedTnodeList->tnodes);
1304 YFREE(dev->allocatedTnodeList);
1305 dev->allocatedTnodeList = tmp;
1309 dev->freeTnodes = NULL;
1310 dev->nFreeTnodes = 0;
1313 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
1315 dev->allocatedTnodeList = NULL;
1316 dev->freeTnodes = NULL;
1317 dev->nFreeTnodes = 0;
1318 dev->nTnodesCreated = 0;
1323 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
1325 __u32 *map = (__u32 *)tn;
1331 pos &= YAFFS_TNODES_LEVEL0_MASK;
1332 val >>= dev->chunkGroupBits;
1334 bitInMap = pos * dev->tnodeWidth;
1335 wordInMap = bitInMap /32;
1336 bitInWord = bitInMap & (32 -1);
1338 mask = dev->tnodeMask << bitInWord;
1340 map[wordInMap] &= ~mask;
1341 map[wordInMap] |= (mask & (val << bitInWord));
1343 if(dev->tnodeWidth > (32-bitInWord)) {
1344 bitInWord = (32 - bitInWord);
1346 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1347 map[wordInMap] &= ~mask;
1348 map[wordInMap] |= (mask & (val >> bitInWord));
1352 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
1354 __u32 *map = (__u32 *)tn;
1360 pos &= YAFFS_TNODES_LEVEL0_MASK;
1362 bitInMap = pos * dev->tnodeWidth;
1363 wordInMap = bitInMap /32;
1364 bitInWord = bitInMap & (32 -1);
1366 val = map[wordInMap] >> bitInWord;
1368 if(dev->tnodeWidth > (32-bitInWord)) {
1369 bitInWord = (32 - bitInWord);
1371 val |= (map[wordInMap] << bitInWord);
1374 val &= dev->tnodeMask;
1375 val <<= dev->chunkGroupBits;
1380 /* ------------------- End of individual tnode manipulation -----------------*/
1382 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1383 * The look up tree is represented by the top tnode and the number of topLevel
1384 * in the tree. 0 means only the level 0 tnode is in the tree.
1387 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1388 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
1389 yaffs_FileStructure * fStruct,
1393 yaffs_Tnode *tn = fStruct->top;
1395 int requiredTallness;
1396 int level = fStruct->topLevel;
1398 /* Check sane level and chunk Id */
1399 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
1403 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1407 /* First check we're tall enough (ie enough topLevel) */
1409 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1410 requiredTallness = 0;
1412 i >>= YAFFS_TNODES_INTERNAL_BITS;
1416 if (requiredTallness > fStruct->topLevel) {
1417 /* Not tall enough, so we can't find it, return NULL. */
1421 /* Traverse down to level 0 */
1422 while (level > 0 && tn) {
1424 internal[(chunkId >>
1425 ( YAFFS_TNODES_LEVEL0_BITS +
1427 YAFFS_TNODES_INTERNAL_BITS)
1429 YAFFS_TNODES_INTERNAL_MASK];
1437 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1438 * This happens in two steps:
1439 * 1. If the tree isn't tall enough, then make it taller.
1440 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1442 * Used when modifying the tree.
1444 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1445 * be plugged into the ttree.
1448 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
1449 yaffs_FileStructure * fStruct,
1451 yaffs_Tnode *passedTn)
1454 int requiredTallness;
1462 /* Check sane level and page Id */
1463 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
1467 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1471 /* First check we're tall enough (ie enough topLevel) */
1473 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1474 requiredTallness = 0;
1476 x >>= YAFFS_TNODES_INTERNAL_BITS;
1481 if (requiredTallness > fStruct->topLevel) {
1482 /* Not tall enough,gotta make the tree taller */
1483 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1485 tn = yaffs_GetTnode(dev);
1488 tn->internal[0] = fStruct->top;
1491 T(YAFFS_TRACE_ERROR,
1492 (TSTR("yaffs: no more tnodes" TENDSTR)));
1496 fStruct->topLevel = requiredTallness;
1499 /* Traverse down to level 0, adding anything we need */
1501 l = fStruct->topLevel;
1505 while (l > 0 && tn) {
1507 ( YAFFS_TNODES_LEVEL0_BITS +
1508 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1509 YAFFS_TNODES_INTERNAL_MASK;
1512 if((l>1) && !tn->internal[x]){
1513 /* Add missing non-level-zero tnode */
1514 tn->internal[x] = yaffs_GetTnode(dev);
1517 /* Looking from level 1 at level 0 */
1519 /* If we already have one, then release it.*/
1521 yaffs_FreeTnode(dev,tn->internal[x]);
1522 tn->internal[x] = passedTn;
1524 } else if(!tn->internal[x]) {
1525 /* Don't have one, none passed in */
1526 tn->internal[x] = yaffs_GetTnode(dev);
1530 tn = tn->internal[x];
1534 /* top is level 0 */
1536 memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1537 yaffs_FreeTnode(dev,passedTn);
1544 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1545 yaffs_ExtendedTags * tags, int objectId,
1550 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1551 if (yaffs_CheckChunkBit
1552 (dev, theChunk / dev->nChunksPerBlock,
1553 theChunk % dev->nChunksPerBlock)) {
1554 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1556 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1568 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1569 * chunks and tnodes in the file
1570 * Returns 1 if the tree was deleted.
1571 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1574 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1575 int chunkOffset, int *limit)
1580 yaffs_ExtendedTags tags;
1582 yaffs_Device *dev = in->myDev;
1589 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1591 if (tn->internal[i]) {
1592 if (limit && (*limit) < 0) {
1596 yaffs_DeleteWorker(in,
1604 YAFFS_TNODES_INTERNAL_BITS)
1609 yaffs_FreeTnode(dev,
1612 tn->internal[i] = NULL;
1617 return (allDone) ? 1 : 0;
1618 } else if (level == 0) {
1621 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1623 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1628 YAFFS_TNODES_LEVEL0_BITS) + i;
1631 yaffs_FindChunkInGroup(dev,
1637 if (foundChunk > 0) {
1638 yaffs_DeleteChunk(dev,
1643 *limit = *limit - 1;
1651 yaffs_PutLevel0Tnode(dev,tn,i,0);
1655 return (i < 0) ? 1 : 0;
1665 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1668 yaffs_BlockInfo *theBlock;
1670 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1672 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1674 theBlock->softDeletions++;
1679 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1680 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1682 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1685 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1686 __u32 level, int chunkOffset)
1691 yaffs_Device *dev = in->myDev;
1696 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1698 if (tn->internal[i]) {
1700 yaffs_SoftDeleteWorker(in,
1706 YAFFS_TNODES_INTERNAL_BITS)
1709 yaffs_FreeTnode(dev,
1712 tn->internal[i] = NULL;
1714 /* Hoosterman... how could this happen? */
1718 return (allDone) ? 1 : 0;
1719 } else if (level == 0) {
1721 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1722 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1724 /* Note this does not find the real chunk, only the chunk group.
1725 * We make an assumption that a chunk group is not larger than
1728 yaffs_SoftDeleteChunk(dev, theChunk);
1729 yaffs_PutLevel0Tnode(dev,tn,i,0);
1743 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1746 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1747 if (obj->nDataChunks <= 0) {
1748 /* Empty file with no duplicate object headers, just delete it immediately */
1749 yaffs_FreeTnode(obj->myDev,
1750 obj->variant.fileVariant.top);
1751 obj->variant.fileVariant.top = NULL;
1752 T(YAFFS_TRACE_TRACING,
1753 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1755 yaffs_DoGenericObjectDeletion(obj);
1757 yaffs_SoftDeleteWorker(obj,
1758 obj->variant.fileVariant.top,
1759 obj->variant.fileVariant.
1761 obj->softDeleted = 1;
1766 /* Pruning removes any part of the file structure tree that is beyond the
1767 * bounds of the file (ie that does not point to chunks).
1769 * A file should only get pruned when its size is reduced.
1771 * Before pruning, the chunks must be pulled from the tree and the
1772 * level 0 tnode entries must be zeroed out.
1773 * Could also use this for file deletion, but that's probably better handled
1774 * by a special case.
1777 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1778 __u32 level, int del0)
1786 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1787 if (tn->internal[i] && level > 0) {
1789 yaffs_PruneWorker(dev, tn->internal[i],
1791 (i == 0) ? del0 : 1);
1794 if (tn->internal[i]) {
1799 if (hasData == 0 && del0) {
1800 /* Free and return NULL */
1802 yaffs_FreeTnode(dev, tn);
1812 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1813 yaffs_FileStructure * fStruct)
1820 if (fStruct->topLevel > 0) {
1822 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1824 /* Now we have a tree with all the non-zero branches NULL but the height
1825 * is the same as it was.
1826 * Let's see if we can trim internal tnodes to shorten the tree.
1827 * We can do this if only the 0th element in the tnode is in use
1828 * (ie all the non-zero are NULL)
1831 while (fStruct->topLevel && !done) {
1835 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1836 if (tn->internal[i]) {
1842 fStruct->top = tn->internal[0];
1843 fStruct->topLevel--;
1844 yaffs_FreeTnode(dev, tn);
1854 /*-------------------- End of File Structure functions.-------------------*/
1856 /* yaffs_CreateFreeObjects creates a bunch more objects and
1857 * adds them to the object free list.
1859 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1862 yaffs_Object *newObjects;
1863 yaffs_ObjectList *list;
1868 /* make these things */
1869 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1870 list = YMALLOC(sizeof(yaffs_ObjectList));
1872 if (!newObjects || !list) {
1877 T(YAFFS_TRACE_ALLOCATE,
1878 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1882 /* Hook them into the free list */
1883 for (i = 0; i < nObjects - 1; i++) {
1884 newObjects[i].siblings.next =
1885 (struct ylist_head *)(&newObjects[i + 1]);
1888 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1889 dev->freeObjects = newObjects;
1890 dev->nFreeObjects += nObjects;
1891 dev->nObjectsCreated += nObjects;
1893 /* Now add this bunch of Objects to a list for freeing up. */
1895 list->objects = newObjects;
1896 list->next = dev->allocatedObjectList;
1897 dev->allocatedObjectList = list;
1903 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1904 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1906 yaffs_Object *tn = NULL;
1908 #ifdef VALGRIND_TEST
1909 tn = YMALLOC(sizeof(yaffs_Object));
1911 /* If there are none left make more */
1912 if (!dev->freeObjects) {
1913 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1916 if (dev->freeObjects) {
1917 tn = dev->freeObjects;
1919 (yaffs_Object *) (dev->freeObjects->siblings.next);
1920 dev->nFreeObjects--;
1924 /* Now sweeten it up... */
1926 memset(tn, 0, sizeof(yaffs_Object));
1929 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1930 YINIT_LIST_HEAD(&(tn->hardLinks));
1931 YINIT_LIST_HEAD(&(tn->hashLink));
1932 YINIT_LIST_HEAD(&tn->siblings);
1935 /* Now make the directory sane */
1937 tn->parent = dev->rootDir;
1938 ylist_add(&(tn->siblings),&dev->rootDir->variant.directoryVariant.children);
1941 /* Add it to the lost and found directory.
1942 * NB Can't put root or lostNFound in lostNFound so
1943 * check if lostNFound exists first
1945 if (dev->lostNFoundDir) {
1946 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1950 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1955 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1960 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1962 obj->fake = 1; /* it is fake so it might have no NAND presence... */
1963 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1964 obj->unlinkAllowed = 0; /* ... or unlink it */
1967 obj->yst_mode = mode;
1969 obj->hdrChunk = 0; /* Not a valid chunk. */
1976 static void yaffs_UnhashObject(yaffs_Object * tn)
1979 yaffs_Device *dev = tn->myDev;
1981 /* If it is still linked into the bucket list, free from the list */
1982 if (!ylist_empty(&tn->hashLink)) {
1983 ylist_del_init(&tn->hashLink);
1984 bucket = yaffs_HashFunction(tn->objectId);
1985 dev->objectBucket[bucket].count--;
1990 /* FreeObject frees up a Object and puts it back on the free list */
1991 static void yaffs_FreeObject(yaffs_Object * tn)
1994 yaffs_Device *dev = tn->myDev;
1999 if(!ylist_empty(&tn->siblings))
2005 /* We're still hooked up to a cached inode.
2006 * Don't delete now, but mark for later deletion
2008 tn->deferedFree = 1;
2013 yaffs_UnhashObject(tn);
2015 #ifdef VALGRIND_TEST
2018 /* Link into the free list. */
2019 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2020 dev->freeObjects = tn;
2021 dev->nFreeObjects++;
2023 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2029 void yaffs_HandleDeferedFree(yaffs_Object * obj)
2031 if (obj->deferedFree) {
2032 yaffs_FreeObject(obj);
2038 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
2040 /* Free the list of allocated Objects */
2042 yaffs_ObjectList *tmp;
2044 while (dev->allocatedObjectList) {
2045 tmp = dev->allocatedObjectList->next;
2046 YFREE(dev->allocatedObjectList->objects);
2047 YFREE(dev->allocatedObjectList);
2049 dev->allocatedObjectList = tmp;
2052 dev->freeObjects = NULL;
2053 dev->nFreeObjects = 0;
2056 static void yaffs_InitialiseObjects(yaffs_Device * dev)
2060 dev->allocatedObjectList = NULL;
2061 dev->freeObjects = NULL;
2062 dev->nFreeObjects = 0;
2064 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2065 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2066 dev->objectBucket[i].count = 0;
2071 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
2076 int lowest = 999999;
2078 /* First let's see if we can find one that's empty. */
2080 for (i = 0; i < 10 && lowest > 0; i++) {
2082 x %= YAFFS_NOBJECT_BUCKETS;
2083 if (dev->objectBucket[x].count < lowest) {
2084 lowest = dev->objectBucket[x].count;
2090 /* If we didn't find an empty list, then try
2091 * looking a bit further for a short one
2094 for (i = 0; i < 10 && lowest > 3; i++) {
2096 x %= YAFFS_NOBJECT_BUCKETS;
2097 if (dev->objectBucket[x].count < lowest) {
2098 lowest = dev->objectBucket[x].count;
2107 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
2109 int bucket = yaffs_FindNiceObjectBucket(dev);
2111 /* Now find an object value that has not already been taken
2112 * by scanning the list.
2116 struct ylist_head *i;
2118 __u32 n = (__u32) bucket;
2120 /* yaffs_CheckObjectHashSanity(); */
2124 n += YAFFS_NOBJECT_BUCKETS;
2125 if (1 || dev->objectBucket[bucket].count > 0) {
2126 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2127 /* If there is already one in the list */
2129 && ylist_entry(i, yaffs_Object,
2130 hashLink)->objectId == n) {
2141 static void yaffs_HashObject(yaffs_Object * in)
2143 int bucket = yaffs_HashFunction(in->objectId);
2144 yaffs_Device *dev = in->myDev;
2146 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2147 dev->objectBucket[bucket].count++;
2151 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
2153 int bucket = yaffs_HashFunction(number);
2154 struct ylist_head *i;
2157 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2158 /* Look if it is in the list */
2160 in = ylist_entry(i, yaffs_Object, hashLink);
2161 if (in->objectId == number) {
2163 /* Don't tell the VFS about this one if it is defered free */
2164 if (in->deferedFree)
2176 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
2177 yaffs_ObjectType type)
2180 yaffs_Object *theObject;
2181 yaffs_Tnode *tn = NULL;
2184 number = yaffs_CreateNewObjectNumber(dev);
2187 theObject = yaffs_AllocateEmptyObject(dev);
2191 if(type == YAFFS_OBJECT_TYPE_FILE){
2192 tn = yaffs_GetTnode(dev);
2194 yaffs_FreeObject(theObject);
2202 theObject->fake = 0;
2203 theObject->renameAllowed = 1;
2204 theObject->unlinkAllowed = 1;
2205 theObject->objectId = number;
2206 yaffs_HashObject(theObject);
2207 theObject->variantType = type;
2208 #ifdef CONFIG_YAFFS_WINCE
2209 yfsd_WinFileTimeNow(theObject->win_atime);
2210 theObject->win_ctime[0] = theObject->win_mtime[0] =
2211 theObject->win_atime[0];
2212 theObject->win_ctime[1] = theObject->win_mtime[1] =
2213 theObject->win_atime[1];
2217 theObject->yst_atime = theObject->yst_mtime =
2218 theObject->yst_ctime = Y_CURRENT_TIME;
2222 theObject->sum_prev = 12345;
2223 theObject->sum_trailer = 6789;
2227 case YAFFS_OBJECT_TYPE_FILE:
2228 theObject->variant.fileVariant.fileSize = 0;
2229 theObject->variant.fileVariant.scannedFileSize = 0;
2230 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2231 theObject->variant.fileVariant.topLevel = 0;
2232 theObject->variant.fileVariant.top = tn;
2234 case YAFFS_OBJECT_TYPE_DIRECTORY:
2235 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2238 case YAFFS_OBJECT_TYPE_SYMLINK:
2239 case YAFFS_OBJECT_TYPE_HARDLINK:
2240 case YAFFS_OBJECT_TYPE_SPECIAL:
2241 /* No action required */
2243 case YAFFS_OBJECT_TYPE_UNKNOWN:
2244 /* todo this should not happen */
2252 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
2254 yaffs_ObjectType type)
2256 yaffs_Object *theObject = NULL;
2259 theObject = yaffs_FindObjectByNumber(dev, number);
2263 theObject = yaffs_CreateNewObject(dev, number, type);
2271 static YCHAR *yaffs_CloneString(const YCHAR * str)
2273 YCHAR *newStr = NULL;
2276 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2278 yaffs_strcpy(newStr, str);
2286 * Mknod (create) a new object.
2287 * equivalentObject only has meaning for a hard link;
2288 * aliasString only has meaning for a sumlink.
2289 * rdev only has meaning for devices (a subset of special objects)
2292 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2293 yaffs_Object * parent,
2298 yaffs_Object * equivalentObject,
2299 const YCHAR * aliasString, __u32 rdev)
2304 yaffs_Device *dev = parent->myDev;
2306 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2307 if (yaffs_FindObjectByName(parent, name)) {
2311 in = yaffs_CreateNewObject(dev, -1, type);
2316 if(type == YAFFS_OBJECT_TYPE_SYMLINK){
2317 str = yaffs_CloneString(aliasString);
2319 yaffs_FreeObject(in);
2329 in->variantType = type;
2331 in->yst_mode = mode;
2333 #ifdef CONFIG_YAFFS_WINCE
2334 yfsd_WinFileTimeNow(in->win_atime);
2335 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2336 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2339 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2341 in->yst_rdev = rdev;
2345 in->nDataChunks = 0;
2347 yaffs_SetObjectName(in, name);
2350 yaffs_AddObjectToDirectory(parent, in);
2352 in->myDev = parent->myDev;
2355 case YAFFS_OBJECT_TYPE_SYMLINK:
2356 in->variant.symLinkVariant.alias = str;
2358 case YAFFS_OBJECT_TYPE_HARDLINK:
2359 in->variant.hardLinkVariant.equivalentObject =
2361 in->variant.hardLinkVariant.equivalentObjectId =
2362 equivalentObject->objectId;
2363 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2365 case YAFFS_OBJECT_TYPE_FILE:
2366 case YAFFS_OBJECT_TYPE_DIRECTORY:
2367 case YAFFS_OBJECT_TYPE_SPECIAL:
2368 case YAFFS_OBJECT_TYPE_UNKNOWN:
2373 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2374 /* Could not create the object header, fail the creation */
2375 yaffs_DestroyObject(in);
2384 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
2385 __u32 mode, __u32 uid, __u32 gid)
2387 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2388 uid, gid, NULL, NULL, 0);
2391 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
2392 __u32 mode, __u32 uid, __u32 gid)
2394 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2395 mode, uid, gid, NULL, NULL, 0);
2398 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
2399 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2401 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2402 uid, gid, NULL, NULL, rdev);
2405 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
2406 __u32 mode, __u32 uid, __u32 gid,
2407 const YCHAR * alias)
2409 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2410 uid, gid, NULL, alias, 0);
2413 /* yaffs_Link returns the object id of the equivalent object.*/
2414 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
2415 yaffs_Object * equivalentObject)
2417 /* Get the real object in case we were fed a hard link as an equivalent object */
2418 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2420 if (yaffs_MknodObject
2421 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2422 equivalentObject, NULL, 0)) {
2423 return equivalentObject;
2430 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
2431 const YCHAR * newName, int force, int shadows)
2436 yaffs_Object *existingTarget;
2438 if (newDir == NULL) {
2439 newDir = obj->parent; /* use the old directory */
2442 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2443 T(YAFFS_TRACE_ALWAYS,
2445 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2450 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2451 if (obj->myDev->isYaffs2) {
2452 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2454 unlinkOp = (newDir == obj->myDev->unlinkedDir
2455 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2458 deleteOp = (newDir == obj->myDev->deletedDir);
2460 existingTarget = yaffs_FindObjectByName(newDir, newName);
2462 /* If the object is a file going into the unlinked directory,
2463 * then it is OK to just stuff it in since duplicate names are allowed.
2464 * else only proceed if the new name does not exist and if we're putting
2465 * it into a directory.
2472 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2473 yaffs_SetObjectName(obj, newName);
2476 yaffs_AddObjectToDirectory(newDir, obj);
2481 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2482 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
2489 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
2490 yaffs_Object * newDir, const YCHAR * newName)
2492 yaffs_Object *obj=NULL;
2493 yaffs_Object *existingTarget=NULL;
2497 if(!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2499 if(!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2502 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2503 /* Special case for case insemsitive systems (eg. WinCE).
2504 * While look-up is case insensitive, the name isn't.
2505 * Therefore we might want to change x.txt to X.txt
2507 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
2512 else if (yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2516 obj = yaffs_FindObjectByName(oldDir, oldName);
2518 if (obj && obj->renameAllowed) {
2520 /* Now do the handling for an existing target, if there is one */
2522 existingTarget = yaffs_FindObjectByName(newDir, newName);
2523 if (existingTarget &&
2524 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2525 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2526 /* There is a target that is a non-empty directory, so we fail */
2527 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2528 } else if (existingTarget && existingTarget != obj) {
2529 /* Nuke the target first, using shadowing,
2530 * but only if it isn't the same object
2532 yaffs_ChangeObjectName(obj, newDir, newName, force,
2533 existingTarget->objectId);
2534 yaffs_UnlinkObject(existingTarget);
2537 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2542 /*------------------------- Block Management and Page Allocation ----------------*/
2544 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
2546 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2548 dev->blockInfo = NULL;
2549 dev->chunkBits = NULL;
2551 dev->allocationBlock = -1; /* force it to get a new one */
2553 /* If the first allocation strategy fails, thry the alternate one */
2554 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2555 if(!dev->blockInfo){
2556 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2557 dev->blockInfoAlt = 1;
2560 dev->blockInfoAlt = 0;
2564 /* Set up dynamic blockinfo stuff. */
2565 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2566 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2567 if(!dev->chunkBits){
2568 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2569 dev->chunkBitsAlt = 1;
2572 dev->chunkBitsAlt = 0;
2575 if (dev->blockInfo && dev->chunkBits) {
2576 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2577 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2585 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
2587 if(dev->blockInfoAlt && dev->blockInfo)
2588 YFREE_ALT(dev->blockInfo);
2589 else if(dev->blockInfo)
2590 YFREE(dev->blockInfo);
2592 dev->blockInfoAlt = 0;
2594 dev->blockInfo = NULL;
2596 if(dev->chunkBitsAlt && dev->chunkBits)
2597 YFREE_ALT(dev->chunkBits);
2598 else if(dev->chunkBits)
2599 YFREE(dev->chunkBits);
2600 dev->chunkBitsAlt = 0;
2601 dev->chunkBits = NULL;
2604 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
2605 yaffs_BlockInfo * bi)
2612 return 1; /* disqualification only applies to yaffs2. */
2614 if (!bi->hasShrinkHeader)
2615 return 1; /* can gc */
2617 /* Find the oldest dirty sequence number if we don't know it and save it
2618 * so we don't have to keep recomputing it.
2620 if (!dev->oldestDirtySequence) {
2621 seq = dev->sequenceNumber;
2623 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2625 b = yaffs_GetBlockInfo(dev, i);
2626 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2627 (b->pagesInUse - b->softDeletions) <
2628 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2629 seq = b->sequenceNumber;
2632 dev->oldestDirtySequence = seq;
2635 /* Can't do gc of this block if there are any blocks older than this one that have
2638 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2642 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2643 * for garbage collection.
2646 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2650 int b = dev->currentDirtyChecker;
2657 yaffs_BlockInfo *bi;
2658 int pendingPrioritisedExist = 0;
2660 /* First let's see if we need to grab a prioritised block */
2661 if(dev->hasPendingPrioritisedGCs){
2662 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2664 bi = yaffs_GetBlockInfo(dev, i);
2665 //yaffs_VerifyBlock(dev,bi,i);
2667 if(bi->gcPrioritise) {
2668 pendingPrioritisedExist = 1;
2669 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2670 yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2671 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2674 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2679 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2680 dev->hasPendingPrioritisedGCs = 0;
2683 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2685 * else (we're doing a leasurely gc), then we only bother to do this if the
2686 * block has only a few pages in use.
2689 dev->nonAggressiveSkip--;
2691 if (!aggressive && (dev->nonAggressiveSkip > 0)) {
2697 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2701 dev->internalEndBlock - dev->internalStartBlock + 1;
2704 dev->internalEndBlock - dev->internalStartBlock + 1;
2705 iterations = iterations / 16;
2706 if (iterations > 200) {
2711 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2713 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2714 b = dev->internalStartBlock;
2717 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2718 T(YAFFS_TRACE_ERROR,
2719 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2723 bi = yaffs_GetBlockInfo(dev, b);
2726 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2733 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2734 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2735 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2737 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2741 dev->currentDirtyChecker = b;
2745 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2746 dev->nChunksPerBlock - pagesInUse,prioritised));
2749 dev->oldestDirtySequence = 0;
2752 dev->nonAggressiveSkip = 4;
2758 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2760 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2764 /* If the block is still healthy erase it and mark as clean.
2765 * If the block has had a data failure, then retire it.
2768 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2769 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2770 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2772 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2774 if (!bi->needsRetiring) {
2775 yaffs_InvalidateCheckpoint(dev);
2776 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2778 dev->nErasureFailures++;
2779 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2780 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2785 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2787 for (i = 0; i < dev->nChunksPerBlock; i++) {
2788 if (!yaffs_CheckChunkErased
2789 (dev, blockNo * dev->nChunksPerBlock + i)) {
2790 T(YAFFS_TRACE_ERROR,
2792 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2793 TENDSTR), blockNo, i));
2799 /* Clean it up... */
2800 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2801 dev->nErasedBlocks++;
2803 bi->softDeletions = 0;
2804 bi->hasShrinkHeader = 0;
2805 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2806 bi->gcPrioritise = 0;
2807 yaffs_ClearChunkBits(dev, blockNo);
2809 T(YAFFS_TRACE_ERASE,
2810 (TSTR("Erased block %d" TENDSTR), blockNo));
2812 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2814 yaffs_RetireBlock(dev, blockNo);
2815 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2816 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2820 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2824 yaffs_BlockInfo *bi;
2826 if (dev->nErasedBlocks < 1) {
2827 /* Hoosterman we've got a problem.
2828 * Can't get space to gc
2830 T(YAFFS_TRACE_ERROR,
2831 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2836 /* Find an empty block. */
2838 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2839 dev->allocationBlockFinder++;
2840 if (dev->allocationBlockFinder < dev->internalStartBlock
2841 || dev->allocationBlockFinder > dev->internalEndBlock) {
2842 dev->allocationBlockFinder = dev->internalStartBlock;
2845 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2847 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2848 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2849 dev->sequenceNumber++;
2850 bi->sequenceNumber = dev->sequenceNumber;
2851 dev->nErasedBlocks--;
2852 T(YAFFS_TRACE_ALLOCATE,
2853 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2854 dev->allocationBlockFinder, dev->sequenceNumber,
2855 dev->nErasedBlocks));
2856 return dev->allocationBlockFinder;
2860 T(YAFFS_TRACE_ALWAYS,
2862 ("yaffs tragedy: no more erased blocks, but there should have been %d"
2863 TENDSTR), dev->nErasedBlocks));
2870 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2872 if(!dev->nCheckpointBlocksRequired &&
2874 /* Not a valid value so recalculate */
2877 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2880 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2882 if(tnodeSize < sizeof(yaffs_Tnode))
2883 tnodeSize = sizeof(yaffs_Tnode);
2885 nBytes += sizeof(yaffs_CheckpointValidity);
2886 nBytes += sizeof(yaffs_CheckpointDevice);
2887 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2888 nBytes += devBlocks * dev->chunkBitmapStride;
2889 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2890 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2891 nBytes += sizeof(yaffs_CheckpointValidity);
2892 nBytes += sizeof(__u32); /* checksum*/
2894 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2896 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2898 dev->nCheckpointBlocksRequired = nBlocks;
2901 return dev->nCheckpointBlocksRequired;
2904 // Check if there's space to allocate...
2905 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2906 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2909 int reservedBlocks = dev->nReservedBlocks;
2910 int checkpointBlocks;
2913 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
2914 dev->blocksInCheckpoint;
2915 if(checkpointBlocks < 0)
2916 checkpointBlocks = 0;
2918 checkpointBlocks =0;
2921 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2923 return (dev->nFreeChunks > reservedChunks);
2926 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2929 yaffs_BlockInfo *bi;
2931 if (dev->allocationBlock < 0) {
2932 /* Get next block to allocate off */
2933 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2934 dev->allocationPage = 0;
2937 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2938 /* Not enough space to allocate unless we're allowed to use the reserve. */
2942 if (dev->nErasedBlocks < dev->nReservedBlocks
2943 && dev->allocationPage == 0) {
2944 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2947 /* Next page please.... */
2948 if (dev->allocationBlock >= 0) {
2949 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2951 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2952 dev->allocationPage;
2954 yaffs_SetChunkBit(dev, dev->allocationBlock,
2955 dev->allocationPage);
2957 dev->allocationPage++;
2961 /* If the block is full set the state to full */
2962 if (dev->allocationPage >= dev->nChunksPerBlock) {
2963 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2964 dev->allocationBlock = -1;
2973 T(YAFFS_TRACE_ERROR,
2974 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2979 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2983 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2985 if (dev->allocationBlock > 0) {
2986 n += (dev->nChunksPerBlock - dev->allocationPage);
2993 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block, int wholeBlock)
2998 int retVal = YAFFS_OK;
3001 int isCheckpointBlock;
3005 int chunksBefore = yaffs_GetErasedChunks(dev);
3008 yaffs_ExtendedTags tags;
3010 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3012 yaffs_Object *object;
3014 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3016 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3018 T(YAFFS_TRACE_TRACING,
3019 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3022 bi->hasShrinkHeader,
3025 /*yaffs_VerifyFreeChunks(dev); */
3027 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
3029 /* Take off the number of soft deleted entries because
3030 * they're going to get really deleted during GC.
3032 dev->nFreeChunks -= bi->softDeletions;
3036 if (isCheckpointBlock ||
3037 !yaffs_StillSomeChunkBits(dev, block)) {
3038 T(YAFFS_TRACE_TRACING,
3040 ("Collecting block %d that has no chunks in use" TENDSTR),
3042 yaffs_BlockBecameDirty(dev, block);
3045 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3047 yaffs_VerifyBlock(dev,bi,block);
3049 maxCopies = (wholeBlock) ? dev->nChunksPerBlock : 10;
3050 oldChunk = block * dev->nChunksPerBlock + dev->gcChunk;
3052 for ( /* init already done */;
3053 retVal == YAFFS_OK &&
3054 dev->gcChunk < dev->nChunksPerBlock &&
3055 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING)&&
3057 dev->gcChunk++, oldChunk++) {
3058 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3060 /* This page is in use and might need to be copied off */
3066 yaffs_InitialiseTags(&tags);
3068 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3072 yaffs_FindObjectByNumber(dev,
3075 T(YAFFS_TRACE_GC_DETAIL,
3077 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3078 dev->gcChunk, tags.objectId, tags.chunkId,
3081 if(object && !yaffs_SkipVerification(dev)){
3082 if(tags.chunkId == 0)
3083 matchingChunk = object->hdrChunk;
3084 else if(object->softDeleted)
3085 matchingChunk = oldChunk; /* Defeat the test */
3087 matchingChunk = yaffs_FindChunkInFile(object,tags.chunkId,NULL);
3089 if(oldChunk != matchingChunk)
3090 T(YAFFS_TRACE_ERROR,
3091 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3092 oldChunk,matchingChunk,tags.objectId, tags.chunkId));
3097 T(YAFFS_TRACE_ERROR,
3099 ("page %d in gc has no object: %d %d %d "
3101 tags.objectId, tags.chunkId, tags.byteCount));
3106 object->softDeleted &&
3107 tags.chunkId != 0) {
3108 /* Data chunk in a soft deleted file, throw it away
3109 * It's a soft deleted data chunk,
3110 * No need to copy this, just forget about it and
3111 * fix up the object.
3114 object->nDataChunks--;
3116 if (object->nDataChunks <= 0) {
3117 /* remeber to clean up the object */
3118 dev->gcCleanupList[cleanups] =
3124 /* Todo object && object->deleted && object->nDataChunks == 0 */
3126 /* Deleted object header with no data chunks.
3127 * Can be discarded and the file deleted.
3129 object->hdrChunk = 0;
3130 yaffs_FreeTnode(object->myDev,
3133 object->variant.fileVariant.top = NULL;
3134 yaffs_DoGenericObjectDeletion(object);
3136 } else if (object) {
3137 /* It's either a data chunk in a live file or
3138 * an ObjectHeader, so we're interested in it.
3139 * NB Need to keep the ObjectHeaders of deleted files
3140 * until the whole file has been deleted off
3142 tags.serialNumber++;
3146 if (tags.chunkId == 0) {
3147 /* It is an object Id,
3148 * We need to nuke the shrinkheader flags first
3149 * We no longer want the shrinkHeader flag since its work is done
3150 * and if it is left in place it will mess up scanning.
3151 * Also, clear out any shadowing stuff
3154 yaffs_ObjectHeader *oh;
3155 oh = (yaffs_ObjectHeader *)buffer;
3157 tags.extraShadows = 0;
3158 tags.extraIsShrinkHeader = 0;
3160 yaffs_VerifyObjectHeader(object,oh,&tags,1);
3164 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3167 retVal = YAFFS_FAIL;
3170 /* Ok, now fix up the Tnodes etc. */
3172 if (tags.chunkId == 0) {
3174 object->hdrChunk = newChunk;
3175 object->serial = tags.serialNumber;
3177 /* It's a data chunk */
3178 yaffs_PutChunkIntoFile
3186 if(retVal == YAFFS_OK)
3187 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3192 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3196 /* Do any required cleanups */
3197 for (i = 0; i < cleanups; i++) {
3198 /* Time to delete the file too */
3200 yaffs_FindObjectByNumber(dev,
3201 dev->gcCleanupList[i]);
3203 yaffs_FreeTnode(dev,
3204 object->variant.fileVariant.
3206 object->variant.fileVariant.top = NULL;
3209 ("yaffs: About to finally delete object %d"
3210 TENDSTR), object->objectId));
3211 yaffs_DoGenericObjectDeletion(object);
3212 object->myDev->nDeletedFiles--;
3219 yaffs_VerifyCollectedBlock(dev,bi,block);
3221 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
3224 ("gc did not increase free chunks before %d after %d"
3225 TENDSTR), chunksBefore, chunksAfter));
3228 /* If the gc completed then clear the current gcBlock so that we find another. */
3229 if(bi->blockState != YAFFS_BLOCK_STATE_COLLECTING){
3239 /* New garbage collector
3240 * If we're very low on erased blocks then we do aggressive garbage collection
3241 * otherwise we do "leasurely" garbage collection.
3242 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3243 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3245 * The idea is to help clear out space in a more spread-out manner.
3246 * Dunno if it really does anything useful.
3248 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
3252 int gcOk = YAFFS_OK;
3255 int checkpointBlockAdjust;
3257 if (dev->isDoingGC) {
3258 /* Bail out so we don't get recursive gc */
3262 /* This loop should pass the first time.
3263 * We'll only see looping here if the erase of the collected block fails.
3269 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3270 if(checkpointBlockAdjust < 0)
3271 checkpointBlockAdjust = 0;
3273 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3274 /* We need a block soon...*/
3277 /* We're in no hurry */
3281 if(dev->gcBlock <= 0){
3282 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3286 block = dev->gcBlock;
3289 dev->garbageCollections++;
3291 dev->passiveGarbageCollections++;
3296 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3297 dev->nErasedBlocks, aggressive));
3299 gcOk = yaffs_GarbageCollectBlock(dev,block,aggressive);
3302 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3305 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3306 TENDSTR), dev->nErasedBlocks, maxTries, block));
3308 } while ((dev->nErasedBlocks < dev->nReservedBlocks) &&
3312 return aggressive ? gcOk : YAFFS_OK;
3315 /*------------------------- TAGS --------------------------------*/
3317 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
3320 return (tags->chunkId == chunkInObject &&
3321 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3326 /*-------------------- Data file manipulation -----------------*/
3328 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
3329 yaffs_ExtendedTags * tags)
3331 /*Get the Tnode, then get the level 0 offset chunk offset */
3334 yaffs_ExtendedTags localTags;
3337 yaffs_Device *dev = in->myDev;
3340 /* Passed a NULL, so use our own tags space */
3344 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3347 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3350 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3356 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
3357 yaffs_ExtendedTags * tags)
3359 /* Get the Tnode, then get the level 0 offset chunk offset */