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.61 2008-10-30 18:25:21 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 retVal == YAFFS_OK &&
3019 chunkInBlock < dev->nChunksPerBlock
3020 && yaffs_StillSomeChunkBits(dev, block);
3021 chunkInBlock++, oldChunk++) {
3022 if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
3024 /* This page is in use and might need to be copied off */
3028 yaffs_InitialiseTags(&tags);
3030 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3034 yaffs_FindObjectByNumber(dev,
3037 T(YAFFS_TRACE_GC_DETAIL,
3039 ("Collecting page %d, %d %d %d " TENDSTR),
3040 chunkInBlock, tags.objectId, tags.chunkId,
3043 if(object && !yaffs_SkipVerification(dev)){
3044 if(tags.chunkId == 0)
3045 matchingChunk = object->hdrChunk;
3046 else if(object->softDeleted)
3047 matchingChunk = oldChunk; /* Defeat the test */
3049 matchingChunk = yaffs_FindChunkInFile(object,tags.chunkId,NULL);
3051 if(oldChunk != matchingChunk)
3052 T(YAFFS_TRACE_ERROR,
3053 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3054 oldChunk,matchingChunk,tags.objectId, tags.chunkId));
3059 T(YAFFS_TRACE_ERROR,
3061 ("page %d in gc has no object: %d %d %d "
3063 tags.objectId, tags.chunkId, tags.byteCount));
3066 if (object && object->deleted
3067 && tags.chunkId != 0) {
3068 /* Data chunk in a deleted file, throw it away
3069 * It's a soft deleted data chunk,
3070 * No need to copy this, just forget about it and
3071 * fix up the object.
3074 object->nDataChunks--;
3076 if (object->nDataChunks <= 0) {
3077 /* remeber to clean up the object */
3078 dev->gcCleanupList[cleanups] =
3084 /* Todo object && object->deleted && object->nDataChunks == 0 */
3086 /* Deleted object header with no data chunks.
3087 * Can be discarded and the file deleted.
3089 object->hdrChunk = 0;
3090 yaffs_FreeTnode(object->myDev,
3093 object->variant.fileVariant.top = NULL;
3094 yaffs_DoGenericObjectDeletion(object);
3096 } else if (object) {
3097 /* It's either a data chunk in a live file or
3098 * an ObjectHeader, so we're interested in it.
3099 * NB Need to keep the ObjectHeaders of deleted files
3100 * until the whole file has been deleted off
3102 tags.serialNumber++;
3106 if (tags.chunkId == 0) {
3107 /* It is an object Id,
3108 * We need to nuke the shrinkheader flags first
3109 * We no longer want the shrinkHeader flag since its work is done
3110 * and if it is left in place it will mess up scanning.
3111 * Also, clear out any shadowing stuff
3114 yaffs_ObjectHeader *oh;
3115 oh = (yaffs_ObjectHeader *)buffer;
3117 oh->shadowsObject = oh->inbandShadowsObject = -1;
3118 tags.extraShadows = 0;
3119 tags.extraIsShrinkHeader = 0;
3121 yaffs_VerifyObjectHeader(object,oh,&tags,1);
3125 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3128 retVal = YAFFS_FAIL;
3131 /* Ok, now fix up the Tnodes etc. */
3133 if (tags.chunkId == 0) {
3135 object->hdrChunk = newChunk;
3136 object->serial = tags.serialNumber;
3138 /* It's a data chunk */
3139 yaffs_PutChunkIntoFile
3147 if(retVal == YAFFS_OK)
3148 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3153 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3156 /* Do any required cleanups */
3157 for (i = 0; i < cleanups; i++) {
3158 /* Time to delete the file too */
3160 yaffs_FindObjectByNumber(dev,
3161 dev->gcCleanupList[i]);
3163 yaffs_FreeTnode(dev,
3164 object->variant.fileVariant.
3166 object->variant.fileVariant.top = NULL;
3169 ("yaffs: About to finally delete object %d"
3170 TENDSTR), object->objectId));
3171 yaffs_DoGenericObjectDeletion(object);
3172 object->myDev->nDeletedFiles--;
3179 yaffs_VerifyCollectedBlock(dev,bi,block);
3181 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
3184 ("gc did not increase free chunks before %d after %d"
3185 TENDSTR), chunksBefore, chunksAfter));
3193 /* New garbage collector
3194 * If we're very low on erased blocks then we do aggressive garbage collection
3195 * otherwise we do "leasurely" garbage collection.
3196 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3197 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3199 * The idea is to help clear out space in a more spread-out manner.
3200 * Dunno if it really does anything useful.
3202 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
3206 int gcOk = YAFFS_OK;
3209 int checkpointBlockAdjust;
3211 if (dev->isDoingGC) {
3212 /* Bail out so we don't get recursive gc */
3216 /* This loop should pass the first time.
3217 * We'll only see looping here if the erase of the collected block fails.
3223 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3224 if(checkpointBlockAdjust < 0)
3225 checkpointBlockAdjust = 0;
3227 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3228 /* We need a block soon...*/
3231 /* We're in no hurry */
3235 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3238 dev->garbageCollections++;
3240 dev->passiveGarbageCollections++;
3245 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3246 dev->nErasedBlocks, aggressive));
3248 gcOk = yaffs_GarbageCollectBlock(dev, block);
3251 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3254 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3255 TENDSTR), dev->nErasedBlocks, maxTries, block));
3257 } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
3260 return aggressive ? gcOk : YAFFS_OK;
3263 /*------------------------- TAGS --------------------------------*/
3265 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
3268 return (tags->chunkId == chunkInObject &&
3269 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3274 /*-------------------- Data file manipulation -----------------*/
3276 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
3277 yaffs_ExtendedTags * tags)
3279 /*Get the Tnode, then get the level 0 offset chunk offset */
3282 yaffs_ExtendedTags localTags;
3285 yaffs_Device *dev = in->myDev;
3288 /* Passed a NULL, so use our own tags space */
3292 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3295 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3298 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3304 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
3305 yaffs_ExtendedTags * tags)
3307 /* Get the Tnode, then get the level 0 offset chunk offset */
3310 yaffs_ExtendedTags localTags;
3312 yaffs_Device *dev = in->myDev;
3316 /* Passed a NULL, so use our own tags space */
3320 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3324 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3327 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3330 /* Delete the entry in the filestructure (if found) */
3332 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
3335 /*T(("No level 0 found for %d\n", chunkInInode)); */
3339 /* T(("Could not find %d to delete\n",chunkInInode)); */
3344 #ifdef YAFFS_PARANOID
3346 static int yaffs_CheckFileSanity(yaffs_Object * in)
3354 yaffs_Tags localTags;
3355 yaffs_Tags *tags = &localTags;
3359 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3360 /* T(("Object not a file\n")); */
3364 objId = in->objectId;
3365 fSize = in->variant.fileVariant.fileSize;
3367 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3369 for (chunk = 1; chunk <= nChunks; chunk++) {
3370 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3375 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
3377 if (yaffs_CheckChunkBits
3378 (dev, theChunk / dev->nChunksPerBlock,
3379 theChunk % dev->nChunksPerBlock)) {
3381 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3385 (tags, in->objectId, chunk, chunkDeleted)) {
3395 /* T(("No level 0 found for %d\n", chunk)); */
3399 return failed ? YAFFS_FAIL : YAFFS_OK;
3404 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
3405 int chunkInNAND, int inScan)
3407 /* NB inScan is zero unless scanning.
3408 * For forward scanning, inScan is > 0;
3409 * for backward scanning inScan is < 0
3413 yaffs_Device *dev = in->myDev;
3415 yaffs_ExtendedTags existingTags;
3416 yaffs_ExtendedTags newTags;
3417 unsigned existingSerial, newSerial;
3419 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3420 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3421 * If it is not during Scanning then something went wrong!
3424 T(YAFFS_TRACE_ERROR,
3426 ("yaffs tragedy:attempt to put data chunk into a non-file"
3431 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3435 tn = yaffs_AddOrFindLevel0Tnode(dev,
3436 &in->variant.fileVariant,
3443 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3446 /* If we're scanning then we need to test for duplicates
3447 * NB This does not need to be efficient since it should only ever
3448 * happen when the power fails during a write, then only one
3449 * chunk should ever be affected.
3451 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3452 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3455 if (existingChunk > 0) {
3456 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3457 * thus we have to do a FindChunkInFile to get the real chunk id.
3459 * We have a duplicate now we need to decide which one to use:
3461 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3462 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3463 * YAFFS1: Get both sets of tags and compare serial numbers.
3467 /* Only do this for forward scanning */
3468 yaffs_ReadChunkWithTagsFromNAND(dev,
3472 /* Do a proper find */
3474 yaffs_FindChunkInFile(in, chunkInInode,
3478 if (existingChunk <= 0) {
3479 /*Hoosterman - how did this happen? */
3481 T(YAFFS_TRACE_ERROR,
3483 ("yaffs tragedy: existing chunk < 0 in scan"
3488 /* NB The deleted flags should be false, otherwise the chunks will
3489 * not be loaded during a scan
3493 newSerial = newTags.serialNumber;
3494 existingSerial = existingTags.serialNumber;
3498 (in->myDev->isYaffs2 ||
3499 existingChunk <= 0 ||
3500 ((existingSerial + 1) & 3) == newSerial)) {
3501 /* Forward scanning.
3503 * Delete the old one and drop through to update the tnode
3505 yaffs_DeleteChunk(dev, existingChunk, 1,
3508 /* Backward scanning or we want to use the existing one
3510 * Delete the new one and return early so that the tnode isn't changed
3512 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3520 if (existingChunk == 0) {
3524 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
3529 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
3532 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3534 if (chunkInNAND >= 0) {
3535 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3538 T(YAFFS_TRACE_NANDACCESS,
3539 (TSTR("Chunk %d not found zero instead" TENDSTR),
3541 /* get sane (zero) data if you read a hole */
3542 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3548 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
3552 yaffs_ExtendedTags tags;
3553 yaffs_BlockInfo *bi;
3560 block = chunkId / dev->nChunksPerBlock;
3561 page = chunkId % dev->nChunksPerBlock;
3564 if(!yaffs_CheckChunkBit(dev,block,page))
3565 T(YAFFS_TRACE_VERIFY,
3566 (TSTR("Deleting invalid chunk %d"TENDSTR),
3569 bi = yaffs_GetBlockInfo(dev, block);
3571 T(YAFFS_TRACE_DELETION,
3572 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3575 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3577 yaffs_InitialiseTags(&tags);
3579 tags.chunkDeleted = 1;
3581 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3582 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3584 dev->nUnmarkedDeletions++;
3587 /* Pull out of the management area.
3588 * If the whole block became dirty, this will kick off an erasure.
3590 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3591 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3592 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3593 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3596 yaffs_ClearChunkBit(dev, block, page);
3600 if (bi->pagesInUse == 0 &&
3601 !bi->hasShrinkHeader &&
3602 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3603 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3604 yaffs_BlockBecameDirty(dev, block);
3608 /* T(("Bad news deleting chunk %d\n",chunkId)); */
3613 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
3614 const __u8 * buffer, int nBytes,
3617 /* Find old chunk Need to do this to get serial number
3618 * Write new one and patch into tree.
3619 * Invalidate old tags.
3623 yaffs_ExtendedTags prevTags;
3626 yaffs_ExtendedTags newTags;
3628 yaffs_Device *dev = in->myDev;
3630 yaffs_CheckGarbageCollection(dev);
3632 /* Get the previous chunk at this location in the file if it exists */
3633 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3635 /* Set up new tags */
3636 yaffs_InitialiseTags(&newTags);
3638 newTags.chunkId = chunkInInode;
3639 newTags.objectId = in->objectId;
3640 newTags.serialNumber =
3641 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
3642 newTags.byteCount = nBytes;
3645 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3648 if (newChunkId >= 0) {
3649 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3651 if (prevChunkId >= 0) {
3652 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3656 yaffs_CheckFileSanity(in);
3662 /* UpdateObjectHeader updates the header on NAND for an object.
3663 * If name is not NULL, then that new name is used.
3665 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
3666 int isShrink, int shadows)
3669 yaffs_BlockInfo *bi;
3671 yaffs_Device *dev = in->myDev;
3678 yaffs_ExtendedTags newTags;
3679 yaffs_ExtendedTags oldTags;
3681 __u8 *buffer = NULL;
3682 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3684 yaffs_ObjectHeader *oh = NULL;
3686 yaffs_strcpy(oldName,_Y("silly old name"));
3690 in == dev->rootDir || /* The rootDir should also be saved */
3693 yaffs_CheckGarbageCollection(dev);
3694 yaffs_CheckObjectDetailsLoaded(in);
3696 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3697 oh = (yaffs_ObjectHeader *) buffer;
3699 prevChunkId = in->hdrChunk;
3701 if (prevChunkId > 0) {
3702 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3705 yaffs_VerifyObjectHeader(in,oh,&oldTags,0);
3707 memcpy(oldName, oh->name, sizeof(oh->name));
3710 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3712 oh->type = in->variantType;
3713 oh->yst_mode = in->yst_mode;
3714 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3716 #ifdef CONFIG_YAFFS_WINCE
3717 oh->win_atime[0] = in->win_atime[0];
3718 oh->win_ctime[0] = in->win_ctime[0];
3719 oh->win_mtime[0] = in->win_mtime[0];
3720 oh->win_atime[1] = in->win_atime[1];
3721 oh->win_ctime[1] = in->win_ctime[1];
3722 oh->win_mtime[1] = in->win_mtime[1];
3724 oh->yst_uid = in->yst_uid;
3725 oh->yst_gid = in->yst_gid;
3726 oh->yst_atime = in->yst_atime;
3727 oh->yst_mtime = in->yst_mtime;
3728 oh->yst_ctime = in->yst_ctime;
3729 oh->yst_rdev = in->yst_rdev;
3732 oh->parentObjectId = in->parent->objectId;
3734 oh->parentObjectId = 0;
3737 if (name && *name) {
3738 memset(oh->name, 0, sizeof(oh->name));
3739 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3740 } else if (prevChunkId>=0) {
3741 memcpy(oh->name, oldName, sizeof(oh->name));
3743 memset(oh->name, 0, sizeof(oh->name));
3746 oh->isShrink = isShrink;
3748 switch (in->variantType) {
3749 case YAFFS_OBJECT_TYPE_UNKNOWN:
3750 /* Should not happen */
3752 case YAFFS_OBJECT_TYPE_FILE:
3754 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3755 || oh->parentObjectId ==
3756 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3757 fileVariant.fileSize;
3759 case YAFFS_OBJECT_TYPE_HARDLINK:
3760 oh->equivalentObjectId =
3761 in->variant.hardLinkVariant.equivalentObjectId;
3763 case YAFFS_OBJECT_TYPE_SPECIAL:
3766 case YAFFS_OBJECT_TYPE_DIRECTORY:
3769 case YAFFS_OBJECT_TYPE_SYMLINK:
3770 yaffs_strncpy(oh->alias,
3771 in->variant.symLinkVariant.alias,
3772 YAFFS_MAX_ALIAS_LENGTH);
3773 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3778 yaffs_InitialiseTags(&newTags);
3780 newTags.chunkId = 0;
3781 newTags.objectId = in->objectId;
3782 newTags.serialNumber = in->serial;
3784 /* Add extra info for file header */
3786 newTags.extraHeaderInfoAvailable = 1;
3787 newTags.extraParentObjectId = oh->parentObjectId;
3788 newTags.extraFileLength = oh->fileSize;
3789 newTags.extraIsShrinkHeader = oh->isShrink;
3790 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3791 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3792 newTags.extraObjectType = in->variantType;
3794 yaffs_VerifyObjectHeader(in,oh,&newTags,1);
3796 /* Create new chunk in NAND */
3798 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3799 (prevChunkId >= 0) ? 1 : 0);
3801 if (newChunkId >= 0) {
3803 in->hdrChunk = newChunkId;
3805 if (prevChunkId >= 0) {
3806 yaffs_DeleteChunk(dev, prevChunkId, 1,
3810 if(!yaffs_ObjectHasCachedWriteData(in))
3813 /* If this was a shrink, then mark the block that the chunk lives on */
3815 bi = yaffs_GetBlockInfo(in->myDev,
3816 newChunkId /in->myDev-> nChunksPerBlock);
3817 bi->hasShrinkHeader = 1;
3822 retVal = newChunkId;
3827 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3832 /*------------------------ Short Operations Cache ----------------------------------------
3833 * In many situations where there is no high level buffering (eg WinCE) a lot of
3834 * reads might be short sequential reads, and a lot of writes may be short
3835 * sequential writes. eg. scanning/writing a jpeg file.
3836 * In these cases, a short read/write cache can provide a huge perfomance benefit
3837 * with dumb-as-a-rock code.
3838 * In Linux, the page cache provides read buffering aand the short op cache provides write
3841 * There are a limited number (~10) of cache chunks per device so that we don't
3842 * need a very intelligent search.
3845 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3847 yaffs_Device *dev = obj->myDev;
3849 yaffs_ChunkCache *cache;
3850 int nCaches = obj->myDev->nShortOpCaches;
3852 for(i = 0; i < nCaches; i++){
3853 cache = &dev->srCache[i];
3854 if (cache->object == obj &&
3863 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3865 yaffs_Device *dev = obj->myDev;
3866 int lowest = -99; /* Stop compiler whining. */
3868 yaffs_ChunkCache *cache;
3869 int chunkWritten = 0;
3870 int nCaches = obj->myDev->nShortOpCaches;
3876 /* Find the dirty cache for this object with the lowest chunk id. */
3877 for (i = 0; i < nCaches; i++) {
3878 if (dev->srCache[i].object == obj &&
3879 dev->srCache[i].dirty) {
3881 || dev->srCache[i].chunkId <
3883 cache = &dev->srCache[i];
3884 lowest = cache->chunkId;
3889 if (cache && !cache->locked) {
3890 /* Write it out and free it up */
3893 yaffs_WriteChunkDataToObject(cache->object,
3899 cache->object = NULL;
3902 } while (cache && chunkWritten > 0);
3905 /* Hoosterman, disk full while writing cache out. */
3906 T(YAFFS_TRACE_ERROR,
3907 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3914 /*yaffs_FlushEntireDeviceCache(dev)
3919 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3922 int nCaches = dev->nShortOpCaches;
3925 /* Find a dirty object in the cache and flush it...
3926 * until there are no further dirty objects.
3930 for( i = 0; i < nCaches && !obj; i++) {
3931 if (dev->srCache[i].object &&
3932 dev->srCache[i].dirty)
3933 obj = dev->srCache[i].object;
3937 yaffs_FlushFilesChunkCache(obj);
3944 /* Grab us a cache chunk for use.
3945 * First look for an empty one.
3946 * Then look for the least recently used non-dirty one.
3947 * Then look for the least recently used dirty one...., flush and look again.
3949 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];
3963 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
3965 yaffs_ChunkCache *cache;
3966 yaffs_Object *theObj;
3971 if (dev->nShortOpCaches > 0) {
3972 /* Try find a non-dirty one... */
3974 cache = yaffs_GrabChunkCacheWorker(dev);
3977 /* They were all dirty, find the last recently used object and flush
3978 * its cache, then find again.
3979 * NB what's here is not very accurate, we actually flush the object
3980 * the last recently used page.
3983 /* With locking we can't assume we can use entry zero */
3990 for (i = 0; i < dev->nShortOpCaches; i++) {
3991 if (dev->srCache[i].object &&
3992 !dev->srCache[i].locked &&
3993 (dev->srCache[i].lastUse < usage || !cache))
3995 usage = dev->srCache[i].lastUse;
3996 theObj = dev->srCache[i].object;
3997 cache = &dev->srCache[i];
4002 if (!cache || cache->dirty) {
4003 /* Flush and try again */
4004 yaffs_FlushFilesChunkCache(theObj);
4005 cache = yaffs_GrabChunkCacheWorker(dev);
4015 /* Find a cached chunk */
4016 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
4019 yaffs_Device *dev = obj->myDev;
4021 if (dev->nShortOpCaches > 0) {
4022 for (i = 0; i < dev->nShortOpCaches; i++) {
4023 if (dev->srCache[i].object == obj &&
4024 dev->srCache[i].chunkId == chunkId) {
4027 return &dev->srCache[i];
4034 /* Mark the chunk for the least recently used algorithym */
4035 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
4039 if (dev->nShortOpCaches > 0) {
4040 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4041 /* Reset the cache usages */
4043 for (i = 1; i < dev->nShortOpCaches; i++) {
4044 dev->srCache[i].lastUse = 0;
4051 cache->lastUse = dev->srLastUse;
4059 /* Invalidate a single cache page.
4060 * Do this when a whole page gets written,
4061 * ie the short cache for this page is no longer valid.
4063 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
4065 if (object->myDev->nShortOpCaches > 0) {
4066 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4069 cache->object = NULL;
4074 /* Invalidate all the cache pages associated with this object
4075 * Do this whenever ther file is deleted or resized.
4077 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
4080 yaffs_Device *dev = in->myDev;
4082 if (dev->nShortOpCaches > 0) {
4083 /* Invalidate it. */
4084 for (i = 0; i < dev->nShortOpCaches; i++) {
4085 if (dev->srCache[i].object == in) {
4086 dev->srCache[i].object = NULL;
4092 /*--------------------- Checkpointing --------------------*/
4095 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
4097 yaffs_CheckpointValidity cp;
4099 memset(&cp,0,sizeof(cp));
4101 cp.structType = sizeof(cp);
4102 cp.magic = YAFFS_MAGIC;
4103 cp.version = YAFFS_CHECKPOINT_VERSION;
4104 cp.head = (head) ? 1 : 0;
4106 return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
4110 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4112 yaffs_CheckpointValidity cp;
4115 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4118 ok = (cp.structType == sizeof(cp)) &&
4119 (cp.magic == YAFFS_MAGIC) &&
4120 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4121 (cp.head == ((head) ? 1 : 0));
4125 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4128 cp->nErasedBlocks = dev->nErasedBlocks;
4129 cp->allocationBlock = dev->allocationBlock;
4130 cp->allocationPage = dev->allocationPage;
4131 cp->nFreeChunks = dev->nFreeChunks;
4133 cp->nDeletedFiles = dev->nDeletedFiles;
4134 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4135 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4136 cp->sequenceNumber = dev->sequenceNumber;
4137 cp->oldestDirtySequence = dev->oldestDirtySequence;
4141 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4142 yaffs_CheckpointDevice *cp)
4144 dev->nErasedBlocks = cp->nErasedBlocks;
4145 dev->allocationBlock = cp->allocationBlock;
4146 dev->allocationPage = cp->allocationPage;
4147 dev->nFreeChunks = cp->nFreeChunks;
4149 dev->nDeletedFiles = cp->nDeletedFiles;
4150 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4151 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4152 dev->sequenceNumber = cp->sequenceNumber;
4153 dev->oldestDirtySequence = cp->oldestDirtySequence;
4157 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4159 yaffs_CheckpointDevice cp;
4161 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4165 /* Write device runtime values*/
4166 yaffs_DeviceToCheckpointDevice(&cp,dev);
4167 cp.structType = sizeof(cp);
4169 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4171 /* Write block info */
4173 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4174 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
4177 /* Write chunk bits */
4179 nBytes = nBlocks * dev->chunkBitmapStride;
4180 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
4186 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4188 yaffs_CheckpointDevice cp;
4190 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4194 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4198 if(cp.structType != sizeof(cp))
4202 yaffs_CheckpointDeviceToDevice(dev,&cp);
4204 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4206 ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
4210 nBytes = nBlocks * dev->chunkBitmapStride;
4212 ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
4217 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4221 cp->objectId = obj->objectId;
4222 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4223 cp->hdrChunk = obj->hdrChunk;
4224 cp->variantType = obj->variantType;
4225 cp->deleted = obj->deleted;
4226 cp->softDeleted = obj->softDeleted;
4227 cp->unlinked = obj->unlinked;
4228 cp->fake = obj->fake;
4229 cp->renameAllowed = obj->renameAllowed;
4230 cp->unlinkAllowed = obj->unlinkAllowed;
4231 cp->serial = obj->serial;
4232 cp->nDataChunks = obj->nDataChunks;
4234 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4235 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4236 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4237 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4240 static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
4243 yaffs_Object *parent;
4245 obj->objectId = cp->objectId;
4248 parent = yaffs_FindOrCreateObjectByNumber(
4251 YAFFS_OBJECT_TYPE_DIRECTORY);
4256 yaffs_AddObjectToDirectory(parent, obj);
4258 obj->hdrChunk = cp->hdrChunk;
4259 obj->variantType = cp->variantType;
4260 obj->deleted = cp->deleted;
4261 obj->softDeleted = cp->softDeleted;
4262 obj->unlinked = cp->unlinked;
4263 obj->fake = cp->fake;
4264 obj->renameAllowed = cp->renameAllowed;
4265 obj->unlinkAllowed = cp->unlinkAllowed;
4266 obj->serial = cp->serial;
4267 obj->nDataChunks = cp->nDataChunks;
4269 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4270 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4271 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4272 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4274 if(obj->hdrChunk > 0)
4275 obj->lazyLoaded = 1;
4280 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
4281 __u32 level, int chunkOffset)
4284 yaffs_Device *dev = in->myDev;
4286 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4288 if(tnodeSize < sizeof(yaffs_Tnode))
4289 tnodeSize = sizeof(yaffs_Tnode);
4295 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
4296 if (tn->internal[i]) {
4297 ok = yaffs_CheckpointTnodeWorker(in,
4300 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4303 } else if (level == 0) {
4304 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4305 /* printf("write tnode at %d\n",baseOffset); */
4306 ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
4308 ok = (yaffs_CheckpointWrite(dev,tn,tnodeSize) == tnodeSize);
4316 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4318 __u32 endMarker = ~0;
4321 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4322 ok = yaffs_CheckpointTnodeWorker(obj,
4323 obj->variant.fileVariant.top,
4324 obj->variant.fileVariant.topLevel,
4327 ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) ==
4334 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4338 yaffs_Device *dev = obj->myDev;
4339 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4342 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4344 if(tnodeSize < sizeof(yaffs_Tnode))
4345 tnodeSize = sizeof(yaffs_Tnode);
4347 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4349 while(ok && (~baseChunk)){
4351 /* Read level 0 tnode */
4354 /* printf("read tnode at %d\n",baseChunk); */
4355 tn = yaffs_GetTnodeRaw(dev);
4357 ok = (yaffs_CheckpointRead(dev,tn,tnodeSize) == tnodeSize);
4362 ok = yaffs_AddOrFindLevel0Tnode(dev,
4370 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4374 T(YAFFS_TRACE_CHECKPOINT,(
4375 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4376 nread,baseChunk,ok));
4382 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4385 yaffs_CheckpointObject cp;
4388 struct ylist_head *lh;
4391 /* Iterate through the objects in each hash entry,
4392 * dumping them to the checkpointing stream.
4395 for(i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++){
4396 ylist_for_each(lh, &dev->objectBucket[i].list) {
4398 obj = ylist_entry(lh, yaffs_Object, hashLink);
4399 if (!obj->deferedFree) {
4400 yaffs_ObjectToCheckpointObject(&cp,obj);
4401 cp.structType = sizeof(cp);
4403 T(YAFFS_TRACE_CHECKPOINT,(
4404 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
4405 cp.objectId,cp.parentId,cp.variantType,cp.hdrChunk,(unsigned) obj));
4407 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4409 if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4410 ok = yaffs_WriteCheckpointTnodes(obj);
4417 /* Dump end of list */
4418 memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
4419 cp.structType = sizeof(cp);
4422 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4427 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4430 yaffs_CheckpointObject cp;
4433 yaffs_Object *hardList = NULL;
4435 while(ok && !done) {
4436 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4437 if(cp.structType != sizeof(cp)) {
4438 T(YAFFS_TRACE_CHECKPOINT,(TSTR("struct size %d instead of %d ok %d"TENDSTR),
4439 cp.structType,sizeof(cp),ok));
4443 T(YAFFS_TRACE_CHECKPOINT,(TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4444 cp.objectId,cp.parentId,cp.variantType,cp.hdrChunk));
4446 if(ok && cp.objectId == ~0)
4449 obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
4451 yaffs_CheckpointObjectToObject(obj,&cp);
4452 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4453 ok = yaffs_ReadCheckpointTnodes(obj);
4454 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4455 obj->hardLinks.next =
4456 (struct ylist_head *)
4466 yaffs_HardlinkFixup(dev,hardList);
4471 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4473 __u32 checkpointSum;
4476 yaffs_GetCheckpointSum(dev,&checkpointSum);
4478 ok = (yaffs_CheckpointWrite(dev,&checkpointSum,sizeof(checkpointSum)) == sizeof(checkpointSum));
4486 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4488 __u32 checkpointSum0;
4489 __u32 checkpointSum1;
4492 yaffs_GetCheckpointSum(dev,&checkpointSum0);
4494 ok = (yaffs_CheckpointRead(dev,&checkpointSum1,sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4499 if(checkpointSum0 != checkpointSum1)
4506 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4511 if(dev->skipCheckpointWrite || !dev->isYaffs2){
4512 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint write" TENDSTR)));
4517 ok = yaffs_CheckpointOpen(dev,1);
4520 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4521 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
4524 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint device" TENDSTR)));
4525 ok = yaffs_WriteCheckpointDevice(dev);
4528 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint objects" TENDSTR)));
4529 ok = yaffs_WriteCheckpointObjects(dev);
4532 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4533 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
4537 ok = yaffs_WriteCheckpointSum(dev);
4541 if(!yaffs_CheckpointClose(dev))
4545 dev->isCheckpointed = 1;
4547 dev->isCheckpointed = 0;
4549 return dev->isCheckpointed;
4552 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4556 if(dev->skipCheckpointRead || !dev->isYaffs2){
4557 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint read" TENDSTR)));
4562 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
4565 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4566 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
4569 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint device" TENDSTR)));
4570 ok = yaffs_ReadCheckpointDevice(dev);
4573 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint objects" TENDSTR)));
4574 ok = yaffs_ReadCheckpointObjects(dev);
4577 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4578 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
4582 ok = yaffs_ReadCheckpointSum(dev);
4583 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint checksum %d" TENDSTR),ok));
4586 if(!yaffs_CheckpointClose(dev))
4590 dev->isCheckpointed = 1;
4592 dev->isCheckpointed = 0;
4598 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4600 if(dev->isCheckpointed ||
4601 dev->blocksInCheckpoint > 0){
4602 dev->isCheckpointed = 0;
4603 yaffs_CheckpointInvalidateStream(dev);
4604 if(dev->superBlock && dev->markSuperBlockDirty)
4605 dev->markSuperBlockDirty(dev->superBlock);
4610 int yaffs_CheckpointSave(yaffs_Device *dev)
4613 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4615 yaffs_VerifyObjects(dev);
4616 yaffs_VerifyBlocks(dev);
4617 yaffs_VerifyFreeChunks(dev);
4619 if(!dev->isCheckpointed) {
4620 yaffs_InvalidateCheckpoint(dev);
4621 yaffs_WriteCheckpointData(dev);
4624 T(YAFFS_TRACE_ALWAYS,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4626 return dev->isCheckpointed;
4629 int yaffs_CheckpointRestore(yaffs_Device *dev)
4632 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4634 retval = yaffs_ReadCheckpointData(dev);
4636 if(dev->isCheckpointed){
4637 yaffs_VerifyObjects(dev);
4638 yaffs_VerifyBlocks(dev);
4639 yaffs_VerifyFreeChunks(dev);
4642 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4647 /*--------------------- File read/write ------------------------
4648 * Read and write have very similar structures.
4649 * In general the read/write has three parts to it
4650 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4651 * Some complete chunks
4652 * An incomplete chunk to end off with
4654 * Curve-balls: the first chunk might also be the last chunk.
4657 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, loff_t offset,
4666 yaffs_ChunkCache *cache;
4673 //chunk = offset / dev->nDataBytesPerChunk + 1;
4674 //start = offset % dev->nDataBytesPerChunk;
4675 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4678 /* OK now check for the curveball where the start and end are in
4681 if ((start + n) < dev->nDataBytesPerChunk) {
4684 nToCopy = dev->nDataBytesPerChunk - start;
4687 cache = yaffs_FindChunkCache(in, chunk);
4689 /* If the chunk is already in the cache or it is less than a whole chunk
4690 * or we're using inband tags then use the cache (if there is caching)
4691 * else bypass the cache.
4693 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4694 if (dev->nShortOpCaches > 0) {
4696 /* If we can't find the data in the cache, then load it up. */
4699 cache = yaffs_GrabChunkCache(in->myDev);
4701 cache->chunkId = chunk;
4704 yaffs_ReadChunkDataFromObject(in, chunk,
4710 yaffs_UseChunkCache(dev, cache, 0);
4714 #ifdef CONFIG_YAFFS_WINCE
4715 yfsd_UnlockYAFFS(TRUE);
4717 memcpy(buffer, &cache->data[start], nToCopy);
4719 #ifdef CONFIG_YAFFS_WINCE
4720 yfsd_LockYAFFS(TRUE);
4724 /* Read into the local buffer then copy..*/
4727 yaffs_GetTempBuffer(dev, __LINE__);
4728 yaffs_ReadChunkDataFromObject(in, chunk,
4730 #ifdef CONFIG_YAFFS_WINCE
4731 yfsd_UnlockYAFFS(TRUE);
4733 memcpy(buffer, &localBuffer[start], nToCopy);
4735 #ifdef CONFIG_YAFFS_WINCE
4736 yfsd_LockYAFFS(TRUE);
4738 yaffs_ReleaseTempBuffer(dev, localBuffer,
4743 #ifdef CONFIG_YAFFS_WINCE
4744 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4746 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4747 * This is because we otherwise screw up WinCE's memory mapper
4749 yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
4751 #ifdef CONFIG_YAFFS_WINCE
4752 yfsd_UnlockYAFFS(TRUE);
4754 memcpy(buffer, localBuffer, dev->nDataBytesPerChunk);
4756 #ifdef CONFIG_YAFFS_WINCE
4757 yfsd_LockYAFFS(TRUE);
4758 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4762 /* A full chunk. Read directly into the supplied buffer. */
4763 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4777 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, loff_t offset,
4778 int nBytes, int writeThrough)
4787 int startOfWrite = offset;
4788 int chunkWritten = 0;
4795 while (n > 0 && chunkWritten >= 0) {
4796 //chunk = offset / dev->nDataBytesPerChunk + 1;
4797 //start = offset % dev->nDataBytesPerChunk;
4798 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4801 /* OK now check for the curveball where the start and end are in
4805 if ((start + n) < dev->nDataBytesPerChunk) {
4808 /* Now folks, to calculate how many bytes to write back....
4809 * If we're overwriting and not writing to then end of file then
4810 * we need to write back as much as was there before.
4814 in->variant.fileVariant.fileSize -
4815 ((chunk - 1) * dev->nDataBytesPerChunk);
4817 if (nBytesRead > dev->nDataBytesPerChunk) {
4818 nBytesRead = dev->nDataBytesPerChunk;
4823 (start + n)) ? nBytesRead : (start + n);
4826 nToCopy = dev->nDataBytesPerChunk - start;
4827 nToWriteBack = dev->nDataBytesPerChunk;
4830 if (nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4831 /* An incomplete start or end chunk (or maybe both start and end chunk),
4832 * or we're using inband tags, so we want to use the cache buffers.
4834 if (dev->nShortOpCaches > 0) {
4835 yaffs_ChunkCache *cache;
4836 /* If we can't find the data in the cache, then load the cache */
4837 cache = yaffs_FindChunkCache(in, chunk);
4840 && yaffs_CheckSpaceForAllocation(in->
4842 cache = yaffs_GrabChunkCache(in->myDev);
4844 cache->chunkId = chunk;
4847 yaffs_ReadChunkDataFromObject(in, chunk,
4853 !yaffs_CheckSpaceForAllocation(in->myDev)){
4854 /* Drop the cache if it was a read cache item and
4855 * no space check has been made for it.
4861 yaffs_UseChunkCache(dev, cache, 1);
4863 #ifdef CONFIG_YAFFS_WINCE
4864 yfsd_UnlockYAFFS(TRUE);
4867 memcpy(&cache->data[start], buffer,
4870 #ifdef CONFIG_YAFFS_WINCE
4871 yfsd_LockYAFFS(TRUE);
4874 cache->nBytes = nToWriteBack;
4878 yaffs_WriteChunkDataToObject
4881 cache->data, cache->nBytes,
4887 chunkWritten = -1; /* fail the write */
4890 /* An incomplete start or end chunk (or maybe both start and end chunk)
4891 * Read into the local buffer then copy, then copy over and write back.
4895 yaffs_GetTempBuffer(dev, __LINE__);
4897 yaffs_ReadChunkDataFromObject(in, chunk,
4900 #ifdef CONFIG_YAFFS_WINCE
4901 yfsd_UnlockYAFFS(TRUE);
4904 memcpy(&localBuffer[start], buffer, nToCopy);
4906 #ifdef CONFIG_YAFFS_WINCE
4907 yfsd_LockYAFFS(TRUE);
4910 yaffs_WriteChunkDataToObject(in, chunk,
4915 yaffs_ReleaseTempBuffer(dev, localBuffer,
4921 /* A full chunk. Write directly from the supplied buffer. */
4923 #ifdef CONFIG_YAFFS_WINCE
4924 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4925 * This is because we otherwise screw up WinCE's memory mapper
4927 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4928 #ifdef CONFIG_YAFFS_WINCE
4929 yfsd_UnlockYAFFS(TRUE);
4931 memcpy(localBuffer, buffer, dev->nDataBytesPerChunk);
4932 #ifdef CONFIG_YAFFS_WINCE
4933 yfsd_LockYAFFS(TRUE);
4936 yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
4937 dev->nDataBytesPerChunk,
4939 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4943 yaffs_WriteChunkDataToObject(in, chunk, buffer,
4944 dev->nDataBytesPerChunk,
4947 /* Since we've overwritten the cached data, we better invalidate it. */
4948 yaffs_InvalidateChunkCache(in, chunk);
4951 if (chunkWritten >= 0) {
4960 /* Update file object */
4962 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
4963 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4972 /* ---------------------- File resizing stuff ------------------ */
4974 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
4977 yaffs_Device *dev = in->myDev;
4978 int oldFileSize = in->variant.fileVariant.fileSize;
4980 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
4982 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
4983 dev->nDataBytesPerChunk;
4987 /* Delete backwards so that we don't end up with holes if
4988 * power is lost part-way through the operation.
4990 for (i = lastDel; i >= startDel; i--) {
4991 /* NB this could be optimised somewhat,
4992 * eg. could retrieve the tags and write them without
4993 * using yaffs_DeleteChunk
4996 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
4999 (dev->internalStartBlock * dev->nChunksPerBlock)
5001 ((dev->internalEndBlock +
5002 1) * dev->nChunksPerBlock)) {
5003 T(YAFFS_TRACE_ALWAYS,
5004 (TSTR("Found daft chunkId %d for %d" TENDSTR),
5008 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5015 int yaffs_ResizeFile(yaffs_Object * in, loff_t newSize)
5018 int oldFileSize = in->variant.fileVariant.fileSize;
5019 __u32 newSizeOfPartialChunk;
5022 yaffs_Device *dev = in->myDev;
5024 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5026 yaffs_FlushFilesChunkCache(in);
5027 yaffs_InvalidateWholeChunkCache(in);
5029 yaffs_CheckGarbageCollection(dev);
5031 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
5035 if (newSize == oldFileSize) {
5039 if (newSize < oldFileSize) {
5041 yaffs_PruneResizedChunks(in, newSize);
5043 if (newSizeOfPartialChunk != 0) {
5044 int lastChunk = 1 + newFullChunks;
5046 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5048 /* Got to read and rewrite the last chunk with its new size and zero pad */
5049 yaffs_ReadChunkDataFromObject(in, lastChunk,
5052 memset(localBuffer + newSizeOfPartialChunk, 0,
5053 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5055 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5056 newSizeOfPartialChunk, 1);
5058 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5061 in->variant.fileVariant.fileSize = newSize;
5063 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5065 /* newsSize > oldFileSize */
5066 in->variant.fileVariant.fileSize = newSize;
5071 /* Write a new object header.
5072 * show we've shrunk the file, if need be
5073 * Do this only if the file is not in the deleted directories.
5076 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5077 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
5078 yaffs_UpdateObjectHeader(in, NULL, 0,
5079 (newSize < oldFileSize) ? 1 : 0, 0);
5085 loff_t yaffs_GetFileSize(yaffs_Object * obj)
5087 obj = yaffs_GetEquivalentObject(obj);
5089 switch (obj->variantType) {
5090 case YAFFS_OBJECT_TYPE_FILE:
5091 return obj->variant.fileVariant.fileSize;
5092 case YAFFS_OBJECT_TYPE_SYMLINK:
5093 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5101 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
5105 yaffs_FlushFilesChunkCache(in);
5107 #ifdef CONFIG_YAFFS_WINCE
5108 yfsd_WinFileTimeNow(in->win_mtime);
5111 in->yst_mtime = Y_CURRENT_TIME;
5117 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5118 0) ? YAFFS_OK : YAFFS_FAIL;
5127 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
5130 /* First off, invalidate the file's data in the cache, without flushing. */
5131 yaffs_InvalidateWholeChunkCache(in);
5133 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5134 /* Move to the unlinked directory so we have a record that it was deleted. */
5135 yaffs_ChangeObjectName(in, in->myDev->deletedDir,_Y("deleted"), 0, 0);
5139 yaffs_RemoveObjectFromDirectory(in);
5140 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5143 yaffs_FreeObject(in);
5148 /* yaffs_DeleteFile deletes the whole file data
5149 * and the inode associated with the file.
5150 * It does not delete the links associated with the file.
5152 static int yaffs_UnlinkFile(yaffs_Object * in)
5156 int immediateDeletion = 0;
5161 immediateDeletion = 1;
5165 if (in->inUse <= 0) {
5166 immediateDeletion = 1;
5170 if (immediateDeletion) {
5172 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5173 _Y("deleted"), 0, 0);
5174 T(YAFFS_TRACE_TRACING,
5175 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5178 in->myDev->nDeletedFiles++;
5179 if (0 && in->myDev->isYaffs2) {
5180 yaffs_ResizeFile(in, 0);
5182 yaffs_SoftDeleteFile(in);
5185 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5186 _Y("unlinked"), 0, 0);
5193 int yaffs_DeleteFile(yaffs_Object * in)
5195 int retVal = YAFFS_OK;
5197 if (in->nDataChunks > 0) {
5198 /* Use soft deletion if there is data in the file */
5199 if (!in->unlinked) {
5200 retVal = yaffs_UnlinkFile(in);
5202 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5204 in->myDev->nDeletedFiles++;
5205 yaffs_SoftDeleteFile(in);
5207 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
5209 /* The file has no data chunks so we toss it immediately */
5210 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5211 in->variant.fileVariant.top = NULL;
5212 yaffs_DoGenericObjectDeletion(in);
5218 static int yaffs_DeleteDirectory(yaffs_Object * in)
5220 /* First check that the directory is empty. */
5221 if (ylist_empty(&in->variant.directoryVariant.children)) {
5222 return yaffs_DoGenericObjectDeletion(in);
5229 static int yaffs_DeleteSymLink(yaffs_Object * in)
5231 YFREE(in->variant.symLinkVariant.alias);
5233 return yaffs_DoGenericObjectDeletion(in);
5236 static int yaffs_DeleteHardLink(yaffs_Object * in)
5238 /* remove this hardlink from the list assocaited with the equivalent
5241 ylist_del(&in->hardLinks);
5242 return yaffs_DoGenericObjectDeletion(in);
5245 static void yaffs_DestroyObject(yaffs_Object * obj)
5247 switch (obj->variantType) {
5248 case YAFFS_OBJECT_TYPE_FILE:
5249 yaffs_DeleteFile(obj);
5251 case YAFFS_OBJECT_TYPE_DIRECTORY:
5252 yaffs_DeleteDirectory(obj);
5254 case YAFFS_OBJECT_TYPE_SYMLINK:
5255 yaffs_DeleteSymLink(obj);
5257 case YAFFS_OBJECT_TYPE_HARDLINK:
5258 yaffs_DeleteHardLink(obj);
5260 case YAFFS_OBJECT_TYPE_SPECIAL:
5261 yaffs_DoGenericObjectDeletion(obj);
5263 case YAFFS_OBJECT_TYPE_UNKNOWN:
5264 break; /* should not happen. */
5268 static int yaffs_UnlinkWorker(yaffs_Object * obj)
5271 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5272 return yaffs_DeleteHardLink(obj);
5273 } else if (!ylist_empty(&obj->hardLinks)) {
5274 /* Curve ball: We're unlinking an object that has a hardlink.
5276 * This problem arises because we are not strictly following
5277 * The Linux link/inode model.
5279 * We can't really delete the object.
5280 * Instead, we do the following:
5281 * - Select a hardlink.
5282 * - Unhook it from the hard links
5283 * - Unhook it from its parent directory (so that the rename can work)
5284 * - Rename the object to the hardlink's name.
5285 * - Delete the hardlink
5290 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5292 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5294 ylist_del_init(&hl->hardLinks);
5295 ylist_del_init(&hl->siblings);
5297 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5299 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
5301 if (retVal == YAFFS_OK) {
5302 retVal = yaffs_DoGenericObjectDeletion(hl);
5307 switch (obj->variantType) {
5308 case YAFFS_OBJECT_TYPE_FILE:
5309 return yaffs_UnlinkFile(obj);
5311 case YAFFS_OBJECT_TYPE_DIRECTORY:
5312 return yaffs_DeleteDirectory(obj);
5314 case YAFFS_OBJECT_TYPE_SYMLINK:
5315 return yaffs_DeleteSymLink(obj);
5317 case YAFFS_OBJECT_TYPE_SPECIAL:
5318 return yaffs_DoGenericObjectDeletion(obj);
5320 case YAFFS_OBJECT_TYPE_HARDLINK:
5321 case YAFFS_OBJECT_TYPE_UNKNOWN:
5329 static int yaffs_UnlinkObject( yaffs_Object *obj)
5332 if (obj && obj->unlinkAllowed) {
5333 return yaffs_UnlinkWorker(obj);
5339 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
5343 obj = yaffs_FindObjectByName(dir, name);
5344 return yaffs_UnlinkObject(obj);
5347 /*----------------------- Initialisation Scanning ---------------------- */
5349 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
5350 int backwardScanning)
5354 if (!backwardScanning) {
5355 /* Handle YAFFS1 forward scanning case
5356 * For YAFFS1 we always do the deletion
5360 /* Handle YAFFS2 case (backward scanning)
5361 * If the shadowed object exists then ignore.
5363 if (yaffs_FindObjectByNumber(dev, objId)) {
5368 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5369 * We put it in unlinked dir to be cleaned up after the scanning
5372 yaffs_FindOrCreateObjectByNumber(dev, objId,
5373 YAFFS_OBJECT_TYPE_FILE);
5374 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5375 obj->variant.fileVariant.shrinkSize = 0;
5376 obj->valid = 1; /* So that we don't read any other info for this file */
5386 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5393 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5395 in = yaffs_FindObjectByNumber(dev,
5396 hl->variant.hardLinkVariant.
5397 equivalentObjectId);
5400 /* Add the hardlink pointers */
5401 hl->variant.hardLinkVariant.equivalentObject = in;
5402 ylist_add(&hl->hardLinks, &in->hardLinks);
5404 /* Todo Need to report/handle this better.
5405 * Got a problem... hardlink to a non-existant object
5407 hl->variant.hardLinkVariant.equivalentObject = NULL;
5408 YINIT_LIST_HEAD(&hl->hardLinks);
5420 static int ybicmp(const void *a, const void *b){
5421 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5422 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5423 register int ablock = ((yaffs_BlockIndex *)a)->block;
5424 register int bblock = ((yaffs_BlockIndex *)b)->block;
5426 return ablock - bblock;
5433 struct yaffs_ShadowFixerStruct {
5436 struct yaffs_ShadowFixerStruct *next;
5439 static int yaffs_Scan(yaffs_Device * dev)
5441 yaffs_ExtendedTags tags;
5451 yaffs_BlockState state;
5452 yaffs_Object *hardList = NULL;
5453 yaffs_BlockInfo *bi;
5454 __u32 sequenceNumber;
5455 yaffs_ObjectHeader *oh;
5457 yaffs_Object *parent;
5459 int alloc_failed = 0;
5461 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5469 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5470 dev->internalStartBlock, dev->internalEndBlock));
5472 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5474 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5476 /* Scan all the blocks to determine their state */
5477 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5478 bi = yaffs_GetBlockInfo(dev, blk);
5479 yaffs_ClearChunkBits(dev, blk);
5481 bi->softDeletions = 0;
5483 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5485 bi->blockState = state;
5486 bi->sequenceNumber = sequenceNumber;
5488 T(YAFFS_TRACE_SCAN_DEBUG,
5489 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5490 state, sequenceNumber));
5492 if (state == YAFFS_BLOCK_STATE_DEAD) {
5493 T(YAFFS_TRACE_BAD_BLOCKS,
5494 (TSTR("block %d is bad" TENDSTR), blk));
5495 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5496 T(YAFFS_TRACE_SCAN_DEBUG,
5497 (TSTR("Block empty " TENDSTR)));
5498 dev->nErasedBlocks++;
5499 dev->nFreeChunks += dev->nChunksPerBlock;
5503 startIterator = dev->internalStartBlock;
5504 endIterator = dev->internalEndBlock;
5506 /* For each block.... */
5507 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5514 blk = blockIterator;
5516 bi = yaffs_GetBlockInfo(dev, blk);
5517 state = bi->blockState;
5521 /* For each chunk in each block that needs scanning....*/
5522 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5523 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5524 /* Read the tags and decide what to do */
5525 chunk = blk * dev->nChunksPerBlock + c;
5527 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5530 /* Let's have a good look at this chunk... */
5532 if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
5538 /*T((" %d %d deleted\n",blk,c)); */
5539 } else if (!tags.chunkUsed) {
5540 /* An unassigned chunk in the block
5541 * This means that either the block is empty or
5542 * this is the one being allocated from
5546 /* We're looking at the first chunk in the block so the block is unused */
5547 state = YAFFS_BLOCK_STATE_EMPTY;
5548 dev->nErasedBlocks++;
5550 /* this is the block being allocated from */
5553 (" Allocating from %d %d" TENDSTR),
5555 state = YAFFS_BLOCK_STATE_ALLOCATING;
5556 dev->allocationBlock = blk;
5557 dev->allocationPage = c;
5558 dev->allocationBlockFinder = blk;
5559 /* Set it to here to encourage the allocator to go forth from here. */
5563 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5564 } else if (tags.chunkId > 0) {
5565 /* chunkId > 0 so it is a data chunk... */
5566 unsigned int endpos;
5568 yaffs_SetChunkBit(dev, blk, c);
5571 in = yaffs_FindOrCreateObjectByNumber(dev,
5574 YAFFS_OBJECT_TYPE_FILE);
5575 /* PutChunkIntoFile checks for a clash (two data chunks with
5576 * the same chunkId).
5583 if(!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,1))
5588 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5591 in->variantType == YAFFS_OBJECT_TYPE_FILE
5592 && in->variant.fileVariant.scannedFileSize <
5594 in->variant.fileVariant.
5595 scannedFileSize = endpos;
5596 if (!dev->useHeaderFileSize) {
5597 in->variant.fileVariant.
5599 in->variant.fileVariant.
5604 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
5606 /* chunkId == 0, so it is an ObjectHeader.
5607 * Thus, we read in the object header and make the object
5609 yaffs_SetChunkBit(dev, blk, c);
5612 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5616 oh = (yaffs_ObjectHeader *) chunkData;
5618 in = yaffs_FindObjectByNumber(dev,
5620 if (in && in->variantType != oh->type) {
5621 /* This should not happen, but somehow
5622 * Wev'e ended up with an objectId that has been reused but not yet
5623 * deleted, and worse still it has changed type. Delete the old object.
5626 yaffs_DestroyObject(in);
5631 in = yaffs_FindOrCreateObjectByNumber(dev,
5639 if (in && oh->shadowsObject > 0) {
5641 struct yaffs_ShadowFixerStruct *fixer;
5642 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
5644 fixer-> next = shadowFixerList;
5645 shadowFixerList = fixer;
5646 fixer->objectId = tags.objectId;
5647 fixer->shadowedId = oh->shadowsObject;
5652 if (in && in->valid) {
5653 /* We have already filled this one. We have a duplicate and need to resolve it. */
5655 unsigned existingSerial = in->serial;
5656 unsigned newSerial = tags.serialNumber;
5658 if (((existingSerial + 1) & 3) == newSerial) {
5659 /* Use new one - destroy the exisiting one */
5660 yaffs_DeleteChunk(dev,
5665 /* Use existing - destroy this one. */
5666 yaffs_DeleteChunk(dev, chunk, 1,
5671 if (in && !in->valid &&
5672 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5673 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5674 /* We only load some info, don't fiddle with directory structure */
5676 in->variantType = oh->type;
5678 in->yst_mode = oh->yst_mode;
5679 #ifdef CONFIG_YAFFS_WINCE
5680 in->win_atime[0] = oh->win_atime[0];
5681 in->win_ctime[0] = oh->win_ctime[0];
5682 in->win_mtime[0] = oh->win_mtime[0];
5683 in->win_atime[1] = oh->win_atime[1];
5684 in->win_ctime[1] = oh->win_ctime[1];
5685 in->win_mtime[1] = oh->win_mtime[1];
5687 in->yst_uid = oh->yst_uid;
5688 in->yst_gid = oh->yst_gid;
5689 in->yst_atime = oh->yst_atime;
5690 in->yst_mtime = oh->yst_mtime;
5691 in->yst_ctime = oh->yst_ctime;
5692 in->yst_rdev = oh->yst_rdev;
5694 in->hdrChunk = chunk;
5696 } else if (in && !in->valid) {
5697 /* we need to load this info */
5700 in->variantType = oh->type;
5702 in->yst_mode = oh->yst_mode;
5703 #ifdef CONFIG_YAFFS_WINCE
5704 in->win_atime[0] = oh->win_atime[0];
5705 in->win_ctime[0] = oh->win_ctime[0];
5706 in->win_mtime[0] = oh->win_mtime[0];
5707 in->win_atime[1] = oh->win_atime[1];
5708 in->win_ctime[1] = oh->win_ctime[1];
5709 in->win_mtime[1] = oh->win_mtime[1];
5711 in->yst_uid = oh->yst_uid;
5712 in->yst_gid = oh->yst_gid;
5713 in->yst_atime = oh->yst_atime;
5714 in->yst_mtime = oh->yst_mtime;
5715 in->yst_ctime = oh->yst_ctime;
5716 in->yst_rdev = oh->yst_rdev;
5718 in->hdrChunk = chunk;
5720 yaffs_SetObjectName(in, oh->name);
5723 /* directory stuff...
5728 yaffs_FindOrCreateObjectByNumber
5729 (dev, oh->parentObjectId,
5730 YAFFS_OBJECT_TYPE_DIRECTORY);
5731 if (parent->variantType ==
5732 YAFFS_OBJECT_TYPE_UNKNOWN) {
5733 /* Set up as a directory */
5734 parent->variantType =
5735 YAFFS_OBJECT_TYPE_DIRECTORY;
5736 YINIT_LIST_HEAD(&parent->variant.
5739 } else if (parent->variantType !=
5740 YAFFS_OBJECT_TYPE_DIRECTORY)
5742 /* Hoosterman, another problem....
5743 * We're trying to use a non-directory as a directory
5746 T(YAFFS_TRACE_ERROR,
5748 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
5750 parent = dev->lostNFoundDir;
5753 yaffs_AddObjectToDirectory(parent, in);
5755 if (0 && (parent == dev->deletedDir ||
5756 parent == dev->unlinkedDir)) {
5757 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
5758 dev->nDeletedFiles++;
5760 /* Note re hardlinks.
5761 * Since we might scan a hardlink before its equivalent object is scanned
5762 * we put them all in a list.
5763 * After scanning is complete, we should have all the objects, so we run through this
5764 * list and fix up all the chains.
5767 switch (in->variantType) {
5768 case YAFFS_OBJECT_TYPE_UNKNOWN:
5769 /* Todo got a problem */
5771 case YAFFS_OBJECT_TYPE_FILE:
5772 if (dev->useHeaderFileSize)
5774 in->variant.fileVariant.
5779 case YAFFS_OBJECT_TYPE_HARDLINK:
5780 in->variant.hardLinkVariant.
5781 equivalentObjectId =
5782 oh->equivalentObjectId;
5783 in->hardLinks.next =
5784 (struct ylist_head *)
5788 case YAFFS_OBJECT_TYPE_DIRECTORY:
5791 case YAFFS_OBJECT_TYPE_SPECIAL:
5794 case YAFFS_OBJECT_TYPE_SYMLINK:
5795 in->variant.symLinkVariant.alias =
5796 yaffs_CloneString(oh->alias);
5797 if(!in->variant.symLinkVariant.alias)
5802 if (parent == dev->deletedDir) {
5803 yaffs_DestroyObject(in);
5804 bi->hasShrinkHeader = 1;
5810 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5811 /* If we got this far while scanning, then the block is fully allocated.*/
5812 state = YAFFS_BLOCK_STATE_FULL;
5815 bi->blockState = state;
5817 /* Now let's see if it was dirty */
5818 if (bi->pagesInUse == 0 &&
5819 !bi->hasShrinkHeader &&
5820 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5821 yaffs_BlockBecameDirty(dev, blk);
5827 /* Ok, we've done all the scanning.
5828 * Fix up the hard link chains.
5829 * We should now have scanned all the objects, now it's time to add these
5833 yaffs_HardlinkFixup(dev,hardList);
5835 /* Handle the unlinked files. Since they were left in an unlinked state we should
5839 struct ylist_head *i;
5840 struct ylist_head *n;
5843 /* Soft delete all the unlinked files */
5844 ylist_for_each_safe(i, n,
5845 &dev->unlinkedDir->variant.directoryVariant.
5848 l = ylist_entry(i, yaffs_Object, siblings);
5849 yaffs_DestroyObject(l);
5854 /* Fix up any shadowed objects */
5856 struct yaffs_ShadowFixerStruct *fixer;
5859 while(shadowFixerList){
5860 fixer = shadowFixerList;
5861 shadowFixerList = fixer->next;
5862 /* Complete the rename transaction by deleting the shadowed object
5863 * then setting the object header to unshadowed.
5865 obj = yaffs_FindObjectByNumber(dev,fixer->shadowedId);
5867 yaffs_DestroyObject(obj);
5869 obj = yaffs_FindObjectByNumber(dev,fixer->objectId);
5871 yaffs_UpdateObjectHeader(obj,NULL,1,0,0);
5878 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5884 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5890 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5893 yaffs_ObjectHeader *oh;
5895 yaffs_ExtendedTags tags;
5897 int alloc_failed = 0;
5905 T(YAFFS_TRACE_SCAN,(TSTR("details for object %d %s loaded" TENDSTR),
5907 in->lazyLoaded ? "not yet" : "already"));
5910 if(in->lazyLoaded && in->hdrChunk > 0){
5912 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5914 result = yaffs_ReadChunkWithTagsFromNAND(dev,in->hdrChunk,chunkData,&tags);
5915 oh = (yaffs_ObjectHeader *) chunkData;
5917 in->yst_mode = oh->yst_mode;
5918 #ifdef CONFIG_YAFFS_WINCE
5919 in->win_atime[0] = oh->win_atime[0];
5920 in->win_ctime[0] = oh->win_ctime[0];
5921 in->win_mtime[0] = oh->win_mtime[0];
5922 in->win_atime[1] = oh->win_atime[1];
5923 in->win_ctime[1] = oh->win_ctime[1];
5924 in->win_mtime[1] = oh->win_mtime[1];
5926 in->yst_uid = oh->yst_uid;
5927 in->yst_gid = oh->yst_gid;
5928 in->yst_atime = oh->yst_atime;
5929 in->yst_mtime = oh->yst_mtime;
5930 in->yst_ctime = oh->yst_ctime;
5931 in->yst_rdev = oh->yst_rdev;
5934 yaffs_SetObjectName(in, oh->name);
5936 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
5937 in->variant.symLinkVariant.alias =
5938 yaffs_CloneString(oh->alias);
5939 if(!in->variant.symLinkVariant.alias)
5940 alloc_failed = 1; /* Not returned to caller */
5943 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
5947 static int yaffs_ScanBackwards(yaffs_Device * dev)
5949 yaffs_ExtendedTags tags;
5954 int nBlocksToScan = 0;
5960 yaffs_BlockState state;
5961 yaffs_Object *hardList = NULL;
5962 yaffs_BlockInfo *bi;
5963 __u32 sequenceNumber;
5964 yaffs_ObjectHeader *oh;
5966 yaffs_Object *parent;
5967 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5973 int foundChunksInBlock;
5974 int equivalentObjectId;
5975 int alloc_failed = 0;
5978 yaffs_BlockIndex *blockIndex = NULL;
5979 int altBlockIndex = 0;
5981 if (!dev->isYaffs2) {
5983 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
5989 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
5990 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
5993 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5995 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
5998 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6004 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6008 dev->blocksInCheckpoint = 0;
6010 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6012 /* Scan all the blocks to determine their state */
6013 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6014 bi = yaffs_GetBlockInfo(dev, blk);
6015 yaffs_ClearChunkBits(dev, blk);
6017 bi->softDeletions = 0;
6019 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6021 bi->blockState = state;
6022 bi->sequenceNumber = sequenceNumber;
6024 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6025 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6027 T(YAFFS_TRACE_SCAN_DEBUG,
6028 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6029 state, sequenceNumber));
6032 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
6033 dev->blocksInCheckpoint++;
6035 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6036 T(YAFFS_TRACE_BAD_BLOCKS,
6037 (TSTR("block %d is bad" TENDSTR), blk));
6038 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6039 T(YAFFS_TRACE_SCAN_DEBUG,
6040 (TSTR("Block empty " TENDSTR)));
6041 dev->nErasedBlocks++;
6042 dev->nFreeChunks += dev->nChunksPerBlock;
6043 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6045 /* Determine the highest sequence number */
6046 if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6047 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6049 blockIndex[nBlocksToScan].seq = sequenceNumber;
6050 blockIndex[nBlocksToScan].block = blk;
6054 if (sequenceNumber >= dev->sequenceNumber) {
6055 dev->sequenceNumber = sequenceNumber;
6058 /* TODO: Nasty sequence number! */
6061 ("Block scanning block %d has bad sequence number %d"
6062 TENDSTR), blk, sequenceNumber));
6069 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6075 /* Sort the blocks */
6076 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6078 /* Use qsort now. */
6079 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6083 /* Dungy old bubble sort... */
6085 yaffs_BlockIndex temp;
6089 for (i = 0; i < nBlocksToScan; i++)
6090 for (j = i + 1; j < nBlocksToScan; j++)
6091 if (blockIndex[i].seq > blockIndex[j].seq) {
6092 temp = blockIndex[j];
6093 blockIndex[j] = blockIndex[i];
6094 blockIndex[i] = temp;
6101 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6103 /* Now scan the blocks looking at the data. */
6105 endIterator = nBlocksToScan - 1;
6106 T(YAFFS_TRACE_SCAN_DEBUG,
6107 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6109 /* For each block.... backwards */
6110 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6112 /* Cooperative multitasking! This loop can run for so
6113 long that watchdog timers expire. */
6116 /* get the block to scan in the correct order */
6117 blk = blockIndex[blockIterator].block;
6119 bi = yaffs_GetBlockInfo(dev, blk);
6122 state = bi->blockState;
6126 /* For each chunk in each block that needs scanning.... */
6127 foundChunksInBlock = 0;
6128 for (c = dev->nChunksPerBlock - 1;
6129 !alloc_failed && c >= 0 &&
6130 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6131 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6132 /* Scan backwards...
6133 * Read the tags and decide what to do
6136 chunk = blk * dev->nChunksPerBlock + c;
6138 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6141 /* Let's have a good look at this chunk... */
6143 if (!tags.chunkUsed) {
6144 /* An unassigned chunk in the block.
6145 * If there are used chunks after this one, then
6146 * it is a chunk that was skipped due to failing the erased
6147 * check. Just skip it so that it can be deleted.
6148 * But, more typically, We get here when this is an unallocated
6149 * chunk and his means that either the block is empty or
6150 * this is the one being allocated from
6153 if(foundChunksInBlock)
6155 /* This is a chunk that was skipped due to failing the erased check */
6157 } else if (c == 0) {
6158 /* We're looking at the first chunk in the block so the block is unused */
6159 state = YAFFS_BLOCK_STATE_EMPTY;
6160 dev->nErasedBlocks++;
6162 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6163 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6164 if(dev->sequenceNumber == bi->sequenceNumber) {
6165 /* this is the block being allocated from */
6169 (" Allocating from %d %d"
6172 state = YAFFS_BLOCK_STATE_ALLOCATING;
6173 dev->allocationBlock = blk;
6174 dev->allocationPage = c;
6175 dev->allocationBlockFinder = blk;
6178 /* This is a partially written block that is not
6179 * the current allocation block. This block must have
6180 * had a write failure, so set up for retirement.
6183 /* bi->needsRetiring = 1; ??? TODO */
6184 bi->gcPrioritise = 1;
6186 T(YAFFS_TRACE_ALWAYS,
6187 (TSTR("Partially written block %d detected" TENDSTR),
6197 } else if (tags.chunkId > 0) {
6198 /* chunkId > 0 so it is a data chunk... */
6199 unsigned int endpos;
6201 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6203 foundChunksInBlock = 1;
6206 yaffs_SetChunkBit(dev, blk, c);
6209 in = yaffs_FindOrCreateObjectByNumber(dev,
6212 YAFFS_OBJECT_TYPE_FILE);
6219 in->variantType == YAFFS_OBJECT_TYPE_FILE
6221 in->variant.fileVariant.shrinkSize) {
6222 /* This has not been invalidated by a resize */
6223 if(!yaffs_PutChunkIntoFile(in, tags.chunkId,
6228 /* File size is calculated by looking at the data chunks if we have not
6229 * seen an object header yet. Stop this practice once we find an object header.
6233 1) * dev->nDataBytesPerChunk +
6236 if (!in->valid && /* have not got an object header yet */
6237 in->variant.fileVariant.
6238 scannedFileSize < endpos) {
6239 in->variant.fileVariant.
6240 scannedFileSize = endpos;
6241 in->variant.fileVariant.
6243 in->variant.fileVariant.
6248 /* This chunk has been invalidated by a resize, so delete */
6249 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6253 /* chunkId == 0, so it is an ObjectHeader.
6254 * Thus, we read in the object header and make the object
6256 foundChunksInBlock = 1;
6258 yaffs_SetChunkBit(dev, blk, c);
6264 if (tags.extraHeaderInfoAvailable) {
6265 in = yaffs_FindOrCreateObjectByNumber
6266 (dev, tags.objectId,
6267 tags.extraObjectType);
6271 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
6274 tags.extraShadows ||
6276 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6277 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
6280 /* If we don't have valid info then we need to read the chunk
6281 * TODO In future we can probably defer reading the chunk and
6282 * living with invalid data until needed.
6285 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6290 oh = (yaffs_ObjectHeader *) chunkData;
6292 if(dev->inbandTags){
6293 /* Fix up the header if they got corrupted by inband tags */
6294 oh->shadowsObject = oh->inbandShadowsObject;
6295 oh->isShrink = oh->inbandIsShrink;
6299 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6304 /* TODO Hoosterman we have a problem! */
6305 T(YAFFS_TRACE_ERROR,
6307 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6308 TENDSTR), tags.objectId, chunk));
6313 /* We have already filled this one.
6314 * We have a duplicate that will be discarded, but
6315 * we first have to suck out resize info if it is a file.
6318 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6320 oh-> type == YAFFS_OBJECT_TYPE_FILE)||
6321 (tags.extraHeaderInfoAvailable &&
6322 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
6325 (oh) ? oh->fileSize : tags.
6327 __u32 parentObjectId =
6329 parentObjectId : tags.
6330 extraParentObjectId;
6334 (oh) ? oh->isShrink : tags.
6335 extraIsShrinkHeader;
6337 /* If it is deleted (unlinked at start also means deleted)
6338 * we treat the file size as being zeroed at this point.
6340 if (parentObjectId ==
6341 YAFFS_OBJECTID_DELETED
6342 || parentObjectId ==
6343 YAFFS_OBJECTID_UNLINKED) {
6349 in->variant.fileVariant.
6350 shrinkSize > thisSize) {
6351 in->variant.fileVariant.
6357 bi->hasShrinkHeader = 1;
6361 /* Use existing - destroy this one. */
6362 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6367 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6369 YAFFS_OBJECTID_LOSTNFOUND)) {
6370 /* We only load some info, don't fiddle with directory structure */
6374 in->variantType = oh->type;
6376 in->yst_mode = oh->yst_mode;
6377 #ifdef CONFIG_YAFFS_WINCE
6378 in->win_atime[0] = oh->win_atime[0];
6379 in->win_ctime[0] = oh->win_ctime[0];
6380 in->win_mtime[0] = oh->win_mtime[0];
6381 in->win_atime[1] = oh->win_atime[1];
6382 in->win_ctime[1] = oh->win_ctime[1];
6383 in->win_mtime[1] = oh->win_mtime[1];
6385 in->yst_uid = oh->yst_uid;
6386 in->yst_gid = oh->yst_gid;
6387 in->yst_atime = oh->yst_atime;
6388 in->yst_mtime = oh->yst_mtime;
6389 in->yst_ctime = oh->yst_ctime;
6390 in->yst_rdev = oh->yst_rdev;
6394 in->variantType = tags.extraObjectType;
6398 in->hdrChunk = chunk;
6400 } else if (!in->valid) {
6401 /* we need to load this info */
6404 in->hdrChunk = chunk;
6407 in->variantType = oh->type;
6409 in->yst_mode = oh->yst_mode;
6410 #ifdef CONFIG_YAFFS_WINCE
6411 in->win_atime[0] = oh->win_atime[0];
6412 in->win_ctime[0] = oh->win_ctime[0];
6413 in->win_mtime[0] = oh->win_mtime[0];
6414 in->win_atime[1] = oh->win_atime[1];
6415 in->win_ctime[1] = oh->win_ctime[1];
6416 in->win_mtime[1] = oh->win_mtime[1];
6418 in->yst_uid = oh->yst_uid;
6419 in->yst_gid = oh->yst_gid;
6420 in->yst_atime = oh->yst_atime;
6421 in->yst_mtime = oh->yst_mtime;
6422 in->yst_ctime = oh->yst_ctime;
6423 in->yst_rdev = oh->yst_rdev;
6426 if (oh->shadowsObject > 0)
6427 yaffs_HandleShadowedObject(dev,
6433 yaffs_SetObjectName(in, oh->name);
6435 yaffs_FindOrCreateObjectByNumber
6436 (dev, oh->parentObjectId,
6437 YAFFS_OBJECT_TYPE_DIRECTORY);
6439 fileSize = oh->fileSize;
6440 isShrink = oh->isShrink;
6441 equivalentObjectId = oh->equivalentObjectId;
6445 in->variantType = tags.extraObjectType;
6447 yaffs_FindOrCreateObjectByNumber
6448 (dev, tags.extraParentObjectId,
6449 YAFFS_OBJECT_TYPE_DIRECTORY);
6450 fileSize = tags.extraFileLength;
6451 isShrink = tags.extraIsShrinkHeader;
6452 equivalentObjectId = tags.extraEquivalentObjectId;
6458 /* directory stuff...
6462 if (parent->variantType ==
6463 YAFFS_OBJECT_TYPE_UNKNOWN) {
6464 /* Set up as a directory */
6465 parent->variantType =
6466 YAFFS_OBJECT_TYPE_DIRECTORY;
6467 YINIT_LIST_HEAD(&parent->variant.
6470 } else if (parent->variantType !=
6471 YAFFS_OBJECT_TYPE_DIRECTORY)
6473 /* Hoosterman, another problem....
6474 * We're trying to use a non-directory as a directory
6477 T(YAFFS_TRACE_ERROR,
6479 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6481 parent = dev->lostNFoundDir;
6484 yaffs_AddObjectToDirectory(parent, in);
6486 itsUnlinked = (parent == dev->deletedDir) ||
6487 (parent == dev->unlinkedDir);
6490 /* Mark the block as having a shrinkHeader */
6491 bi->hasShrinkHeader = 1;
6494 /* Note re hardlinks.
6495 * Since we might scan a hardlink before its equivalent object is scanned
6496 * we put them all in a list.
6497 * After scanning is complete, we should have all the objects, so we run
6498 * through this list and fix up all the chains.
6501 switch (in->variantType) {
6502 case YAFFS_OBJECT_TYPE_UNKNOWN:
6503 /* Todo got a problem */
6505 case YAFFS_OBJECT_TYPE_FILE:
6507 if (in->variant.fileVariant.
6508 scannedFileSize < fileSize) {
6509 /* This covers the case where the file size is greater
6510 * than where the data is
6511 * This will happen if the file is resized to be larger
6512 * than its current data extents.
6514 in->variant.fileVariant.fileSize = fileSize;
6515 in->variant.fileVariant.scannedFileSize =
6516 in->variant.fileVariant.fileSize;
6520 in->variant.fileVariant.shrinkSize > fileSize) {
6521 in->variant.fileVariant.shrinkSize = fileSize;
6525 case YAFFS_OBJECT_TYPE_HARDLINK:
6527 in->variant.hardLinkVariant.equivalentObjectId =
6529 in->hardLinks.next =
6530 (struct ylist_head *) hardList;
6534 case YAFFS_OBJECT_TYPE_DIRECTORY:
6537 case YAFFS_OBJECT_TYPE_SPECIAL:
6540 case YAFFS_OBJECT_TYPE_SYMLINK:
6542 in->variant.symLinkVariant.alias =
6543 yaffs_CloneString(oh->
6545 if(!in->variant.symLinkVariant.alias)
6555 } /* End of scanning for each chunk */
6557 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6558 /* If we got this far while scanning, then the block is fully allocated. */
6559 state = YAFFS_BLOCK_STATE_FULL;
6562 bi->blockState = state;
6564 /* Now let's see if it was dirty */
6565 if (bi->pagesInUse == 0 &&
6566 !bi->hasShrinkHeader &&
6567 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6568 yaffs_BlockBecameDirty(dev, blk);
6574 YFREE_ALT(blockIndex);
6578 /* Ok, we've done all the scanning.
6579 * Fix up the hard link chains.
6580 * We should now have scanned all the objects, now it's time to add these
6583 yaffs_HardlinkFixup(dev,hardList);
6587 * Sort out state of unlinked and deleted objects.
6590 struct ylist_head *i;
6591 struct ylist_head *n;
6595 /* Soft delete all the unlinked files */
6596 ylist_for_each_safe(i, n,
6597 &dev->unlinkedDir->variant.directoryVariant.
6600 l = ylist_entry(i, yaffs_Object, siblings);
6601 yaffs_DestroyObject(l);
6605 /* Soft delete all the deletedDir files */
6606 ylist_for_each_safe(i, n,
6607 &dev->deletedDir->variant.directoryVariant.
6610 l = ylist_entry(i, yaffs_Object, siblings);
6611 yaffs_DestroyObject(l);
6617 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6623 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6628 /*------------------------------ Directory Functions ----------------------------- */
6630 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
6632 yaffs_Device *dev = obj->myDev;
6634 if(dev && dev->removeObjectCallback)
6635 dev->removeObjectCallback(obj);
6637 ylist_del_init(&obj->siblings);
6642 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
6647 T(YAFFS_TRACE_ALWAYS,
6649 ("tragedy: Trying to add an object to a null pointer directory"
6653 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6654 T(YAFFS_TRACE_ALWAYS,
6656 ("tragedy: Trying to add an object to a non-directory"
6661 if (obj->siblings.prev == NULL) {
6662 /* Not initialised */
6663 YINIT_LIST_HEAD(&obj->siblings);
6665 } else if (!ylist_empty(&obj->siblings)) {
6666 /* If it is holed up somewhere else, un hook it */
6667 yaffs_RemoveObjectFromDirectory(obj);
6670 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
6671 obj->parent = directory;
6673 if (directory == obj->myDev->unlinkedDir
6674 || directory == obj->myDev->deletedDir) {
6676 obj->myDev->nUnlinkedFiles++;
6677 obj->renameAllowed = 0;
6681 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
6686 struct ylist_head *i;
6687 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
6696 T(YAFFS_TRACE_ALWAYS,
6698 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6702 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6703 T(YAFFS_TRACE_ALWAYS,
6705 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6709 sum = yaffs_CalcNameSum(name);
6711 ylist_for_each(i, &directory->variant.directoryVariant.children) {
6713 l = ylist_entry(i, yaffs_Object, siblings);
6715 yaffs_CheckObjectDetailsLoaded(l);
6717 /* Special case for lost-n-found */
6718 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6719 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
6722 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0){
6723 /* LostnFound chunk called Objxxx
6726 yaffs_GetObjectName(l, buffer,
6727 YAFFS_MAX_NAME_LENGTH);
6728 if (yaffs_strncmp(name, buffer,YAFFS_MAX_NAME_LENGTH) == 0) {
6741 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
6742 int (*fn) (yaffs_Object *))
6744 struct ylist_head *i;
6748 T(YAFFS_TRACE_ALWAYS,
6750 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6754 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6755 T(YAFFS_TRACE_ALWAYS,
6757 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6761 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
6763 l = ylist_entry(i, yaffs_Object, siblings);
6775 /* GetEquivalentObject dereferences any hard links to get to the
6779 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
6781 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
6782 /* We want the object id of the equivalent object, not this one */
6783 obj = obj->variant.hardLinkVariant.equivalentObject;
6784 yaffs_CheckObjectDetailsLoaded(obj);
6790 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
6792 memset(name, 0, buffSize * sizeof(YCHAR));
6794 yaffs_CheckObjectDetailsLoaded(obj);
6796 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6797 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
6798 } else if (obj->hdrChunk <= 0) {
6800 /* make up a name */
6801 yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX,
6803 yaffs_strncpy(name, locName, buffSize - 1);
6806 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
6807 else if (obj->shortName[0]) {
6808 yaffs_strcpy(name, obj->shortName);
6813 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
6815 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
6817 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
6819 if (obj->hdrChunk > 0) {
6820 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
6821 obj->hdrChunk, buffer,
6824 yaffs_strncpy(name, oh->name, buffSize - 1);
6826 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
6829 return yaffs_strlen(name);
6832 int yaffs_GetObjectFileLength(yaffs_Object * obj)
6835 /* Dereference any hard linking */
6836 obj = yaffs_GetEquivalentObject(obj);
6838 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
6839 return obj->variant.fileVariant.fileSize;
6841 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6842 return yaffs_strlen(obj->variant.symLinkVariant.alias);
6844 /* Only a directory should drop through to here */
6845 return obj->myDev->nDataBytesPerChunk;
6849 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
6852 struct ylist_head *i;
6854 if (!obj->unlinked) {
6855 count++; /* the object itself */
6857 ylist_for_each(i, &obj->hardLinks) {
6858 count++; /* add the hard links; */
6864 int yaffs_GetObjectInode(yaffs_Object * obj)
6866 obj = yaffs_GetEquivalentObject(obj);
6868 return obj->objectId;
6871 unsigned yaffs_GetObjectType(yaffs_Object * obj)
6873 obj = yaffs_GetEquivalentObject(obj);
6875 switch (obj->variantType) {
6876 case YAFFS_OBJECT_TYPE_FILE:
6879 case YAFFS_OBJECT_TYPE_DIRECTORY:
6882 case YAFFS_OBJECT_TYPE_SYMLINK:
6885 case YAFFS_OBJECT_TYPE_HARDLINK:
6888 case YAFFS_OBJECT_TYPE_SPECIAL:
6889 if (S_ISFIFO(obj->yst_mode))
6891 if (S_ISCHR(obj->yst_mode))
6893 if (S_ISBLK(obj->yst_mode))
6895 if (S_ISSOCK(obj->yst_mode))
6903 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
6905 obj = yaffs_GetEquivalentObject(obj);
6906 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6907 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
6909 return yaffs_CloneString(_Y(""));
6913 #ifndef CONFIG_YAFFS_WINCE
6915 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
6917 unsigned int valid = attr->ia_valid;
6919 if (valid & ATTR_MODE)
6920 obj->yst_mode = attr->ia_mode;
6921 if (valid & ATTR_UID)
6922 obj->yst_uid = attr->ia_uid;
6923 if (valid & ATTR_GID)
6924 obj->yst_gid = attr->ia_gid;
6926 if (valid & ATTR_ATIME)
6927 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
6928 if (valid & ATTR_CTIME)
6929 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
6930 if (valid & ATTR_MTIME)
6931 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
6933 if (valid & ATTR_SIZE)
6934 yaffs_ResizeFile(obj, attr->ia_size);
6936 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6941 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
6943 unsigned int valid = 0;
6945 attr->ia_mode = obj->yst_mode;
6947 attr->ia_uid = obj->yst_uid;
6949 attr->ia_gid = obj->yst_gid;
6952 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
6953 valid |= ATTR_ATIME;
6954 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
6955 valid |= ATTR_CTIME;
6956 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
6957 valid |= ATTR_MTIME;
6959 attr->ia_size = yaffs_GetFileSize(obj);
6962 attr->ia_valid = valid;
6971 int yaffs_DumpObject(yaffs_Object * obj)
6975 yaffs_GetObjectName(obj, name, 256);
6977 T(YAFFS_TRACE_ALWAYS,
6979 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
6980 " chunk %d type %d size %d\n"
6981 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
6982 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
6983 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
6989 /*---------------------------- Initialisation code -------------------------------------- */
6991 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
6994 /* Common functions, gotta have */
6995 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
6998 #ifdef CONFIG_YAFFS_YAFFS2
7000 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7001 if (dev->writeChunkWithTagsToNAND &&
7002 dev->readChunkWithTagsFromNAND &&
7003 !dev->writeChunkToNAND &&
7004 !dev->readChunkFromNAND &&
7005 dev->markNANDBlockBad && dev->queryNANDBlock)
7009 /* Can use the "spare" style interface for yaffs1 */
7010 if (!dev->isYaffs2 &&
7011 !dev->writeChunkWithTagsToNAND &&
7012 !dev->readChunkWithTagsFromNAND &&
7013 dev->writeChunkToNAND &&
7014 dev->readChunkFromNAND &&
7015 !dev->markNANDBlockBad && !dev->queryNANDBlock)
7022 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7024 /* Initialise the unlinked, deleted, root and lost and found directories */
7026 dev->lostNFoundDir = dev->rootDir = NULL;
7027 dev->unlinkedDir = dev->deletedDir = NULL;
7030 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7033 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7036 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7037 YAFFS_ROOT_MODE | S_IFDIR);
7038 dev->lostNFoundDir =
7039 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7040 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7042 if(dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir){
7043 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7050 int yaffs_GutsInitialise(yaffs_Device * dev)
7052 int init_failed = 0;
7056 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7058 /* Check stuff that must be set */
7061 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7065 dev->internalStartBlock = dev->startBlock;
7066 dev->internalEndBlock = dev->endBlock;
7067 dev->blockOffset = 0;
7068 dev->chunkOffset = 0;
7069 dev->nFreeChunks = 0;
7071 if (dev->startBlock == 0) {
7072 dev->internalStartBlock = dev->startBlock + 1;
7073 dev->internalEndBlock = dev->endBlock + 1;
7074 dev->blockOffset = 1;
7075 dev->chunkOffset = dev->nChunksPerBlock;
7078 /* Check geometry parameters. */
7080 if ((!dev->inbandTags && dev->isYaffs2 && dev->totalBytesPerChunk < 1024) ||
7081 (!dev->isYaffs2 && dev->totalBytesPerChunk != 512) ||
7082 (dev->inbandTags && !dev->isYaffs2 ) ||
7083 dev->nChunksPerBlock < 2 ||
7084 dev->nReservedBlocks < 2 ||
7085 dev->internalStartBlock <= 0 ||
7086 dev->internalEndBlock <= 0 ||
7087 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
7089 T(YAFFS_TRACE_ALWAYS,
7091 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7092 TENDSTR), dev->totalBytesPerChunk, dev->isYaffs2 ? "2" : "", dev->inbandTags));
7096 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7097 T(YAFFS_TRACE_ALWAYS,
7098 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7102 /* Sort out space for inband tags, if required */
7104 dev->nDataBytesPerChunk = dev->totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7106 dev->nDataBytesPerChunk = dev->totalBytesPerChunk;
7108 /* Got the right mix of functions? */
7109 if (!yaffs_CheckDevFunctions(dev)) {
7110 /* Function missing */
7111 T(YAFFS_TRACE_ALWAYS,
7113 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7118 /* This is really a compilation check. */
7119 if (!yaffs_CheckStructures()) {
7120 T(YAFFS_TRACE_ALWAYS,
7121 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7125 if (dev->isMounted) {
7126 T(YAFFS_TRACE_ALWAYS,
7127 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7131 /* Finished with most checks. One or two more checks happen later on too. */
7135 /* OK now calculate a few things for the device */
7138 * Calculate all the chunk size manipulation numbers:
7140 x = dev->nDataBytesPerChunk;
7141 /* We always use dev->chunkShift and dev->chunkDiv */
7142 dev->chunkShift = Shifts(x);
7143 x >>= dev->chunkShift;
7145 /* We only use chunk mask if chunkDiv is 1 */
7146 dev->chunkMask = (1<<dev->chunkShift) - 1;
7149 * Calculate chunkGroupBits.
7150 * We need to find the next power of 2 > than internalEndBlock
7153 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7157 /* Set up tnode width if wide tnodes are enabled. */
7158 if(!dev->wideTnodesDisabled){
7159 /* bits must be even so that we end up with 32-bit words */
7163 dev->tnodeWidth = 16;
7165 dev->tnodeWidth = bits;
7168 dev->tnodeWidth = 16;
7170 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7172 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7173 * so if the bitwidth of the
7174 * chunk range we're using is greater than 16 we need
7175 * to figure out chunk shift and chunkGroupSize
7178 if (bits <= dev->tnodeWidth)
7179 dev->chunkGroupBits = 0;
7181 dev->chunkGroupBits = bits - dev->tnodeWidth;
7184 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7186 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7187 /* We have a problem because the soft delete won't work if
7188 * the chunk group size > chunks per block.
7189 * This can be remedied by using larger "virtual blocks".
7191 T(YAFFS_TRACE_ALWAYS,
7192 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7197 /* OK, we've finished verifying the device, lets continue with initialisation */
7199 /* More device initialisation */
7200 dev->garbageCollections = 0;
7201 dev->passiveGarbageCollections = 0;
7202 dev->currentDirtyChecker = 0;
7203 dev->bufferedBlock = -1;
7204 dev->doingBufferedBlockRewrite = 0;
7205 dev->nDeletedFiles = 0;
7206 dev->nBackgroundDeletions = 0;
7207 dev->nUnlinkedFiles = 0;
7209 dev->eccUnfixed = 0;
7210 dev->tagsEccFixed = 0;
7211 dev->tagsEccUnfixed = 0;
7212 dev->nErasureFailures = 0;
7213 dev->nErasedBlocks = 0;
7215 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7217 /* Initialise temporary buffers and caches. */
7218 if(!yaffs_InitialiseTempBuffers(dev))
7221 dev->srCache = NULL;
7222 dev->gcCleanupList = NULL;
7226 dev->nShortOpCaches > 0) {
7229 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7231 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
7232 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7235 dev->srCache = YMALLOC(srCacheBytes);
7237 buf = (__u8 *) dev->srCache;
7240 memset(dev->srCache,0,srCacheBytes);
7242 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7243 dev->srCache[i].object = NULL;
7244 dev->srCache[i].lastUse = 0;
7245 dev->srCache[i].dirty = 0;
7246 dev->srCache[i].data = buf = YMALLOC_DMA(dev->totalBytesPerChunk);
7257 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7258 if(!dev->gcCleanupList)
7262 if (dev->isYaffs2) {
7263 dev->useHeaderFileSize = 1;
7265 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7268 yaffs_InitialiseTnodes(dev);
7269 yaffs_InitialiseObjects(dev);
7271 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7276 /* Now scan the flash. */
7277 if (dev->isYaffs2) {
7278 if(yaffs_CheckpointRestore(dev)) {
7279 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7280 T(YAFFS_TRACE_ALWAYS,
7281 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7284 /* Clean up the mess caused by an aborted checkpoint load
7285 * and scan backwards.
7287 yaffs_DeinitialiseBlocks(dev);
7288 yaffs_DeinitialiseTnodes(dev);
7289 yaffs_DeinitialiseObjects(dev);
7292 dev->nErasedBlocks = 0;
7293 dev->nFreeChunks = 0;
7294 dev->allocationBlock = -1;
7295 dev->allocationPage = -1;
7296 dev->nDeletedFiles = 0;
7297 dev->nUnlinkedFiles = 0;
7298 dev->nBackgroundDeletions = 0;
7299 dev->oldestDirtySequence = 0;
7301 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7304 yaffs_InitialiseTnodes(dev);
7305 yaffs_InitialiseObjects(dev);
7307 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7310 if(!init_failed && !yaffs_ScanBackwards(dev))
7314 if(!yaffs_Scan(dev))
7319 /* Clean up the mess */
7320 T(YAFFS_TRACE_TRACING,
7321 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7323 yaffs_Deinitialise(dev);
7327 /* Zero out stats */
7328 dev->nPageReads = 0;
7329 dev->nPageWrites = 0;
7330 dev->nBlockErasures = 0;
7332 dev->nRetriedWrites = 0;
7334 dev->nRetiredBlocks = 0;
7336 yaffs_VerifyFreeChunks(dev);
7337 yaffs_VerifyBlocks(dev);
7340 T(YAFFS_TRACE_TRACING,
7341 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7346 void yaffs_Deinitialise(yaffs_Device * dev)
7348 if (dev->isMounted) {
7351 yaffs_DeinitialiseBlocks(dev);
7352 yaffs_DeinitialiseTnodes(dev);
7353 yaffs_DeinitialiseObjects(dev);
7354 if (dev->nShortOpCaches > 0 &&
7357 for (i = 0; i < dev->nShortOpCaches; i++) {
7358 if(dev->srCache[i].data)
7359 YFREE(dev->srCache[i].data);
7360 dev->srCache[i].data = NULL;
7363 YFREE(dev->srCache);
7364 dev->srCache = NULL;
7367 YFREE(dev->gcCleanupList);
7369 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
7370 YFREE(dev->tempBuffer[i].buffer);
7379 static int yaffs_CountFreeChunks(yaffs_Device * dev)
7384 yaffs_BlockInfo *blk;
7386 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7388 blk = yaffs_GetBlockInfo(dev, b);
7390 switch (blk->blockState) {
7391 case YAFFS_BLOCK_STATE_EMPTY:
7392 case YAFFS_BLOCK_STATE_ALLOCATING:
7393 case YAFFS_BLOCK_STATE_COLLECTING:
7394 case YAFFS_BLOCK_STATE_FULL:
7396 (dev->nChunksPerBlock - blk->pagesInUse +
7397 blk->softDeletions);
7408 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
7410 /* This is what we report to the outside world */
7413 int nDirtyCacheChunks;
7414 int blocksForCheckpoint;
7417 nFree = dev->nFreeChunks;
7419 nFree = yaffs_CountFreeChunks(dev);
7422 nFree += dev->nDeletedFiles;
7424 /* Now count the number of dirty chunks in the cache and subtract those */
7428 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7429 if (dev->srCache[i].dirty)
7430 nDirtyCacheChunks++;
7434 nFree -= nDirtyCacheChunks;
7436 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7438 /* Now we figure out how much to reserve for the checkpoint and report that... */
7439 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7440 if(blocksForCheckpoint < 0)
7441 blocksForCheckpoint = 0;
7443 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7452 static int yaffs_freeVerificationFailures;
7454 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
7459 if(yaffs_SkipVerification(dev))
7462 counted = yaffs_CountFreeChunks(dev);
7464 difference = dev->nFreeChunks - counted;
7467 T(YAFFS_TRACE_ALWAYS,
7468 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7469 dev->nFreeChunks, counted, difference));
7470 yaffs_freeVerificationFailures++;
7474 /*---------------------------------------- YAFFS test code ----------------------*/
7476 #define yaffs_CheckStruct(structure,syze, name) \
7478 if(sizeof(structure) != syze) \
7480 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
7481 name,syze,sizeof(structure))); \
7482 return YAFFS_FAIL; \
7486 static int yaffs_CheckStructures(void)
7488 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
7489 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
7490 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
7491 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7492 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode");
7494 #ifndef CONFIG_YAFFS_WINCE
7495 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");