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.78 2009-01-27 02:52:45 charles Exp $";
19 #include "yaffsinterface.h"
20 #include "yaffs_guts.h"
21 #include "yaffs_tagsvalidity.h"
22 #include "yaffs_getblockinfo.h"
24 #include "yaffs_tagscompat.h"
25 #ifndef CONFIG_YAFFS_USE_OWN_SORT
26 #include "yaffs_qsort.h"
28 #include "yaffs_nand.h"
30 #include "yaffs_checkptrw.h"
32 #include "yaffs_nand.h"
33 #include "yaffs_packedtags2.h"
36 #define YAFFS_PASSIVE_GC_CHUNKS 2
38 #include "yaffs_ecc.h"
41 /* Robustification (if it ever comes about...) */
42 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
43 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk);
44 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
46 const yaffs_ExtendedTags * tags);
47 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
48 const yaffs_ExtendedTags * tags);
50 /* Other local prototypes */
51 static int yaffs_UnlinkObject( yaffs_Object *obj);
52 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
54 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
56 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
58 yaffs_ExtendedTags * tags,
60 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
61 int chunkInNAND, int inScan);
63 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
64 yaffs_ObjectType type);
65 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
67 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
68 int force, int isShrink, int shadows);
69 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
70 static int yaffs_CheckStructures(void);
71 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
72 int chunkOffset, int *limit);
73 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
75 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
78 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
81 static int yaffs_UnlinkWorker(yaffs_Object * obj);
82 static void yaffs_DestroyObject(yaffs_Object * obj);
84 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
87 loff_t yaffs_GetFileSize(yaffs_Object * obj);
89 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr);
91 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
93 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
95 static void yaffs_VerifyDirectory(yaffs_Object *directory);
97 static int yaffs_CheckFileSanity(yaffs_Object * in);
99 #define yaffs_CheckFileSanity(in)
102 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
103 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
105 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
107 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
108 yaffs_ExtendedTags * tags);
110 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos);
111 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
112 yaffs_FileStructure * fStruct,
116 /* Function to calculate chunk and offset */
118 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut, __u32 *offsetOut)
123 chunk = (__u32)(addr >> dev->chunkShift);
125 if(dev->chunkDiv == 1)
127 /* easy power of 2 case */
128 offset = (__u32)(addr & dev->chunkMask);
132 /* Non power-of-2 case */
136 chunk /= dev->chunkDiv;
138 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
139 offset = (__u32)(addr - chunkBase);
146 /* Function to return the number of shifts for a power of 2 greater than or equal
147 * to the given number
148 * Note we don't try to cater for all possible numbers and this does not have to
149 * be hellishly efficient.
152 static __u32 ShiftsGE(__u32 x)
157 nShifts = extraBits = 0;
160 if(x & 1) extraBits++;
171 /* Function to return the number of shifts to get a 1 in bit 0
174 static __u32 Shifts(__u32 x)
193 * Temporary buffer manipulations.
196 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
199 __u8 *buf = (__u8 *)1;
201 memset(dev->tempBuffer,0,sizeof(dev->tempBuffer));
203 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
204 dev->tempBuffer[i].line = 0; /* not in use */
205 dev->tempBuffer[i].buffer = buf =
206 YMALLOC_DMA(dev->totalBytesPerChunk);
209 return buf ? YAFFS_OK : YAFFS_FAIL;
213 __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
218 if(dev->tempInUse > dev->maxTemp)
219 dev->maxTemp = dev->tempInUse;
221 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
222 if (dev->tempBuffer[i].line == 0) {
223 dev->tempBuffer[i].line = lineNo;
224 if ((i + 1) > dev->maxTemp) {
225 dev->maxTemp = i + 1;
226 for (j = 0; j <= i; j++)
227 dev->tempBuffer[j].maxLine =
228 dev->tempBuffer[j].line;
231 return dev->tempBuffer[i].buffer;
235 T(YAFFS_TRACE_BUFFERS,
236 (TSTR("Out of temp buffers at line %d, other held by lines:"),
238 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
239 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
241 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
244 * If we got here then we have to allocate an unmanaged one
248 dev->unmanagedTempAllocations++;
249 return YMALLOC(dev->nDataBytesPerChunk);
253 void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
260 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
261 if (dev->tempBuffer[i].buffer == buffer) {
262 dev->tempBuffer[i].line = 0;
268 /* assume it is an unmanaged one. */
269 T(YAFFS_TRACE_BUFFERS,
270 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
273 dev->unmanagedTempDeallocations++;
279 * Determine if we have a managed buffer.
281 int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
284 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
285 if (dev->tempBuffer[i].buffer == buffer)
290 for (i = 0; i < dev->nShortOpCaches; i++) {
291 if( dev->srCache[i].data == buffer )
296 if (buffer == dev->checkpointBuffer)
299 T(YAFFS_TRACE_ALWAYS,
300 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
307 * Chunk bitmap manipulations
310 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
312 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
314 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
318 return dev->chunkBits +
319 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
322 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
324 if(blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
325 chunk < 0 || chunk >= dev->nChunksPerBlock) {
327 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),blk,chunk));
332 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
334 __u8 *blkBits = yaffs_BlockBits(dev, blk);
336 memset(blkBits, 0, dev->chunkBitmapStride);
339 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
341 __u8 *blkBits = yaffs_BlockBits(dev, blk);
343 yaffs_VerifyChunkBitId(dev,blk,chunk);
345 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
348 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
350 __u8 *blkBits = yaffs_BlockBits(dev, blk);
352 yaffs_VerifyChunkBitId(dev,blk,chunk);
354 blkBits[chunk / 8] |= (1 << (chunk & 7));
357 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
359 __u8 *blkBits = yaffs_BlockBits(dev, blk);
360 yaffs_VerifyChunkBitId(dev,blk,chunk);
362 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
365 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
367 __u8 *blkBits = yaffs_BlockBits(dev, blk);
369 for (i = 0; i < dev->chunkBitmapStride; i++) {
377 static int yaffs_CountChunkBits(yaffs_Device * dev, int blk)
379 __u8 *blkBits = yaffs_BlockBits(dev, blk);
382 for (i = 0; i < dev->chunkBitmapStride; i++) {
399 static int yaffs_SkipVerification(yaffs_Device *dev)
401 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
404 static int yaffs_SkipFullVerification(yaffs_Device *dev)
406 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
409 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
411 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
414 static const char * blockStateName[] = {
427 static void yaffs_VerifyBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
432 if(yaffs_SkipVerification(dev))
435 /* Report illegal runtime states */
436 if(bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
437 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has undefined state %d"TENDSTR),n,bi->blockState));
439 switch(bi->blockState){
440 case YAFFS_BLOCK_STATE_UNKNOWN:
441 case YAFFS_BLOCK_STATE_SCANNING:
442 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
443 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has bad run-state %s"TENDSTR),
444 n,blockStateName[bi->blockState]));
447 /* Check pages in use and soft deletions are legal */
449 actuallyUsed = bi->pagesInUse - bi->softDeletions;
451 if(bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
452 bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
453 actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock)
454 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
455 n,bi->pagesInUse,bi->softDeletions));
458 /* Check chunk bitmap legal */
459 inUse = yaffs_CountChunkBits(dev,n);
460 if(inUse != bi->pagesInUse)
461 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
462 n,bi->pagesInUse,inUse));
464 /* Check that the sequence number is valid.
465 * Ten million is legal, but is very unlikely
468 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
469 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000 ))
470 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has suspect sequence number of %d"TENDSTR),
471 n,bi->sequenceNumber));
475 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
477 yaffs_VerifyBlock(dev,bi,n);
479 /* After collection the block should be in the erased state */
480 /* This will need to change if we do partial gc */
482 if(bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
483 bi->blockState != YAFFS_BLOCK_STATE_EMPTY){
484 T(YAFFS_TRACE_ERROR,(TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
489 static void yaffs_VerifyBlocks(yaffs_Device *dev)
492 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
493 int nIllegalBlockStates = 0;
496 if(yaffs_SkipVerification(dev))
499 memset(nBlocksPerState,0,sizeof(nBlocksPerState));
502 for(i = dev->internalStartBlock; i <= dev->internalEndBlock; i++){
503 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
504 yaffs_VerifyBlock(dev,bi,i);
506 if(bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
507 nBlocksPerState[bi->blockState]++;
509 nIllegalBlockStates++;
513 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
514 T(YAFFS_TRACE_VERIFY,(TSTR("Block summary"TENDSTR)));
516 T(YAFFS_TRACE_VERIFY,(TSTR("%d blocks have illegal states"TENDSTR),nIllegalBlockStates));
517 if(nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
518 T(YAFFS_TRACE_VERIFY,(TSTR("Too many allocating blocks"TENDSTR)));
520 for(i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
521 T(YAFFS_TRACE_VERIFY,
522 (TSTR("%s %d blocks"TENDSTR),
523 blockStateName[i],nBlocksPerState[i]));
525 if(dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
526 T(YAFFS_TRACE_VERIFY,
527 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
528 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
530 if(dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
531 T(YAFFS_TRACE_VERIFY,
532 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
533 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
535 if(nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
536 T(YAFFS_TRACE_VERIFY,
537 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
538 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
540 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
545 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
546 * case those tests will not be performed.
548 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
550 if(obj && yaffs_SkipVerification(obj->myDev))
553 if(!(tags && obj && oh)){
554 T(YAFFS_TRACE_VERIFY,
555 (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR),
556 (__u32)tags,(__u32)obj,(__u32)oh));
560 if(oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
561 oh->type > YAFFS_OBJECT_TYPE_MAX)
562 T(YAFFS_TRACE_VERIFY,
563 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
564 tags->objectId, oh->type));
566 if(tags->objectId != obj->objectId)
567 T(YAFFS_TRACE_VERIFY,
568 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
569 tags->objectId, obj->objectId));
573 * Check that the object's parent ids match if parentCheck requested.
575 * Tests do not apply to the root object.
578 if(parentCheck && tags->objectId > 1 && !obj->parent)
579 T(YAFFS_TRACE_VERIFY,
580 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
581 tags->objectId, oh->parentObjectId));
584 if(parentCheck && obj->parent &&
585 oh->parentObjectId != obj->parent->objectId &&
586 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
587 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
588 T(YAFFS_TRACE_VERIFY,
589 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
590 tags->objectId, oh->parentObjectId, obj->parent->objectId));
593 if(tags->objectId > 1 && oh->name[0] == 0) /* Null name */
594 T(YAFFS_TRACE_VERIFY,
595 (TSTR("Obj %d header name is NULL"TENDSTR),
598 if(tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
599 T(YAFFS_TRACE_VERIFY,
600 (TSTR("Obj %d header name is 0xFF"TENDSTR),
606 static int yaffs_VerifyTnodeWorker(yaffs_Object * obj, yaffs_Tnode * tn,
607 __u32 level, int chunkOffset)
610 yaffs_Device *dev = obj->myDev;
616 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
617 if (tn->internal[i]) {
618 ok = yaffs_VerifyTnodeWorker(obj,
621 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
624 } else if (level == 0) {
625 yaffs_ExtendedTags tags;
626 __u32 objectId = obj->objectId;
628 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
630 for(i = 0; i < YAFFS_NTNODES_LEVEL0; i++){
631 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
634 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
635 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
636 if(tags.objectId != objectId || tags.chunkId != chunkOffset){
637 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
638 objectId, chunkOffset, theChunk,
639 tags.objectId, tags.chunkId));
652 static void yaffs_VerifyFile(yaffs_Object *obj)
654 int requiredTallness;
660 yaffs_ExtendedTags tags;
667 if(yaffs_SkipVerification(obj->myDev))
671 objectId = obj->objectId;
673 /* Check file size is consistent with tnode depth */
674 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
675 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
676 requiredTallness = 0;
678 x >>= YAFFS_TNODES_INTERNAL_BITS;
682 actualTallness = obj->variant.fileVariant.topLevel;
684 if(requiredTallness > actualTallness )
685 T(YAFFS_TRACE_VERIFY,
686 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
687 obj->objectId,actualTallness, requiredTallness));
690 /* Check that the chunks in the tnode tree are all correct.
691 * We do this by scanning through the tnode tree and
692 * checking the tags for every chunk match.
695 if(yaffs_SkipNANDVerification(dev))
698 for(i = 1; i <= lastChunk; i++){
699 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant,i);
702 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
704 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
705 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
706 if(tags.objectId != objectId || tags.chunkId != i){
707 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
708 objectId, i, theChunk,
709 tags.objectId, tags.chunkId));
719 static void yaffs_VerifyHardLink(yaffs_Object *obj)
721 if(obj && yaffs_SkipVerification(obj->myDev))
724 /* Verify sane equivalent object */
727 static void yaffs_VerifySymlink(yaffs_Object *obj)
729 if(obj && yaffs_SkipVerification(obj->myDev))
732 /* Verify symlink string */
735 static void yaffs_VerifySpecial(yaffs_Object *obj)
737 if(obj && yaffs_SkipVerification(obj->myDev))
741 static void yaffs_VerifyObject(yaffs_Object *obj)
750 __u32 chunkShouldNotBeDeleted;
756 if(obj->beingCreated)
761 if(yaffs_SkipVerification(dev))
764 /* Check sane object header chunk */
766 chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
767 chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
769 chunkInRange = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
770 chunkIdOk = chunkInRange || obj->hdrChunk == 0;
771 chunkValid = chunkInRange &&
772 yaffs_CheckChunkBit(dev,
773 obj->hdrChunk / dev->nChunksPerBlock,
774 obj->hdrChunk % dev->nChunksPerBlock);
775 chunkShouldNotBeDeleted = chunkInRange && !chunkValid;
778 (!chunkIdOk || chunkShouldNotBeDeleted)) {
779 T(YAFFS_TRACE_VERIFY,
780 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
781 obj->objectId,obj->hdrChunk,
782 chunkIdOk ? "" : ",out of range",
783 chunkShouldNotBeDeleted ? ",marked as deleted" : ""));
786 if(chunkValid &&!yaffs_SkipNANDVerification(dev)) {
787 yaffs_ExtendedTags tags;
788 yaffs_ObjectHeader *oh;
789 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
791 oh = (yaffs_ObjectHeader *)buffer;
793 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk,buffer, &tags);
795 yaffs_VerifyObjectHeader(obj,oh,&tags,1);
797 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
800 /* Verify it has a parent */
801 if(obj && !obj->fake &&
802 (!obj->parent || obj->parent->myDev != dev)){
803 T(YAFFS_TRACE_VERIFY,
804 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
805 obj->objectId,obj->parent));
808 /* Verify parent is a directory */
809 if(obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
810 T(YAFFS_TRACE_VERIFY,
811 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
812 obj->objectId,obj->parent->variantType));
815 switch(obj->variantType){
816 case YAFFS_OBJECT_TYPE_FILE:
817 yaffs_VerifyFile(obj);
819 case YAFFS_OBJECT_TYPE_SYMLINK:
820 yaffs_VerifySymlink(obj);
822 case YAFFS_OBJECT_TYPE_DIRECTORY:
823 yaffs_VerifyDirectory(obj);
825 case YAFFS_OBJECT_TYPE_HARDLINK:
826 yaffs_VerifyHardLink(obj);
828 case YAFFS_OBJECT_TYPE_SPECIAL:
829 yaffs_VerifySpecial(obj);
831 case YAFFS_OBJECT_TYPE_UNKNOWN:
833 T(YAFFS_TRACE_VERIFY,
834 (TSTR("Obj %d has illegaltype %d"TENDSTR),
835 obj->objectId,obj->variantType));
842 static void yaffs_VerifyObjects(yaffs_Device *dev)
846 struct ylist_head *lh;
848 if(yaffs_SkipVerification(dev))
851 /* Iterate through the objects in each hash entry */
853 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++){
854 ylist_for_each(lh, &dev->objectBucket[i].list) {
856 obj = ylist_entry(lh, yaffs_Object, hashLink);
857 yaffs_VerifyObject(obj);
866 * Simple hash function. Needs to have a reasonable spread
869 static Y_INLINE int yaffs_HashFunction(int n)
872 return (n % YAFFS_NOBJECT_BUCKETS);
876 * Access functions to useful fake objects.
877 * Note that root might have a presence in NAND if permissions are set.
880 yaffs_Object *yaffs_Root(yaffs_Device * dev)
885 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
887 return dev->lostNFoundDir;
892 * Erased NAND checking functions
895 int yaffs_CheckFF(__u8 * buffer, int nBytes)
897 /* Horrible, slow implementation */
906 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
910 int retval = YAFFS_OK;
911 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
912 yaffs_ExtendedTags tags;
915 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
917 if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
921 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
922 T(YAFFS_TRACE_NANDACCESS,
923 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
927 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
933 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
935 yaffs_ExtendedTags * tags,
942 yaffs_InvalidateCheckpoint(dev);
945 yaffs_BlockInfo *bi = 0;
948 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
954 /* First check this chunk is erased, if it needs
955 * checking. The checking policy (unless forced
956 * always on) is as follows:
958 * Check the first page we try to write in a block.
959 * If the check passes then we don't need to check any
960 * more. If the check fails, we check again...
961 * If the block has been erased, we don't need to check.
963 * However, if the block has been prioritised for gc,
964 * then we think there might be something odd about
965 * this block and stop using it.
967 * Rationale: We should only ever see chunks that have
968 * not been erased if there was a partially written
969 * chunk due to power loss. This checking policy should
970 * catch that case with very few checks and thus save a
971 * lot of checks that are most likely not needed.
973 if (bi->gcPrioritise) {
974 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
975 /* try another chunk */
979 /* let's give it a try */
982 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
983 bi->skipErasedCheck = 0;
985 if (!bi->skipErasedCheck) {
986 erasedOk = yaffs_CheckChunkErased(dev, chunk);
987 if (erasedOk != YAFFS_OK) {
989 (TSTR ("**>> yaffs chunk %d was not erased"
992 /* try another chunk */
995 bi->skipErasedCheck = 1;
998 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
1000 if (writeOk != YAFFS_OK) {
1001 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
1002 /* try another chunk */
1006 /* Copy the data into the robustification buffer */
1007 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1009 } while (writeOk != YAFFS_OK &&
1010 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1016 T(YAFFS_TRACE_ERROR,
1017 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1020 dev->nRetriedWrites += (attempts - 1);
1027 * Block retiring for handling a broken block.
1030 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
1032 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1034 yaffs_InvalidateCheckpoint(dev);
1036 if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
1037 if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
1038 T(YAFFS_TRACE_ALWAYS, (TSTR(
1039 "yaffs: Failed to mark bad and erase block %d"
1040 TENDSTR), blockInNAND));
1043 yaffs_ExtendedTags tags;
1044 int chunkId = blockInNAND * dev->nChunksPerBlock;
1046 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
1048 memset(buffer, 0xff, dev->nDataBytesPerChunk);
1049 yaffs_InitialiseTags(&tags);
1050 tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
1051 if (dev->writeChunkWithTagsToNAND(dev, chunkId -
1052 dev->chunkOffset, buffer, &tags) != YAFFS_OK)
1053 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
1054 TCONT("write bad block marker to block %d")
1055 TENDSTR), blockInNAND));
1057 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
1061 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1062 bi->gcPrioritise = 0;
1063 bi->needsRetiring = 0;
1065 dev->nRetiredBlocks++;
1069 * Functions for robustisizing TODO
1073 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
1075 const yaffs_ExtendedTags * tags)
1079 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
1080 const yaffs_ExtendedTags * tags)
1084 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1086 if(!bi->gcPrioritise){
1087 bi->gcPrioritise = 1;
1088 dev->hasPendingPrioritisedGCs = 1;
1089 bi->chunkErrorStrikes ++;
1091 if(bi->chunkErrorStrikes > 3){
1092 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1093 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1100 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
1103 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1104 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1106 yaffs_HandleChunkError(dev,bi);
1110 /* Was an actual write failure, so mark the block for retirement */
1111 bi->needsRetiring = 1;
1112 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1113 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1118 /* Delete the chunk */
1119 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1123 /*---------------- Name handling functions ------------*/
1125 static __u16 yaffs_CalcNameSum(const YCHAR * name)
1130 const YUCHAR *bname = (const YUCHAR *) name;
1132 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1134 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1135 sum += yaffs_toupper(*bname) * i;
1137 sum += (*bname) * i;
1146 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
1148 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1149 memset(obj->shortName,0,sizeof (YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1150 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
1151 yaffs_strcpy(obj->shortName, name);
1153 obj->shortName[0] = _Y('\0');
1156 obj->sum = yaffs_CalcNameSum(name);
1159 /*-------------------- TNODES -------------------
1161 * List of spare tnodes
1162 * The list is hooked together using the first pointer
1166 /* yaffs_CreateTnodes creates a bunch more tnodes and
1167 * adds them to the tnode free list.
1168 * Don't use this function directly
1171 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
1175 yaffs_Tnode *newTnodes;
1179 yaffs_TnodeList *tnl;
1184 /* Calculate the tnode size in bytes for variable width tnode support.
1185 * Must be a multiple of 32-bits */
1186 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1188 if(tnodeSize < sizeof(yaffs_Tnode))
1189 tnodeSize = sizeof(yaffs_Tnode);
1192 /* make these things */
1194 newTnodes = YMALLOC(nTnodes * tnodeSize);
1195 mem = (__u8 *)newTnodes;
1198 T(YAFFS_TRACE_ERROR,
1199 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1203 /* Hook them into the free list */
1205 for (i = 0; i < nTnodes - 1; i++) {
1206 newTnodes[i].internal[0] = &newTnodes[i + 1];
1207 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1208 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1212 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1213 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1214 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1216 dev->freeTnodes = newTnodes;
1218 /* New hookup for wide tnodes */
1219 for(i = 0; i < nTnodes -1; i++) {
1220 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1221 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1222 curr->internal[0] = next;
1225 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1226 curr->internal[0] = dev->freeTnodes;
1227 dev->freeTnodes = (yaffs_Tnode *)mem;
1232 dev->nFreeTnodes += nTnodes;
1233 dev->nTnodesCreated += nTnodes;
1235 /* Now add this bunch of tnodes to a list for freeing up.
1236 * NB If we can't add this to the management list it isn't fatal
1237 * but it just means we can't free this bunch of tnodes later.
1240 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1242 T(YAFFS_TRACE_ERROR,
1244 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1248 tnl->tnodes = newTnodes;
1249 tnl->next = dev->allocatedTnodeList;
1250 dev->allocatedTnodeList = tnl;
1253 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1258 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1260 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
1262 yaffs_Tnode *tn = NULL;
1264 /* If there are none left make more */
1265 if (!dev->freeTnodes) {
1266 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1269 if (dev->freeTnodes) {
1270 tn = dev->freeTnodes;
1271 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1272 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1273 /* Hoosterman, this thing looks like it isn't in the list */
1274 T(YAFFS_TRACE_ALWAYS,
1275 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1278 dev->freeTnodes = dev->freeTnodes->internal[0];
1282 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1287 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
1289 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1290 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1292 if(tnodeSize < sizeof(yaffs_Tnode))
1293 tnodeSize = sizeof(yaffs_Tnode);
1296 memset(tn, 0, tnodeSize);
1301 /* FreeTnode frees up a tnode and puts it back on the free list */
1302 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
1305 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1306 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1307 /* Hoosterman, this thing looks like it is already in the list */
1308 T(YAFFS_TRACE_ALWAYS,
1309 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1311 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1313 tn->internal[0] = dev->freeTnodes;
1314 dev->freeTnodes = tn;
1317 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1321 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
1323 /* Free the list of allocated tnodes */
1324 yaffs_TnodeList *tmp;
1326 while (dev->allocatedTnodeList) {
1327 tmp = dev->allocatedTnodeList->next;
1329 YFREE(dev->allocatedTnodeList->tnodes);
1330 YFREE(dev->allocatedTnodeList);
1331 dev->allocatedTnodeList = tmp;
1335 dev->freeTnodes = NULL;
1336 dev->nFreeTnodes = 0;
1339 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
1341 dev->allocatedTnodeList = NULL;
1342 dev->freeTnodes = NULL;
1343 dev->nFreeTnodes = 0;
1344 dev->nTnodesCreated = 0;
1349 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
1351 __u32 *map = (__u32 *)tn;
1357 pos &= YAFFS_TNODES_LEVEL0_MASK;
1358 val >>= dev->chunkGroupBits;
1360 bitInMap = pos * dev->tnodeWidth;
1361 wordInMap = bitInMap /32;
1362 bitInWord = bitInMap & (32 -1);
1364 mask = dev->tnodeMask << bitInWord;
1366 map[wordInMap] &= ~mask;
1367 map[wordInMap] |= (mask & (val << bitInWord));
1369 if(dev->tnodeWidth > (32-bitInWord)) {
1370 bitInWord = (32 - bitInWord);
1372 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1373 map[wordInMap] &= ~mask;
1374 map[wordInMap] |= (mask & (val >> bitInWord));
1378 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
1380 __u32 *map = (__u32 *)tn;
1386 pos &= YAFFS_TNODES_LEVEL0_MASK;
1388 bitInMap = pos * dev->tnodeWidth;
1389 wordInMap = bitInMap /32;
1390 bitInWord = bitInMap & (32 -1);
1392 val = map[wordInMap] >> bitInWord;
1394 if(dev->tnodeWidth > (32-bitInWord)) {
1395 bitInWord = (32 - bitInWord);
1397 val |= (map[wordInMap] << bitInWord);
1400 val &= dev->tnodeMask;
1401 val <<= dev->chunkGroupBits;
1406 /* ------------------- End of individual tnode manipulation -----------------*/
1408 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1409 * The look up tree is represented by the top tnode and the number of topLevel
1410 * in the tree. 0 means only the level 0 tnode is in the tree.
1413 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1414 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
1415 yaffs_FileStructure * fStruct,
1419 yaffs_Tnode *tn = fStruct->top;
1421 int requiredTallness;
1422 int level = fStruct->topLevel;
1424 /* Check sane level and chunk Id */
1425 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
1429 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1433 /* First check we're tall enough (ie enough topLevel) */
1435 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1436 requiredTallness = 0;
1438 i >>= YAFFS_TNODES_INTERNAL_BITS;
1442 if (requiredTallness > fStruct->topLevel) {
1443 /* Not tall enough, so we can't find it, return NULL. */
1447 /* Traverse down to level 0 */
1448 while (level > 0 && tn) {
1450 internal[(chunkId >>
1451 ( YAFFS_TNODES_LEVEL0_BITS +
1453 YAFFS_TNODES_INTERNAL_BITS)
1455 YAFFS_TNODES_INTERNAL_MASK];
1463 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1464 * This happens in two steps:
1465 * 1. If the tree isn't tall enough, then make it taller.
1466 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1468 * Used when modifying the tree.
1470 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1471 * be plugged into the ttree.
1474 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
1475 yaffs_FileStructure * fStruct,
1477 yaffs_Tnode *passedTn)
1480 int requiredTallness;
1488 /* Check sane level and page Id */
1489 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
1493 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1497 /* First check we're tall enough (ie enough topLevel) */
1499 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1500 requiredTallness = 0;
1502 x >>= YAFFS_TNODES_INTERNAL_BITS;
1507 if (requiredTallness > fStruct->topLevel) {
1508 /* Not tall enough,gotta make the tree taller */
1509 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1511 tn = yaffs_GetTnode(dev);
1514 tn->internal[0] = fStruct->top;
1517 T(YAFFS_TRACE_ERROR,
1518 (TSTR("yaffs: no more tnodes" TENDSTR)));
1522 fStruct->topLevel = requiredTallness;
1525 /* Traverse down to level 0, adding anything we need */
1527 l = fStruct->topLevel;
1531 while (l > 0 && tn) {
1533 ( YAFFS_TNODES_LEVEL0_BITS +
1534 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1535 YAFFS_TNODES_INTERNAL_MASK;
1538 if((l>1) && !tn->internal[x]){
1539 /* Add missing non-level-zero tnode */
1540 tn->internal[x] = yaffs_GetTnode(dev);
1543 /* Looking from level 1 at level 0 */
1545 /* If we already have one, then release it.*/
1547 yaffs_FreeTnode(dev,tn->internal[x]);
1548 tn->internal[x] = passedTn;
1550 } else if(!tn->internal[x]) {
1551 /* Don't have one, none passed in */
1552 tn->internal[x] = yaffs_GetTnode(dev);
1556 tn = tn->internal[x];
1560 /* top is level 0 */
1562 memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1563 yaffs_FreeTnode(dev,passedTn);
1570 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1571 yaffs_ExtendedTags * tags, int objectId,
1576 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1577 if (yaffs_CheckChunkBit
1578 (dev, theChunk / dev->nChunksPerBlock,
1579 theChunk % dev->nChunksPerBlock)) {
1580 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1582 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1594 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1595 * chunks and tnodes in the file
1596 * Returns 1 if the tree was deleted.
1597 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1600 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1601 int chunkOffset, int *limit)
1606 yaffs_ExtendedTags tags;
1608 yaffs_Device *dev = in->myDev;
1615 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1617 if (tn->internal[i]) {
1618 if (limit && (*limit) < 0) {
1622 yaffs_DeleteWorker(in,
1630 YAFFS_TNODES_INTERNAL_BITS)
1635 yaffs_FreeTnode(dev,
1638 tn->internal[i] = NULL;
1643 return (allDone) ? 1 : 0;
1644 } else if (level == 0) {
1647 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1649 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1654 YAFFS_TNODES_LEVEL0_BITS) + i;
1657 yaffs_FindChunkInGroup(dev,
1663 if (foundChunk > 0) {
1664 yaffs_DeleteChunk(dev,
1669 *limit = *limit - 1;
1677 yaffs_PutLevel0Tnode(dev,tn,i,0);
1681 return (i < 0) ? 1 : 0;
1691 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1694 yaffs_BlockInfo *theBlock;
1696 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1698 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1700 theBlock->softDeletions++;
1705 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1706 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1708 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1711 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1712 __u32 level, int chunkOffset)
1717 yaffs_Device *dev = in->myDev;
1722 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1724 if (tn->internal[i]) {
1726 yaffs_SoftDeleteWorker(in,
1732 YAFFS_TNODES_INTERNAL_BITS)
1735 yaffs_FreeTnode(dev,
1738 tn->internal[i] = NULL;
1740 /* Hoosterman... how could this happen? */
1744 return (allDone) ? 1 : 0;
1745 } else if (level == 0) {
1747 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1748 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1750 /* Note this does not find the real chunk, only the chunk group.
1751 * We make an assumption that a chunk group is not larger than
1754 yaffs_SoftDeleteChunk(dev, theChunk);
1755 yaffs_PutLevel0Tnode(dev,tn,i,0);
1769 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1772 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1773 if (obj->nDataChunks <= 0) {
1774 /* Empty file with no duplicate object headers, just delete it immediately */
1775 yaffs_FreeTnode(obj->myDev,
1776 obj->variant.fileVariant.top);
1777 obj->variant.fileVariant.top = NULL;
1778 T(YAFFS_TRACE_TRACING,
1779 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1781 yaffs_DoGenericObjectDeletion(obj);
1783 yaffs_SoftDeleteWorker(obj,
1784 obj->variant.fileVariant.top,
1785 obj->variant.fileVariant.
1787 obj->softDeleted = 1;
1792 /* Pruning removes any part of the file structure tree that is beyond the
1793 * bounds of the file (ie that does not point to chunks).
1795 * A file should only get pruned when its size is reduced.
1797 * Before pruning, the chunks must be pulled from the tree and the
1798 * level 0 tnode entries must be zeroed out.
1799 * Could also use this for file deletion, but that's probably better handled
1800 * by a special case.
1803 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1804 __u32 level, int del0)
1812 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1813 if (tn->internal[i] && level > 0) {
1815 yaffs_PruneWorker(dev, tn->internal[i],
1817 (i == 0) ? del0 : 1);
1820 if (tn->internal[i]) {
1825 if (hasData == 0 && del0) {
1826 /* Free and return NULL */
1828 yaffs_FreeTnode(dev, tn);
1838 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1839 yaffs_FileStructure * fStruct)
1846 if (fStruct->topLevel > 0) {
1848 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1850 /* Now we have a tree with all the non-zero branches NULL but the height
1851 * is the same as it was.
1852 * Let's see if we can trim internal tnodes to shorten the tree.
1853 * We can do this if only the 0th element in the tnode is in use
1854 * (ie all the non-zero are NULL)
1857 while (fStruct->topLevel && !done) {
1861 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1862 if (tn->internal[i]) {
1868 fStruct->top = tn->internal[0];
1869 fStruct->topLevel--;
1870 yaffs_FreeTnode(dev, tn);
1880 /*-------------------- End of File Structure functions.-------------------*/
1882 /* yaffs_CreateFreeObjects creates a bunch more objects and
1883 * adds them to the object free list.
1885 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1888 yaffs_Object *newObjects;
1889 yaffs_ObjectList *list;
1894 /* make these things */
1895 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1896 list = YMALLOC(sizeof(yaffs_ObjectList));
1898 if (!newObjects || !list) {
1903 T(YAFFS_TRACE_ALLOCATE,
1904 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1908 /* Hook them into the free list */
1909 for (i = 0; i < nObjects - 1; i++) {
1910 newObjects[i].siblings.next =
1911 (struct ylist_head *)(&newObjects[i + 1]);
1914 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1915 dev->freeObjects = newObjects;
1916 dev->nFreeObjects += nObjects;
1917 dev->nObjectsCreated += nObjects;
1919 /* Now add this bunch of Objects to a list for freeing up. */
1921 list->objects = newObjects;
1922 list->next = dev->allocatedObjectList;
1923 dev->allocatedObjectList = list;
1929 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1930 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1932 yaffs_Object *tn = NULL;
1934 #ifdef VALGRIND_TEST
1935 tn = YMALLOC(sizeof(yaffs_Object));
1937 /* If there are none left make more */
1938 if (!dev->freeObjects) {
1939 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1942 if (dev->freeObjects) {
1943 tn = dev->freeObjects;
1945 (yaffs_Object *) (dev->freeObjects->siblings.next);
1946 dev->nFreeObjects--;
1950 /* Now sweeten it up... */
1952 memset(tn, 0, sizeof(yaffs_Object));
1953 tn->beingCreated = 1;
1957 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1958 YINIT_LIST_HEAD(&(tn->hardLinks));
1959 YINIT_LIST_HEAD(&(tn->hashLink));
1960 YINIT_LIST_HEAD(&tn->siblings);
1963 /* Now make the directory sane */
1965 tn->parent = dev->rootDir;
1966 ylist_add(&(tn->siblings),&dev->rootDir->variant.directoryVariant.children);
1969 /* Add it to the lost and found directory.
1970 * NB Can't put root or lostNFound in lostNFound so
1971 * check if lostNFound exists first
1973 if (dev->lostNFoundDir) {
1974 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1977 tn->beingCreated = 0;
1980 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1985 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1990 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1992 obj->fake = 1; /* it is fake so it might have no NAND presence... */
1993 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1994 obj->unlinkAllowed = 0; /* ... or unlink it */
1997 obj->yst_mode = mode;
1999 obj->hdrChunk = 0; /* Not a valid chunk. */
2006 static void yaffs_UnhashObject(yaffs_Object * tn)
2009 yaffs_Device *dev = tn->myDev;
2011 /* If it is still linked into the bucket list, free from the list */
2012 if (!ylist_empty(&tn->hashLink)) {
2013 ylist_del_init(&tn->hashLink);
2014 bucket = yaffs_HashFunction(tn->objectId);
2015 dev->objectBucket[bucket].count--;
2020 /* FreeObject frees up a Object and puts it back on the free list */
2021 static void yaffs_FreeObject(yaffs_Object * tn)
2024 yaffs_Device *dev = tn->myDev;
2029 if(!ylist_empty(&tn->siblings))
2035 /* We're still hooked up to a cached inode.
2036 * Don't delete now, but mark for later deletion
2038 tn->deferedFree = 1;
2043 yaffs_UnhashObject(tn);
2045 #ifdef VALGRIND_TEST
2048 /* Link into the free list. */
2049 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2050 dev->freeObjects = tn;
2051 dev->nFreeObjects++;
2053 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2059 void yaffs_HandleDeferedFree(yaffs_Object * obj)
2061 if (obj->deferedFree) {
2062 yaffs_FreeObject(obj);
2068 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
2070 /* Free the list of allocated Objects */
2072 yaffs_ObjectList *tmp;
2074 while (dev->allocatedObjectList) {
2075 tmp = dev->allocatedObjectList->next;
2076 YFREE(dev->allocatedObjectList->objects);
2077 YFREE(dev->allocatedObjectList);
2079 dev->allocatedObjectList = tmp;
2082 dev->freeObjects = NULL;
2083 dev->nFreeObjects = 0;
2086 static void yaffs_InitialiseObjects(yaffs_Device * dev)
2090 dev->allocatedObjectList = NULL;
2091 dev->freeObjects = NULL;
2092 dev->nFreeObjects = 0;
2094 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2095 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2096 dev->objectBucket[i].count = 0;
2101 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
2106 int lowest = 999999;
2108 /* First let's see if we can find one that's empty. */
2110 for (i = 0; i < 10 && lowest > 0; i++) {
2112 x %= YAFFS_NOBJECT_BUCKETS;
2113 if (dev->objectBucket[x].count < lowest) {
2114 lowest = dev->objectBucket[x].count;
2120 /* If we didn't find an empty list, then try
2121 * looking a bit further for a short one
2124 for (i = 0; i < 10 && lowest > 3; i++) {
2126 x %= YAFFS_NOBJECT_BUCKETS;
2127 if (dev->objectBucket[x].count < lowest) {
2128 lowest = dev->objectBucket[x].count;
2137 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
2139 int bucket = yaffs_FindNiceObjectBucket(dev);
2141 /* Now find an object value that has not already been taken
2142 * by scanning the list.
2146 struct ylist_head *i;
2148 __u32 n = (__u32) bucket;
2150 /* yaffs_CheckObjectHashSanity(); */
2154 n += YAFFS_NOBJECT_BUCKETS;
2155 if (1 || dev->objectBucket[bucket].count > 0) {
2156 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2157 /* If there is already one in the list */
2159 && ylist_entry(i, yaffs_Object,
2160 hashLink)->objectId == n) {
2171 static void yaffs_HashObject(yaffs_Object * in)
2173 int bucket = yaffs_HashFunction(in->objectId);
2174 yaffs_Device *dev = in->myDev;
2176 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2177 dev->objectBucket[bucket].count++;
2181 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
2183 int bucket = yaffs_HashFunction(number);
2184 struct ylist_head *i;
2187 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2188 /* Look if it is in the list */
2190 in = ylist_entry(i, yaffs_Object, hashLink);
2191 if (in->objectId == number) {
2193 /* Don't tell the VFS about this one if it is defered free */
2194 if (in->deferedFree)
2206 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
2207 yaffs_ObjectType type)
2210 yaffs_Object *theObject;
2211 yaffs_Tnode *tn = NULL;
2214 number = yaffs_CreateNewObjectNumber(dev);
2217 theObject = yaffs_AllocateEmptyObject(dev);
2221 if(type == YAFFS_OBJECT_TYPE_FILE){
2222 tn = yaffs_GetTnode(dev);
2224 yaffs_FreeObject(theObject);
2232 theObject->fake = 0;
2233 theObject->renameAllowed = 1;
2234 theObject->unlinkAllowed = 1;
2235 theObject->objectId = number;
2236 yaffs_HashObject(theObject);
2237 theObject->variantType = type;
2238 #ifdef CONFIG_YAFFS_WINCE
2239 yfsd_WinFileTimeNow(theObject->win_atime);
2240 theObject->win_ctime[0] = theObject->win_mtime[0] =
2241 theObject->win_atime[0];
2242 theObject->win_ctime[1] = theObject->win_mtime[1] =
2243 theObject->win_atime[1];
2247 theObject->yst_atime = theObject->yst_mtime =
2248 theObject->yst_ctime = Y_CURRENT_TIME;
2251 case YAFFS_OBJECT_TYPE_FILE:
2252 theObject->variant.fileVariant.fileSize = 0;
2253 theObject->variant.fileVariant.scannedFileSize = 0;
2254 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2255 theObject->variant.fileVariant.topLevel = 0;
2256 theObject->variant.fileVariant.top = tn;
2258 case YAFFS_OBJECT_TYPE_DIRECTORY:
2259 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2262 case YAFFS_OBJECT_TYPE_SYMLINK:
2263 case YAFFS_OBJECT_TYPE_HARDLINK:
2264 case YAFFS_OBJECT_TYPE_SPECIAL:
2265 /* No action required */
2267 case YAFFS_OBJECT_TYPE_UNKNOWN:
2268 /* todo this should not happen */
2276 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
2278 yaffs_ObjectType type)
2280 yaffs_Object *theObject = NULL;
2283 theObject = yaffs_FindObjectByNumber(dev, number);
2287 theObject = yaffs_CreateNewObject(dev, number, type);
2295 static YCHAR *yaffs_CloneString(const YCHAR * str)
2297 YCHAR *newStr = NULL;
2300 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2302 yaffs_strcpy(newStr, str);
2310 * Mknod (create) a new object.
2311 * equivalentObject only has meaning for a hard link;
2312 * aliasString only has meaning for a sumlink.
2313 * rdev only has meaning for devices (a subset of special objects)
2316 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2317 yaffs_Object * parent,
2322 yaffs_Object * equivalentObject,
2323 const YCHAR * aliasString, __u32 rdev)
2328 yaffs_Device *dev = parent->myDev;
2330 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2331 if (yaffs_FindObjectByName(parent, name)) {
2335 in = yaffs_CreateNewObject(dev, -1, type);
2340 if(type == YAFFS_OBJECT_TYPE_SYMLINK){
2341 str = yaffs_CloneString(aliasString);
2343 yaffs_FreeObject(in);
2353 in->variantType = type;
2355 in->yst_mode = mode;
2357 #ifdef CONFIG_YAFFS_WINCE
2358 yfsd_WinFileTimeNow(in->win_atime);
2359 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2360 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2363 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2365 in->yst_rdev = rdev;
2369 in->nDataChunks = 0;
2371 yaffs_SetObjectName(in, name);
2374 yaffs_AddObjectToDirectory(parent, in);
2376 in->myDev = parent->myDev;
2379 case YAFFS_OBJECT_TYPE_SYMLINK:
2380 in->variant.symLinkVariant.alias = str;
2382 case YAFFS_OBJECT_TYPE_HARDLINK:
2383 in->variant.hardLinkVariant.equivalentObject =
2385 in->variant.hardLinkVariant.equivalentObjectId =
2386 equivalentObject->objectId;
2387 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2389 case YAFFS_OBJECT_TYPE_FILE:
2390 case YAFFS_OBJECT_TYPE_DIRECTORY:
2391 case YAFFS_OBJECT_TYPE_SPECIAL:
2392 case YAFFS_OBJECT_TYPE_UNKNOWN:
2397 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2398 /* Could not create the object header, fail the creation */
2399 yaffs_DestroyObject(in);
2408 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
2409 __u32 mode, __u32 uid, __u32 gid)
2411 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2412 uid, gid, NULL, NULL, 0);
2415 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
2416 __u32 mode, __u32 uid, __u32 gid)
2418 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2419 mode, uid, gid, NULL, NULL, 0);
2422 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
2423 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2425 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2426 uid, gid, NULL, NULL, rdev);
2429 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
2430 __u32 mode, __u32 uid, __u32 gid,
2431 const YCHAR * alias)
2433 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2434 uid, gid, NULL, alias, 0);
2437 /* yaffs_Link returns the object id of the equivalent object.*/
2438 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
2439 yaffs_Object * equivalentObject)
2441 /* Get the real object in case we were fed a hard link as an equivalent object */
2442 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2444 if (yaffs_MknodObject
2445 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2446 equivalentObject, NULL, 0)) {
2447 return equivalentObject;
2454 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
2455 const YCHAR * newName, int force, int shadows)
2460 yaffs_Object *existingTarget;
2462 if (newDir == NULL) {
2463 newDir = obj->parent; /* use the old directory */
2466 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2467 T(YAFFS_TRACE_ALWAYS,
2469 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2474 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2475 if (obj->myDev->isYaffs2) {
2476 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2478 unlinkOp = (newDir == obj->myDev->unlinkedDir
2479 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2482 deleteOp = (newDir == obj->myDev->deletedDir);
2484 existingTarget = yaffs_FindObjectByName(newDir, newName);
2486 /* If the object is a file going into the unlinked directory,
2487 * then it is OK to just stuff it in since duplicate names are allowed.
2488 * else only proceed if the new name does not exist and if we're putting
2489 * it into a directory.
2496 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2497 yaffs_SetObjectName(obj, newName);
2500 yaffs_AddObjectToDirectory(newDir, obj);
2505 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2506 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
2513 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
2514 yaffs_Object * newDir, const YCHAR * newName)
2516 yaffs_Object *obj=NULL;
2517 yaffs_Object *existingTarget=NULL;
2521 if(!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2523 if(!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2526 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2527 /* Special case for case insemsitive systems (eg. WinCE).
2528 * While look-up is case insensitive, the name isn't.
2529 * Therefore we might want to change x.txt to X.txt
2531 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
2536 else if (yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2540 obj = yaffs_FindObjectByName(oldDir, oldName);
2542 if (obj && obj->renameAllowed) {
2544 /* Now do the handling for an existing target, if there is one */
2546 existingTarget = yaffs_FindObjectByName(newDir, newName);
2547 if (existingTarget &&
2548 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2549 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2550 /* There is a target that is a non-empty directory, so we fail */
2551 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2552 } else if (existingTarget && existingTarget != obj) {
2553 /* Nuke the target first, using shadowing,
2554 * but only if it isn't the same object
2556 yaffs_ChangeObjectName(obj, newDir, newName, force,
2557 existingTarget->objectId);
2558 yaffs_UnlinkObject(existingTarget);
2561 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2566 /*------------------------- Block Management and Page Allocation ----------------*/
2568 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
2570 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2572 dev->blockInfo = NULL;
2573 dev->chunkBits = NULL;
2575 dev->allocationBlock = -1; /* force it to get a new one */
2577 /* If the first allocation strategy fails, thry the alternate one */
2578 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2579 if(!dev->blockInfo){
2580 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2581 dev->blockInfoAlt = 1;
2584 dev->blockInfoAlt = 0;
2588 /* Set up dynamic blockinfo stuff. */
2589 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2590 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2591 if(!dev->chunkBits){
2592 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2593 dev->chunkBitsAlt = 1;
2596 dev->chunkBitsAlt = 0;
2599 if (dev->blockInfo && dev->chunkBits) {
2600 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2601 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2609 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
2611 if(dev->blockInfoAlt && dev->blockInfo)
2612 YFREE_ALT(dev->blockInfo);
2613 else if(dev->blockInfo)
2614 YFREE(dev->blockInfo);
2616 dev->blockInfoAlt = 0;
2618 dev->blockInfo = NULL;
2620 if(dev->chunkBitsAlt && dev->chunkBits)
2621 YFREE_ALT(dev->chunkBits);
2622 else if(dev->chunkBits)
2623 YFREE(dev->chunkBits);
2624 dev->chunkBitsAlt = 0;
2625 dev->chunkBits = NULL;
2628 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
2629 yaffs_BlockInfo * bi)
2636 return 1; /* disqualification only applies to yaffs2. */
2638 if (!bi->hasShrinkHeader)
2639 return 1; /* can gc */
2641 /* Find the oldest dirty sequence number if we don't know it and save it
2642 * so we don't have to keep recomputing it.
2644 if (!dev->oldestDirtySequence) {
2645 seq = dev->sequenceNumber;
2647 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2649 b = yaffs_GetBlockInfo(dev, i);
2650 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2651 (b->pagesInUse - b->softDeletions) <
2652 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2653 seq = b->sequenceNumber;
2656 dev->oldestDirtySequence = seq;
2659 /* Can't do gc of this block if there are any blocks older than this one that have
2662 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2666 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2667 * for garbage collection.
2670 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2674 int b = dev->currentDirtyChecker;
2681 yaffs_BlockInfo *bi;
2682 int pendingPrioritisedExist = 0;
2684 /* First let's see if we need to grab a prioritised block */
2685 if(dev->hasPendingPrioritisedGCs){
2686 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2688 bi = yaffs_GetBlockInfo(dev, i);
2689 //yaffs_VerifyBlock(dev,bi,i);
2691 if(bi->gcPrioritise) {
2692 pendingPrioritisedExist = 1;
2693 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2694 yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2695 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2698 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2703 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2704 dev->hasPendingPrioritisedGCs = 0;
2707 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2709 * else (we're doing a leasurely gc), then we only bother to do this if the
2710 * block has only a few pages in use.
2713 dev->nonAggressiveSkip--;
2715 if (!aggressive && (dev->nonAggressiveSkip > 0)) {
2721 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2725 dev->internalEndBlock - dev->internalStartBlock + 1;
2728 dev->internalEndBlock - dev->internalStartBlock + 1;
2729 iterations = iterations / 16;
2730 if (iterations > 200) {
2735 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2737 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2738 b = dev->internalStartBlock;
2741 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2742 T(YAFFS_TRACE_ERROR,
2743 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2747 bi = yaffs_GetBlockInfo(dev, b);
2750 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2757 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2758 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2759 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2761 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2765 dev->currentDirtyChecker = b;
2769 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2770 dev->nChunksPerBlock - pagesInUse,prioritised));
2773 dev->oldestDirtySequence = 0;
2776 dev->nonAggressiveSkip = 4;
2782 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2784 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2788 /* If the block is still healthy erase it and mark as clean.
2789 * If the block has had a data failure, then retire it.
2792 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2793 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2794 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2796 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2798 if (!bi->needsRetiring) {
2799 yaffs_InvalidateCheckpoint(dev);
2800 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2802 dev->nErasureFailures++;
2803 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2804 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2809 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2811 for (i = 0; i < dev->nChunksPerBlock; i++) {
2812 if (!yaffs_CheckChunkErased
2813 (dev, blockNo * dev->nChunksPerBlock + i)) {
2814 T(YAFFS_TRACE_ERROR,
2816 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2817 TENDSTR), blockNo, i));
2823 /* Clean it up... */
2824 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2825 dev->nErasedBlocks++;
2827 bi->softDeletions = 0;
2828 bi->hasShrinkHeader = 0;
2829 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2830 bi->gcPrioritise = 0;
2831 yaffs_ClearChunkBits(dev, blockNo);
2833 T(YAFFS_TRACE_ERASE,
2834 (TSTR("Erased block %d" TENDSTR), blockNo));
2836 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2838 yaffs_RetireBlock(dev, blockNo);
2839 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2840 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2844 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2848 yaffs_BlockInfo *bi;
2850 if (dev->nErasedBlocks < 1) {
2851 /* Hoosterman we've got a problem.
2852 * Can't get space to gc
2854 T(YAFFS_TRACE_ERROR,
2855 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2860 /* Find an empty block. */
2862 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2863 dev->allocationBlockFinder++;
2864 if (dev->allocationBlockFinder < dev->internalStartBlock
2865 || dev->allocationBlockFinder > dev->internalEndBlock) {
2866 dev->allocationBlockFinder = dev->internalStartBlock;
2869 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2871 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2872 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2873 dev->sequenceNumber++;
2874 bi->sequenceNumber = dev->sequenceNumber;
2875 dev->nErasedBlocks--;
2876 T(YAFFS_TRACE_ALLOCATE,
2877 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2878 dev->allocationBlockFinder, dev->sequenceNumber,
2879 dev->nErasedBlocks));
2880 return dev->allocationBlockFinder;
2884 T(YAFFS_TRACE_ALWAYS,
2886 ("yaffs tragedy: no more erased blocks, but there should have been %d"
2887 TENDSTR), dev->nErasedBlocks));
2894 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2896 if(!dev->nCheckpointBlocksRequired &&
2898 /* Not a valid value so recalculate */
2901 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2904 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2906 if(tnodeSize < sizeof(yaffs_Tnode))
2907 tnodeSize = sizeof(yaffs_Tnode);
2909 nBytes += sizeof(yaffs_CheckpointValidity);
2910 nBytes += sizeof(yaffs_CheckpointDevice);
2911 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2912 nBytes += devBlocks * dev->chunkBitmapStride;
2913 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2914 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2915 nBytes += sizeof(yaffs_CheckpointValidity);
2916 nBytes += sizeof(__u32); /* checksum*/
2918 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2920 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2922 dev->nCheckpointBlocksRequired = nBlocks;
2925 return dev->nCheckpointBlocksRequired;
2928 // Check if there's space to allocate...
2929 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2930 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2933 int reservedBlocks = dev->nReservedBlocks;
2934 int checkpointBlocks;
2937 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
2938 dev->blocksInCheckpoint;
2939 if(checkpointBlocks < 0)
2940 checkpointBlocks = 0;
2942 checkpointBlocks =0;
2945 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2947 return (dev->nFreeChunks > reservedChunks);
2950 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2953 yaffs_BlockInfo *bi;
2955 if (dev->allocationBlock < 0) {
2956 /* Get next block to allocate off */
2957 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2958 dev->allocationPage = 0;
2961 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2962 /* Not enough space to allocate unless we're allowed to use the reserve. */
2966 if (dev->nErasedBlocks < dev->nReservedBlocks
2967 && dev->allocationPage == 0) {
2968 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2971 /* Next page please.... */
2972 if (dev->allocationBlock >= 0) {
2973 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2975 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2976 dev->allocationPage;
2978 yaffs_SetChunkBit(dev, dev->allocationBlock,
2979 dev->allocationPage);
2981 dev->allocationPage++;
2985 /* If the block is full set the state to full */
2986 if (dev->allocationPage >= dev->nChunksPerBlock) {
2987 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2988 dev->allocationBlock = -1;
2997 T(YAFFS_TRACE_ERROR,
2998 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
3003 static int yaffs_GetErasedChunks(yaffs_Device * dev)
3007 n = dev->nErasedBlocks * dev->nChunksPerBlock;
3009 if (dev->allocationBlock > 0) {
3010 n += (dev->nChunksPerBlock - dev->allocationPage);
3017 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block, int wholeBlock)
3022 int retVal = YAFFS_OK;
3025 int isCheckpointBlock;
3029 int chunksBefore = yaffs_GetErasedChunks(dev);
3032 yaffs_ExtendedTags tags;
3034 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3036 yaffs_Object *object;
3038 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3040 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3042 T(YAFFS_TRACE_TRACING,
3043 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3046 bi->hasShrinkHeader,
3049 /*yaffs_VerifyFreeChunks(dev); */
3051 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
3053 /* Take off the number of soft deleted entries because
3054 * they're going to get really deleted during GC.
3056 dev->nFreeChunks -= bi->softDeletions;
3060 if (isCheckpointBlock ||
3061 !yaffs_StillSomeChunkBits(dev, block)) {
3062 T(YAFFS_TRACE_TRACING,
3064 ("Collecting block %d that has no chunks in use" TENDSTR),
3066 yaffs_BlockBecameDirty(dev, block);
3069 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3071 yaffs_VerifyBlock(dev,bi,block);
3073 maxCopies = (wholeBlock) ? dev->nChunksPerBlock : 10;
3074 oldChunk = block * dev->nChunksPerBlock + dev->gcChunk;
3076 for ( /* init already done */;
3077 retVal == YAFFS_OK &&
3078 dev->gcChunk < dev->nChunksPerBlock &&
3079 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING)&&
3081 dev->gcChunk++, oldChunk++) {
3082 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3084 /* This page is in use and might need to be copied off */
3090 yaffs_InitialiseTags(&tags);
3092 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3096 yaffs_FindObjectByNumber(dev,
3099 T(YAFFS_TRACE_GC_DETAIL,
3101 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3102 dev->gcChunk, tags.objectId, tags.chunkId,
3105 if(object && !yaffs_SkipVerification(dev)){
3106 if(tags.chunkId == 0)
3107 matchingChunk = object->hdrChunk;
3108 else if(object->softDeleted)
3109 matchingChunk = oldChunk; /* Defeat the test */
3111 matchingChunk = yaffs_FindChunkInFile(object,tags.chunkId,NULL);
3113 if(oldChunk != matchingChunk)
3114 T(YAFFS_TRACE_ERROR,
3115 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3116 oldChunk,matchingChunk,tags.objectId, tags.chunkId));
3121 T(YAFFS_TRACE_ERROR,
3123 ("page %d in gc has no object: %d %d %d "
3125 tags.objectId, tags.chunkId, tags.byteCount));
3130 object->softDeleted &&
3131 tags.chunkId != 0) {
3132 /* Data chunk in a soft deleted file, throw it away
3133 * It's a soft deleted data chunk,
3134 * No need to copy this, just forget about it and
3135 * fix up the object.
3138 object->nDataChunks--;
3140 if (object->nDataChunks <= 0) {
3141 /* remeber to clean up the object */
3142 dev->gcCleanupList[cleanups] =
3148 /* Todo object && object->deleted && object->nDataChunks == 0 */
3150 /* Deleted object header with no data chunks.
3151 * Can be discarded and the file deleted.
3153 object->hdrChunk = 0;
3154 yaffs_FreeTnode(object->myDev,
3157 object->variant.fileVariant.top = NULL;
3158 yaffs_DoGenericObjectDeletion(object);
3160 } else if (object) {
3161 /* It's either a data chunk in a live file or
3162 * an ObjectHeader, so we're interested in it.
3163 * NB Need to keep the ObjectHeaders of deleted files
3164 * until the whole file has been deleted off
3166 tags.serialNumber++;
3170 if (tags.chunkId == 0) {
3171 /* It is an object Id,
3172 * We need to nuke the shrinkheader flags first
3173 * We no longer want the shrinkHeader flag since its work is done
3174 * and if it is left in place it will mess up scanning.
3177 yaffs_ObjectHeader *oh;
3178 oh = (yaffs_ObjectHeader *)buffer;
3180 tags.extraIsShrinkHeader = 0;
3182 yaffs_VerifyObjectHeader(object,oh,&tags,1);
3186 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3189 retVal = YAFFS_FAIL;
3192 /* Ok, now fix up the Tnodes etc. */
3194 if (tags.chunkId == 0) {
3196 object->hdrChunk = newChunk;
3197 object->serial = tags.serialNumber;
3199 /* It's a data chunk */
3200 yaffs_PutChunkIntoFile
3208 if(retVal == YAFFS_OK)
3209 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3214 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3217 /* Do any required cleanups */
3218 for (i = 0; i < cleanups; i++) {
3219 /* Time to delete the file too */
3221 yaffs_FindObjectByNumber(dev,
3222 dev->gcCleanupList[i]);
3224 yaffs_FreeTnode(dev,
3225 object->variant.fileVariant.
3227 object->variant.fileVariant.top = NULL;
3230 ("yaffs: About to finally delete object %d"
3231 TENDSTR), object->objectId));
3232 yaffs_DoGenericObjectDeletion(object);
3233 object->myDev->nDeletedFiles--;
3240 yaffs_VerifyCollectedBlock(dev,bi,block);
3242 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
3245 ("gc did not increase free chunks before %d after %d"
3246 TENDSTR), chunksBefore, chunksAfter));
3249 /* If the gc completed then clear the current gcBlock so that we find another. */
3250 if(bi->blockState != YAFFS_BLOCK_STATE_COLLECTING){
3260 /* New garbage collector
3261 * If we're very low on erased blocks then we do aggressive garbage collection
3262 * otherwise we do "leasurely" garbage collection.
3263 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3264 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3266 * The idea is to help clear out space in a more spread-out manner.
3267 * Dunno if it really does anything useful.
3269 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
3273 int gcOk = YAFFS_OK;
3276 int checkpointBlockAdjust;
3278 if (dev->isDoingGC) {
3279 /* Bail out so we don't get recursive gc */
3283 /* This loop should pass the first time.
3284 * We'll only see looping here if the erase of the collected block fails.
3290 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3291 if(checkpointBlockAdjust < 0)
3292 checkpointBlockAdjust = 0;
3294 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3295 /* We need a block soon...*/
3298 /* We're in no hurry */
3302 if(dev->gcBlock <= 0){
3303 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3307 block = dev->gcBlock;
3310 dev->garbageCollections++;
3312 dev->passiveGarbageCollections++;
3317 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3318 dev->nErasedBlocks, aggressive));
3320 gcOk = yaffs_GarbageCollectBlock(dev,block,aggressive);
3323 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3326 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3327 TENDSTR), dev->nErasedBlocks, maxTries, block));
3329 } while ((dev->nErasedBlocks < dev->nReservedBlocks) &&
3333 return aggressive ? gcOk : YAFFS_OK;
3336 /*------------------------- TAGS --------------------------------*/
3338 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
3341 return (tags->chunkId == chunkInObject &&
3342 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3347 /*-------------------- Data file manipulation -----------------*/
3349 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
3350 yaffs_ExtendedTags * tags)
3352 /*Get the Tnode, then get the level 0 offset chunk offset */