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.60 2008-10-30 17:58:44 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 #ifdef YAFFS_PARANOID
101 static int yaffs_CheckFileSanity(yaffs_Object * in);
103 #define yaffs_CheckFileSanity(in)
106 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
107 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
109 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
111 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
112 yaffs_ExtendedTags * tags);
114 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos);
115 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
116 yaffs_FileStructure * fStruct,
120 /* Function to calculate chunk and offset */
122 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut, __u32 *offsetOut)
127 chunk = (__u32)(addr >> dev->chunkShift);
129 if(dev->chunkDiv == 1)
131 /* easy power of 2 case */
132 offset = (__u32)(addr & dev->chunkMask);
136 /* Non power-of-2 case */
140 chunk /= dev->chunkDiv;
142 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
143 offset = (__u32)(addr - chunkBase);
150 /* Function to return the number of shifts for a power of 2 greater than or equal
151 * to the given number
152 * Note we don't try to cater for all possible numbers and this does not have to
153 * be hellishly efficient.
156 static __u32 ShiftsGE(__u32 x)
161 nShifts = extraBits = 0;
164 if(x & 1) extraBits++;
175 /* Function to return the number of shifts to get a 1 in bit 0
178 static __u32 Shifts(__u32 x)
197 * Temporary buffer manipulations.
200 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
203 __u8 *buf = (__u8 *)1;
205 memset(dev->tempBuffer,0,sizeof(dev->tempBuffer));
207 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
208 dev->tempBuffer[i].line = 0; /* not in use */
209 dev->tempBuffer[i].buffer = buf =
210 YMALLOC_DMA(dev->totalBytesPerChunk);
213 return buf ? YAFFS_OK : YAFFS_FAIL;
217 __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
222 if(dev->tempInUse > dev->maxTemp)
223 dev->maxTemp = dev->tempInUse;
225 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
226 if (dev->tempBuffer[i].line == 0) {
227 dev->tempBuffer[i].line = lineNo;
228 if ((i + 1) > dev->maxTemp) {
229 dev->maxTemp = i + 1;
230 for (j = 0; j <= i; j++)
231 dev->tempBuffer[j].maxLine =
232 dev->tempBuffer[j].line;
235 return dev->tempBuffer[i].buffer;
239 T(YAFFS_TRACE_BUFFERS,
240 (TSTR("Out of temp buffers at line %d, other held by lines:"),
242 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
243 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
245 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
248 * If we got here then we have to allocate an unmanaged one
252 dev->unmanagedTempAllocations++;
253 return YMALLOC(dev->nDataBytesPerChunk);
257 void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
264 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
265 if (dev->tempBuffer[i].buffer == buffer) {
266 dev->tempBuffer[i].line = 0;
272 /* assume it is an unmanaged one. */
273 T(YAFFS_TRACE_BUFFERS,
274 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
277 dev->unmanagedTempDeallocations++;
283 * Determine if we have a managed buffer.
285 int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
288 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
289 if (dev->tempBuffer[i].buffer == buffer)
294 for (i = 0; i < dev->nShortOpCaches; i++) {
295 if( dev->srCache[i].data == buffer )
300 if (buffer == dev->checkpointBuffer)
303 T(YAFFS_TRACE_ALWAYS,
304 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
311 * Chunk bitmap manipulations
314 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
316 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
318 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
322 return dev->chunkBits +
323 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
326 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
328 if(blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
329 chunk < 0 || chunk >= dev->nChunksPerBlock) {
331 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),blk,chunk));
336 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
338 __u8 *blkBits = yaffs_BlockBits(dev, blk);
340 memset(blkBits, 0, dev->chunkBitmapStride);
343 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
345 __u8 *blkBits = yaffs_BlockBits(dev, blk);
347 yaffs_VerifyChunkBitId(dev,blk,chunk);
349 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
352 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
354 __u8 *blkBits = yaffs_BlockBits(dev, blk);
356 yaffs_VerifyChunkBitId(dev,blk,chunk);
358 blkBits[chunk / 8] |= (1 << (chunk & 7));
361 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
363 __u8 *blkBits = yaffs_BlockBits(dev, blk);
364 yaffs_VerifyChunkBitId(dev,blk,chunk);
366 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
369 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
371 __u8 *blkBits = yaffs_BlockBits(dev, blk);
373 for (i = 0; i < dev->chunkBitmapStride; i++) {
381 static int yaffs_CountChunkBits(yaffs_Device * dev, int blk)
383 __u8 *blkBits = yaffs_BlockBits(dev, blk);
386 for (i = 0; i < dev->chunkBitmapStride; i++) {
403 static int yaffs_SkipVerification(yaffs_Device *dev)
405 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));
416 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
418 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
421 static const char * blockStateName[] = {
434 static void yaffs_VerifyBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
439 if(yaffs_SkipVerification(dev))
442 /* Report illegal runtime states */
443 if(bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
444 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has undefined state %d"TENDSTR),n,bi->blockState));
446 switch(bi->blockState){
447 case YAFFS_BLOCK_STATE_UNKNOWN:
448 case YAFFS_BLOCK_STATE_SCANNING:
449 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
450 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has bad run-state %s"TENDSTR),
451 n,blockStateName[bi->blockState]));
454 /* Check pages in use and soft deletions are legal */
456 actuallyUsed = bi->pagesInUse - bi->softDeletions;
458 if(bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
459 bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
460 actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock)
461 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
462 n,bi->pagesInUse,bi->softDeletions));
465 /* Check chunk bitmap legal */
466 inUse = yaffs_CountChunkBits(dev,n);
467 if(inUse != bi->pagesInUse)
468 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
469 n,bi->pagesInUse,inUse));
471 /* Check that the sequence number is valid.
472 * Ten million is legal, but is very unlikely
475 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
476 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000 ))
477 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has suspect sequence number of %d"TENDSTR),
478 n,bi->sequenceNumber));
482 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
484 yaffs_VerifyBlock(dev,bi,n);
486 /* After collection the block should be in the erased state */
487 /* TODO: This will need to change if we do partial gc */
489 if(bi->blockState != YAFFS_BLOCK_STATE_EMPTY){
490 T(YAFFS_TRACE_ERROR,(TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
495 static void yaffs_VerifyBlocks(yaffs_Device *dev)
498 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
499 int nIllegalBlockStates = 0;
502 if(yaffs_SkipVerification(dev))
505 memset(nBlocksPerState,0,sizeof(nBlocksPerState));
508 for(i = dev->internalStartBlock; i <= dev->internalEndBlock; i++){
509 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
510 yaffs_VerifyBlock(dev,bi,i);
512 if(bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
513 nBlocksPerState[bi->blockState]++;
515 nIllegalBlockStates++;
519 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
520 T(YAFFS_TRACE_VERIFY,(TSTR("Block summary"TENDSTR)));
522 T(YAFFS_TRACE_VERIFY,(TSTR("%d blocks have illegal states"TENDSTR),nIllegalBlockStates));
523 if(nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
524 T(YAFFS_TRACE_VERIFY,(TSTR("Too many allocating blocks"TENDSTR)));
526 for(i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
527 T(YAFFS_TRACE_VERIFY,
528 (TSTR("%s %d blocks"TENDSTR),
529 blockStateName[i],nBlocksPerState[i]));
531 if(dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
532 T(YAFFS_TRACE_VERIFY,
533 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
534 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
536 if(dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
537 T(YAFFS_TRACE_VERIFY,
538 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
539 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
541 if(nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
542 T(YAFFS_TRACE_VERIFY,
543 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
544 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
546 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
551 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
552 * case those tests will not be performed.
554 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
556 if(obj && yaffs_SkipVerification(obj->myDev))
559 if(!(tags && obj && oh)){
560 T(YAFFS_TRACE_VERIFY,
561 (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR),
562 (__u32)tags,(__u32)obj,(__u32)oh));
566 if(oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
567 oh->type > YAFFS_OBJECT_TYPE_MAX)
568 T(YAFFS_TRACE_VERIFY,
569 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
570 tags->objectId, oh->type));
572 if(tags->objectId != obj->objectId)
573 T(YAFFS_TRACE_VERIFY,
574 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
575 tags->objectId, obj->objectId));
579 * Check that the object's parent ids match if parentCheck requested.
581 * Tests do not apply to the root object.
584 if(parentCheck && tags->objectId > 1 && !obj->parent)
585 T(YAFFS_TRACE_VERIFY,
586 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
587 tags->objectId, oh->parentObjectId));
590 if(parentCheck && obj->parent &&
591 oh->parentObjectId != obj->parent->objectId &&
592 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
593 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
594 T(YAFFS_TRACE_VERIFY,
595 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
596 tags->objectId, oh->parentObjectId, obj->parent->objectId));
599 if(tags->objectId > 1 && oh->name[0] == 0) /* Null name */
600 T(YAFFS_TRACE_VERIFY,
601 (TSTR("Obj %d header name is NULL"TENDSTR),
604 if(tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
605 T(YAFFS_TRACE_VERIFY,
606 (TSTR("Obj %d header name is 0xFF"TENDSTR),
612 static int yaffs_VerifyTnodeWorker(yaffs_Object * obj, yaffs_Tnode * tn,
613 __u32 level, int chunkOffset)
616 yaffs_Device *dev = obj->myDev;
622 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
623 if (tn->internal[i]) {
624 ok = yaffs_VerifyTnodeWorker(obj,
627 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
630 } else if (level == 0) {
631 yaffs_ExtendedTags tags;
632 __u32 objectId = obj->objectId;
634 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
636 for(i = 0; i < YAFFS_NTNODES_LEVEL0; i++){
637 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
640 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
641 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
642 if(tags.objectId != objectId || tags.chunkId != chunkOffset){
643 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
644 objectId, chunkOffset, theChunk,
645 tags.objectId, tags.chunkId));
658 static void yaffs_VerifyFile(yaffs_Object *obj)
660 int requiredTallness;
666 yaffs_ExtendedTags tags;
673 if(yaffs_SkipVerification(obj->myDev))
677 objectId = obj->objectId;
679 /* Check file size is consistent with tnode depth */
680 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
681 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
682 requiredTallness = 0;
684 x >>= YAFFS_TNODES_INTERNAL_BITS;
688 actualTallness = obj->variant.fileVariant.topLevel;
690 if(requiredTallness > actualTallness )
691 T(YAFFS_TRACE_VERIFY,
692 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
693 obj->objectId,actualTallness, requiredTallness));
696 /* Check that the chunks in the tnode tree are all correct.
697 * We do this by scanning through the tnode tree and
698 * checking the tags for every chunk match.
701 if(yaffs_SkipNANDVerification(dev))
704 for(i = 1; i <= lastChunk; i++){
705 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant,i);
708 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
710 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
711 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
712 if(tags.objectId != objectId || tags.chunkId != i){
713 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
714 objectId, i, theChunk,
715 tags.objectId, tags.chunkId));
724 static void yaffs_VerifyDirectory(yaffs_Object *obj)
726 if(obj && yaffs_SkipVerification(obj->myDev))
731 static void yaffs_VerifyHardLink(yaffs_Object *obj)
733 if(obj && yaffs_SkipVerification(obj->myDev))
736 /* Verify sane equivalent object */
739 static void yaffs_VerifySymlink(yaffs_Object *obj)
741 if(obj && yaffs_SkipVerification(obj->myDev))
744 /* Verify symlink string */
747 static void yaffs_VerifySpecial(yaffs_Object *obj)
749 if(obj && yaffs_SkipVerification(obj->myDev))
753 static void yaffs_VerifyObject(yaffs_Object *obj)
768 if(yaffs_SkipVerification(dev))
771 /* Check sane object header chunk */
773 chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
774 chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
776 chunkIdOk = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
777 chunkIsLive = chunkIdOk &&
778 yaffs_CheckChunkBit(dev,
779 obj->hdrChunk / dev->nChunksPerBlock,
780 obj->hdrChunk % dev->nChunksPerBlock);
782 (!chunkIdOk || !chunkIsLive)) {
783 T(YAFFS_TRACE_VERIFY,
784 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
785 obj->objectId,obj->hdrChunk,
786 chunkIdOk ? "" : ",out of range",
787 chunkIsLive || !chunkIdOk ? "" : ",marked as deleted"));
790 if(chunkIdOk && chunkIsLive &&!yaffs_SkipNANDVerification(dev)) {
791 yaffs_ExtendedTags tags;
792 yaffs_ObjectHeader *oh;
793 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
795 oh = (yaffs_ObjectHeader *)buffer;
797 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk,buffer, &tags);
799 yaffs_VerifyObjectHeader(obj,oh,&tags,1);
801 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
804 /* Verify it has a parent */
805 if(obj && !obj->fake &&
806 (!obj->parent || obj->parent->myDev != dev)){
807 T(YAFFS_TRACE_VERIFY,
808 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
809 obj->objectId,obj->parent));
812 /* Verify parent is a directory */
813 if(obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
814 T(YAFFS_TRACE_VERIFY,
815 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
816 obj->objectId,obj->parent->variantType));
819 switch(obj->variantType){
820 case YAFFS_OBJECT_TYPE_FILE:
821 yaffs_VerifyFile(obj);
823 case YAFFS_OBJECT_TYPE_SYMLINK:
824 yaffs_VerifySymlink(obj);
826 case YAFFS_OBJECT_TYPE_DIRECTORY:
827 yaffs_VerifyDirectory(obj);
829 case YAFFS_OBJECT_TYPE_HARDLINK:
830 yaffs_VerifyHardLink(obj);
832 case YAFFS_OBJECT_TYPE_SPECIAL:
833 yaffs_VerifySpecial(obj);
835 case YAFFS_OBJECT_TYPE_UNKNOWN:
837 T(YAFFS_TRACE_VERIFY,
838 (TSTR("Obj %d has illegaltype %d"TENDSTR),
839 obj->objectId,obj->variantType));
846 static void yaffs_VerifyObjects(yaffs_Device *dev)
850 struct ylist_head *lh;
852 if(yaffs_SkipVerification(dev))
855 /* Iterate through the objects in each hash entry */
857 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++){
858 ylist_for_each(lh, &dev->objectBucket[i].list) {
860 obj = ylist_entry(lh, yaffs_Object, hashLink);
861 yaffs_VerifyObject(obj);
870 * Simple hash function. Needs to have a reasonable spread
873 static Y_INLINE int yaffs_HashFunction(int n)
876 return (n % YAFFS_NOBJECT_BUCKETS);
880 * Access functions to useful fake objects.
881 * Note that root might have a presence in NAND if permissions are set.
884 yaffs_Object *yaffs_Root(yaffs_Device * dev)
889 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
891 return dev->lostNFoundDir;
896 * Erased NAND checking functions
899 int yaffs_CheckFF(__u8 * buffer, int nBytes)
901 /* Horrible, slow implementation */
910 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
914 int retval = YAFFS_OK;
915 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
916 yaffs_ExtendedTags tags;
919 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
921 if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
925 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
926 T(YAFFS_TRACE_NANDACCESS,
927 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
931 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
937 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
939 yaffs_ExtendedTags * tags,
946 yaffs_InvalidateCheckpoint(dev);
949 yaffs_BlockInfo *bi = 0;
952 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
958 /* First check this chunk is erased, if it needs
959 * checking. The checking policy (unless forced
960 * always on) is as follows:
962 * Check the first page we try to write in a block.
963 * If the check passes then we don't need to check any
964 * more. If the check fails, we check again...
965 * If the block has been erased, we don't need to check.
967 * However, if the block has been prioritised for gc,
968 * then we think there might be something odd about
969 * this block and stop using it.
971 * Rationale: We should only ever see chunks that have
972 * not been erased if there was a partially written
973 * chunk due to power loss. This checking policy should
974 * catch that case with very few checks and thus save a
975 * lot of checks that are most likely not needed.
977 if (bi->gcPrioritise) {
978 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
979 /* try another chunk */
983 /* let's give it a try */
986 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
987 bi->skipErasedCheck = 0;
989 if (!bi->skipErasedCheck) {
990 erasedOk = yaffs_CheckChunkErased(dev, chunk);
991 if (erasedOk != YAFFS_OK) {
993 (TSTR ("**>> yaffs chunk %d was not erased"
996 /* try another chunk */
999 bi->skipErasedCheck = 1;
1002 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
1004 if (writeOk != YAFFS_OK) {
1005 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
1006 /* try another chunk */
1010 /* Copy the data into the robustification buffer */
1011 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1013 } while (writeOk != YAFFS_OK &&
1014 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1020 T(YAFFS_TRACE_ERROR,
1021 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1024 dev->nRetriedWrites += (attempts - 1);
1031 * Block retiring for handling a broken block.
1034 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
1036 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1038 yaffs_InvalidateCheckpoint(dev);
1040 yaffs_MarkBlockBad(dev, blockInNAND);
1042 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1043 bi->gcPrioritise = 0;
1044 bi->needsRetiring = 0;
1046 dev->nRetiredBlocks++;
1050 * Functions for robustisizing TODO
1054 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
1056 const yaffs_ExtendedTags * tags)
1060 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
1061 const yaffs_ExtendedTags * tags)
1065 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1067 if(!bi->gcPrioritise){
1068 bi->gcPrioritise = 1;
1069 dev->hasPendingPrioritisedGCs = 1;
1070 bi->chunkErrorStrikes ++;
1072 if(bi->chunkErrorStrikes > 3){
1073 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1074 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1081 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
1084 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1085 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1087 yaffs_HandleChunkError(dev,bi);
1091 /* Was an actual write failure, so mark the block for retirement */
1092 bi->needsRetiring = 1;
1093 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1094 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1099 /* Delete the chunk */
1100 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1104 /*---------------- Name handling functions ------------*/
1106 static __u16 yaffs_CalcNameSum(const YCHAR * name)
1111 YUCHAR *bname = (YUCHAR *) name;
1113 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1115 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1116 sum += yaffs_toupper(*bname) * i;
1118 sum += (*bname) * i;
1127 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
1129 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1130 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
1131 yaffs_strcpy(obj->shortName, name);
1133 obj->shortName[0] = _Y('\0');
1136 obj->sum = yaffs_CalcNameSum(name);
1139 /*-------------------- TNODES -------------------
1141 * List of spare tnodes
1142 * The list is hooked together using the first pointer
1146 /* yaffs_CreateTnodes creates a bunch more tnodes and
1147 * adds them to the tnode free list.
1148 * Don't use this function directly
1151 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
1155 yaffs_Tnode *newTnodes;
1159 yaffs_TnodeList *tnl;
1164 /* Calculate the tnode size in bytes for variable width tnode support.
1165 * Must be a multiple of 32-bits */
1166 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1168 if(tnodeSize < sizeof(yaffs_Tnode))
1169 tnodeSize = sizeof(yaffs_Tnode);
1172 /* make these things */
1174 newTnodes = YMALLOC(nTnodes * tnodeSize);
1175 mem = (__u8 *)newTnodes;
1178 T(YAFFS_TRACE_ERROR,
1179 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1183 /* Hook them into the free list */
1185 for (i = 0; i < nTnodes - 1; i++) {
1186 newTnodes[i].internal[0] = &newTnodes[i + 1];
1187 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1188 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1192 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1193 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1194 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1196 dev->freeTnodes = newTnodes;
1198 /* New hookup for wide tnodes */
1199 for(i = 0; i < nTnodes -1; i++) {
1200 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1201 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1202 curr->internal[0] = next;
1205 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1206 curr->internal[0] = dev->freeTnodes;
1207 dev->freeTnodes = (yaffs_Tnode *)mem;
1212 dev->nFreeTnodes += nTnodes;
1213 dev->nTnodesCreated += nTnodes;
1215 /* Now add this bunch of tnodes to a list for freeing up.
1216 * NB If we can't add this to the management list it isn't fatal
1217 * but it just means we can't free this bunch of tnodes later.
1220 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1222 T(YAFFS_TRACE_ERROR,
1224 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1228 tnl->tnodes = newTnodes;
1229 tnl->next = dev->allocatedTnodeList;
1230 dev->allocatedTnodeList = tnl;
1233 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1238 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1240 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
1242 yaffs_Tnode *tn = NULL;
1244 /* If there are none left make more */
1245 if (!dev->freeTnodes) {
1246 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1249 if (dev->freeTnodes) {
1250 tn = dev->freeTnodes;
1251 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1252 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1253 /* Hoosterman, this thing looks like it isn't in the list */
1254 T(YAFFS_TRACE_ALWAYS,
1255 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1258 dev->freeTnodes = dev->freeTnodes->internal[0];
1262 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1267 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
1269 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1270 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1272 if(tnodeSize < sizeof(yaffs_Tnode))
1273 tnodeSize = sizeof(yaffs_Tnode);
1276 memset(tn, 0, tnodeSize);
1281 /* FreeTnode frees up a tnode and puts it back on the free list */
1282 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
1285 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1286 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1287 /* Hoosterman, this thing looks like it is already in the list */
1288 T(YAFFS_TRACE_ALWAYS,
1289 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1291 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1293 tn->internal[0] = dev->freeTnodes;
1294 dev->freeTnodes = tn;
1297 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1301 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
1303 /* Free the list of allocated tnodes */
1304 yaffs_TnodeList *tmp;
1306 while (dev->allocatedTnodeList) {
1307 tmp = dev->allocatedTnodeList->next;
1309 YFREE(dev->allocatedTnodeList->tnodes);
1310 YFREE(dev->allocatedTnodeList);
1311 dev->allocatedTnodeList = tmp;
1315 dev->freeTnodes = NULL;
1316 dev->nFreeTnodes = 0;
1319 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
1321 dev->allocatedTnodeList = NULL;
1322 dev->freeTnodes = NULL;
1323 dev->nFreeTnodes = 0;
1324 dev->nTnodesCreated = 0;
1329 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
1331 __u32 *map = (__u32 *)tn;
1337 pos &= YAFFS_TNODES_LEVEL0_MASK;
1338 val >>= dev->chunkGroupBits;
1340 bitInMap = pos * dev->tnodeWidth;
1341 wordInMap = bitInMap /32;
1342 bitInWord = bitInMap & (32 -1);
1344 mask = dev->tnodeMask << bitInWord;
1346 map[wordInMap] &= ~mask;
1347 map[wordInMap] |= (mask & (val << bitInWord));
1349 if(dev->tnodeWidth > (32-bitInWord)) {
1350 bitInWord = (32 - bitInWord);
1352 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1353 map[wordInMap] &= ~mask;
1354 map[wordInMap] |= (mask & (val >> bitInWord));
1358 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
1360 __u32 *map = (__u32 *)tn;
1366 pos &= YAFFS_TNODES_LEVEL0_MASK;
1368 bitInMap = pos * dev->tnodeWidth;
1369 wordInMap = bitInMap /32;
1370 bitInWord = bitInMap & (32 -1);
1372 val = map[wordInMap] >> bitInWord;
1374 if(dev->tnodeWidth > (32-bitInWord)) {
1375 bitInWord = (32 - bitInWord);
1377 val |= (map[wordInMap] << bitInWord);
1380 val &= dev->tnodeMask;
1381 val <<= dev->chunkGroupBits;
1386 /* ------------------- End of individual tnode manipulation -----------------*/
1388 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1389 * The look up tree is represented by the top tnode and the number of topLevel
1390 * in the tree. 0 means only the level 0 tnode is in the tree.
1393 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1394 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
1395 yaffs_FileStructure * fStruct,
1399 yaffs_Tnode *tn = fStruct->top;
1401 int requiredTallness;
1402 int level = fStruct->topLevel;
1404 /* Check sane level and chunk Id */
1405 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
1409 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1413 /* First check we're tall enough (ie enough topLevel) */
1415 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1416 requiredTallness = 0;
1418 i >>= YAFFS_TNODES_INTERNAL_BITS;
1422 if (requiredTallness > fStruct->topLevel) {
1423 /* Not tall enough, so we can't find it, return NULL. */
1427 /* Traverse down to level 0 */
1428 while (level > 0 && tn) {
1430 internal[(chunkId >>
1431 ( YAFFS_TNODES_LEVEL0_BITS +
1433 YAFFS_TNODES_INTERNAL_BITS)
1435 YAFFS_TNODES_INTERNAL_MASK];
1443 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1444 * This happens in two steps:
1445 * 1. If the tree isn't tall enough, then make it taller.
1446 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1448 * Used when modifying the tree.
1450 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1451 * be plugged into the ttree.
1454 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
1455 yaffs_FileStructure * fStruct,
1457 yaffs_Tnode *passedTn)
1460 int requiredTallness;
1468 /* Check sane level and page Id */
1469 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
1473 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1477 /* First check we're tall enough (ie enough topLevel) */
1479 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1480 requiredTallness = 0;
1482 x >>= YAFFS_TNODES_INTERNAL_BITS;
1487 if (requiredTallness > fStruct->topLevel) {
1488 /* Not tall enough,gotta make the tree taller */
1489 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1491 tn = yaffs_GetTnode(dev);
1494 tn->internal[0] = fStruct->top;
1497 T(YAFFS_TRACE_ERROR,
1498 (TSTR("yaffs: no more tnodes" TENDSTR)));
1502 fStruct->topLevel = requiredTallness;
1505 /* Traverse down to level 0, adding anything we need */
1507 l = fStruct->topLevel;
1511 while (l > 0 && tn) {
1513 ( YAFFS_TNODES_LEVEL0_BITS +
1514 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1515 YAFFS_TNODES_INTERNAL_MASK;
1518 if((l>1) && !tn->internal[x]){
1519 /* Add missing non-level-zero tnode */
1520 tn->internal[x] = yaffs_GetTnode(dev);
1523 /* Looking from level 1 at level 0 */
1525 /* If we already have one, then release it.*/
1527 yaffs_FreeTnode(dev,tn->internal[x]);
1528 tn->internal[x] = passedTn;
1530 } else if(!tn->internal[x]) {
1531 /* Don't have one, none passed in */
1532 tn->internal[x] = yaffs_GetTnode(dev);
1536 tn = tn->internal[x];
1540 /* top is level 0 */
1542 memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1543 yaffs_FreeTnode(dev,passedTn);
1550 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1551 yaffs_ExtendedTags * tags, int objectId,
1556 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1557 if (yaffs_CheckChunkBit
1558 (dev, theChunk / dev->nChunksPerBlock,
1559 theChunk % dev->nChunksPerBlock)) {
1560 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1562 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1574 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1575 * chunks and tnodes in the file
1576 * Returns 1 if the tree was deleted.
1577 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1580 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1581 int chunkOffset, int *limit)
1586 yaffs_ExtendedTags tags;
1588 yaffs_Device *dev = in->myDev;
1595 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1597 if (tn->internal[i]) {
1598 if (limit && (*limit) < 0) {
1602 yaffs_DeleteWorker(in,
1610 YAFFS_TNODES_INTERNAL_BITS)
1615 yaffs_FreeTnode(dev,
1618 tn->internal[i] = NULL;
1623 return (allDone) ? 1 : 0;
1624 } else if (level == 0) {
1627 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1629 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1634 YAFFS_TNODES_LEVEL0_BITS) + i;
1637 yaffs_FindChunkInGroup(dev,
1643 if (foundChunk > 0) {
1644 yaffs_DeleteChunk(dev,
1649 *limit = *limit - 1;
1657 yaffs_PutLevel0Tnode(dev,tn,i,0);
1661 return (i < 0) ? 1 : 0;
1671 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1674 yaffs_BlockInfo *theBlock;
1676 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1678 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1680 theBlock->softDeletions++;
1685 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1686 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1688 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1691 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1692 __u32 level, int chunkOffset)
1697 yaffs_Device *dev = in->myDev;
1702 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1704 if (tn->internal[i]) {
1706 yaffs_SoftDeleteWorker(in,
1712 YAFFS_TNODES_INTERNAL_BITS)
1715 yaffs_FreeTnode(dev,
1718 tn->internal[i] = NULL;
1720 /* Hoosterman... how could this happen? */
1724 return (allDone) ? 1 : 0;
1725 } else if (level == 0) {
1727 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1728 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1730 /* Note this does not find the real chunk, only the chunk group.
1731 * We make an assumption that a chunk group is not larger than
1734 yaffs_SoftDeleteChunk(dev, theChunk);
1735 yaffs_PutLevel0Tnode(dev,tn,i,0);
1749 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1752 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1753 if (obj->nDataChunks <= 0) {
1754 /* Empty file with no duplicate object headers, just delete it immediately */
1755 yaffs_FreeTnode(obj->myDev,
1756 obj->variant.fileVariant.top);
1757 obj->variant.fileVariant.top = NULL;
1758 T(YAFFS_TRACE_TRACING,
1759 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1761 yaffs_DoGenericObjectDeletion(obj);
1763 yaffs_SoftDeleteWorker(obj,
1764 obj->variant.fileVariant.top,
1765 obj->variant.fileVariant.
1767 obj->softDeleted = 1;
1772 /* Pruning removes any part of the file structure tree that is beyond the
1773 * bounds of the file (ie that does not point to chunks).
1775 * A file should only get pruned when its size is reduced.
1777 * Before pruning, the chunks must be pulled from the tree and the
1778 * level 0 tnode entries must be zeroed out.
1779 * Could also use this for file deletion, but that's probably better handled
1780 * by a special case.
1783 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1784 __u32 level, int del0)
1792 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1793 if (tn->internal[i] && level > 0) {
1795 yaffs_PruneWorker(dev, tn->internal[i],
1797 (i == 0) ? del0 : 1);
1800 if (tn->internal[i]) {
1805 if (hasData == 0 && del0) {
1806 /* Free and return NULL */
1808 yaffs_FreeTnode(dev, tn);
1818 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1819 yaffs_FileStructure * fStruct)
1826 if (fStruct->topLevel > 0) {
1828 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1830 /* Now we have a tree with all the non-zero branches NULL but the height
1831 * is the same as it was.
1832 * Let's see if we can trim internal tnodes to shorten the tree.
1833 * We can do this if only the 0th element in the tnode is in use
1834 * (ie all the non-zero are NULL)
1837 while (fStruct->topLevel && !done) {
1841 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1842 if (tn->internal[i]) {
1848 fStruct->top = tn->internal[0];
1849 fStruct->topLevel--;
1850 yaffs_FreeTnode(dev, tn);
1860 /*-------------------- End of File Structure functions.-------------------*/
1862 /* yaffs_CreateFreeObjects creates a bunch more objects and
1863 * adds them to the object free list.
1865 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1868 yaffs_Object *newObjects;
1869 yaffs_ObjectList *list;
1874 /* make these things */
1875 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1876 list = YMALLOC(sizeof(yaffs_ObjectList));
1878 if (!newObjects || !list) {
1883 T(YAFFS_TRACE_ALLOCATE,
1884 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1888 /* Hook them into the free list */
1889 for (i = 0; i < nObjects - 1; i++) {
1890 newObjects[i].siblings.next =
1891 (struct ylist_head *)(&newObjects[i + 1]);
1894 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1895 dev->freeObjects = newObjects;
1896 dev->nFreeObjects += nObjects;
1897 dev->nObjectsCreated += nObjects;
1899 /* Now add this bunch of Objects to a list for freeing up. */
1901 list->objects = newObjects;
1902 list->next = dev->allocatedObjectList;
1903 dev->allocatedObjectList = list;
1909 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1910 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1912 yaffs_Object *tn = NULL;
1914 /* If there are none left make more */
1915 if (!dev->freeObjects) {
1916 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1919 if (dev->freeObjects) {
1920 tn = dev->freeObjects;
1922 (yaffs_Object *) (dev->freeObjects->siblings.next);
1923 dev->nFreeObjects--;
1925 /* Now sweeten it up... */
1927 memset(tn, 0, sizeof(yaffs_Object));
1930 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1931 YINIT_LIST_HEAD(&(tn->hardLinks));
1932 YINIT_LIST_HEAD(&(tn->hashLink));
1933 YINIT_LIST_HEAD(&tn->siblings);
1935 /* Add it to the lost and found directory.
1936 * NB Can't put root or lostNFound in lostNFound so
1937 * check if lostNFound exists first
1939 if (dev->lostNFoundDir) {
1940 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1944 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1949 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1954 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1956 obj->fake = 1; /* it is fake so it might have no NAND presence... */
1957 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1958 obj->unlinkAllowed = 0; /* ... or unlink it */
1961 obj->yst_mode = mode;
1963 obj->hdrChunk = 0; /* Not a valid chunk. */
1970 static void yaffs_UnhashObject(yaffs_Object * tn)
1973 yaffs_Device *dev = tn->myDev;
1975 /* If it is still linked into the bucket list, free from the list */
1976 if (!ylist_empty(&tn->hashLink)) {
1977 ylist_del_init(&tn->hashLink);
1978 bucket = yaffs_HashFunction(tn->objectId);
1979 dev->objectBucket[bucket].count--;
1984 /* FreeObject frees up a Object and puts it back on the free list */
1985 static void yaffs_FreeObject(yaffs_Object * tn)
1988 yaffs_Device *dev = tn->myDev;
1992 /* We're still hooked up to a cached inode.
1993 * Don't delete now, but mark for later deletion
1995 tn->deferedFree = 1;
2000 yaffs_UnhashObject(tn);
2002 /* Link into the free list. */
2003 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2004 dev->freeObjects = tn;
2005 dev->nFreeObjects++;
2007 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2013 void yaffs_HandleDeferedFree(yaffs_Object * obj)
2015 if (obj->deferedFree) {
2016 yaffs_FreeObject(obj);
2022 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
2024 /* Free the list of allocated Objects */
2026 yaffs_ObjectList *tmp;
2028 while (dev->allocatedObjectList) {
2029 tmp = dev->allocatedObjectList->next;
2030 YFREE(dev->allocatedObjectList->objects);
2031 YFREE(dev->allocatedObjectList);
2033 dev->allocatedObjectList = tmp;
2036 dev->freeObjects = NULL;
2037 dev->nFreeObjects = 0;
2040 static void yaffs_InitialiseObjects(yaffs_Device * dev)
2044 dev->allocatedObjectList = NULL;
2045 dev->freeObjects = NULL;
2046 dev->nFreeObjects = 0;
2048 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2049 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2050 dev->objectBucket[i].count = 0;
2055 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
2060 int lowest = 999999;
2062 /* First let's see if we can find one that's empty. */
2064 for (i = 0; i < 10 && lowest > 0; i++) {
2066 x %= YAFFS_NOBJECT_BUCKETS;
2067 if (dev->objectBucket[x].count < lowest) {
2068 lowest = dev->objectBucket[x].count;
2074 /* If we didn't find an empty list, then try
2075 * looking a bit further for a short one
2078 for (i = 0; i < 10 && lowest > 3; i++) {
2080 x %= YAFFS_NOBJECT_BUCKETS;
2081 if (dev->objectBucket[x].count < lowest) {
2082 lowest = dev->objectBucket[x].count;
2091 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
2093 int bucket = yaffs_FindNiceObjectBucket(dev);
2095 /* Now find an object value that has not already been taken
2096 * by scanning the list.
2100 struct ylist_head *i;
2102 __u32 n = (__u32) bucket;
2104 /* yaffs_CheckObjectHashSanity(); */
2108 n += YAFFS_NOBJECT_BUCKETS;
2109 if (1 || dev->objectBucket[bucket].count > 0) {
2110 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2111 /* If there is already one in the list */
2113 && ylist_entry(i, yaffs_Object,
2114 hashLink)->objectId == n) {
2125 static void yaffs_HashObject(yaffs_Object * in)
2127 int bucket = yaffs_HashFunction(in->objectId);
2128 yaffs_Device *dev = in->myDev;
2130 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2131 dev->objectBucket[bucket].count++;
2135 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
2137 int bucket = yaffs_HashFunction(number);
2138 struct ylist_head *i;
2141 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2142 /* Look if it is in the list */
2144 in = ylist_entry(i, yaffs_Object, hashLink);
2145 if (in->objectId == number) {
2147 /* Don't tell the VFS about this one if it is defered free */
2148 if (in->deferedFree)
2160 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
2161 yaffs_ObjectType type)
2164 yaffs_Object *theObject;
2165 yaffs_Tnode *tn = NULL;
2168 number = yaffs_CreateNewObjectNumber(dev);
2171 theObject = yaffs_AllocateEmptyObject(dev);
2175 if(type == YAFFS_OBJECT_TYPE_FILE){
2176 tn = yaffs_GetTnode(dev);
2178 yaffs_FreeObject(theObject);
2186 theObject->fake = 0;
2187 theObject->renameAllowed = 1;
2188 theObject->unlinkAllowed = 1;
2189 theObject->objectId = number;
2190 yaffs_HashObject(theObject);
2191 theObject->variantType = type;
2192 #ifdef CONFIG_YAFFS_WINCE
2193 yfsd_WinFileTimeNow(theObject->win_atime);
2194 theObject->win_ctime[0] = theObject->win_mtime[0] =
2195 theObject->win_atime[0];
2196 theObject->win_ctime[1] = theObject->win_mtime[1] =
2197 theObject->win_atime[1];
2201 theObject->yst_atime = theObject->yst_mtime =
2202 theObject->yst_ctime = Y_CURRENT_TIME;
2205 case YAFFS_OBJECT_TYPE_FILE:
2206 theObject->variant.fileVariant.fileSize = 0;
2207 theObject->variant.fileVariant.scannedFileSize = 0;
2208 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2209 theObject->variant.fileVariant.topLevel = 0;
2210 theObject->variant.fileVariant.top = tn;
2212 case YAFFS_OBJECT_TYPE_DIRECTORY:
2213 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2216 case YAFFS_OBJECT_TYPE_SYMLINK:
2217 case YAFFS_OBJECT_TYPE_HARDLINK:
2218 case YAFFS_OBJECT_TYPE_SPECIAL:
2219 /* No action required */
2221 case YAFFS_OBJECT_TYPE_UNKNOWN:
2222 /* todo this should not happen */
2230 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
2232 yaffs_ObjectType type)
2234 yaffs_Object *theObject = NULL;
2237 theObject = yaffs_FindObjectByNumber(dev, number);
2241 theObject = yaffs_CreateNewObject(dev, number, type);
2249 static YCHAR *yaffs_CloneString(const YCHAR * str)
2251 YCHAR *newStr = NULL;
2254 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2256 yaffs_strcpy(newStr, str);
2264 * Mknod (create) a new object.
2265 * equivalentObject only has meaning for a hard link;
2266 * aliasString only has meaning for a sumlink.
2267 * rdev only has meaning for devices (a subset of special objects)
2270 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2271 yaffs_Object * parent,
2276 yaffs_Object * equivalentObject,
2277 const YCHAR * aliasString, __u32 rdev)
2282 yaffs_Device *dev = parent->myDev;
2284 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2285 if (yaffs_FindObjectByName(parent, name)) {
2289 in = yaffs_CreateNewObject(dev, -1, type);
2294 if(type == YAFFS_OBJECT_TYPE_SYMLINK){
2295 str = yaffs_CloneString(aliasString);
2297 yaffs_FreeObject(in);
2307 in->variantType = type;
2309 in->yst_mode = mode;
2311 #ifdef CONFIG_YAFFS_WINCE
2312 yfsd_WinFileTimeNow(in->win_atime);
2313 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2314 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2317 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2319 in->yst_rdev = rdev;
2323 in->nDataChunks = 0;
2325 yaffs_SetObjectName(in, name);
2328 yaffs_AddObjectToDirectory(parent, in);
2330 in->myDev = parent->myDev;
2333 case YAFFS_OBJECT_TYPE_SYMLINK:
2334 in->variant.symLinkVariant.alias = str;
2336 case YAFFS_OBJECT_TYPE_HARDLINK:
2337 in->variant.hardLinkVariant.equivalentObject =
2339 in->variant.hardLinkVariant.equivalentObjectId =
2340 equivalentObject->objectId;
2341 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2343 case YAFFS_OBJECT_TYPE_FILE:
2344 case YAFFS_OBJECT_TYPE_DIRECTORY:
2345 case YAFFS_OBJECT_TYPE_SPECIAL:
2346 case YAFFS_OBJECT_TYPE_UNKNOWN:
2351 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2352 /* Could not create the object header, fail the creation */
2353 yaffs_DestroyObject(in);
2362 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
2363 __u32 mode, __u32 uid, __u32 gid)
2365 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2366 uid, gid, NULL, NULL, 0);
2369 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
2370 __u32 mode, __u32 uid, __u32 gid)
2372 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2373 mode, uid, gid, NULL, NULL, 0);
2376 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
2377 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2379 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2380 uid, gid, NULL, NULL, rdev);
2383 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
2384 __u32 mode, __u32 uid, __u32 gid,
2385 const YCHAR * alias)
2387 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2388 uid, gid, NULL, alias, 0);
2391 /* yaffs_Link returns the object id of the equivalent object.*/
2392 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
2393 yaffs_Object * equivalentObject)
2395 /* Get the real object in case we were fed a hard link as an equivalent object */
2396 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2398 if (yaffs_MknodObject
2399 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2400 equivalentObject, NULL, 0)) {
2401 return equivalentObject;
2408 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
2409 const YCHAR * newName, int force, int shadows)
2414 yaffs_Object *existingTarget;
2416 if (newDir == NULL) {
2417 newDir = obj->parent; /* use the old directory */
2420 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2421 T(YAFFS_TRACE_ALWAYS,
2423 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2428 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2429 if (obj->myDev->isYaffs2) {
2430 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2432 unlinkOp = (newDir == obj->myDev->unlinkedDir
2433 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2436 deleteOp = (newDir == obj->myDev->deletedDir);
2438 existingTarget = yaffs_FindObjectByName(newDir, newName);
2440 /* If the object is a file going into the unlinked directory,
2441 * then it is OK to just stuff it in since duplicate names are allowed.
2442 * else only proceed if the new name does not exist and if we're putting
2443 * it into a directory.
2450 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2451 yaffs_SetObjectName(obj, newName);
2454 yaffs_AddObjectToDirectory(newDir, obj);
2459 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2460 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
2467 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
2468 yaffs_Object * newDir, const YCHAR * newName)
2471 yaffs_Object *existingTarget;
2474 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2475 /* Special case for case insemsitive systems (eg. WinCE).
2476 * While look-up is case insensitive, the name isn't.
2477 * Therefore we might want to change x.txt to X.txt
2479 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
2484 obj = yaffs_FindObjectByName(oldDir, oldName);
2485 /* Check new name to long. */
2486 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK &&
2487 yaffs_strlen(newName) > YAFFS_MAX_ALIAS_LENGTH)
2490 else if (obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK &&
2491 yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2495 if (obj && obj->renameAllowed) {
2497 /* Now do the handling for an existing target, if there is one */
2499 existingTarget = yaffs_FindObjectByName(newDir, newName);
2500 if (existingTarget &&
2501 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2502 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2503 /* There is a target that is a non-empty directory, so we fail */
2504 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2505 } else if (existingTarget && existingTarget != obj) {
2506 /* Nuke the target first, using shadowing,
2507 * but only if it isn't the same object
2509 yaffs_ChangeObjectName(obj, newDir, newName, force,
2510 existingTarget->objectId);
2511 yaffs_UnlinkObject(existingTarget);
2514 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2519 /*------------------------- Block Management and Page Allocation ----------------*/
2521 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
2523 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2525 dev->blockInfo = NULL;
2526 dev->chunkBits = NULL;
2528 dev->allocationBlock = -1; /* force it to get a new one */
2530 /* If the first allocation strategy fails, thry the alternate one */
2531 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2532 if(!dev->blockInfo){
2533 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2534 dev->blockInfoAlt = 1;
2537 dev->blockInfoAlt = 0;
2541 /* Set up dynamic blockinfo stuff. */
2542 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2543 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2544 if(!dev->chunkBits){
2545 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2546 dev->chunkBitsAlt = 1;
2549 dev->chunkBitsAlt = 0;
2552 if (dev->blockInfo && dev->chunkBits) {
2553 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2554 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2562 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
2564 if(dev->blockInfoAlt && dev->blockInfo)
2565 YFREE_ALT(dev->blockInfo);
2566 else if(dev->blockInfo)
2567 YFREE(dev->blockInfo);
2569 dev->blockInfoAlt = 0;
2571 dev->blockInfo = NULL;
2573 if(dev->chunkBitsAlt && dev->chunkBits)
2574 YFREE_ALT(dev->chunkBits);
2575 else if(dev->chunkBits)
2576 YFREE(dev->chunkBits);
2577 dev->chunkBitsAlt = 0;
2578 dev->chunkBits = NULL;
2581 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
2582 yaffs_BlockInfo * bi)
2589 return 1; /* disqualification only applies to yaffs2. */
2591 if (!bi->hasShrinkHeader)
2592 return 1; /* can gc */
2594 /* Find the oldest dirty sequence number if we don't know it and save it
2595 * so we don't have to keep recomputing it.
2597 if (!dev->oldestDirtySequence) {
2598 seq = dev->sequenceNumber;
2600 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2602 b = yaffs_GetBlockInfo(dev, i);
2603 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2604 (b->pagesInUse - b->softDeletions) <
2605 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2606 seq = b->sequenceNumber;
2609 dev->oldestDirtySequence = seq;
2612 /* Can't do gc of this block if there are any blocks older than this one that have
2615 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2619 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2620 * for garbage collection.
2623 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2627 int b = dev->currentDirtyChecker;
2634 yaffs_BlockInfo *bi;
2635 int pendingPrioritisedExist = 0;
2637 /* First let's see if we need to grab a prioritised block */
2638 if(dev->hasPendingPrioritisedGCs){
2639 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2641 bi = yaffs_GetBlockInfo(dev, i);
2642 //yaffs_VerifyBlock(dev,bi,i);
2644 if(bi->gcPrioritise) {
2645 pendingPrioritisedExist = 1;
2646 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2647 yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2648 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2651 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2656 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2657 dev->hasPendingPrioritisedGCs = 0;
2660 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2662 * else (we're doing a leasurely gc), then we only bother to do this if the
2663 * block has only a few pages in use.
2666 dev->nonAggressiveSkip--;
2668 if (!aggressive && (dev->nonAggressiveSkip > 0)) {
2674 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2678 dev->internalEndBlock - dev->internalStartBlock + 1;
2681 dev->internalEndBlock - dev->internalStartBlock + 1;
2682 iterations = iterations / 16;
2683 if (iterations > 200) {
2688 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2690 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2691 b = dev->internalStartBlock;
2694 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2695 T(YAFFS_TRACE_ERROR,
2696 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2700 bi = yaffs_GetBlockInfo(dev, b);
2703 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2710 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2711 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2712 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2714 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2718 dev->currentDirtyChecker = b;
2722 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2723 dev->nChunksPerBlock - pagesInUse,prioritised));
2726 dev->oldestDirtySequence = 0;
2729 dev->nonAggressiveSkip = 4;
2735 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2737 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2741 /* If the block is still healthy erase it and mark as clean.
2742 * If the block has had a data failure, then retire it.
2745 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2746 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2747 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2749 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2751 if (!bi->needsRetiring) {
2752 yaffs_InvalidateCheckpoint(dev);
2753 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2755 dev->nErasureFailures++;
2756 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2757 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2762 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2764 for (i = 0; i < dev->nChunksPerBlock; i++) {
2765 if (!yaffs_CheckChunkErased
2766 (dev, blockNo * dev->nChunksPerBlock + i)) {
2767 T(YAFFS_TRACE_ERROR,
2769 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2770 TENDSTR), blockNo, i));
2776 /* Clean it up... */
2777 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2778 dev->nErasedBlocks++;
2780 bi->softDeletions = 0;
2781 bi->hasShrinkHeader = 0;
2782 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2783 bi->gcPrioritise = 0;
2784 yaffs_ClearChunkBits(dev, blockNo);
2786 T(YAFFS_TRACE_ERASE,
2787 (TSTR("Erased block %d" TENDSTR), blockNo));
2789 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2791 yaffs_RetireBlock(dev, blockNo);
2792 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2793 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2797 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2801 yaffs_BlockInfo *bi;
2803 if (dev->nErasedBlocks < 1) {
2804 /* Hoosterman we've got a problem.
2805 * Can't get space to gc
2807 T(YAFFS_TRACE_ERROR,
2808 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2813 /* Find an empty block. */
2815 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2816 dev->allocationBlockFinder++;
2817 if (dev->allocationBlockFinder < dev->internalStartBlock
2818 || dev->allocationBlockFinder > dev->internalEndBlock) {
2819 dev->allocationBlockFinder = dev->internalStartBlock;
2822 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2824 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2825 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2826 dev->sequenceNumber++;
2827 bi->sequenceNumber = dev->sequenceNumber;
2828 dev->nErasedBlocks--;
2829 T(YAFFS_TRACE_ALLOCATE,
2830 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2831 dev->allocationBlockFinder, dev->sequenceNumber,
2832 dev->nErasedBlocks));
2833 return dev->allocationBlockFinder;
2837 T(YAFFS_TRACE_ALWAYS,
2839 ("yaffs tragedy: no more erased blocks, but there should have been %d"
2840 TENDSTR), dev->nErasedBlocks));
2847 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2849 if(!dev->nCheckpointBlocksRequired){
2850 /* Not a valid value so recalculate */
2853 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2856 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2858 if(tnodeSize < sizeof(yaffs_Tnode))
2859 tnodeSize = sizeof(yaffs_Tnode);
2861 nBytes += sizeof(yaffs_CheckpointValidity);
2862 nBytes += sizeof(yaffs_CheckpointDevice);
2863 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2864 nBytes += devBlocks * dev->chunkBitmapStride;
2865 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2866 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2867 nBytes += sizeof(yaffs_CheckpointValidity);
2868 nBytes += sizeof(__u32); /* checksum*/
2870 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2872 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2874 dev->nCheckpointBlocksRequired = nBlocks;
2877 return dev->nCheckpointBlocksRequired;
2880 // Check if there's space to allocate...
2881 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2882 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2885 int reservedBlocks = dev->nReservedBlocks;
2886 int checkpointBlocks;
2888 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
2889 if(checkpointBlocks < 0)
2890 checkpointBlocks = 0;
2892 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2894 return (dev->nFreeChunks > reservedChunks);
2897 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2900 yaffs_BlockInfo *bi;
2902 if (dev->allocationBlock < 0) {
2903 /* Get next block to allocate off */
2904 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2905 dev->allocationPage = 0;
2908 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2909 /* Not enough space to allocate unless we're allowed to use the reserve. */
2913 if (dev->nErasedBlocks < dev->nReservedBlocks
2914 && dev->allocationPage == 0) {
2915 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2918 /* Next page please.... */
2919 if (dev->allocationBlock >= 0) {
2920 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2922 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2923 dev->allocationPage;
2925 yaffs_SetChunkBit(dev, dev->allocationBlock,
2926 dev->allocationPage);
2928 dev->allocationPage++;
2932 /* If the block is full set the state to full */
2933 if (dev->allocationPage >= dev->nChunksPerBlock) {
2934 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2935 dev->allocationBlock = -1;
2944 T(YAFFS_TRACE_ERROR,
2945 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2950 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2954 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2956 if (dev->allocationBlock > 0) {
2957 n += (dev->nChunksPerBlock - dev->allocationPage);
2964 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2970 int retVal = YAFFS_OK;
2973 int isCheckpointBlock;
2976 int chunksBefore = yaffs_GetErasedChunks(dev);
2979 yaffs_ExtendedTags tags;
2981 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2983 yaffs_Object *object;
2985 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2987 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2989 T(YAFFS_TRACE_TRACING,
2990 (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2991 bi->pagesInUse, bi->hasShrinkHeader));
2993 /*yaffs_VerifyFreeChunks(dev); */
2995 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2997 /* Take off the number of soft deleted entries because
2998 * they're going to get really deleted during GC.
3000 dev->nFreeChunks -= bi->softDeletions;
3004 if (isCheckpointBlock ||
3005 !yaffs_StillSomeChunkBits(dev, block)) {
3006 T(YAFFS_TRACE_TRACING,
3008 ("Collecting block %d that has no chunks in use" TENDSTR),
3010 yaffs_BlockBecameDirty(dev, block);
3013 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3015 yaffs_VerifyBlock(dev,bi,block);
3017 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
3018 chunkInBlock < dev->nChunksPerBlock
3019 && yaffs_StillSomeChunkBits(dev, block);
3020 chunkInBlock++, oldChunk++) {
3021 if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
3023 /* This page is in use and might need to be copied off */
3027 yaffs_InitialiseTags(&tags);
3029 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3033 yaffs_FindObjectByNumber(dev,
3036 T(YAFFS_TRACE_GC_DETAIL,
3038 ("Collecting page %d, %d %d %d " TENDSTR),
3039 chunkInBlock, tags.objectId, tags.chunkId,
3042 if(object && !yaffs_SkipVerification(dev)){
3043 if(tags.chunkId == 0)
3044 matchingChunk = object->hdrChunk;
3045 else if(object->softDeleted)
3046 matchingChunk = oldChunk; /* Defeat the test */
3048 matchingChunk = yaffs_FindChunkInFile(object,tags.chunkId,NULL);
3050 if(oldChunk != matchingChunk)
3051 T(YAFFS_TRACE_ERROR,
3052 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3053 oldChunk,matchingChunk,tags.objectId, tags.chunkId));
3058 T(YAFFS_TRACE_ERROR,
3060 ("page %d in gc has no object: %d %d %d "
3062 tags.objectId, tags.chunkId, tags.byteCount));
3065 if (object && object->deleted
3066 && tags.chunkId != 0) {
3067 /* Data chunk in a deleted file, throw it away
3068 * It's a soft deleted data chunk,
3069 * No need to copy this, just forget about it and
3070 * fix up the object.
3073 object->nDataChunks--;
3075 if (object->nDataChunks <= 0) {
3076 /* remeber to clean up the object */
3077 dev->gcCleanupList[cleanups] =
3083 /* Todo object && object->deleted && object->nDataChunks == 0 */
3085 /* Deleted object header with no data chunks.
3086 * Can be discarded and the file deleted.
3088 object->hdrChunk = 0;
3089 yaffs_FreeTnode(object->myDev,
3092 object->variant.fileVariant.top = NULL;
3093 yaffs_DoGenericObjectDeletion(object);
3095 } else if (object) {
3096 /* It's either a data chunk in a live file or
3097 * an ObjectHeader, so we're interested in it.
3098 * NB Need to keep the ObjectHeaders of deleted files
3099 * until the whole file has been deleted off
3101 tags.serialNumber++;
3105 if (tags.chunkId == 0) {
3106 /* It is an object Id,
3107 * We need to nuke the shrinkheader flags first
3108 * We no longer want the shrinkHeader flag since its work is done
3109 * and if it is left in place it will mess up scanning.
3110 * Also, clear out any shadowing stuff
3113 yaffs_ObjectHeader *oh;
3114 oh = (yaffs_ObjectHeader *)buffer;
3116 oh->shadowsObject = oh->inbandShadowsObject = -1;
3117 tags.extraShadows = 0;
3118 tags.extraIsShrinkHeader = 0;
3120 yaffs_VerifyObjectHeader(object,oh,&tags,1);
3124 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3127 retVal = YAFFS_FAIL;
3130 /* Ok, now fix up the Tnodes etc. */
3132 if (tags.chunkId == 0) {
3134 object->hdrChunk = newChunk;
3135 object->serial = tags.serialNumber;
3137 /* It's a data chunk */
3138 yaffs_PutChunkIntoFile
3146 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3151 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3154 /* Do any required cleanups */
3155 for (i = 0; i < cleanups; i++) {
3156 /* Time to delete the file too */
3158 yaffs_FindObjectByNumber(dev,
3159 dev->gcCleanupList[i]);
3161 yaffs_FreeTnode(dev,
3162 object->variant.fileVariant.
3164 object->variant.fileVariant.top = NULL;
3167 ("yaffs: About to finally delete object %d"
3168 TENDSTR), object->objectId));
3169 yaffs_DoGenericObjectDeletion(object);
3170 object->myDev->nDeletedFiles--;
3177 yaffs_VerifyCollectedBlock(dev,bi,block);
3179 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
3182 ("gc did not increase free chunks before %d after %d"
3183 TENDSTR), chunksBefore, chunksAfter));
3191 /* New garbage collector
3192 * If we're very low on erased blocks then we do aggressive garbage collection
3193 * otherwise we do "leasurely" garbage collection.
3194 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3195 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3197 * The idea is to help clear out space in a more spread-out manner.
3198 * Dunno if it really does anything useful.
3200 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
3204 int gcOk = YAFFS_OK;
3207 int checkpointBlockAdjust;
3209 if (dev->isDoingGC) {
3210 /* Bail out so we don't get recursive gc */
3214 /* This loop should pass the first time.
3215 * We'll only see looping here if the erase of the collected block fails.
3221 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3222 if(checkpointBlockAdjust < 0)
3223 checkpointBlockAdjust = 0;
3225 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3226 /* We need a block soon...*/
3229 /* We're in no hurry */
3233 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3236 dev->garbageCollections++;
3238 dev->passiveGarbageCollections++;
3243 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3244 dev->nErasedBlocks, aggressive));
3246 gcOk = yaffs_GarbageCollectBlock(dev, block);
3249 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3252 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3253 TENDSTR), dev->nErasedBlocks, maxTries, block));
3255 } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
3258 return aggressive ? gcOk : YAFFS_OK;
3261 /*------------------------- TAGS --------------------------------*/
3263 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
3266 return (tags->chunkId == chunkInObject &&
3267 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3272 /*-------------------- Data file manipulation -----------------*/
3274 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
3275 yaffs_ExtendedTags * tags)
3277 /*Get the Tnode, then get the level 0 offset chunk offset */
3280 yaffs_ExtendedTags localTags;
3283 yaffs_Device *dev = in->myDev;
3286 /* Passed a NULL, so use our own tags space */
3290 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3293 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3296 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3302 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
3303 yaffs_ExtendedTags * tags)
3305 /* Get the Tnode, then get the level 0 offset chunk offset */
3308 yaffs_ExtendedTags localTags;
3310 yaffs_Device *dev = in->myDev;
3314 /* Passed a NULL, so use our own tags space */
3318 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3322 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3325 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3328 /* Delete the entry in the filestructure (if found) */
3330 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
3333 /*T(("No level 0 found for %d\n", chunkInInode)); */
3337 /* T(("Could not find %d to delete\n",chunkInInode)); */
3342 #ifdef YAFFS_PARANOID
3344 static int yaffs_CheckFileSanity(yaffs_Object * in)
3352 yaffs_Tags localTags;
3353 yaffs_Tags *tags = &localTags;
3357 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3358 /* T(("Object not a file\n")); */
3362 objId = in->objectId;
3363 fSize = in->variant.fileVariant.fileSize;
3365 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3367 for (chunk = 1; chunk <= nChunks; chunk++) {
3368 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3373 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
3375 if (yaffs_CheckChunkBits
3376 (dev, theChunk / dev->nChunksPerBlock,
3377 theChunk % dev->nChunksPerBlock)) {
3379 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3383 (tags, in->objectId, chunk, chunkDeleted)) {
3393 /* T(("No level 0 found for %d\n", chunk)); */
3397 return failed ? YAFFS_FAIL : YAFFS_OK;
3402 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
3403 int chunkInNAND, int inScan)
3405 /* NB inScan is zero unless scanning.
3406 * For forward scanning, inScan is > 0;
3407 * for backward scanning inScan is < 0
3411 yaffs_Device *dev = in->myDev;
3413 yaffs_ExtendedTags existingTags;
3414 yaffs_ExtendedTags newTags;
3415 unsigned existingSerial, newSerial;
3417 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3418 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3419 * If it is not during Scanning then something went wrong!
3422 T(YAFFS_TRACE_ERROR,
3424 ("yaffs tragedy:attempt to put data chunk into a non-file"
3429 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3433 tn = yaffs_AddOrFindLevel0Tnode(dev,
3434 &in->variant.fileVariant,
3441 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3444 /* If we're scanning then we need to test for duplicates
3445 * NB This does not need to be efficient since it should only ever
3446 * happen when the power fails during a write, then only one
3447 * chunk should ever be affected.
3449 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3450 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3453 if (existingChunk > 0) {
3454 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3455 * thus we have to do a FindChunkInFile to get the real chunk id.
3457 * We have a duplicate now we need to decide which one to use:
3459 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3460 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3461 * YAFFS1: Get both sets of tags and compare serial numbers.
3465 /* Only do this for forward scanning */
3466 yaffs_ReadChunkWithTagsFromNAND(dev,
3470 /* Do a proper find */
3472 yaffs_FindChunkInFile(in, chunkInInode,
3476 if (existingChunk <= 0) {
3477 /*Hoosterman - how did this happen? */
3479 T(YAFFS_TRACE_ERROR,
3481 ("yaffs tragedy: existing chunk < 0 in scan"
3486 /* NB The deleted flags should be false, otherwise the chunks will
3487 * not be loaded during a scan
3491 newSerial = newTags.serialNumber;
3492 existingSerial = existingTags.serialNumber;
3496 (in->myDev->isYaffs2 ||
3497 existingChunk <= 0 ||
3498 ((existingSerial + 1) & 3) == newSerial)) {
3499 /* Forward scanning.
3501 * Delete the old one and drop through to update the tnode
3503 yaffs_DeleteChunk(dev, existingChunk, 1,
3506 /* Backward scanning or we want to use the existing one
3508 * Delete the new one and return early so that the tnode isn't changed
3510 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3518 if (existingChunk == 0) {
3522 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
3527 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
3530 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3532 if (chunkInNAND >= 0) {
3533 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3536 T(YAFFS_TRACE_NANDACCESS,
3537 (TSTR("Chunk %d not found zero instead" TENDSTR),
3539 /* get sane (zero) data if you read a hole */
3540 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3546 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
3550 yaffs_ExtendedTags tags;
3551 yaffs_BlockInfo *bi;
3558 block = chunkId / dev->nChunksPerBlock;
3559 page = chunkId % dev->nChunksPerBlock;
3562 if(!yaffs_CheckChunkBit(dev,block,page))
3563 T(YAFFS_TRACE_VERIFY,
3564 (TSTR("Deleting invalid chunk %d"TENDSTR),
3567 bi = yaffs_GetBlockInfo(dev, block);
3569 T(YAFFS_TRACE_DELETION,
3570 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3573 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3575 yaffs_InitialiseTags(&tags);
3577 tags.chunkDeleted = 1;
3579 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3580 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3582 dev->nUnmarkedDeletions++;
3585 /* Pull out of the management area.
3586 * If the whole block became dirty, this will kick off an erasure.
3588 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3589 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3590 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3591 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3594 yaffs_ClearChunkBit(dev, block, page);
3598 if (bi->pagesInUse == 0 &&
3599 !bi->hasShrinkHeader &&
3600 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3601 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3602 yaffs_BlockBecameDirty(dev, block);
3606 /* T(("Bad news deleting chunk %d\n",chunkId)); */
3611 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
3612 const __u8 * buffer, int nBytes,
3615 /* Find old chunk Need to do this to get serial number
3616 * Write new one and patch into tree.
3617 * Invalidate old tags.
3621 yaffs_ExtendedTags prevTags;
3624 yaffs_ExtendedTags newTags;
3626 yaffs_Device *dev = in->myDev;
3628 yaffs_CheckGarbageCollection(dev);
3630 /* Get the previous chunk at this location in the file if it exists */
3631 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3633 /* Set up new tags */
3634 yaffs_InitialiseTags(&newTags);
3636 newTags.chunkId = chunkInInode;
3637 newTags.objectId = in->objectId;
3638 newTags.serialNumber =
3639 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
3640 newTags.byteCount = nBytes;
3643 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3646 if (newChunkId >= 0) {
3647 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3649 if (prevChunkId >= 0) {
3650 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3654 yaffs_CheckFileSanity(in);
3660 /* UpdateObjectHeader updates the header on NAND for an object.
3661 * If name is not NULL, then that new name is used.
3663 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
3664 int isShrink, int shadows)
3667 yaffs_BlockInfo *bi;
3669 yaffs_Device *dev = in->myDev;
3676 yaffs_ExtendedTags newTags;
3677 yaffs_ExtendedTags oldTags;
3679 __u8 *buffer = NULL;
3680 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3682 yaffs_ObjectHeader *oh = NULL;
3684 yaffs_strcpy(oldName,_Y("silly old name"));
3688 in == dev->rootDir || /* The rootDir should also be saved */
3691 yaffs_CheckGarbageCollection(dev);
3692 yaffs_CheckObjectDetailsLoaded(in);
3694 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3695 oh = (yaffs_ObjectHeader *) buffer;
3697 prevChunkId = in->hdrChunk;
3699 if (prevChunkId > 0) {
3700 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3703 yaffs_VerifyObjectHeader(in,oh,&oldTags,0);
3705 memcpy(oldName, oh->name, sizeof(oh->name));
3708 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3710 oh->type = in->variantType;
3711 oh->yst_mode = in->yst_mode;
3712 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3714 #ifdef CONFIG_YAFFS_WINCE
3715 oh->win_atime[0] = in->win_atime[0];
3716 oh->win_ctime[0] = in->win_ctime[0];
3717 oh->win_mtime[0] = in->win_mtime[0];
3718 oh->win_atime[1] = in->win_atime[1];
3719 oh->win_ctime[1] = in->win_ctime[1];
3720 oh->win_mtime[1] = in->win_mtime[1];
3722 oh->yst_uid = in->yst_uid;
3723 oh->yst_gid = in->yst_gid;
3724 oh->yst_atime = in->yst_atime;
3725 oh->yst_mtime = in->yst_mtime;
3726 oh->yst_ctime = in->yst_ctime;
3727 oh->yst_rdev = in->yst_rdev;
3730 oh->parentObjectId = in->parent->objectId;
3732 oh->parentObjectId = 0;
3735 if (name && *name) {
3736 memset(oh->name, 0, sizeof(oh->name));
3737 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3738 } else if (prevChunkId>=0) {
3739 memcpy(oh->name, oldName, sizeof(oh->name));
3741 memset(oh->name, 0, sizeof(oh->name));
3744 oh->isShrink = isShrink;
3746 switch (in->variantType) {
3747 case YAFFS_OBJECT_TYPE_UNKNOWN:
3748 /* Should not happen */
3750 case YAFFS_OBJECT_TYPE_FILE:
3752 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3753 || oh->parentObjectId ==
3754 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3755 fileVariant.fileSize;
3757 case YAFFS_OBJECT_TYPE_HARDLINK:
3758 oh->equivalentObjectId =
3759 in->variant.hardLinkVariant.equivalentObjectId;
3761 case YAFFS_OBJECT_TYPE_SPECIAL:
3764 case YAFFS_OBJECT_TYPE_DIRECTORY:
3767 case YAFFS_OBJECT_TYPE_SYMLINK:
3768 yaffs_strncpy(oh->alias,
3769 in->variant.symLinkVariant.alias,
3770 YAFFS_MAX_ALIAS_LENGTH);
3771 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3776 yaffs_InitialiseTags(&newTags);
3778 newTags.chunkId = 0;
3779 newTags.objectId = in->objectId;
3780 newTags.serialNumber = in->serial;
3782 /* Add extra info for file header */
3784 newTags.extraHeaderInfoAvailable = 1;
3785 newTags.extraParentObjectId = oh->parentObjectId;
3786 newTags.extraFileLength = oh->fileSize;
3787 newTags.extraIsShrinkHeader = oh->isShrink;
3788 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3789 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3790 newTags.extraObjectType = in->variantType;
3792 yaffs_VerifyObjectHeader(in,oh,&newTags,1);
3794 /* Create new chunk in NAND */
3796 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3797 (prevChunkId >= 0) ? 1 : 0);
3799 if (newChunkId >= 0) {
3801 in->hdrChunk = newChunkId;
3803 if (prevChunkId >= 0) {
3804 yaffs_DeleteChunk(dev, prevChunkId, 1,
3808 if(!yaffs_ObjectHasCachedWriteData(in))
3811 /* If this was a shrink, then mark the block that the chunk lives on */
3813 bi = yaffs_GetBlockInfo(in->myDev,
3814 newChunkId /in->myDev-> nChunksPerBlock);
3815 bi->hasShrinkHeader = 1;
3820 retVal = newChunkId;
3825 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3830 /*------------------------ Short Operations Cache ----------------------------------------
3831 * In many situations where there is no high level buffering (eg WinCE) a lot of
3832 * reads might be short sequential reads, and a lot of writes may be short
3833 * sequential writes. eg. scanning/writing a jpeg file.
3834 * In these cases, a short read/write cache can provide a huge perfomance benefit
3835 * with dumb-as-a-rock code.
3836 * In Linux, the page cache provides read buffering aand the short op cache provides write
3839 * There are a limited number (~10) of cache chunks per device so that we don't
3840 * need a very intelligent search.
3843 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3845 yaffs_Device *dev = obj->myDev;
3847 yaffs_ChunkCache *cache;
3848 int nCaches = obj->myDev->nShortOpCaches;
3850 for(i = 0; i < nCaches; i++){
3851 cache = &dev->srCache[i];
3852 if (cache->object == obj &&
3861 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3863 yaffs_Device *dev = obj->myDev;
3864 int lowest = -99; /* Stop compiler whining. */
3866 yaffs_ChunkCache *cache;
3867 int chunkWritten = 0;
3868 int nCaches = obj->myDev->nShortOpCaches;
3874 /* Find the dirty cache for this object with the lowest chunk id. */
3875 for (i = 0; i < nCaches; i++) {
3876 if (dev->srCache[i].object == obj &&
3877 dev->srCache[i].dirty) {
3879 || dev->srCache[i].chunkId <
3881 cache = &dev->srCache[i];
3882 lowest = cache->chunkId;
3887 if (cache && !cache->locked) {
3888 /* Write it out and free it up */
3891 yaffs_WriteChunkDataToObject(cache->object,
3897 cache->object = NULL;
3900 } while (cache && chunkWritten > 0);
3903 /* Hoosterman, disk full while writing cache out. */
3904 T(YAFFS_TRACE_ERROR,
3905 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3912 /*yaffs_FlushEntireDeviceCache(dev)
3917 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3920 int nCaches = dev->nShortOpCaches;
3923 /* Find a dirty object in the cache and flush it...
3924 * until there are no further dirty objects.
3928 for( i = 0; i < nCaches && !obj; i++) {
3929 if (dev->srCache[i].object &&
3930 dev->srCache[i].dirty)
3931 obj = dev->srCache[i].object;
3935 yaffs_FlushFilesChunkCache(obj);
3942 /* Grab us a cache chunk for use.
3943 * First look for an empty one.
3944 * Then look for the least recently used non-dirty one.
3945 * Then look for the least recently used dirty one...., flush and look again.
3947 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
3953 if (dev->nShortOpCaches > 0) {
3954 for (i = 0; i < dev->nShortOpCaches; i++) {
3955 if (!dev->srCache[i].object)
3956 return &dev->srCache[i];
3962 usage = 0; /* just to stop the compiler grizzling */
3964 for (i = 0; i < dev->nShortOpCaches; i++) {
3965 if (!dev->srCache[i].dirty &&
3966 ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
3968 usage = dev->srCache[i].lastUse;
3974 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3981 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
3983 yaffs_ChunkCache *cache;
3984 yaffs_Object *theObj;
3989 if (dev->nShortOpCaches > 0) {
3990 /* Try find a non-dirty one... */
3992 cache = yaffs_GrabChunkCacheWorker(dev);
3995 /* They were all dirty, find the last recently used object and flush
3996 * its cache, then find again.
3997 * NB what's here is not very accurate, we actually flush the object
3998 * the last recently used page.
4001 /* With locking we can't assume we can use entry zero */
4008 for (i = 0; i < dev->nShortOpCaches; i++) {
4009 if (dev->srCache[i].object &&
4010 !dev->srCache[i].locked &&
4011 (dev->srCache[i].lastUse < usage || !cache))
4013 usage = dev->srCache[i].lastUse;
4014 theObj = dev->srCache[i].object;
4015 cache = &dev->srCache[i];
4020 if (!cache || cache->dirty) {
4021 /* Flush and try again */
4022 yaffs_FlushFilesChunkCache(theObj);
4023 cache = yaffs_GrabChunkCacheWorker(dev);
4033 /* Find a cached chunk */
4034 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
4037 yaffs_Device *dev = obj->myDev;
4039 if (dev->nShortOpCaches > 0) {
4040 for (i = 0; i < dev->nShortOpCaches; i++) {
4041 if (dev->srCache[i].object == obj &&
4042 dev->srCache[i].chunkId == chunkId) {
4045 return &dev->srCache[i];
4052 /* Mark the chunk for the least recently used algorithym */
4053 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
4057 if (dev->nShortOpCaches > 0) {
4058 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4059 /* Reset the cache usages */
4061 for (i = 1; i < dev->nShortOpCaches; i++) {
4062 dev->srCache[i].lastUse = 0;
4069 cache->lastUse = dev->srLastUse;
4077 /* Invalidate a single cache page.
4078 * Do this when a whole page gets written,
4079 * ie the short cache for this page is no longer valid.
4081 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
4083 if (object->myDev->nShortOpCaches > 0) {
4084 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4087 cache->object = NULL;
4092 /* Invalidate all the cache pages associated with this object
4093 * Do this whenever ther file is deleted or resized.
4095 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
4098 yaffs_Device *dev = in->myDev;
4100 if (dev->nShortOpCaches > 0) {
4101 /* Invalidate it. */
4102 for (i = 0; i < dev->nShortOpCaches; i++) {
4103 if (dev->srCache[i].object == in) {
4104 dev->srCache[i].object = NULL;
4110 /*--------------------- Checkpointing --------------------*/
4113 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
4115 yaffs_CheckpointValidity cp;
4117 memset(&cp,0,sizeof(cp));
4119 cp.structType = sizeof(cp);
4120 cp.magic = YAFFS_MAGIC;
4121 cp.version = YAFFS_CHECKPOINT_VERSION;
4122 cp.head = (head) ? 1 : 0;
4124 return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
4128 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4130 yaffs_CheckpointValidity cp;
4133 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4136 ok = (cp.structType == sizeof(cp)) &&
4137 (cp.magic == YAFFS_MAGIC) &&
4138 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4139 (cp.head == ((head) ? 1 : 0));
4143 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4146 cp->nErasedBlocks = dev->nErasedBlocks;
4147 cp->allocationBlock = dev->allocationBlock;
4148 cp->allocationPage = dev->allocationPage;
4149 cp->nFreeChunks = dev->nFreeChunks;
4151 cp->nDeletedFiles = dev->nDeletedFiles;
4152 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4153 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4154 cp->sequenceNumber = dev->sequenceNumber;
4155 cp->oldestDirtySequence = dev->oldestDirtySequence;
4159 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4160 yaffs_CheckpointDevice *cp)
4162 dev->nErasedBlocks = cp->nErasedBlocks;
4163 dev->allocationBlock = cp->allocationBlock;
4164 dev->allocationPage = cp->allocationPage;
4165 dev->nFreeChunks = cp->nFreeChunks;
4167 dev->nDeletedFiles = cp->nDeletedFiles;
4168 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4169 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4170 dev->sequenceNumber = cp->sequenceNumber;
4171 dev->oldestDirtySequence = cp->oldestDirtySequence;
4175 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4177 yaffs_CheckpointDevice cp;
4179 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4183 /* Write device runtime values*/
4184 yaffs_DeviceToCheckpointDevice(&cp,dev);
4185 cp.structType = sizeof(cp);
4187 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4189 /* Write block info */
4191 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4192 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
4195 /* Write chunk bits */
4197 nBytes = nBlocks * dev->chunkBitmapStride;
4198 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
4204 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4206 yaffs_CheckpointDevice cp;
4208 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4212 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4216 if(cp.structType != sizeof(cp))
4220 yaffs_CheckpointDeviceToDevice(dev,&cp);
4222 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4224 ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
4228 nBytes = nBlocks * dev->chunkBitmapStride;
4230 ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
4235 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4239 cp->objectId = obj->objectId;
4240 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4241 cp->hdrChunk = obj->hdrChunk;
4242 cp->variantType = obj->variantType;
4243 cp->deleted = obj->deleted;
4244 cp->softDeleted = obj->softDeleted;
4245 cp->unlinked = obj->unlinked;
4246 cp->fake = obj->fake;
4247 cp->renameAllowed = obj->renameAllowed;
4248 cp->unlinkAllowed = obj->unlinkAllowed;
4249 cp->serial = obj->serial;
4250 cp->nDataChunks = obj->nDataChunks;
4252 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4253 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4254 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4255 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4258 static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
4261 yaffs_Object *parent;
4263 obj->objectId = cp->objectId;
4266 parent = yaffs_FindOrCreateObjectByNumber(
4269 YAFFS_OBJECT_TYPE_DIRECTORY);
4274 yaffs_AddObjectToDirectory(parent, obj);
4276 obj->hdrChunk = cp->hdrChunk;
4277 obj->variantType = cp->variantType;
4278 obj->deleted = cp->deleted;
4279 obj->softDeleted = cp->softDeleted;
4280 obj->unlinked = cp->unlinked;
4281 obj->fake = cp->fake;
4282 obj->renameAllowed = cp->renameAllowed;
4283 obj->unlinkAllowed = cp->unlinkAllowed;
4284 obj->serial = cp->serial;
4285 obj->nDataChunks = cp->nDataChunks;
4287 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4288 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4289 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4290 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4292 if(obj->hdrChunk > 0)
4293 obj->lazyLoaded = 1;
4298 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
4299 __u32 level, int chunkOffset)
4302 yaffs_Device *dev = in->myDev;
4304 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4306 if(tnodeSize < sizeof(yaffs_Tnode))
4307 tnodeSize = sizeof(yaffs_Tnode);
4313 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
4314 if (tn->internal[i]) {
4315 ok = yaffs_CheckpointTnodeWorker(in,
4318 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4321 } else if (level == 0) {
4322 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4323 /* printf("write tnode at %d\n",baseOffset); */
4324 ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
4326 ok = (yaffs_CheckpointWrite(dev,tn,tnodeSize) == tnodeSize);
4334 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4336 __u32 endMarker = ~0;
4339 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4340 ok = yaffs_CheckpointTnodeWorker(obj,
4341 obj->variant.fileVariant.top,
4342 obj->variant.fileVariant.topLevel,
4345 ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) ==
4352 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4356 yaffs_Device *dev = obj->myDev;
4357 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4360 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4362 if(tnodeSize < sizeof(yaffs_Tnode))
4363 tnodeSize = sizeof(yaffs_Tnode);
4365 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4367 while(ok && (~baseChunk)){
4369 /* Read level 0 tnode */
4372 /* printf("read tnode at %d\n",baseChunk); */
4373 tn = yaffs_GetTnodeRaw(dev);
4375 ok = (yaffs_CheckpointRead(dev,tn,tnodeSize) == tnodeSize);
4380 ok = yaffs_AddOrFindLevel0Tnode(dev,
4388 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4392 T(YAFFS_TRACE_CHECKPOINT,(
4393 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4394 nread,baseChunk,ok));
4400 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4403 yaffs_CheckpointObject cp;
4406 struct ylist_head *lh;
4409 /* Iterate through the objects in each hash entry,
4410 * dumping them to the checkpointing stream.
4413 for(i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++){
4414 ylist_for_each(lh, &dev->objectBucket[i].list) {
4416 obj = ylist_entry(lh, yaffs_Object, hashLink);
4417 if (!obj->deferedFree) {
4418 yaffs_ObjectToCheckpointObject(&cp,obj);
4419 cp.structType = sizeof(cp);
4421 T(YAFFS_TRACE_CHECKPOINT,(
4422 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
4423 cp.objectId,cp.parentId,cp.variantType,cp.hdrChunk,(unsigned) obj));
4425 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4427 if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4428 ok = yaffs_WriteCheckpointTnodes(obj);
4435 /* Dump end of list */
4436 memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
4437 cp.structType = sizeof(cp);
4440 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4445 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4448 yaffs_CheckpointObject cp;
4451 yaffs_Object *hardList = NULL;
4453 while(ok && !done) {
4454 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4455 if(cp.structType != sizeof(cp)) {
4456 T(YAFFS_TRACE_CHECKPOINT,(TSTR("struct size %d instead of %d ok %d"TENDSTR),
4457 cp.structType,sizeof(cp),ok));
4461 T(YAFFS_TRACE_CHECKPOINT,(TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4462 cp.objectId,cp.parentId,cp.variantType,cp.hdrChunk));
4464 if(ok && cp.objectId == ~0)
4467 obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
4469 yaffs_CheckpointObjectToObject(obj,&cp);
4470 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4471 ok = yaffs_ReadCheckpointTnodes(obj);
4472 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4473 obj->hardLinks.next =
4474 (struct ylist_head *)
4484 yaffs_HardlinkFixup(dev,hardList);
4489 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4491 __u32 checkpointSum;
4494 yaffs_GetCheckpointSum(dev,&checkpointSum);
4496 ok = (yaffs_CheckpointWrite(dev,&checkpointSum,sizeof(checkpointSum)) == sizeof(checkpointSum));
4504 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4506 __u32 checkpointSum0;
4507 __u32 checkpointSum1;
4510 yaffs_GetCheckpointSum(dev,&checkpointSum0);
4512 ok = (yaffs_CheckpointRead(dev,&checkpointSum1,sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4517 if(checkpointSum0 != checkpointSum1)
4524 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4529 if(dev->skipCheckpointWrite || !dev->isYaffs2){
4530 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint write" TENDSTR)));
4535 ok = yaffs_CheckpointOpen(dev,1);
4538 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4539 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
4542 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint device" TENDSTR)));
4543 ok = yaffs_WriteCheckpointDevice(dev);
4546 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint objects" TENDSTR)));
4547 ok = yaffs_WriteCheckpointObjects(dev);
4550 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4551 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
4555 ok = yaffs_WriteCheckpointSum(dev);
4559 if(!yaffs_CheckpointClose(dev))
4563 dev->isCheckpointed = 1;
4565 dev->isCheckpointed = 0;
4567 return dev->isCheckpointed;
4570 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4574 if(dev->skipCheckpointRead || !dev->isYaffs2){
4575 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint read" TENDSTR)));
4580 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
4583 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4584 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
4587 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint device" TENDSTR)));
4588 ok = yaffs_ReadCheckpointDevice(dev);
4591 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint objects" TENDSTR)));
4592 ok = yaffs_ReadCheckpointObjects(dev);
4595 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4596 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
4600 ok = yaffs_ReadCheckpointSum(dev);
4601 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint checksum %d" TENDSTR),ok));
4604 if(!yaffs_CheckpointClose(dev))
4608 dev->isCheckpointed = 1;
4610 dev->isCheckpointed = 0;
4616 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4618 if(dev->isCheckpointed ||
4619 dev->blocksInCheckpoint > 0){
4620 dev->isCheckpointed = 0;
4621 yaffs_CheckpointInvalidateStream(dev);
4622 if(dev->superBlock && dev->markSuperBlockDirty)
4623 dev->markSuperBlockDirty(dev->superBlock);
4628 int yaffs_CheckpointSave(yaffs_Device *dev)
4631 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4633 yaffs_VerifyObjects(dev);
4634 yaffs_VerifyBlocks(dev);
4635 yaffs_VerifyFreeChunks(dev);
4637 if(!dev->isCheckpointed) {
4638 yaffs_InvalidateCheckpoint(dev);
4639 yaffs_WriteCheckpointData(dev);
4642 T(YAFFS_TRACE_ALWAYS,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4644 return dev->isCheckpointed;
4647 int yaffs_CheckpointRestore(yaffs_Device *dev)
4650 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4652 retval = yaffs_ReadCheckpointData(dev);
4654 if(dev->isCheckpointed){
4655 yaffs_VerifyObjects(dev);
4656 yaffs_VerifyBlocks(dev);
4657 yaffs_VerifyFreeChunks(dev);
4660 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4665 /*--------------------- File read/write ------------------------
4666 * Read and write have very similar structures.
4667 * In general the read/write has three parts to it
4668 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4669 * Some complete chunks
4670 * An incomplete chunk to end off with
4672 * Curve-balls: the first chunk might also be the last chunk.
4675 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, loff_t offset,
4684 yaffs_ChunkCache *cache;
4691 //chunk = offset / dev->nDataBytesPerChunk + 1;
4692 //start = offset % dev->nDataBytesPerChunk;
4693 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4696 /* OK now check for the curveball where the start and end are in
4699 if ((start + n) < dev->nDataBytesPerChunk) {
4702 nToCopy = dev->nDataBytesPerChunk - start;
4705 cache = yaffs_FindChunkCache(in, chunk);
4707 /* If the chunk is already in the cache or it is less than a whole chunk
4708 * or we're using inband tags then use the cache (if there is caching)
4709 * else bypass the cache.
4711 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4712 if (dev->nShortOpCaches > 0) {
4714 /* If we can't find the data in the cache, then load it up. */
4717 cache = yaffs_GrabChunkCache(in->myDev);
4719 cache->chunkId = chunk;
4722 yaffs_ReadChunkDataFromObject(in, chunk,
4728 yaffs_UseChunkCache(dev, cache, 0);
4732 #ifdef CONFIG_YAFFS_WINCE
4733 yfsd_UnlockYAFFS(TRUE);
4735 memcpy(buffer, &cache->data[start], nToCopy);
4737 #ifdef CONFIG_YAFFS_WINCE
4738 yfsd_LockYAFFS(TRUE);
4742 /* Read into the local buffer then copy..*/
4745 yaffs_GetTempBuffer(dev, __LINE__);
4746 yaffs_ReadChunkDataFromObject(in, chunk,
4748 #ifdef CONFIG_YAFFS_WINCE
4749 yfsd_UnlockYAFFS(TRUE);
4751 memcpy(buffer, &localBuffer[start], nToCopy);
4753 #ifdef CONFIG_YAFFS_WINCE
4754 yfsd_LockYAFFS(TRUE);
4756 yaffs_ReleaseTempBuffer(dev, localBuffer,
4761 #ifdef CONFIG_YAFFS_WINCE
4762 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4764 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4765 * This is because we otherwise screw up WinCE's memory mapper
4767 yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
4769 #ifdef CONFIG_YAFFS_WINCE
4770 yfsd_UnlockYAFFS(TRUE);
4772 memcpy(buffer, localBuffer, dev->nDataBytesPerChunk);
4774 #ifdef CONFIG_YAFFS_WINCE
4775 yfsd_LockYAFFS(TRUE);
4776 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4780 /* A full chunk. Read directly into the supplied buffer. */
4781 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4795 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, loff_t offset,
4796 int nBytes, int writeThrough)
4805 int startOfWrite = offset;
4806 int chunkWritten = 0;
4813 while (n > 0 && chunkWritten >= 0) {
4814 //chunk = offset / dev->nDataBytesPerChunk + 1;
4815 //start = offset % dev->nDataBytesPerChunk;
4816 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4819 /* OK now check for the curveball where the start and end are in
4823 if ((start + n) < dev->nDataBytesPerChunk) {
4826 /* Now folks, to calculate how many bytes to write back....
4827 * If we're overwriting and not writing to then end of file then
4828 * we need to write back as much as was there before.
4832 in->variant.fileVariant.fileSize -
4833 ((chunk - 1) * dev->nDataBytesPerChunk);
4835 if (nBytesRead > dev->nDataBytesPerChunk) {
4836 nBytesRead = dev->nDataBytesPerChunk;
4841 (start + n)) ? nBytesRead : (start + n);
4844 nToCopy = dev->nDataBytesPerChunk - start;
4845 nToWriteBack = dev->nDataBytesPerChunk;
4848 if (nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4849 /* An incomplete start or end chunk (or maybe both start and end chunk),
4850 * or we're using inband tags, so we want to use the cache buffers.
4852 if (dev->nShortOpCaches > 0) {
4853 yaffs_ChunkCache *cache;
4854 /* If we can't find the data in the cache, then load the cache */
4855 cache = yaffs_FindChunkCache(in, chunk);
4858 && yaffs_CheckSpaceForAllocation(in->
4860 cache = yaffs_GrabChunkCache(in->myDev);
4862 cache->chunkId = chunk;
4865 yaffs_ReadChunkDataFromObject(in, chunk,
4871 !yaffs_CheckSpaceForAllocation(in->myDev)){
4872 /* Drop the cache if it was a read cache item and
4873 * no space check has been made for it.
4879 yaffs_UseChunkCache(dev, cache, 1);
4881 #ifdef CONFIG_YAFFS_WINCE
4882 yfsd_UnlockYAFFS(TRUE);
4885 memcpy(&cache->data[start], buffer,
4888 #ifdef CONFIG_YAFFS_WINCE
4889 yfsd_LockYAFFS(TRUE);
4892 cache->nBytes = nToWriteBack;
4896 yaffs_WriteChunkDataToObject
4899 cache->data, cache->nBytes,
4905 chunkWritten = -1; /* fail the write */
4908 /* An incomplete start or end chunk (or maybe both start and end chunk)
4909 * Read into the local buffer then copy, then copy over and write back.
4913 yaffs_GetTempBuffer(dev, __LINE__);
4915 yaffs_ReadChunkDataFromObject(in, chunk,
4918 #ifdef CONFIG_YAFFS_WINCE
4919 yfsd_UnlockYAFFS(TRUE);
4922 memcpy(&localBuffer[start], buffer, nToCopy);
4924 #ifdef CONFIG_YAFFS_WINCE
4925 yfsd_LockYAFFS(TRUE);
4928 yaffs_WriteChunkDataToObject(in, chunk,
4933 yaffs_ReleaseTempBuffer(dev, localBuffer,
4939 /* A full chunk. Write directly from the supplied buffer. */
4941 #ifdef CONFIG_YAFFS_WINCE
4942 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4943 * This is because we otherwise screw up WinCE's memory mapper
4945 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4946 #ifdef CONFIG_YAFFS_WINCE
4947 yfsd_UnlockYAFFS(TRUE);
4949 memcpy(localBuffer, buffer, dev->nDataBytesPerChunk);
4950 #ifdef CONFIG_YAFFS_WINCE
4951 yfsd_LockYAFFS(TRUE);
4954 yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
4955 dev->nDataBytesPerChunk,
4957 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4961 yaffs_WriteChunkDataToObject(in, chunk, buffer,
4962 dev->nDataBytesPerChunk,
4965 /* Since we've overwritten the cached data, we better invalidate it. */
4966 yaffs_InvalidateChunkCache(in, chunk);
4969 if (chunkWritten >= 0) {
4978 /* Update file object */
4980 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
4981 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4990 /* ---------------------- File resizing stuff ------------------ */
4992 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
4995 yaffs_Device *dev = in->myDev;
4996 int oldFileSize = in->variant.fileVariant.fileSize;
4998 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
5000 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
5001 dev->nDataBytesPerChunk;
5005 /* Delete backwards so that we don't end up with holes if
5006 * power is lost part-way through the operation.
5008 for (i = lastDel; i >= startDel; i--) {
5009 /* NB this could be optimised somewhat,
5010 * eg. could retrieve the tags and write them without
5011 * using yaffs_DeleteChunk
5014 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5017 (dev->internalStartBlock * dev->nChunksPerBlock)
5019 ((dev->internalEndBlock +
5020 1) * dev->nChunksPerBlock)) {
5021 T(YAFFS_TRACE_ALWAYS,
5022 (TSTR("Found daft chunkId %d for %d" TENDSTR),
5026 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5033 int yaffs_ResizeFile(yaffs_Object * in, loff_t newSize)
5036 int oldFileSize = in->variant.fileVariant.fileSize;
5037 __u32 newSizeOfPartialChunk;
5040 yaffs_Device *dev = in->myDev;
5042 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5044 yaffs_FlushFilesChunkCache(in);
5045 yaffs_InvalidateWholeChunkCache(in);
5047 yaffs_CheckGarbageCollection(dev);
5049 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
5053 if (newSize == oldFileSize) {
5057 if (newSize < oldFileSize) {
5059 yaffs_PruneResizedChunks(in, newSize);
5061 if (newSizeOfPartialChunk != 0) {
5062 int lastChunk = 1 + newFullChunks;
5064 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5066 /* Got to read and rewrite the last chunk with its new size and zero pad */
5067 yaffs_ReadChunkDataFromObject(in, lastChunk,
5070 memset(localBuffer + newSizeOfPartialChunk, 0,
5071 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5073 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5074 newSizeOfPartialChunk, 1);
5076 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5079 in->variant.fileVariant.fileSize = newSize;
5081 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5083 /* newsSize > oldFileSize */
5084 in->variant.fileVariant.fileSize = newSize;
5089 /* Write a new object header.
5090 * show we've shrunk the file, if need be
5091 * Do this only if the file is not in the deleted directories.
5094 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5095 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
5096 yaffs_UpdateObjectHeader(in, NULL, 0,
5097 (newSize < oldFileSize) ? 1 : 0, 0);
5103 loff_t yaffs_GetFileSize(yaffs_Object * obj)
5105 obj = yaffs_GetEquivalentObject(obj);
5107 switch (obj->variantType) {
5108 case YAFFS_OBJECT_TYPE_FILE:
5109 return obj->variant.fileVariant.fileSize;
5110 case YAFFS_OBJECT_TYPE_SYMLINK:
5111 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5119 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
5123 yaffs_FlushFilesChunkCache(in);
5125 #ifdef CONFIG_YAFFS_WINCE
5126 yfsd_WinFileTimeNow(in->win_mtime);
5129 in->yst_mtime = Y_CURRENT_TIME;
5135 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5136 0) ? YAFFS_OK : YAFFS_FAIL;
5145 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
5148 /* First off, invalidate the file's data in the cache, without flushing. */
5149 yaffs_InvalidateWholeChunkCache(in);
5151 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5152 /* Move to the unlinked directory so we have a record that it was deleted. */
5153 yaffs_ChangeObjectName(in, in->myDev->deletedDir,_Y("deleted"), 0, 0);
5157 yaffs_RemoveObjectFromDirectory(in);
5158 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5161 yaffs_FreeObject(in);
5166 /* yaffs_DeleteFile deletes the whole file data
5167 * and the inode associated with the file.
5168 * It does not delete the links associated with the file.
5170 static int yaffs_UnlinkFile(yaffs_Object * in)
5174 int immediateDeletion = 0;
5179 immediateDeletion = 1;
5183 if (in->inUse <= 0) {
5184 immediateDeletion = 1;
5188 if (immediateDeletion) {
5190 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5191 _Y("deleted"), 0, 0);
5192 T(YAFFS_TRACE_TRACING,
5193 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5196 in->myDev->nDeletedFiles++;
5197 if (0 && in->myDev->isYaffs2) {
5198 yaffs_ResizeFile(in, 0);
5200 yaffs_SoftDeleteFile(in);
5203 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5204 _Y("unlinked"), 0, 0);
5211 int yaffs_DeleteFile(yaffs_Object * in)
5213 int retVal = YAFFS_OK;
5215 if (in->nDataChunks > 0) {
5216 /* Use soft deletion if there is data in the file */
5217 if (!in->unlinked) {
5218 retVal = yaffs_UnlinkFile(in);
5220 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5222 in->myDev->nDeletedFiles++;
5223 yaffs_SoftDeleteFile(in);
5225 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
5227 /* The file has no data chunks so we toss it immediately */
5228 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5229 in->variant.fileVariant.top = NULL;
5230 yaffs_DoGenericObjectDeletion(in);
5236 static int yaffs_DeleteDirectory(yaffs_Object * in)
5238 /* First check that the directory is empty. */
5239 if (ylist_empty(&in->variant.directoryVariant.children)) {
5240 return yaffs_DoGenericObjectDeletion(in);
5247 static int yaffs_DeleteSymLink(yaffs_Object * in)
5249 YFREE(in->variant.symLinkVariant.alias);
5251 return yaffs_DoGenericObjectDeletion(in);
5254 static int yaffs_DeleteHardLink(yaffs_Object * in)
5256 /* remove this hardlink from the list assocaited with the equivalent
5259 ylist_del(&in->hardLinks);
5260 return yaffs_DoGenericObjectDeletion(in);
5263 static void yaffs_DestroyObject(yaffs_Object * obj)
5265 switch (obj->variantType) {
5266 case YAFFS_OBJECT_TYPE_FILE:
5267 yaffs_DeleteFile(obj);
5269 case YAFFS_OBJECT_TYPE_DIRECTORY:
5270 yaffs_DeleteDirectory(obj);
5272 case YAFFS_OBJECT_TYPE_SYMLINK:
5273 yaffs_DeleteSymLink(obj);
5275 case YAFFS_OBJECT_TYPE_HARDLINK:
5276 yaffs_DeleteHardLink(obj);
5278 case YAFFS_OBJECT_TYPE_SPECIAL:
5279 yaffs_DoGenericObjectDeletion(obj);
5281 case YAFFS_OBJECT_TYPE_UNKNOWN:
5282 break; /* should not happen. */
5286 static int yaffs_UnlinkWorker(yaffs_Object * obj)
5289 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5290 return yaffs_DeleteHardLink(obj);
5291 } else if (!ylist_empty(&obj->hardLinks)) {
5292 /* Curve ball: We're unlinking an object that has a hardlink.
5294 * This problem arises because we are not strictly following
5295 * The Linux link/inode model.
5297 * We can't really delete the object.
5298 * Instead, we do the following:
5299 * - Select a hardlink.
5300 * - Unhook it from the hard links
5301 * - Unhook it from its parent directory (so that the rename can work)
5302 * - Rename the object to the hardlink's name.
5303 * - Delete the hardlink
5308 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5310 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5312 ylist_del_init(&hl->hardLinks);
5313 ylist_del_init(&hl->siblings);
5315 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5317 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
5319 if (retVal == YAFFS_OK) {
5320 retVal = yaffs_DoGenericObjectDeletion(hl);
5325 switch (obj->variantType) {
5326 case YAFFS_OBJECT_TYPE_FILE:
5327 return yaffs_UnlinkFile(obj);
5329 case YAFFS_OBJECT_TYPE_DIRECTORY:
5330 return yaffs_DeleteDirectory(obj);
5332 case YAFFS_OBJECT_TYPE_SYMLINK:
5333 return yaffs_DeleteSymLink(obj);
5335 case YAFFS_OBJECT_TYPE_SPECIAL:
5336 return yaffs_DoGenericObjectDeletion(obj);
5338 case YAFFS_OBJECT_TYPE_HARDLINK:
5339 case YAFFS_OBJECT_TYPE_UNKNOWN:
5347 static int yaffs_UnlinkObject( yaffs_Object *obj)
5350 if (obj && obj->unlinkAllowed) {
5351 return yaffs_UnlinkWorker(obj);
5357 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
5361 obj = yaffs_FindObjectByName(dir, name);
5362 return yaffs_UnlinkObject(obj);
5365 /*----------------------- Initialisation Scanning ---------------------- */
5367 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
5368 int backwardScanning)
5372 if (!backwardScanning) {
5373 /* Handle YAFFS1 forward scanning case
5374 * For YAFFS1 we always do the deletion
5378 /* Handle YAFFS2 case (backward scanning)
5379 * If the shadowed object exists then ignore.
5381 if (yaffs_FindObjectByNumber(dev, objId)) {
5386 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5387 * We put it in unlinked dir to be cleaned up after the scanning
5390 yaffs_FindOrCreateObjectByNumber(dev, objId,
5391 YAFFS_OBJECT_TYPE_FILE);
5392 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5393 obj->variant.fileVariant.shrinkSize = 0;
5394 obj->valid = 1; /* So that we don't read any other info for this file */
5404 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5411 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5413 in = yaffs_FindObjectByNumber(dev,
5414 hl->variant.hardLinkVariant.
5415 equivalentObjectId);
5418 /* Add the hardlink pointers */
5419 hl->variant.hardLinkVariant.equivalentObject = in;
5420 ylist_add(&hl->hardLinks, &in->hardLinks);
5422 /* Todo Need to report/handle this better.
5423 * Got a problem... hardlink to a non-existant object
5425 hl->variant.hardLinkVariant.equivalentObject = NULL;
5426 YINIT_LIST_HEAD(&hl->hardLinks);
5438 static int ybicmp(const void *a, const void *b){
5439 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5440 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5441 register int ablock = ((yaffs_BlockIndex *)a)->block;
5442 register int bblock = ((yaffs_BlockIndex *)b)->block;
5444 return ablock - bblock;
5451 struct yaffs_ShadowFixerStruct {
5454 struct yaffs_ShadowFixerStruct *next;
5457 static int yaffs_Scan(yaffs_Device * dev)
5459 yaffs_ExtendedTags tags;
5469 yaffs_BlockState state;
5470 yaffs_Object *hardList = NULL;
5471 yaffs_BlockInfo *bi;
5472 __u32 sequenceNumber;
5473 yaffs_ObjectHeader *oh;
5475 yaffs_Object *parent;
5477 int alloc_failed = 0;
5479 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5487 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5488 dev->internalStartBlock, dev->internalEndBlock));
5490 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5492 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5494 /* Scan all the blocks to determine their state */
5495 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5496 bi = yaffs_GetBlockInfo(dev, blk);
5497 yaffs_ClearChunkBits(dev, blk);
5499 bi->softDeletions = 0;
5501 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5503 bi->blockState = state;
5504 bi->sequenceNumber = sequenceNumber;
5506 T(YAFFS_TRACE_SCAN_DEBUG,
5507 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5508 state, sequenceNumber));
5510 if (state == YAFFS_BLOCK_STATE_DEAD) {
5511 T(YAFFS_TRACE_BAD_BLOCKS,
5512 (TSTR("block %d is bad" TENDSTR), blk));
5513 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5514 T(YAFFS_TRACE_SCAN_DEBUG,
5515 (TSTR("Block empty " TENDSTR)));
5516 dev->nErasedBlocks++;
5517 dev->nFreeChunks += dev->nChunksPerBlock;
5521 startIterator = dev->internalStartBlock;
5522 endIterator = dev->internalEndBlock;
5524 /* For each block.... */
5525 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5532 blk = blockIterator;
5534 bi = yaffs_GetBlockInfo(dev, blk);
5535 state = bi->blockState;
5539 /* For each chunk in each block that needs scanning....*/
5540 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5541 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5542 /* Read the tags and decide what to do */
5543 chunk = blk * dev->nChunksPerBlock + c;
5545 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5548 /* Let's have a good look at this chunk... */
5550 if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
5556 /*T((" %d %d deleted\n",blk,c)); */
5557 } else if (!tags.chunkUsed) {
5558 /* An unassigned chunk in the block
5559 * This means that either the block is empty or
5560 * this is the one being allocated from
5564 /* We're looking at the first chunk in the block so the block is unused */
5565 state = YAFFS_BLOCK_STATE_EMPTY;
5566 dev->nErasedBlocks++;
5568 /* this is the block being allocated from */
5571 (" Allocating from %d %d" TENDSTR),
5573 state = YAFFS_BLOCK_STATE_ALLOCATING;
5574 dev->allocationBlock = blk;
5575 dev->allocationPage = c;
5576 dev->allocationBlockFinder = blk;
5577 /* Set it to here to encourage the allocator to go forth from here. */
5581 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5582 } else if (tags.chunkId > 0) {
5583 /* chunkId > 0 so it is a data chunk... */
5584 unsigned int endpos;
5586 yaffs_SetChunkBit(dev, blk, c);
5589 in = yaffs_FindOrCreateObjectByNumber(dev,
5592 YAFFS_OBJECT_TYPE_FILE);
5593 /* PutChunkIntoFile checks for a clash (two data chunks with
5594 * the same chunkId).
5601 if(!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,1))
5606 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5609 in->variantType == YAFFS_OBJECT_TYPE_FILE
5610 && in->variant.fileVariant.scannedFileSize <
5612 in->variant.fileVariant.
5613 scannedFileSize = endpos;
5614 if (!dev->useHeaderFileSize) {
5615 in->variant.fileVariant.
5617 in->variant.fileVariant.
5622 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
5624 /* chunkId == 0, so it is an ObjectHeader.
5625 * Thus, we read in the object header and make the object
5627 yaffs_SetChunkBit(dev, blk, c);
5630 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5634 oh = (yaffs_ObjectHeader *) chunkData;
5636 in = yaffs_FindObjectByNumber(dev,
5638 if (in && in->variantType != oh->type) {
5639 /* This should not happen, but somehow
5640 * Wev'e ended up with an objectId that has been reused but not yet
5641 * deleted, and worse still it has changed type. Delete the old object.
5644 yaffs_DestroyObject(in);
5649 in = yaffs_FindOrCreateObjectByNumber(dev,
5657 if (in && oh->shadowsObject > 0) {
5659 struct yaffs_ShadowFixerStruct *fixer;
5660 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
5662 fixer-> next = shadowFixerList;
5663 shadowFixerList = fixer;
5664 fixer->objectId = tags.objectId;
5665 fixer->shadowedId = oh->shadowsObject;
5670 if (in && in->valid) {
5671 /* We have already filled this one. We have a duplicate and need to resolve it. */
5673 unsigned existingSerial = in->serial;
5674 unsigned newSerial = tags.serialNumber;
5676 if (((existingSerial + 1) & 3) == newSerial) {
5677 /* Use new one - destroy the exisiting one */
5678 yaffs_DeleteChunk(dev,
5683 /* Use existing - destroy this one. */
5684 yaffs_DeleteChunk(dev, chunk, 1,
5689 if (in && !in->valid &&
5690 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5691 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5692 /* We only load some info, don't fiddle with directory structure */
5694 in->variantType = oh->type;
5696 in->yst_mode = oh->yst_mode;
5697 #ifdef CONFIG_YAFFS_WINCE
5698 in->win_atime[0] = oh->win_atime[0];
5699 in->win_ctime[0] = oh->win_ctime[0];
5700 in->win_mtime[0] = oh->win_mtime[0];
5701 in->win_atime[1] = oh->win_atime[1];
5702 in->win_ctime[1] = oh->win_ctime[1];
5703 in->win_mtime[1] = oh->win_mtime[1];
5705 in->yst_uid = oh->yst_uid;
5706 in->yst_gid = oh->yst_gid;
5707 in->yst_atime = oh->yst_atime;
5708 in->yst_mtime = oh->yst_mtime;
5709 in->yst_ctime = oh->yst_ctime;
5710 in->yst_rdev = oh->yst_rdev;
5712 in->hdrChunk = chunk;
5714 } else if (in && !in->valid) {
5715 /* we need to load this info */
5718 in->variantType = oh->type;
5720 in->yst_mode = oh->yst_mode;
5721 #ifdef CONFIG_YAFFS_WINCE
5722 in->win_atime[0] = oh->win_atime[0];
5723 in->win_ctime[0] = oh->win_ctime[0];
5724 in->win_mtime[0] = oh->win_mtime[0];
5725 in->win_atime[1] = oh->win_atime[1];
5726 in->win_ctime[1] = oh->win_ctime[1];
5727 in->win_mtime[1] = oh->win_mtime[1];
5729 in->yst_uid = oh->yst_uid;
5730 in->yst_gid = oh->yst_gid;
5731 in->yst_atime = oh->yst_atime;
5732 in->yst_mtime = oh->yst_mtime;
5733 in->yst_ctime = oh->yst_ctime;
5734 in->yst_rdev = oh->yst_rdev;
5736 in->hdrChunk = chunk;
5738 yaffs_SetObjectName(in, oh->name);
5741 /* directory stuff...
5746 yaffs_FindOrCreateObjectByNumber
5747 (dev, oh->parentObjectId,
5748 YAFFS_OBJECT_TYPE_DIRECTORY);
5749 if (parent->variantType ==
5750 YAFFS_OBJECT_TYPE_UNKNOWN) {
5751 /* Set up as a directory */
5752 parent->variantType =
5753 YAFFS_OBJECT_TYPE_DIRECTORY;
5754 YINIT_LIST_HEAD(&parent->variant.
5757 } else if (parent->variantType !=
5758 YAFFS_OBJECT_TYPE_DIRECTORY)
5760 /* Hoosterman, another problem....
5761 * We're trying to use a non-directory as a directory
5764 T(YAFFS_TRACE_ERROR,
5766 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
5768 parent = dev->lostNFoundDir;
5771 yaffs_AddObjectToDirectory(parent, in);
5773 if (0 && (parent == dev->deletedDir ||
5774 parent == dev->unlinkedDir)) {
5775 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
5776 dev->nDeletedFiles++;
5778 /* Note re hardlinks.
5779 * Since we might scan a hardlink before its equivalent object is scanned
5780 * we put them all in a list.
5781 * After scanning is complete, we should have all the objects, so we run through this
5782 * list and fix up all the chains.
5785 switch (in->variantType) {
5786 case YAFFS_OBJECT_TYPE_UNKNOWN:
5787 /* Todo got a problem */
5789 case YAFFS_OBJECT_TYPE_FILE:
5790 if (dev->useHeaderFileSize)
5792 in->variant.fileVariant.
5797 case YAFFS_OBJECT_TYPE_HARDLINK:
5798 in->variant.hardLinkVariant.
5799 equivalentObjectId =
5800 oh->equivalentObjectId;
5801 in->hardLinks.next =
5802 (struct ylist_head *)
5806 case YAFFS_OBJECT_TYPE_DIRECTORY:
5809 case YAFFS_OBJECT_TYPE_SPECIAL:
5812 case YAFFS_OBJECT_TYPE_SYMLINK:
5813 in->variant.symLinkVariant.alias =
5814 yaffs_CloneString(oh->alias);
5815 if(!in->variant.symLinkVariant.alias)
5820 if (parent == dev->deletedDir) {
5821 yaffs_DestroyObject(in);
5822 bi->hasShrinkHeader = 1;
5828 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5829 /* If we got this far while scanning, then the block is fully allocated.*/
5830 state = YAFFS_BLOCK_STATE_FULL;
5833 bi->blockState = state;
5835 /* Now let's see if it was dirty */
5836 if (bi->pagesInUse == 0 &&
5837 !bi->hasShrinkHeader &&
5838 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5839 yaffs_BlockBecameDirty(dev, blk);
5845 /* Ok, we've done all the scanning.
5846 * Fix up the hard link chains.
5847 * We should now have scanned all the objects, now it's time to add these
5851 yaffs_HardlinkFixup(dev,hardList);
5853 /* Handle the unlinked files. Since they were left in an unlinked state we should
5857 struct ylist_head *i;
5858 struct ylist_head *n;
5861 /* Soft delete all the unlinked files */
5862 ylist_for_each_safe(i, n,
5863 &dev->unlinkedDir->variant.directoryVariant.
5866 l = ylist_entry(i, yaffs_Object, siblings);
5867 yaffs_DestroyObject(l);
5872 /* Fix up any shadowed objects */
5874 struct yaffs_ShadowFixerStruct *fixer;
5877 while(shadowFixerList){
5878 fixer = shadowFixerList;
5879 shadowFixerList = fixer->next;
5880 /* Complete the rename transaction by deleting the shadowed object
5881 * then setting the object header to unshadowed.
5883 obj = yaffs_FindObjectByNumber(dev,fixer->shadowedId);
5885 yaffs_DestroyObject(obj);
5887 obj = yaffs_FindObjectByNumber(dev,fixer->objectId);
5889 yaffs_UpdateObjectHeader(obj,NULL,1,0,0);
5896 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5902 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5908 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5911 yaffs_ObjectHeader *oh;
5913 yaffs_ExtendedTags tags;
5915 int alloc_failed = 0;
5923 T(YAFFS_TRACE_SCAN,(TSTR("details for object %d %s loaded" TENDSTR),
5925 in->lazyLoaded ? "not yet" : "already"));
5928 if(in->lazyLoaded && in->hdrChunk > 0){
5930 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5932 result = yaffs_ReadChunkWithTagsFromNAND(dev,in->hdrChunk,chunkData,&tags);
5933 oh = (yaffs_ObjectHeader *) chunkData;
5935 in->yst_mode = oh->yst_mode;
5936 #ifdef CONFIG_YAFFS_WINCE
5937 in->win_atime[0] = oh->win_atime[0];
5938 in->win_ctime[0] = oh->win_ctime[0];
5939 in->win_mtime[0] = oh->win_mtime[0];
5940 in->win_atime[1] = oh->win_atime[1];
5941 in->win_ctime[1] = oh->win_ctime[1];
5942 in->win_mtime[1] = oh->win_mtime[1];
5944 in->yst_uid = oh->yst_uid;
5945 in->yst_gid = oh->yst_gid;
5946 in->yst_atime = oh->yst_atime;
5947 in->yst_mtime = oh->yst_mtime;
5948 in->yst_ctime = oh->yst_ctime;
5949 in->yst_rdev = oh->yst_rdev;
5952 yaffs_SetObjectName(in, oh->name);
5954 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
5955 in->variant.symLinkVariant.alias =
5956 yaffs_CloneString(oh->alias);
5957 if(!in->variant.symLinkVariant.alias)
5958 alloc_failed = 1; /* Not returned to caller */
5961 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
5965 static int yaffs_ScanBackwards(yaffs_Device * dev)
5967 yaffs_ExtendedTags tags;
5972 int nBlocksToScan = 0;
5978 yaffs_BlockState state;
5979 yaffs_Object *hardList = NULL;
5980 yaffs_BlockInfo *bi;
5981 __u32 sequenceNumber;
5982 yaffs_ObjectHeader *oh;
5984 yaffs_Object *parent;
5985 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5991 int foundChunksInBlock;
5992 int equivalentObjectId;
5993 int alloc_failed = 0;
5996 yaffs_BlockIndex *blockIndex = NULL;
5997 int altBlockIndex = 0;
5999 if (!dev->isYaffs2) {
6001 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6007 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
6008 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6011 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6013 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6016 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6022 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6026 dev->blocksInCheckpoint = 0;
6028 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6030 /* Scan all the blocks to determine their state */
6031 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6032 bi = yaffs_GetBlockInfo(dev, blk);
6033 yaffs_ClearChunkBits(dev, blk);
6035 bi->softDeletions = 0;
6037 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6039 bi->blockState = state;
6040 bi->sequenceNumber = sequenceNumber;
6042 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6043 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6045 T(YAFFS_TRACE_SCAN_DEBUG,
6046 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6047 state, sequenceNumber));
6050 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
6051 dev->blocksInCheckpoint++;
6053 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6054 T(YAFFS_TRACE_BAD_BLOCKS,
6055 (TSTR("block %d is bad" TENDSTR), blk));
6056 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6057 T(YAFFS_TRACE_SCAN_DEBUG,
6058 (TSTR("Block empty " TENDSTR)));
6059 dev->nErasedBlocks++;
6060 dev->nFreeChunks += dev->nChunksPerBlock;
6061 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6063 /* Determine the highest sequence number */
6064 if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6065 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6067 blockIndex[nBlocksToScan].seq = sequenceNumber;
6068 blockIndex[nBlocksToScan].block = blk;
6072 if (sequenceNumber >= dev->sequenceNumber) {
6073 dev->sequenceNumber = sequenceNumber;
6076 /* TODO: Nasty sequence number! */
6079 ("Block scanning block %d has bad sequence number %d"
6080 TENDSTR), blk, sequenceNumber));
6087 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6093 /* Sort the blocks */
6094 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6096 /* Use qsort now. */
6097 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6101 /* Dungy old bubble sort... */
6103 yaffs_BlockIndex temp;
6107 for (i = 0; i < nBlocksToScan; i++)
6108 for (j = i + 1; j < nBlocksToScan; j++)
6109 if (blockIndex[i].seq > blockIndex[j].seq) {
6110 temp = blockIndex[j];
6111 blockIndex[j] = blockIndex[i];
6112 blockIndex[i] = temp;
6119 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6121 /* Now scan the blocks looking at the data. */
6123 endIterator = nBlocksToScan - 1;
6124 T(YAFFS_TRACE_SCAN_DEBUG,
6125 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6127 /* For each block.... backwards */
6128 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6130 /* Cooperative multitasking! This loop can run for so
6131 long that watchdog timers expire. */
6134 /* get the block to scan in the correct order */
6135 blk = blockIndex[blockIterator].block;
6137 bi = yaffs_GetBlockInfo(dev, blk);
6140 state = bi->blockState;
6144 /* For each chunk in each block that needs scanning.... */
6145 foundChunksInBlock = 0;
6146 for (c = dev->nChunksPerBlock - 1;
6147 !alloc_failed && c >= 0 &&
6148 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6149 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6150 /* Scan backwards...
6151 * Read the tags and decide what to do
6154 chunk = blk * dev->nChunksPerBlock + c;
6156 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6159 /* Let's have a good look at this chunk... */
6161 if (!tags.chunkUsed) {
6162 /* An unassigned chunk in the block.
6163 * If there are used chunks after this one, then
6164 * it is a chunk that was skipped due to failing the erased
6165 * check. Just skip it so that it can be deleted.
6166 * But, more typically, We get here when this is an unallocated
6167 * chunk and his means that either the block is empty or
6168 * this is the one being allocated from
6171 if(foundChunksInBlock)
6173 /* This is a chunk that was skipped due to failing the erased check */
6175 } else if (c == 0) {
6176 /* We're looking at the first chunk in the block so the block is unused */
6177 state = YAFFS_BLOCK_STATE_EMPTY;
6178 dev->nErasedBlocks++;
6180 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6181 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6182 if(dev->sequenceNumber == bi->sequenceNumber) {
6183 /* this is the block being allocated from */
6187 (" Allocating from %d %d"
6190 state = YAFFS_BLOCK_STATE_ALLOCATING;
6191 dev->allocationBlock = blk;
6192 dev->allocationPage = c;
6193 dev->allocationBlockFinder = blk;
6196 /* This is a partially written block that is not
6197 * the current allocation block. This block must have
6198 * had a write failure, so set up for retirement.
6201 /* bi->needsRetiring = 1; ??? TODO */
6202 bi->gcPrioritise = 1;
6204 T(YAFFS_TRACE_ALWAYS,
6205 (TSTR("Partially written block %d detected" TENDSTR),
6215 } else if (tags.chunkId > 0) {
6216 /* chunkId > 0 so it is a data chunk... */
6217 unsigned int endpos;
6219 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6221 foundChunksInBlock = 1;
6224 yaffs_SetChunkBit(dev, blk, c);
6227 in = yaffs_FindOrCreateObjectByNumber(dev,
6230 YAFFS_OBJECT_TYPE_FILE);
6237 in->variantType == YAFFS_OBJECT_TYPE_FILE
6239 in->variant.fileVariant.shrinkSize) {
6240 /* This has not been invalidated by a resize */
6241 if(!yaffs_PutChunkIntoFile(in, tags.chunkId,
6246 /* File size is calculated by looking at the data chunks if we have not
6247 * seen an object header yet. Stop this practice once we find an object header.
6251 1) * dev->nDataBytesPerChunk +
6254 if (!in->valid && /* have not got an object header yet */
6255 in->variant.fileVariant.
6256 scannedFileSize < endpos) {
6257 in->variant.fileVariant.
6258 scannedFileSize = endpos;
6259 in->variant.fileVariant.
6261 in->variant.fileVariant.
6266 /* This chunk has been invalidated by a resize, so delete */
6267 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6271 /* chunkId == 0, so it is an ObjectHeader.
6272 * Thus, we read in the object header and make the object
6274 foundChunksInBlock = 1;
6276 yaffs_SetChunkBit(dev, blk, c);
6282 if (tags.extraHeaderInfoAvailable) {
6283 in = yaffs_FindOrCreateObjectByNumber
6284 (dev, tags.objectId,
6285 tags.extraObjectType);
6289 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
6292 tags.extraShadows ||
6294 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6295 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
6298 /* If we don't have valid info then we need to read the chunk
6299 * TODO In future we can probably defer reading the chunk and
6300 * living with invalid data until needed.
6303 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6308 oh = (yaffs_ObjectHeader *) chunkData;
6310 if(dev->inbandTags){
6311 /* Fix up the header if they got corrupted by inband tags */
6312 oh->shadowsObject = oh->inbandShadowsObject;
6313 oh->isShrink = oh->inbandIsShrink;
6317 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6322 /* TODO Hoosterman we have a problem! */
6323 T(YAFFS_TRACE_ERROR,
6325 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6326 TENDSTR), tags.objectId, chunk));
6331 /* We have already filled this one.
6332 * We have a duplicate that will be discarded, but
6333 * we first have to suck out resize info if it is a file.
6336 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6338 oh-> type == YAFFS_OBJECT_TYPE_FILE)||
6339 (tags.extraHeaderInfoAvailable &&
6340 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
6343 (oh) ? oh->fileSize : tags.
6345 __u32 parentObjectId =
6347 parentObjectId : tags.
6348 extraParentObjectId;
6352 (oh) ? oh->isShrink : tags.
6353 extraIsShrinkHeader;
6355 /* If it is deleted (unlinked at start also means deleted)
6356 * we treat the file size as being zeroed at this point.
6358 if (parentObjectId ==
6359 YAFFS_OBJECTID_DELETED
6360 || parentObjectId ==
6361 YAFFS_OBJECTID_UNLINKED) {
6367 in->variant.fileVariant.
6368 shrinkSize > thisSize) {
6369 in->variant.fileVariant.
6375 bi->hasShrinkHeader = 1;
6379 /* Use existing - destroy this one. */
6380 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6385 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6387 YAFFS_OBJECTID_LOSTNFOUND)) {
6388 /* We only load some info, don't fiddle with directory structure */
6392 in->variantType = oh->type;
6394 in->yst_mode = oh->yst_mode;
6395 #ifdef CONFIG_YAFFS_WINCE
6396 in->win_atime[0] = oh->win_atime[0];
6397 in->win_ctime[0] = oh->win_ctime[0];
6398 in->win_mtime[0] = oh->win_mtime[0];
6399 in->win_atime[1] = oh->win_atime[1];
6400 in->win_ctime[1] = oh->win_ctime[1];
6401 in->win_mtime[1] = oh->win_mtime[1];
6403 in->yst_uid = oh->yst_uid;
6404 in->yst_gid = oh->yst_gid;
6405 in->yst_atime = oh->yst_atime;
6406 in->yst_mtime = oh->yst_mtime;
6407 in->yst_ctime = oh->yst_ctime;
6408 in->yst_rdev = oh->yst_rdev;
6412 in->variantType = tags.extraObjectType;
6416 in->hdrChunk = chunk;
6418 } else if (!in->valid) {
6419 /* we need to load this info */
6422 in->hdrChunk = chunk;
6425 in->variantType = oh->type;
6427 in->yst_mode = oh->yst_mode;
6428 #ifdef CONFIG_YAFFS_WINCE
6429 in->win_atime[0] = oh->win_atime[0];
6430 in->win_ctime[0] = oh->win_ctime[0];
6431 in->win_mtime[0] = oh->win_mtime[0];
6432 in->win_atime[1] = oh->win_atime[1];
6433 in->win_ctime[1] = oh->win_ctime[1];
6434 in->win_mtime[1] = oh->win_mtime[1];
6436 in->yst_uid = oh->yst_uid;
6437 in->yst_gid = oh->yst_gid;
6438 in->yst_atime = oh->yst_atime;
6439 in->yst_mtime = oh->yst_mtime;
6440 in->yst_ctime = oh->yst_ctime;
6441 in->yst_rdev = oh->yst_rdev;
6444 if (oh->shadowsObject > 0)
6445 yaffs_HandleShadowedObject(dev,
6451 yaffs_SetObjectName(in, oh->name);
6453 yaffs_FindOrCreateObjectByNumber
6454 (dev, oh->parentObjectId,
6455 YAFFS_OBJECT_TYPE_DIRECTORY);
6457 fileSize = oh->fileSize;
6458 isShrink = oh->isShrink;
6459 equivalentObjectId = oh->equivalentObjectId;
6463 in->variantType = tags.extraObjectType;
6465 yaffs_FindOrCreateObjectByNumber
6466 (dev, tags.extraParentObjectId,
6467 YAFFS_OBJECT_TYPE_DIRECTORY);
6468 fileSize = tags.extraFileLength;
6469 isShrink = tags.extraIsShrinkHeader;
6470 equivalentObjectId = tags.extraEquivalentObjectId;
6476 /* directory stuff...
6480 if (parent->variantType ==
6481 YAFFS_OBJECT_TYPE_UNKNOWN) {
6482 /* Set up as a directory */
6483 parent->variantType =
6484 YAFFS_OBJECT_TYPE_DIRECTORY;
6485 YINIT_LIST_HEAD(&parent->variant.
6488 } else if (parent->variantType !=
6489 YAFFS_OBJECT_TYPE_DIRECTORY)
6491 /* Hoosterman, another problem....
6492 * We're trying to use a non-directory as a directory
6495 T(YAFFS_TRACE_ERROR,
6497 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6499 parent = dev->lostNFoundDir;
6502 yaffs_AddObjectToDirectory(parent, in);
6504 itsUnlinked = (parent == dev->deletedDir) ||
6505 (parent == dev->unlinkedDir);
6508 /* Mark the block as having a shrinkHeader */
6509 bi->hasShrinkHeader = 1;
6512 /* Note re hardlinks.
6513 * Since we might scan a hardlink before its equivalent object is scanned
6514 * we put them all in a list.
6515 * After scanning is complete, we should have all the objects, so we run
6516 * through this list and fix up all the chains.
6519 switch (in->variantType) {
6520 case YAFFS_OBJECT_TYPE_UNKNOWN:
6521 /* Todo got a problem */
6523 case YAFFS_OBJECT_TYPE_FILE:
6525 if (in->variant.fileVariant.
6526 scannedFileSize < fileSize) {
6527 /* This covers the case where the file size is greater
6528 * than where the data is
6529 * This will happen if the file is resized to be larger
6530 * than its current data extents.
6532 in->variant.fileVariant.fileSize = fileSize;
6533 in->variant.fileVariant.scannedFileSize =
6534 in->variant.fileVariant.fileSize;
6538 in->variant.fileVariant.shrinkSize > fileSize) {
6539 in->variant.fileVariant.shrinkSize = fileSize;
6543 case YAFFS_OBJECT_TYPE_HARDLINK:
6545 in->variant.hardLinkVariant.equivalentObjectId =
6547 in->hardLinks.next =
6548 (struct ylist_head *) hardList;
6552 case YAFFS_OBJECT_TYPE_DIRECTORY:
6555 case YAFFS_OBJECT_TYPE_SPECIAL:
6558 case YAFFS_OBJECT_TYPE_SYMLINK:
6560 in->variant.symLinkVariant.alias =
6561 yaffs_CloneString(oh->
6563 if(!in->variant.symLinkVariant.alias)
6573 } /* End of scanning for each chunk */
6575 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6576 /* If we got this far while scanning, then the block is fully allocated. */
6577 state = YAFFS_BLOCK_STATE_FULL;
6580 bi->blockState = state;
6582 /* Now let's see if it was dirty */
6583 if (bi->pagesInUse == 0 &&
6584 !bi->hasShrinkHeader &&
6585 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6586 yaffs_BlockBecameDirty(dev, blk);
6592 YFREE_ALT(blockIndex);
6596 /* Ok, we've done all the scanning.
6597 * Fix up the hard link chains.
6598 * We should now have scanned all the objects, now it's time to add these
6601 yaffs_HardlinkFixup(dev,hardList);
6605 * Sort out state of unlinked and deleted objects.
6608 struct ylist_head *i;
6609 struct ylist_head *n;
6613 /* Soft delete all the unlinked files */
6614 ylist_for_each_safe(i, n,
6615 &dev->unlinkedDir->variant.directoryVariant.
6618 l = ylist_entry(i, yaffs_Object, siblings);
6619 yaffs_DestroyObject(l);
6623 /* Soft delete all the deletedDir files */
6624 ylist_for_each_safe(i, n,
6625 &dev->deletedDir->variant.directoryVariant.
6628 l = ylist_entry(i, yaffs_Object, siblings);
6629 yaffs_DestroyObject(l);
6635 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6641 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6646 /*------------------------------ Directory Functions ----------------------------- */
6648 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
6650 yaffs_Device *dev = obj->myDev;
6652 if(dev && dev->removeObjectCallback)
6653 dev->removeObjectCallback(obj);
6655 ylist_del_init(&obj->siblings);
6660 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
6665 T(YAFFS_TRACE_ALWAYS,
6667 ("tragedy: Trying to add an object to a null pointer directory"
6671 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6672 T(YAFFS_TRACE_ALWAYS,
6674 ("tragedy: Trying to add an object to a non-directory"
6679 if (obj->siblings.prev == NULL) {
6680 /* Not initialised */
6681 YINIT_LIST_HEAD(&obj->siblings);
6683 } else if (!ylist_empty(&obj->siblings)) {
6684 /* If it is holed up somewhere else, un hook it */
6685 yaffs_RemoveObjectFromDirectory(obj);
6688 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
6689 obj->parent = directory;
6691 if (directory == obj->myDev->unlinkedDir
6692 || directory == obj->myDev->deletedDir) {
6694 obj->myDev->nUnlinkedFiles++;
6695 obj->renameAllowed = 0;
6699 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
6704 struct ylist_head *i;
6705 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
6714 T(YAFFS_TRACE_ALWAYS,
6716 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6720 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6721 T(YAFFS_TRACE_ALWAYS,
6723 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6727 sum = yaffs_CalcNameSum(name);
6729 ylist_for_each(i, &directory->variant.directoryVariant.children) {
6731 l = ylist_entry(i, yaffs_Object, siblings);
6733 yaffs_CheckObjectDetailsLoaded(l);
6735 /* Special case for lost-n-found */
6736 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6737 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
6740 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0){
6741 /* LostnFound chunk called Objxxx
6744 yaffs_GetObjectName(l, buffer,
6745 YAFFS_MAX_NAME_LENGTH);
6746 if (yaffs_strncmp(name, buffer,YAFFS_MAX_NAME_LENGTH) == 0) {
6759 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
6760 int (*fn) (yaffs_Object *))
6762 struct ylist_head *i;
6766 T(YAFFS_TRACE_ALWAYS,
6768 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6772 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6773 T(YAFFS_TRACE_ALWAYS,
6775 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6779 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
6781 l = ylist_entry(i, yaffs_Object, siblings);
6793 /* GetEquivalentObject dereferences any hard links to get to the
6797 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
6799 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
6800 /* We want the object id of the equivalent object, not this one */
6801 obj = obj->variant.hardLinkVariant.equivalentObject;
6802 yaffs_CheckObjectDetailsLoaded(obj);
6808 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
6810 memset(name, 0, buffSize * sizeof(YCHAR));
6812 yaffs_CheckObjectDetailsLoaded(obj);
6814 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6815 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
6816 } else if (obj->hdrChunk <= 0) {
6818 /* make up a name */
6819 yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX,
6821 yaffs_strncpy(name, locName, buffSize - 1);
6824 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
6825 else if (obj->shortName[0]) {
6826 yaffs_strcpy(name, obj->shortName);
6831 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
6833 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
6835 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
6837 if (obj->hdrChunk > 0) {
6838 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
6839 obj->hdrChunk, buffer,
6842 yaffs_strncpy(name, oh->name, buffSize - 1);
6844 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
6847 return yaffs_strlen(name);
6850 int yaffs_GetObjectFileLength(yaffs_Object * obj)
6853 /* Dereference any hard linking */
6854 obj = yaffs_GetEquivalentObject(obj);
6856 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
6857 return obj->variant.fileVariant.fileSize;
6859 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6860 return yaffs_strlen(obj->variant.symLinkVariant.alias);
6862 /* Only a directory should drop through to here */
6863 return obj->myDev->nDataBytesPerChunk;
6867 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
6870 struct ylist_head *i;
6872 if (!obj->unlinked) {
6873 count++; /* the object itself */
6875 ylist_for_each(i, &obj->hardLinks) {
6876 count++; /* add the hard links; */
6882 int yaffs_GetObjectInode(yaffs_Object * obj)
6884 obj = yaffs_GetEquivalentObject(obj);
6886 return obj->objectId;
6889 unsigned yaffs_GetObjectType(yaffs_Object * obj)
6891 obj = yaffs_GetEquivalentObject(obj);
6893 switch (obj->variantType) {
6894 case YAFFS_OBJECT_TYPE_FILE:
6897 case YAFFS_OBJECT_TYPE_DIRECTORY:
6900 case YAFFS_OBJECT_TYPE_SYMLINK:
6903 case YAFFS_OBJECT_TYPE_HARDLINK:
6906 case YAFFS_OBJECT_TYPE_SPECIAL:
6907 if (S_ISFIFO(obj->yst_mode))
6909 if (S_ISCHR(obj->yst_mode))
6911 if (S_ISBLK(obj->yst_mode))
6913 if (S_ISSOCK(obj->yst_mode))
6921 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
6923 obj = yaffs_GetEquivalentObject(obj);
6924 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6925 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
6927 return yaffs_CloneString(_Y(""));
6931 #ifndef CONFIG_YAFFS_WINCE
6933 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
6935 unsigned int valid = attr->ia_valid;
6937 if (valid & ATTR_MODE)
6938 obj->yst_mode = attr->ia_mode;
6939 if (valid & ATTR_UID)
6940 obj->yst_uid = attr->ia_uid;
6941 if (valid & ATTR_GID)
6942 obj->yst_gid = attr->ia_gid;
6944 if (valid & ATTR_ATIME)
6945 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
6946 if (valid & ATTR_CTIME)
6947 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
6948 if (valid & ATTR_MTIME)
6949 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
6951 if (valid & ATTR_SIZE)
6952 yaffs_ResizeFile(obj, attr->ia_size);
6954 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6959 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
6961 unsigned int valid = 0;
6963 attr->ia_mode = obj->yst_mode;
6965 attr->ia_uid = obj->yst_uid;
6967 attr->ia_gid = obj->yst_gid;
6970 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
6971 valid |= ATTR_ATIME;
6972 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
6973 valid |= ATTR_CTIME;
6974 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
6975 valid |= ATTR_MTIME;
6977 attr->ia_size = yaffs_GetFileSize(obj);
6980 attr->ia_valid = valid;
6989 int yaffs_DumpObject(yaffs_Object * obj)
6993 yaffs_GetObjectName(obj, name, 256);
6995 T(YAFFS_TRACE_ALWAYS,
6997 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
6998 " chunk %d type %d size %d\n"
6999 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7000 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7001 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7007 /*---------------------------- Initialisation code -------------------------------------- */
7009 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
7012 /* Common functions, gotta have */
7013 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
7016 #ifdef CONFIG_YAFFS_YAFFS2
7018 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7019 if (dev->writeChunkWithTagsToNAND &&
7020 dev->readChunkWithTagsFromNAND &&
7021 !dev->writeChunkToNAND &&
7022 !dev->readChunkFromNAND &&
7023 dev->markNANDBlockBad && dev->queryNANDBlock)
7027 /* Can use the "spare" style interface for yaffs1 */
7028 if (!dev->isYaffs2 &&
7029 !dev->writeChunkWithTagsToNAND &&
7030 !dev->readChunkWithTagsFromNAND &&
7031 dev->writeChunkToNAND &&
7032 dev->readChunkFromNAND &&
7033 !dev->markNANDBlockBad && !dev->queryNANDBlock)
7040 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7042 /* Initialise the unlinked, deleted, root and lost and found directories */
7044 dev->lostNFoundDir = dev->rootDir = NULL;
7045 dev->unlinkedDir = dev->deletedDir = NULL;
7048 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7051 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7054 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7055 YAFFS_ROOT_MODE | S_IFDIR);
7056 dev->lostNFoundDir =
7057 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7058 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7060 if(dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir){
7061 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7068 int yaffs_GutsInitialise(yaffs_Device * dev)
7070 int init_failed = 0;
7074 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7076 /* Check stuff that must be set */
7079 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7083 dev->internalStartBlock = dev->startBlock;
7084 dev->internalEndBlock = dev->endBlock;
7085 dev->blockOffset = 0;
7086 dev->chunkOffset = 0;
7087 dev->nFreeChunks = 0;
7089 if (dev->startBlock == 0) {
7090 dev->internalStartBlock = dev->startBlock + 1;
7091 dev->internalEndBlock = dev->endBlock + 1;
7092 dev->blockOffset = 1;
7093 dev->chunkOffset = dev->nChunksPerBlock;
7096 /* Check geometry parameters. */
7098 if ((!dev->inbandTags && dev->isYaffs2 && dev->totalBytesPerChunk < 1024) ||
7099 (!dev->isYaffs2 && dev->totalBytesPerChunk != 512) ||
7100 (dev->inbandTags && !dev->isYaffs2 ) ||
7101 dev->nChunksPerBlock < 2 ||
7102 dev->nReservedBlocks < 2 ||
7103 dev->internalStartBlock <= 0 ||
7104 dev->internalEndBlock <= 0 ||
7105 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
7107 T(YAFFS_TRACE_ALWAYS,
7109 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7110 TENDSTR), dev->totalBytesPerChunk, dev->isYaffs2 ? "2" : "", dev->inbandTags));
7114 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7115 T(YAFFS_TRACE_ALWAYS,
7116 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7120 /* Sort out space for inband tags, if required */
7122 dev->nDataBytesPerChunk = dev->totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7124 dev->nDataBytesPerChunk = dev->totalBytesPerChunk;
7126 /* Got the right mix of functions? */
7127 if (!yaffs_CheckDevFunctions(dev)) {
7128 /* Function missing */
7129 T(YAFFS_TRACE_ALWAYS,
7131 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7136 /* This is really a compilation check. */
7137 if (!yaffs_CheckStructures()) {
7138 T(YAFFS_TRACE_ALWAYS,
7139 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7143 if (dev->isMounted) {
7144 T(YAFFS_TRACE_ALWAYS,
7145 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7149 /* Finished with most checks. One or two more checks happen later on too. */
7153 /* OK now calculate a few things for the device */
7156 * Calculate all the chunk size manipulation numbers:
7158 x = dev->nDataBytesPerChunk;
7159 /* We always use dev->chunkShift and dev->chunkDiv */
7160 dev->chunkShift = Shifts(x);
7161 x >>= dev->chunkShift;
7163 /* We only use chunk mask if chunkDiv is 1 */
7164 dev->chunkMask = (1<<dev->chunkShift) - 1;
7167 * Calculate chunkGroupBits.
7168 * We need to find the next power of 2 > than internalEndBlock
7171 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7175 /* Set up tnode width if wide tnodes are enabled. */
7176 if(!dev->wideTnodesDisabled){
7177 /* bits must be even so that we end up with 32-bit words */
7181 dev->tnodeWidth = 16;
7183 dev->tnodeWidth = bits;
7186 dev->tnodeWidth = 16;
7188 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7190 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7191 * so if the bitwidth of the
7192 * chunk range we're using is greater than 16 we need
7193 * to figure out chunk shift and chunkGroupSize
7196 if (bits <= dev->tnodeWidth)
7197 dev->chunkGroupBits = 0;
7199 dev->chunkGroupBits = bits - dev->tnodeWidth;
7202 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7204 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7205 /* We have a problem because the soft delete won't work if
7206 * the chunk group size > chunks per block.
7207 * This can be remedied by using larger "virtual blocks".
7209 T(YAFFS_TRACE_ALWAYS,
7210 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7215 /* OK, we've finished verifying the device, lets continue with initialisation */
7217 /* More device initialisation */
7218 dev->garbageCollections = 0;
7219 dev->passiveGarbageCollections = 0;
7220 dev->currentDirtyChecker = 0;
7221 dev->bufferedBlock = -1;
7222 dev->doingBufferedBlockRewrite = 0;
7223 dev->nDeletedFiles = 0;
7224 dev->nBackgroundDeletions = 0;
7225 dev->nUnlinkedFiles = 0;
7227 dev->eccUnfixed = 0;
7228 dev->tagsEccFixed = 0;
7229 dev->tagsEccUnfixed = 0;
7230 dev->nErasureFailures = 0;
7231 dev->nErasedBlocks = 0;
7233 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7235 /* Initialise temporary buffers and caches. */
7236 if(!yaffs_InitialiseTempBuffers(dev))
7239 dev->srCache = NULL;
7240 dev->gcCleanupList = NULL;
7244 dev->nShortOpCaches > 0) {
7247 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7249 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
7250 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7253 dev->srCache = YMALLOC(srCacheBytes);
7255 buf = (__u8 *) dev->srCache;
7258 memset(dev->srCache,0,srCacheBytes);
7260 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7261 dev->srCache[i].object = NULL;
7262 dev->srCache[i].lastUse = 0;
7263 dev->srCache[i].dirty = 0;
7264 dev->srCache[i].data = buf = YMALLOC_DMA(dev->totalBytesPerChunk);
7275 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7276 if(!dev->gcCleanupList)
7280 if (dev->isYaffs2) {
7281 dev->useHeaderFileSize = 1;
7283 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7286 yaffs_InitialiseTnodes(dev);
7287 yaffs_InitialiseObjects(dev);
7289 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7294 /* Now scan the flash. */
7295 if (dev->isYaffs2) {
7296 if(yaffs_CheckpointRestore(dev)) {
7297 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7298 T(YAFFS_TRACE_ALWAYS,
7299 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7302 /* Clean up the mess caused by an aborted checkpoint load
7303 * and scan backwards.
7305 yaffs_DeinitialiseBlocks(dev);
7306 yaffs_DeinitialiseTnodes(dev);
7307 yaffs_DeinitialiseObjects(dev);
7310 dev->nErasedBlocks = 0;
7311 dev->nFreeChunks = 0;
7312 dev->allocationBlock = -1;
7313 dev->allocationPage = -1;
7314 dev->nDeletedFiles = 0;
7315 dev->nUnlinkedFiles = 0;
7316 dev->nBackgroundDeletions = 0;
7317 dev->oldestDirtySequence = 0;
7319 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7322 yaffs_InitialiseTnodes(dev);
7323 yaffs_InitialiseObjects(dev);
7325 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7328 if(!init_failed && !yaffs_ScanBackwards(dev))
7332 if(!yaffs_Scan(dev))
7337 /* Clean up the mess */
7338 T(YAFFS_TRACE_TRACING,
7339 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7341 yaffs_Deinitialise(dev);
7345 /* Zero out stats */
7346 dev->nPageReads = 0;
7347 dev->nPageWrites = 0;
7348 dev->nBlockErasures = 0;
7350 dev->nRetriedWrites = 0;
7352 dev->nRetiredBlocks = 0;
7354 yaffs_VerifyFreeChunks(dev);
7355 yaffs_VerifyBlocks(dev);
7358 T(YAFFS_TRACE_TRACING,
7359 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7364 void yaffs_Deinitialise(yaffs_Device * dev)
7366 if (dev->isMounted) {
7369 yaffs_DeinitialiseBlocks(dev);
7370 yaffs_DeinitialiseTnodes(dev);
7371 yaffs_DeinitialiseObjects(dev);
7372 if (dev->nShortOpCaches > 0 &&
7375 for (i = 0; i < dev->nShortOpCaches; i++) {
7376 if(dev->srCache[i].data)
7377 YFREE(dev->srCache[i].data);
7378 dev->srCache[i].data = NULL;
7381 YFREE(dev->srCache);
7382 dev->srCache = NULL;
7385 YFREE(dev->gcCleanupList);
7387 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
7388 YFREE(dev->tempBuffer[i].buffer);
7397 static int yaffs_CountFreeChunks(yaffs_Device * dev)
7402 yaffs_BlockInfo *blk;
7404 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7406 blk = yaffs_GetBlockInfo(dev, b);
7408 switch (blk->blockState) {
7409 case YAFFS_BLOCK_STATE_EMPTY:
7410 case YAFFS_BLOCK_STATE_ALLOCATING:
7411 case YAFFS_BLOCK_STATE_COLLECTING:
7412 case YAFFS_BLOCK_STATE_FULL:
7414 (dev->nChunksPerBlock - blk->pagesInUse +
7415 blk->softDeletions);
7426 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
7428 /* This is what we report to the outside world */
7431 int nDirtyCacheChunks;
7432 int blocksForCheckpoint;
7435 nFree = dev->nFreeChunks;
7437 nFree = yaffs_CountFreeChunks(dev);
7440 nFree += dev->nDeletedFiles;
7442 /* Now count the number of dirty chunks in the cache and subtract those */
7446 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7447 if (dev->srCache[i].dirty)
7448 nDirtyCacheChunks++;
7452 nFree -= nDirtyCacheChunks;
7454 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7456 /* Now we figure out how much to reserve for the checkpoint and report that... */
7457 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7458 if(blocksForCheckpoint < 0)
7459 blocksForCheckpoint = 0;
7461 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7470 static int yaffs_freeVerificationFailures;
7472 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
7477 if(yaffs_SkipVerification(dev))
7480 counted = yaffs_CountFreeChunks(dev);
7482 difference = dev->nFreeChunks - counted;
7485 T(YAFFS_TRACE_ALWAYS,
7486 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7487 dev->nFreeChunks, counted, difference));
7488 yaffs_freeVerificationFailures++;
7492 /*---------------------------------------- YAFFS test code ----------------------*/
7494 #define yaffs_CheckStruct(structure,syze, name) \
7496 if(sizeof(structure) != syze) \
7498 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
7499 name,syze,sizeof(structure))); \
7500 return YAFFS_FAIL; \
7504 static int yaffs_CheckStructures(void)
7506 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
7507 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
7508 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
7509 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7510 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode");
7512 #ifndef CONFIG_YAFFS_WINCE
7513 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");