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.49 2007-05-15 20:07:40 charles Exp $";
19 #include "yaffsinterface.h"
20 #include "yaffs_guts.h"
21 #include "yaffs_tagsvalidity.h"
23 #include "yaffs_tagscompat.h"
24 #ifndef CONFIG_YAFFS_USE_OWN_SORT
25 #include "yaffs_qsort.h"
27 #include "yaffs_nand.h"
29 #include "yaffs_checkptrw.h"
31 #include "yaffs_nand.h"
32 #include "yaffs_packedtags2.h"
35 #ifdef CONFIG_YAFFS_WINCE
36 void yfsd_LockYAFFS(BOOL fsLockOnly);
37 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
40 #define YAFFS_PASSIVE_GC_CHUNKS 2
42 #include "yaffs_ecc.h"
45 /* Robustification (if it ever comes about...) */
46 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
47 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk);
48 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
50 const yaffs_ExtendedTags * tags);
51 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
52 const yaffs_ExtendedTags * tags);
54 /* Other local prototypes */
55 static int yaffs_UnlinkObject( yaffs_Object *obj);
56 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
58 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
60 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
62 yaffs_ExtendedTags * tags,
64 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
65 int chunkInNAND, int inScan);
67 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
68 yaffs_ObjectType type);
69 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
71 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
72 int force, int isShrink, int shadows);
73 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
74 static int yaffs_CheckStructures(void);
75 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
76 int chunkOffset, int *limit);
77 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
79 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
81 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo);
82 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
85 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
88 static int yaffs_UnlinkWorker(yaffs_Object * obj);
89 static void yaffs_DestroyObject(yaffs_Object * obj);
91 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
94 loff_t yaffs_GetFileSize(yaffs_Object * obj);
96 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr);
98 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
100 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
102 #ifdef YAFFS_PARANOID
103 static int yaffs_CheckFileSanity(yaffs_Object * in);
105 #define yaffs_CheckFileSanity(in)
108 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
109 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
111 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
113 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
114 yaffs_ExtendedTags * tags);
116 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos);
117 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
118 yaffs_FileStructure * fStruct,
122 /* Function to calculate chunk and offset */
124 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, __u32 *chunk, __u32 *offset)
127 /* Easy-peasy power of 2 case */
128 *chunk = (__u32)(addr >> dev->chunkShift);
129 *offset = (__u32)(addr & dev->chunkMask);
131 else if(dev->crumbsPerChunk)
133 /* Case where we're using "crumbs" */
134 *offset = (__u32)(addr & dev->crumbMask);
135 addr >>= dev->crumbShift;
136 *chunk = ((__u32)addr)/dev->crumbsPerChunk;
137 *offset += ((addr - (*chunk * dev->crumbsPerChunk)) << dev->crumbShift);
143 /* Function to return the number of shifts for a power of 2 greater than or equal
144 * to the given number
145 * Note we don't try to cater for all possible numbers and this does not have to
146 * be hellishly efficient.
149 static __u32 ShiftsGE(__u32 x)
154 nShifts = extraBits = 0;
157 if(x & 1) extraBits++;
168 /* Function to return the number of shifts to get a 1 in bit 0
171 static __u32 ShiftDiv(__u32 x)
190 * Temporary buffer manipulations.
193 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
196 __u8 *buf = (__u8 *)1;
198 memset(dev->tempBuffer,0,sizeof(dev->tempBuffer));
200 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
201 dev->tempBuffer[i].line = 0; /* not in use */
202 dev->tempBuffer[i].buffer = buf =
203 YMALLOC_DMA(dev->nDataBytesPerChunk);
206 return buf ? YAFFS_OK : YAFFS_FAIL;
210 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
213 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
214 if (dev->tempBuffer[i].line == 0) {
215 dev->tempBuffer[i].line = lineNo;
216 if ((i + 1) > dev->maxTemp) {
217 dev->maxTemp = i + 1;
218 for (j = 0; j <= i; j++)
219 dev->tempBuffer[j].maxLine =
220 dev->tempBuffer[j].line;
223 return dev->tempBuffer[i].buffer;
227 T(YAFFS_TRACE_BUFFERS,
228 (TSTR("Out of temp buffers at line %d, other held by lines:"),
230 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
231 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
233 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
236 * If we got here then we have to allocate an unmanaged one
240 dev->unmanagedTempAllocations++;
241 return YMALLOC(dev->nDataBytesPerChunk);
245 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
249 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
250 if (dev->tempBuffer[i].buffer == buffer) {
251 dev->tempBuffer[i].line = 0;
257 /* assume it is an unmanaged one. */
258 T(YAFFS_TRACE_BUFFERS,
259 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
262 dev->unmanagedTempDeallocations++;
268 * Determine if we have a managed buffer.
270 int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
273 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
274 if (dev->tempBuffer[i].buffer == buffer)
279 for (i = 0; i < dev->nShortOpCaches; i++) {
280 if( dev->srCache[i].data == buffer )
285 if (buffer == dev->checkpointBuffer)
288 T(YAFFS_TRACE_ALWAYS,
289 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
296 * Chunk bitmap manipulations
299 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
301 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
303 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
307 return dev->chunkBits +
308 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
311 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
313 if(blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
314 chunk < 0 || chunk >= dev->nChunksPerBlock) {
316 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),blk,chunk));
321 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
323 __u8 *blkBits = yaffs_BlockBits(dev, blk);
325 memset(blkBits, 0, dev->chunkBitmapStride);
328 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
330 __u8 *blkBits = yaffs_BlockBits(dev, blk);
332 yaffs_VerifyChunkBitId(dev,blk,chunk);
334 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
337 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
339 __u8 *blkBits = yaffs_BlockBits(dev, blk);
341 yaffs_VerifyChunkBitId(dev,blk,chunk);
343 blkBits[chunk / 8] |= (1 << (chunk & 7));
346 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
348 __u8 *blkBits = yaffs_BlockBits(dev, blk);
349 yaffs_VerifyChunkBitId(dev,blk,chunk);
351 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
354 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
356 __u8 *blkBits = yaffs_BlockBits(dev, blk);
358 for (i = 0; i < dev->chunkBitmapStride; i++) {
366 static int yaffs_CountChunkBits(yaffs_Device * dev, int blk)
368 __u8 *blkBits = yaffs_BlockBits(dev, blk);
371 for (i = 0; i < dev->chunkBitmapStride; i++) {
388 static int yaffs_SkipVerification(yaffs_Device *dev)
390 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
393 static int yaffs_SkipFullVerification(yaffs_Device *dev)
395 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
398 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
400 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
403 static const char * blockStateName[] = {
416 static void yaffs_VerifyBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
421 if(yaffs_SkipVerification(dev))
424 /* Report illegal runtime states */
425 if(bi->blockState <0 || bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
426 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has undefined state %d"TENDSTR),n,bi->blockState));
428 switch(bi->blockState){
429 case YAFFS_BLOCK_STATE_UNKNOWN:
430 case YAFFS_BLOCK_STATE_SCANNING:
431 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
432 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has bad run-state %s"TENDSTR),
433 n,blockStateName[bi->blockState]));
436 /* Check pages in use and soft deletions are legal */
438 actuallyUsed = bi->pagesInUse - bi->softDeletions;
440 if(bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
441 bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
442 actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock)
443 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
444 n,bi->pagesInUse,bi->softDeletions));
447 /* Check chunk bitmap legal */
448 inUse = yaffs_CountChunkBits(dev,n);
449 if(inUse != bi->pagesInUse)
450 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
451 n,bi->pagesInUse,inUse));
453 /* Check that the sequence number is valid.
454 * Ten million is legal, but is very unlikely
457 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
458 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000 ))
459 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has suspect sequence number of %d"TENDSTR),
460 n,bi->sequenceNumber));
464 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
466 yaffs_VerifyBlock(dev,bi,n);
468 /* After collection the block should be in the erased state */
469 /* TODO: This will need to change if we do partial gc */
471 if(bi->blockState != YAFFS_BLOCK_STATE_EMPTY){
472 T(YAFFS_TRACE_ERROR,(TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
477 static void yaffs_VerifyBlocks(yaffs_Device *dev)
480 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
481 int nIllegalBlockStates = 0;
484 if(yaffs_SkipVerification(dev))
487 memset(nBlocksPerState,0,sizeof(nBlocksPerState));
490 for(i = dev->internalStartBlock; i <= dev->internalEndBlock; i++){
491 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
492 yaffs_VerifyBlock(dev,bi,i);
494 if(bi->blockState >=0 && bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
495 nBlocksPerState[bi->blockState]++;
497 nIllegalBlockStates++;
501 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
502 T(YAFFS_TRACE_VERIFY,(TSTR("Block summary"TENDSTR)));
504 T(YAFFS_TRACE_VERIFY,(TSTR("%d blocks have illegal states"TENDSTR),nIllegalBlockStates));
505 if(nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
506 T(YAFFS_TRACE_VERIFY,(TSTR("Too many allocating blocks"TENDSTR)));
508 for(i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
509 T(YAFFS_TRACE_VERIFY,
510 (TSTR("%s %d blocks"TENDSTR),
511 blockStateName[i],nBlocksPerState[i]));
513 if(dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
514 T(YAFFS_TRACE_VERIFY,
515 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
516 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
518 if(dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
519 T(YAFFS_TRACE_VERIFY,
520 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
521 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
523 if(nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
524 T(YAFFS_TRACE_VERIFY,
525 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
526 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
528 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
533 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
534 * case those tests will not be performed.
536 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
538 if(yaffs_SkipVerification(obj->myDev))
541 if(!(tags && obj && oh)){
542 T(YAFFS_TRACE_VERIFY,
543 (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR),
544 (__u32)tags,(__u32)obj,(__u32)oh));
548 if(oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
549 oh->type > YAFFS_OBJECT_TYPE_MAX)
550 T(YAFFS_TRACE_VERIFY,
551 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
552 tags->objectId, oh->type));
554 if(tags->objectId != obj->objectId)
555 T(YAFFS_TRACE_VERIFY,
556 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
557 tags->objectId, obj->objectId));
561 * Check that the object's parent ids match if parentCheck requested.
563 * Tests do not apply to the root object.
566 if(parentCheck && tags->objectId > 1 && !obj->parent)
567 T(YAFFS_TRACE_VERIFY,
568 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
569 tags->objectId, oh->parentObjectId));
572 if(parentCheck && obj->parent &&
573 oh->parentObjectId != obj->parent->objectId &&
574 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
575 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
576 T(YAFFS_TRACE_VERIFY,
577 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
578 tags->objectId, oh->parentObjectId, obj->parent->objectId));
581 if(tags->objectId > 1 && oh->name[0] == 0) /* Null name */
582 T(YAFFS_TRACE_VERIFY,
583 (TSTR("Obj %d header name is NULL"TENDSTR),
586 if(tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
587 T(YAFFS_TRACE_VERIFY,
588 (TSTR("Obj %d header name is 0xFF"TENDSTR),
594 static int yaffs_VerifyTnodeWorker(yaffs_Object * obj, yaffs_Tnode * tn,
595 __u32 level, int chunkOffset)
598 yaffs_Device *dev = obj->myDev;
600 int nTnodeBytes = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
605 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
606 if (tn->internal[i]) {
607 ok = yaffs_VerifyTnodeWorker(obj,
610 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
613 } else if (level == 0) {
615 yaffs_ExtendedTags tags;
616 __u32 objectId = obj->objectId;
618 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
620 for(i = 0; i < YAFFS_NTNODES_LEVEL0; i++){
621 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
624 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
625 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
626 if(tags.objectId != objectId || tags.chunkId != chunkOffset){
627 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
628 objectId, chunkOffset, theChunk,
629 tags.objectId, tags.chunkId));
642 static void yaffs_VerifyFile(yaffs_Object *obj)
644 int requiredTallness;
651 yaffs_ExtendedTags tags;
655 if(obj && yaffs_SkipVerification(obj->myDev))
659 objectId = obj->objectId;
661 /* Check file size is consistent with tnode depth */
662 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
663 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
664 requiredTallness = 0;
666 x >>= YAFFS_TNODES_INTERNAL_BITS;
670 actualTallness = obj->variant.fileVariant.topLevel;
672 if(requiredTallness > actualTallness )
673 T(YAFFS_TRACE_VERIFY,
674 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
675 obj->objectId,actualTallness, requiredTallness));
678 /* Check that the chunks in the tnode tree are all correct.
679 * We do this by scanning through the tnode tree and
680 * checking the tags for every chunk match.
683 if(yaffs_SkipNANDVerification(dev))
686 for(i = 1; i <= lastChunk; i++){
687 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant,i);
690 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
692 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
693 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
694 if(tags.objectId != objectId || tags.chunkId != i){
695 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
696 objectId, i, theChunk,
697 tags.objectId, tags.chunkId));
706 static void yaffs_VerifyDirectory(yaffs_Object *obj)
708 if(obj && yaffs_SkipVerification(obj->myDev))
713 static void yaffs_VerifyHardLink(yaffs_Object *obj)
715 if(obj && yaffs_SkipVerification(obj->myDev))
718 /* Verify sane equivalent object */
721 static void yaffs_VerifySymlink(yaffs_Object *obj)
723 if(obj && yaffs_SkipVerification(obj->myDev))
726 /* Verify symlink string */
729 static void yaffs_VerifySpecial(yaffs_Object *obj)
731 if(obj && yaffs_SkipVerification(obj->myDev))
735 static void yaffs_VerifyObject(yaffs_Object *obj)
750 if(yaffs_SkipVerification(dev))
753 /* Check sane object header chunk */
755 chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
756 chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
758 chunkIdOk = (obj->chunkId >= chunkMin && obj->chunkId <= chunkMax);
759 chunkIsLive = chunkIdOk &&
760 yaffs_CheckChunkBit(dev,
761 obj->chunkId / dev->nChunksPerBlock,
762 obj->chunkId % dev->nChunksPerBlock);
764 (!chunkIdOk || !chunkIsLive)) {
765 T(YAFFS_TRACE_VERIFY,
766 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
767 obj->objectId,obj->chunkId,
768 chunkIdOk ? "" : ",out of range",
769 chunkIsLive || !chunkIdOk ? "" : ",marked as deleted"));
772 if(chunkIdOk && chunkIsLive &&!yaffs_SkipNANDVerification(dev)) {
773 yaffs_ExtendedTags tags;
774 yaffs_ObjectHeader *oh;
775 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
777 oh = (yaffs_ObjectHeader *)buffer;
779 yaffs_ReadChunkWithTagsFromNAND(dev, obj->chunkId,buffer, &tags);
781 yaffs_VerifyObjectHeader(obj,oh,&tags,1);
783 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
786 /* Verify it has a parent */
787 if(obj && !obj->fake &&
788 (!obj->parent || obj->parent->myDev != dev)){
789 T(YAFFS_TRACE_VERIFY,
790 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
791 obj->objectId,obj->parent));
794 /* Verify parent is a directory */
795 if(obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
796 T(YAFFS_TRACE_VERIFY,
797 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
798 obj->objectId,obj->parent->variantType));
801 switch(obj->variantType){
802 case YAFFS_OBJECT_TYPE_FILE:
803 yaffs_VerifyFile(obj);
805 case YAFFS_OBJECT_TYPE_SYMLINK:
806 yaffs_VerifySymlink(obj);
808 case YAFFS_OBJECT_TYPE_DIRECTORY:
809 yaffs_VerifyDirectory(obj);
811 case YAFFS_OBJECT_TYPE_HARDLINK:
812 yaffs_VerifyHardLink(obj);
814 case YAFFS_OBJECT_TYPE_SPECIAL:
815 yaffs_VerifySpecial(obj);
817 case YAFFS_OBJECT_TYPE_UNKNOWN:
819 T(YAFFS_TRACE_VERIFY,
820 (TSTR("Obj %d has illegaltype %d"TENDSTR),
821 obj->objectId,obj->variantType));
828 static void yaffs_VerifyObjects(yaffs_Device *dev)
832 struct list_head *lh;
834 if(yaffs_SkipVerification(dev))
837 /* Iterate through the objects in each hash entry */
839 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++){
840 list_for_each(lh, &dev->objectBucket[i].list) {
842 obj = list_entry(lh, yaffs_Object, hashLink);
843 yaffs_VerifyObject(obj);
852 * Simple hash function. Needs to have a reasonable spread
855 static Y_INLINE int yaffs_HashFunction(int n)
858 return (n % YAFFS_NOBJECT_BUCKETS);
862 * Access functions to useful fake objects
865 yaffs_Object *yaffs_Root(yaffs_Device * dev)
870 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
872 return dev->lostNFoundDir;
877 * Erased NAND checking functions
880 int yaffs_CheckFF(__u8 * buffer, int nBytes)
882 /* Horrible, slow implementation */
891 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
895 int retval = YAFFS_OK;
896 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
897 yaffs_ExtendedTags tags;
900 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
902 if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
906 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
907 T(YAFFS_TRACE_NANDACCESS,
908 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
912 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
918 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
920 yaffs_ExtendedTags * tags,
930 yaffs_InvalidateCheckpoint(dev);
933 chunk = yaffs_AllocateChunk(dev, useReserve,&bi);
936 /* First check this chunk is erased, if it needs checking.
937 * The checking policy (unless forced always on) is as follows:
938 * Check the first page we try to write in a block.
939 * - If the check passes then we don't need to check any more.
940 * - If the check fails, we check again...
941 * If the block has been erased, we don't need to check.
943 * However, if the block has been prioritised for gc, then
944 * we think there might be something odd about this block
948 * We should only ever see chunks that have not been erased
949 * if there was a partially written chunk due to power loss
950 * This checking policy should catch that case with very
951 * few checks and thus save a lot of checks that are most likely not
955 if(bi->gcPrioritise){
956 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
958 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
960 bi->skipErasedCheck = 0;
963 if(!bi->skipErasedCheck){
964 erasedOk = yaffs_CheckChunkErased(dev, chunk);
965 if(erasedOk && !bi->gcPrioritise)
966 bi->skipErasedCheck = 1;
972 ("**>> yaffs chunk %d was not erased"
976 yaffs_WriteChunkWithTagsToNAND(dev, chunk,
984 * Copy the data into the robustification buffer.
985 * NB We do this at the end to prevent duplicates in the case of a write error.
988 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
991 /* The erased check or write failed */
992 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
997 } while (chunk >= 0 && !writeOk);
1000 T(YAFFS_TRACE_ERROR,
1001 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1003 dev->nRetriedWrites += (attempts - 1);
1010 * Block retiring for handling a broken block.
1013 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
1015 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1017 yaffs_InvalidateCheckpoint(dev);
1019 yaffs_MarkBlockBad(dev, blockInNAND);
1021 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1022 bi->gcPrioritise = 0;
1023 bi->needsRetiring = 0;
1025 dev->nRetiredBlocks++;
1029 * Functions for robustisizing TODO
1033 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
1035 const yaffs_ExtendedTags * tags)
1039 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
1040 const yaffs_ExtendedTags * tags)
1044 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1046 if(!bi->gcPrioritise){
1047 bi->gcPrioritise = 1;
1048 dev->hasPendingPrioritisedGCs = 1;
1049 bi->chunkErrorStrikes ++;
1051 if(bi->chunkErrorStrikes > 3){
1052 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1053 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1060 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
1063 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1064 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1066 yaffs_HandleChunkError(dev,bi);
1070 /* Was an actual write failure, so mark the block for retirement */
1071 bi->needsRetiring = 1;
1072 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1073 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1078 /* Delete the chunk */
1079 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1083 /*---------------- Name handling functions ------------*/
1085 static __u16 yaffs_CalcNameSum(const YCHAR * name)
1090 YUCHAR *bname = (YUCHAR *) name;
1092 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1094 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1095 sum += yaffs_toupper(*bname) * i;
1097 sum += (*bname) * i;
1106 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
1108 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1109 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
1110 yaffs_strcpy(obj->shortName, name);
1112 obj->shortName[0] = _Y('\0');
1115 obj->sum = yaffs_CalcNameSum(name);
1118 /*-------------------- TNODES -------------------
1120 * List of spare tnodes
1121 * The list is hooked together using the first pointer
1125 /* yaffs_CreateTnodes creates a bunch more tnodes and
1126 * adds them to the tnode free list.
1127 * Don't use this function directly
1130 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
1134 yaffs_Tnode *newTnodes;
1138 yaffs_TnodeList *tnl;
1143 /* Calculate the tnode size in bytes for variable width tnode support.
1144 * Must be a multiple of 32-bits */
1145 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1147 /* make these things */
1149 newTnodes = YMALLOC(nTnodes * tnodeSize);
1150 mem = (__u8 *)newTnodes;
1153 T(YAFFS_TRACE_ERROR,
1154 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1158 /* Hook them into the free list */
1160 for (i = 0; i < nTnodes - 1; i++) {
1161 newTnodes[i].internal[0] = &newTnodes[i + 1];
1162 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1163 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1167 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1168 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1169 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1171 dev->freeTnodes = newTnodes;
1173 /* New hookup for wide tnodes */
1174 for(i = 0; i < nTnodes -1; i++) {
1175 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1176 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1177 curr->internal[0] = next;
1180 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1181 curr->internal[0] = dev->freeTnodes;
1182 dev->freeTnodes = (yaffs_Tnode *)mem;
1187 dev->nFreeTnodes += nTnodes;
1188 dev->nTnodesCreated += nTnodes;
1190 /* Now add this bunch of tnodes to a list for freeing up.
1191 * NB If we can't add this to the management list it isn't fatal
1192 * but it just means we can't free this bunch of tnodes later.
1195 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1197 T(YAFFS_TRACE_ERROR,
1199 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1203 tnl->tnodes = newTnodes;
1204 tnl->next = dev->allocatedTnodeList;
1205 dev->allocatedTnodeList = tnl;
1208 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1213 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1215 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
1217 yaffs_Tnode *tn = NULL;
1219 /* If there are none left make more */
1220 if (!dev->freeTnodes) {
1221 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1224 if (dev->freeTnodes) {
1225 tn = dev->freeTnodes;
1226 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1227 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1228 /* Hoosterman, this thing looks like it isn't in the list */
1229 T(YAFFS_TRACE_ALWAYS,
1230 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1233 dev->freeTnodes = dev->freeTnodes->internal[0];
1240 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
1242 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1245 memset(tn, 0, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1250 /* FreeTnode frees up a tnode and puts it back on the free list */
1251 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
1254 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1255 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1256 /* Hoosterman, this thing looks like it is already in the list */
1257 T(YAFFS_TRACE_ALWAYS,
1258 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1260 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1262 tn->internal[0] = dev->freeTnodes;
1263 dev->freeTnodes = tn;
1268 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
1270 /* Free the list of allocated tnodes */
1271 yaffs_TnodeList *tmp;
1273 while (dev->allocatedTnodeList) {
1274 tmp = dev->allocatedTnodeList->next;
1276 YFREE(dev->allocatedTnodeList->tnodes);
1277 YFREE(dev->allocatedTnodeList);
1278 dev->allocatedTnodeList = tmp;
1282 dev->freeTnodes = NULL;
1283 dev->nFreeTnodes = 0;
1286 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
1288 dev->allocatedTnodeList = NULL;
1289 dev->freeTnodes = NULL;
1290 dev->nFreeTnodes = 0;
1291 dev->nTnodesCreated = 0;
1296 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
1298 __u32 *map = (__u32 *)tn;
1304 pos &= YAFFS_TNODES_LEVEL0_MASK;
1305 val >>= dev->chunkGroupBits;
1307 bitInMap = pos * dev->tnodeWidth;
1308 wordInMap = bitInMap /32;
1309 bitInWord = bitInMap & (32 -1);
1311 mask = dev->tnodeMask << bitInWord;
1313 map[wordInMap] &= ~mask;
1314 map[wordInMap] |= (mask & (val << bitInWord));
1316 if(dev->tnodeWidth > (32-bitInWord)) {
1317 bitInWord = (32 - bitInWord);
1319 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1320 map[wordInMap] &= ~mask;
1321 map[wordInMap] |= (mask & (val >> bitInWord));
1325 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
1327 __u32 *map = (__u32 *)tn;
1333 pos &= YAFFS_TNODES_LEVEL0_MASK;
1335 bitInMap = pos * dev->tnodeWidth;
1336 wordInMap = bitInMap /32;
1337 bitInWord = bitInMap & (32 -1);
1339 val = map[wordInMap] >> bitInWord;
1341 if(dev->tnodeWidth > (32-bitInWord)) {
1342 bitInWord = (32 - bitInWord);
1344 val |= (map[wordInMap] << bitInWord);
1347 val &= dev->tnodeMask;
1348 val <<= dev->chunkGroupBits;
1353 /* ------------------- End of individual tnode manipulation -----------------*/
1355 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1356 * The look up tree is represented by the top tnode and the number of topLevel
1357 * in the tree. 0 means only the level 0 tnode is in the tree.
1360 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1361 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
1362 yaffs_FileStructure * fStruct,
1366 yaffs_Tnode *tn = fStruct->top;
1368 int requiredTallness;
1369 int level = fStruct->topLevel;
1371 /* Check sane level and chunk Id */
1372 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
1376 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1380 /* First check we're tall enough (ie enough topLevel) */
1382 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1383 requiredTallness = 0;
1385 i >>= YAFFS_TNODES_INTERNAL_BITS;
1389 if (requiredTallness > fStruct->topLevel) {
1390 /* Not tall enough, so we can't find it, return NULL. */
1394 /* Traverse down to level 0 */
1395 while (level > 0 && tn) {
1397 internal[(chunkId >>
1398 ( YAFFS_TNODES_LEVEL0_BITS +
1400 YAFFS_TNODES_INTERNAL_BITS)
1402 YAFFS_TNODES_INTERNAL_MASK];
1410 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1411 * This happens in two steps:
1412 * 1. If the tree isn't tall enough, then make it taller.
1413 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1415 * Used when modifying the tree.
1417 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1418 * be plugged into the ttree.
1421 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
1422 yaffs_FileStructure * fStruct,
1424 yaffs_Tnode *passedTn)
1427 int requiredTallness;
1435 /* Check sane level and page Id */
1436 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
1440 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1444 /* First check we're tall enough (ie enough topLevel) */
1446 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1447 requiredTallness = 0;
1449 x >>= YAFFS_TNODES_INTERNAL_BITS;
1454 if (requiredTallness > fStruct->topLevel) {
1455 /* Not tall enough,gotta make the tree taller */
1456 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1458 tn = yaffs_GetTnode(dev);
1461 tn->internal[0] = fStruct->top;
1464 T(YAFFS_TRACE_ERROR,
1465 (TSTR("yaffs: no more tnodes" TENDSTR)));
1469 fStruct->topLevel = requiredTallness;
1472 /* Traverse down to level 0, adding anything we need */
1474 l = fStruct->topLevel;
1478 while (l > 0 && tn) {
1480 ( YAFFS_TNODES_LEVEL0_BITS +
1481 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1482 YAFFS_TNODES_INTERNAL_MASK;
1485 if((l>1) && !tn->internal[x]){
1486 /* Add missing non-level-zero tnode */
1487 tn->internal[x] = yaffs_GetTnode(dev);
1490 /* Looking from level 1 at level 0 */
1492 /* If we already have one, then release it.*/
1494 yaffs_FreeTnode(dev,tn->internal[x]);
1495 tn->internal[x] = passedTn;
1497 } else if(!tn->internal[x]) {
1498 /* Don't have one, none passed in */
1499 tn->internal[x] = yaffs_GetTnode(dev);
1503 tn = tn->internal[x];
1507 /* top is level 0 */
1509 memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1510 yaffs_FreeTnode(dev,passedTn);
1517 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1518 yaffs_ExtendedTags * tags, int objectId,
1523 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1524 if (yaffs_CheckChunkBit
1525 (dev, theChunk / dev->nChunksPerBlock,
1526 theChunk % dev->nChunksPerBlock)) {
1527 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1529 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1541 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1542 * chunks and tnodes in the file
1543 * Returns 1 if the tree was deleted.
1544 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1547 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1548 int chunkOffset, int *limit)
1553 yaffs_ExtendedTags tags;
1555 yaffs_Device *dev = in->myDev;
1562 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1564 if (tn->internal[i]) {
1565 if (limit && (*limit) < 0) {
1569 yaffs_DeleteWorker(in,
1577 YAFFS_TNODES_INTERNAL_BITS)
1582 yaffs_FreeTnode(dev,
1585 tn->internal[i] = NULL;
1590 return (allDone) ? 1 : 0;
1591 } else if (level == 0) {
1594 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1596 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1601 YAFFS_TNODES_LEVEL0_BITS) + i;
1604 yaffs_FindChunkInGroup(dev,
1610 if (foundChunk > 0) {
1611 yaffs_DeleteChunk(dev,
1616 *limit = *limit - 1;
1624 yaffs_PutLevel0Tnode(dev,tn,i,0);
1628 return (i < 0) ? 1 : 0;
1638 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1641 yaffs_BlockInfo *theBlock;
1643 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1645 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1647 theBlock->softDeletions++;
1652 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1653 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1655 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1658 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1659 __u32 level, int chunkOffset)
1664 yaffs_Device *dev = in->myDev;
1669 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1671 if (tn->internal[i]) {
1673 yaffs_SoftDeleteWorker(in,
1679 YAFFS_TNODES_INTERNAL_BITS)
1682 yaffs_FreeTnode(dev,
1685 tn->internal[i] = NULL;
1687 /* Hoosterman... how could this happen? */
1691 return (allDone) ? 1 : 0;
1692 } else if (level == 0) {
1694 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1695 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1697 /* Note this does not find the real chunk, only the chunk group.
1698 * We make an assumption that a chunk group is not larger than
1701 yaffs_SoftDeleteChunk(dev, theChunk);
1702 yaffs_PutLevel0Tnode(dev,tn,i,0);
1716 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1719 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1720 if (obj->nDataChunks <= 0) {
1721 /* Empty file with no duplicate object headers, just delete it immediately */
1722 yaffs_FreeTnode(obj->myDev,
1723 obj->variant.fileVariant.top);
1724 obj->variant.fileVariant.top = NULL;
1725 T(YAFFS_TRACE_TRACING,
1726 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1728 yaffs_DoGenericObjectDeletion(obj);
1730 yaffs_SoftDeleteWorker(obj,
1731 obj->variant.fileVariant.top,
1732 obj->variant.fileVariant.
1734 obj->softDeleted = 1;
1739 /* Pruning removes any part of the file structure tree that is beyond the
1740 * bounds of the file (ie that does not point to chunks).
1742 * A file should only get pruned when its size is reduced.
1744 * Before pruning, the chunks must be pulled from the tree and the
1745 * level 0 tnode entries must be zeroed out.
1746 * Could also use this for file deletion, but that's probably better handled
1747 * by a special case.
1750 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1751 __u32 level, int del0)
1759 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1760 if (tn->internal[i] && level > 0) {
1762 yaffs_PruneWorker(dev, tn->internal[i],
1764 (i == 0) ? del0 : 1);
1767 if (tn->internal[i]) {
1772 if (hasData == 0 && del0) {
1773 /* Free and return NULL */
1775 yaffs_FreeTnode(dev, tn);
1785 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1786 yaffs_FileStructure * fStruct)
1793 if (fStruct->topLevel > 0) {
1795 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1797 /* Now we have a tree with all the non-zero branches NULL but the height
1798 * is the same as it was.
1799 * Let's see if we can trim internal tnodes to shorten the tree.
1800 * We can do this if only the 0th element in the tnode is in use
1801 * (ie all the non-zero are NULL)
1804 while (fStruct->topLevel && !done) {
1808 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1809 if (tn->internal[i]) {
1815 fStruct->top = tn->internal[0];
1816 fStruct->topLevel--;
1817 yaffs_FreeTnode(dev, tn);
1827 /*-------------------- End of File Structure functions.-------------------*/
1829 /* yaffs_CreateFreeObjects creates a bunch more objects and
1830 * adds them to the object free list.
1832 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1835 yaffs_Object *newObjects;
1836 yaffs_ObjectList *list;
1841 /* make these things */
1842 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1843 list = YMALLOC(sizeof(yaffs_ObjectList));
1845 if (!newObjects || !list) {
1850 T(YAFFS_TRACE_ALLOCATE,
1851 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1855 /* Hook them into the free list */
1856 for (i = 0; i < nObjects - 1; i++) {
1857 newObjects[i].siblings.next =
1858 (struct list_head *)(&newObjects[i + 1]);
1861 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1862 dev->freeObjects = newObjects;
1863 dev->nFreeObjects += nObjects;
1864 dev->nObjectsCreated += nObjects;
1866 /* Now add this bunch of Objects to a list for freeing up. */
1868 list->objects = newObjects;
1869 list->next = dev->allocatedObjectList;
1870 dev->allocatedObjectList = list;
1876 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1877 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1879 yaffs_Object *tn = NULL;
1881 /* If there are none left make more */
1882 if (!dev->freeObjects) {
1883 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1886 if (dev->freeObjects) {
1887 tn = dev->freeObjects;
1889 (yaffs_Object *) (dev->freeObjects->siblings.next);
1890 dev->nFreeObjects--;
1892 /* Now sweeten it up... */
1894 memset(tn, 0, sizeof(yaffs_Object));
1897 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1898 INIT_LIST_HEAD(&(tn->hardLinks));
1899 INIT_LIST_HEAD(&(tn->hashLink));
1900 INIT_LIST_HEAD(&tn->siblings);
1902 /* Add it to the lost and found directory.
1903 * NB Can't put root or lostNFound in lostNFound so
1904 * check if lostNFound exists first
1906 if (dev->lostNFoundDir) {
1907 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1914 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1919 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1921 obj->fake = 1; /* it is fake so it has no NAND presence... */
1922 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1923 obj->unlinkAllowed = 0; /* ... or unlink it */
1926 obj->yst_mode = mode;
1928 obj->chunkId = 0; /* Not a valid chunk. */
1935 static void yaffs_UnhashObject(yaffs_Object * tn)
1938 yaffs_Device *dev = tn->myDev;
1940 /* If it is still linked into the bucket list, free from the list */
1941 if (!list_empty(&tn->hashLink)) {
1942 list_del_init(&tn->hashLink);
1943 bucket = yaffs_HashFunction(tn->objectId);
1944 dev->objectBucket[bucket].count--;
1949 /* FreeObject frees up a Object and puts it back on the free list */
1950 static void yaffs_FreeObject(yaffs_Object * tn)
1953 yaffs_Device *dev = tn->myDev;
1957 /* We're still hooked up to a cached inode.
1958 * Don't delete now, but mark for later deletion
1960 tn->deferedFree = 1;
1965 yaffs_UnhashObject(tn);
1967 /* Link into the free list. */
1968 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1969 dev->freeObjects = tn;
1970 dev->nFreeObjects++;
1975 void yaffs_HandleDeferedFree(yaffs_Object * obj)
1977 if (obj->deferedFree) {
1978 yaffs_FreeObject(obj);
1984 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
1986 /* Free the list of allocated Objects */
1988 yaffs_ObjectList *tmp;
1990 while (dev->allocatedObjectList) {
1991 tmp = dev->allocatedObjectList->next;
1992 YFREE(dev->allocatedObjectList->objects);
1993 YFREE(dev->allocatedObjectList);
1995 dev->allocatedObjectList = tmp;
1998 dev->freeObjects = NULL;
1999 dev->nFreeObjects = 0;
2002 static void yaffs_InitialiseObjects(yaffs_Device * dev)
2006 dev->allocatedObjectList = NULL;
2007 dev->freeObjects = NULL;
2008 dev->nFreeObjects = 0;
2010 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2011 INIT_LIST_HEAD(&dev->objectBucket[i].list);
2012 dev->objectBucket[i].count = 0;
2017 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
2022 int lowest = 999999;
2024 /* First let's see if we can find one that's empty. */
2026 for (i = 0; i < 10 && lowest > 0; i++) {
2028 x %= YAFFS_NOBJECT_BUCKETS;
2029 if (dev->objectBucket[x].count < lowest) {
2030 lowest = dev->objectBucket[x].count;
2036 /* If we didn't find an empty list, then try
2037 * looking a bit further for a short one
2040 for (i = 0; i < 10 && lowest > 3; i++) {
2042 x %= YAFFS_NOBJECT_BUCKETS;
2043 if (dev->objectBucket[x].count < lowest) {
2044 lowest = dev->objectBucket[x].count;
2053 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
2055 int bucket = yaffs_FindNiceObjectBucket(dev);
2057 /* Now find an object value that has not already been taken
2058 * by scanning the list.
2062 struct list_head *i;
2064 __u32 n = (__u32) bucket;
2066 /* yaffs_CheckObjectHashSanity(); */
2070 n += YAFFS_NOBJECT_BUCKETS;
2071 if (1 || dev->objectBucket[bucket].count > 0) {
2072 list_for_each(i, &dev->objectBucket[bucket].list) {
2073 /* If there is already one in the list */
2075 && list_entry(i, yaffs_Object,
2076 hashLink)->objectId == n) {
2087 static void yaffs_HashObject(yaffs_Object * in)
2089 int bucket = yaffs_HashFunction(in->objectId);
2090 yaffs_Device *dev = in->myDev;
2092 list_add(&in->hashLink, &dev->objectBucket[bucket].list);
2093 dev->objectBucket[bucket].count++;
2097 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
2099 int bucket = yaffs_HashFunction(number);
2100 struct list_head *i;
2103 list_for_each(i, &dev->objectBucket[bucket].list) {
2104 /* Look if it is in the list */
2106 in = list_entry(i, yaffs_Object, hashLink);
2107 if (in->objectId == number) {
2109 /* Don't tell the VFS about this one if it is defered free */
2110 if (in->deferedFree)
2122 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
2123 yaffs_ObjectType type)
2126 yaffs_Object *theObject;
2130 number = yaffs_CreateNewObjectNumber(dev);
2133 theObject = yaffs_AllocateEmptyObject(dev);
2137 if(type == YAFFS_OBJECT_TYPE_FILE){
2138 tn = yaffs_GetTnode(dev);
2140 yaffs_FreeObject(theObject);
2148 theObject->fake = 0;
2149 theObject->renameAllowed = 1;
2150 theObject->unlinkAllowed = 1;
2151 theObject->objectId = number;
2152 yaffs_HashObject(theObject);
2153 theObject->variantType = type;
2154 #ifdef CONFIG_YAFFS_WINCE
2155 yfsd_WinFileTimeNow(theObject->win_atime);
2156 theObject->win_ctime[0] = theObject->win_mtime[0] =
2157 theObject->win_atime[0];
2158 theObject->win_ctime[1] = theObject->win_mtime[1] =
2159 theObject->win_atime[1];
2163 theObject->yst_atime = theObject->yst_mtime =
2164 theObject->yst_ctime = Y_CURRENT_TIME;
2167 case YAFFS_OBJECT_TYPE_FILE:
2168 theObject->variant.fileVariant.fileSize = 0;
2169 theObject->variant.fileVariant.scannedFileSize = 0;
2170 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2171 theObject->variant.fileVariant.topLevel = 0;
2172 theObject->variant.fileVariant.top = tn;
2174 case YAFFS_OBJECT_TYPE_DIRECTORY:
2175 INIT_LIST_HEAD(&theObject->variant.directoryVariant.
2178 case YAFFS_OBJECT_TYPE_SYMLINK:
2179 case YAFFS_OBJECT_TYPE_HARDLINK:
2180 case YAFFS_OBJECT_TYPE_SPECIAL:
2181 /* No action required */
2183 case YAFFS_OBJECT_TYPE_UNKNOWN:
2184 /* todo this should not happen */
2192 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
2194 yaffs_ObjectType type)
2196 yaffs_Object *theObject = NULL;
2199 theObject = yaffs_FindObjectByNumber(dev, number);
2203 theObject = yaffs_CreateNewObject(dev, number, type);
2211 static YCHAR *yaffs_CloneString(const YCHAR * str)
2213 YCHAR *newStr = NULL;
2216 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2218 yaffs_strcpy(newStr, str);
2226 * Mknod (create) a new object.
2227 * equivalentObject only has meaning for a hard link;
2228 * aliasString only has meaning for a sumlink.
2229 * rdev only has meaning for devices (a subset of special objects)
2232 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2233 yaffs_Object * parent,
2238 yaffs_Object * equivalentObject,
2239 const YCHAR * aliasString, __u32 rdev)
2244 yaffs_Device *dev = parent->myDev;
2246 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2247 if (yaffs_FindObjectByName(parent, name)) {
2251 in = yaffs_CreateNewObject(dev, -1, type);
2253 if(type == YAFFS_OBJECT_TYPE_SYMLINK){
2254 str = yaffs_CloneString(aliasString);
2256 yaffs_FreeObject(in);
2266 in->variantType = type;
2268 in->yst_mode = mode;
2270 #ifdef CONFIG_YAFFS_WINCE
2271 yfsd_WinFileTimeNow(in->win_atime);
2272 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2273 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2276 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2278 in->yst_rdev = rdev;
2282 in->nDataChunks = 0;
2284 yaffs_SetObjectName(in, name);
2287 yaffs_AddObjectToDirectory(parent, in);
2289 in->myDev = parent->myDev;
2292 case YAFFS_OBJECT_TYPE_SYMLINK:
2293 in->variant.symLinkVariant.alias = str;
2295 case YAFFS_OBJECT_TYPE_HARDLINK:
2296 in->variant.hardLinkVariant.equivalentObject =
2298 in->variant.hardLinkVariant.equivalentObjectId =
2299 equivalentObject->objectId;
2300 list_add(&in->hardLinks, &equivalentObject->hardLinks);
2302 case YAFFS_OBJECT_TYPE_FILE:
2303 case YAFFS_OBJECT_TYPE_DIRECTORY:
2304 case YAFFS_OBJECT_TYPE_SPECIAL:
2305 case YAFFS_OBJECT_TYPE_UNKNOWN:
2310 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2311 /* Could not create the object header, fail the creation */
2312 yaffs_DestroyObject(in);
2321 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
2322 __u32 mode, __u32 uid, __u32 gid)
2324 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2325 uid, gid, NULL, NULL, 0);
2328 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
2329 __u32 mode, __u32 uid, __u32 gid)
2331 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2332 mode, uid, gid, NULL, NULL, 0);
2335 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
2336 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2338 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2339 uid, gid, NULL, NULL, rdev);
2342 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
2343 __u32 mode, __u32 uid, __u32 gid,
2344 const YCHAR * alias)
2346 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2347 uid, gid, NULL, alias, 0);
2350 /* yaffs_Link returns the object id of the equivalent object.*/
2351 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
2352 yaffs_Object * equivalentObject)
2354 /* Get the real object in case we were fed a hard link as an equivalent object */
2355 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2357 if (yaffs_MknodObject
2358 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2359 equivalentObject, NULL, 0)) {
2360 return equivalentObject;
2367 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
2368 const YCHAR * newName, int force, int shadows)
2373 yaffs_Object *existingTarget;
2375 if (newDir == NULL) {
2376 newDir = obj->parent; /* use the old directory */
2379 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2380 T(YAFFS_TRACE_ALWAYS,
2382 ("tragendy: yaffs_ChangeObjectName: newDir is not a directory"
2387 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2388 if (obj->myDev->isYaffs2) {
2389 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2391 unlinkOp = (newDir == obj->myDev->unlinkedDir
2392 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2395 deleteOp = (newDir == obj->myDev->deletedDir);
2397 existingTarget = yaffs_FindObjectByName(newDir, newName);
2399 /* If the object is a file going into the unlinked directory,
2400 * then it is OK to just stuff it in since duplicate names are allowed.
2401 * else only proceed if the new name does not exist and if we're putting
2402 * it into a directory.
2409 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2410 yaffs_SetObjectName(obj, newName);
2413 yaffs_AddObjectToDirectory(newDir, obj);
2418 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2419 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
2426 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
2427 yaffs_Object * newDir, const YCHAR * newName)
2430 yaffs_Object *existingTarget;
2433 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2434 /* Special case for case insemsitive systems (eg. WinCE).
2435 * While look-up is case insensitive, the name isn't.
2436 * Therefore we might want to change x.txt to X.txt
2438 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
2443 obj = yaffs_FindObjectByName(oldDir, oldName);
2444 /* Check new name to long. */
2445 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK &&
2446 yaffs_strlen(newName) > YAFFS_MAX_ALIAS_LENGTH)
2449 else if (obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK &&
2450 yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2454 if (obj && obj->renameAllowed) {
2456 /* Now do the handling for an existing target, if there is one */
2458 existingTarget = yaffs_FindObjectByName(newDir, newName);
2459 if (existingTarget &&
2460 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2461 !list_empty(&existingTarget->variant.directoryVariant.children)) {
2462 /* There is a target that is a non-empty directory, so we fail */
2463 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2464 } else if (existingTarget && existingTarget != obj) {
2465 /* Nuke the target first, using shadowing,
2466 * but only if it isn't the same object
2468 yaffs_ChangeObjectName(obj, newDir, newName, force,
2469 existingTarget->objectId);
2470 yaffs_UnlinkObject(existingTarget);
2473 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2478 /*------------------------- Block Management and Page Allocation ----------------*/
2480 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
2482 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2484 dev->blockInfo = NULL;
2485 dev->chunkBits = NULL;
2487 dev->allocationBlock = -1; /* force it to get a new one */
2489 /* If the first allocation strategy fails, thry the alternate one */
2490 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2491 if(!dev->blockInfo){
2492 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2493 dev->blockInfoAlt = 1;
2496 dev->blockInfoAlt = 0;
2500 /* Set up dynamic blockinfo stuff. */
2501 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2502 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2503 if(!dev->chunkBits){
2504 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2505 dev->chunkBitsAlt = 1;
2508 dev->chunkBitsAlt = 0;
2511 if (dev->blockInfo && dev->chunkBits) {
2512 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2513 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2521 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
2523 if(dev->blockInfoAlt && dev->blockInfo)
2524 YFREE_ALT(dev->blockInfo);
2525 else if(dev->blockInfo)
2526 YFREE(dev->blockInfo);
2528 dev->blockInfoAlt = 0;
2530 dev->blockInfo = NULL;
2532 if(dev->chunkBitsAlt && dev->chunkBits)
2533 YFREE_ALT(dev->chunkBits);
2534 else if(dev->chunkBits)
2535 YFREE(dev->chunkBits);
2536 dev->chunkBitsAlt = 0;
2537 dev->chunkBits = NULL;
2540 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
2541 yaffs_BlockInfo * bi)
2548 return 1; /* disqualification only applies to yaffs2. */
2550 if (!bi->hasShrinkHeader)
2551 return 1; /* can gc */
2553 /* Find the oldest dirty sequence number if we don't know it and save it
2554 * so we don't have to keep recomputing it.
2556 if (!dev->oldestDirtySequence) {
2557 seq = dev->sequenceNumber;
2559 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2561 b = yaffs_GetBlockInfo(dev, i);
2562 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2563 (b->pagesInUse - b->softDeletions) <
2564 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2565 seq = b->sequenceNumber;
2568 dev->oldestDirtySequence = seq;
2571 /* Can't do gc of this block if there are any blocks older than this one that have
2574 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2578 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2579 * for garbage collection.
2582 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2586 int b = dev->currentDirtyChecker;
2593 yaffs_BlockInfo *bi;
2594 static int nonAggressiveSkip = 0;
2595 int pendingPrioritisedExist = 0;
2597 /* First let's see if we need to grab a prioritised block */
2598 if(dev->hasPendingPrioritisedGCs){
2599 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2601 bi = yaffs_GetBlockInfo(dev, i);
2602 //yaffs_VerifyBlock(dev,bi,i);
2604 if(bi->gcPrioritise) {
2605 pendingPrioritisedExist = 1;
2606 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2607 yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2608 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2611 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2616 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2617 dev->hasPendingPrioritisedGCs = 0;
2620 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2622 * else (we're doing a leasurely gc), then we only bother to do this if the
2623 * block has only a few pages in use.
2626 nonAggressiveSkip--;
2628 if (!aggressive && (nonAggressiveSkip > 0)) {
2634 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2638 dev->internalEndBlock - dev->internalStartBlock + 1;
2641 dev->internalEndBlock - dev->internalStartBlock + 1;
2642 iterations = iterations / 16;
2643 if (iterations > 200) {
2648 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2650 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2651 b = dev->internalStartBlock;
2654 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2655 T(YAFFS_TRACE_ERROR,
2656 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2660 bi = yaffs_GetBlockInfo(dev, b);
2663 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2670 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2671 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2672 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2674 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2678 dev->currentDirtyChecker = b;
2682 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2683 dev->nChunksPerBlock - pagesInUse,prioritised));
2686 dev->oldestDirtySequence = 0;
2689 nonAggressiveSkip = 4;
2695 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2697 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2701 /* If the block is still healthy erase it and mark as clean.
2702 * If the block has had a data failure, then retire it.
2705 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2706 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2707 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2709 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2711 if (!bi->needsRetiring) {
2712 yaffs_InvalidateCheckpoint(dev);
2713 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2715 dev->nErasureFailures++;
2716 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2717 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2722 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2724 for (i = 0; i < dev->nChunksPerBlock; i++) {
2725 if (!yaffs_CheckChunkErased
2726 (dev, blockNo * dev->nChunksPerBlock + i)) {
2727 T(YAFFS_TRACE_ERROR,
2729 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2730 TENDSTR), blockNo, i));
2736 /* Clean it up... */
2737 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2738 dev->nErasedBlocks++;
2740 bi->softDeletions = 0;
2741 bi->hasShrinkHeader = 0;
2742 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2743 bi->gcPrioritise = 0;
2744 yaffs_ClearChunkBits(dev, blockNo);
2746 T(YAFFS_TRACE_ERASE,
2747 (TSTR("Erased block %d" TENDSTR), blockNo));
2749 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2751 yaffs_RetireBlock(dev, blockNo);
2752 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2753 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2757 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2761 yaffs_BlockInfo *bi;
2763 if (dev->nErasedBlocks < 1) {
2764 /* Hoosterman we've got a problem.
2765 * Can't get space to gc
2767 T(YAFFS_TRACE_ERROR,
2768 (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2773 /* Find an empty block. */
2775 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2776 dev->allocationBlockFinder++;
2777 if (dev->allocationBlockFinder < dev->internalStartBlock
2778 || dev->allocationBlockFinder > dev->internalEndBlock) {
2779 dev->allocationBlockFinder = dev->internalStartBlock;
2782 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2784 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2785 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2786 dev->sequenceNumber++;
2787 bi->sequenceNumber = dev->sequenceNumber;
2788 dev->nErasedBlocks--;
2789 T(YAFFS_TRACE_ALLOCATE,
2790 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2791 dev->allocationBlockFinder, dev->sequenceNumber,
2792 dev->nErasedBlocks));
2793 return dev->allocationBlockFinder;
2797 T(YAFFS_TRACE_ALWAYS,
2799 ("yaffs tragedy: no more eraased blocks, but there should have been %d"
2800 TENDSTR), dev->nErasedBlocks));
2806 // Check if there's space to allocate...
2807 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2808 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2811 int reservedBlocks = dev->nReservedBlocks;
2812 int checkpointBlocks;
2814 checkpointBlocks = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
2815 if(checkpointBlocks < 0)
2816 checkpointBlocks = 0;
2818 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2820 return (dev->nFreeChunks > reservedChunks);
2823 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2826 yaffs_BlockInfo *bi;
2828 if (dev->allocationBlock < 0) {
2829 /* Get next block to allocate off */
2830 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2831 dev->allocationPage = 0;
2834 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2835 /* Not enough space to allocate unless we're allowed to use the reserve. */
2839 if (dev->nErasedBlocks < dev->nReservedBlocks
2840 && dev->allocationPage == 0) {
2841 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2844 /* Next page please.... */
2845 if (dev->allocationBlock >= 0) {
2846 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2848 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2849 dev->allocationPage;
2851 yaffs_SetChunkBit(dev, dev->allocationBlock,
2852 dev->allocationPage);
2854 dev->allocationPage++;
2858 /* If the block is full set the state to full */
2859 if (dev->allocationPage >= dev->nChunksPerBlock) {
2860 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2861 dev->allocationBlock = -1;
2870 T(YAFFS_TRACE_ERROR,
2871 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2876 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2880 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2882 if (dev->allocationBlock > 0) {
2883 n += (dev->nChunksPerBlock - dev->allocationPage);
2890 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2896 int retVal = YAFFS_OK;
2899 int isCheckpointBlock;
2902 int chunksBefore = yaffs_GetErasedChunks(dev);
2905 yaffs_ExtendedTags tags;
2907 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2909 yaffs_Object *object;
2911 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2913 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2915 T(YAFFS_TRACE_TRACING,
2916 (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2917 bi->pagesInUse, bi->hasShrinkHeader));
2919 /*yaffs_VerifyFreeChunks(dev); */
2921 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2923 /* Take off the number of soft deleted entries because
2924 * they're going to get really deleted during GC.
2926 dev->nFreeChunks -= bi->softDeletions;
2930 if (isCheckpointBlock ||
2931 !yaffs_StillSomeChunkBits(dev, block)) {
2932 T(YAFFS_TRACE_TRACING,
2934 ("Collecting block %d that has no chunks in use" TENDSTR),
2936 yaffs_BlockBecameDirty(dev, block);
2939 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2941 yaffs_VerifyBlock(dev,bi,block);
2943 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
2944 chunkInBlock < dev->nChunksPerBlock
2945 && yaffs_StillSomeChunkBits(dev, block);
2946 chunkInBlock++, oldChunk++) {
2947 if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
2949 /* This page is in use and might need to be copied off */
2953 yaffs_InitialiseTags(&tags);
2955 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2959 yaffs_FindObjectByNumber(dev,
2962 T(YAFFS_TRACE_GC_DETAIL,
2964 ("Collecting page %d, %d %d %d " TENDSTR),
2965 chunkInBlock, tags.objectId, tags.chunkId,
2968 if(object && !yaffs_SkipVerification(dev)){
2969 if(tags.chunkId == 0)
2970 matchingChunk = object->chunkId;
2971 else if(object->softDeleted)
2972 matchingChunk = oldChunk; /* Defeat the test */
2974 matchingChunk = yaffs_FindChunkInFile(object,tags.chunkId,NULL);
2976 if(oldChunk != matchingChunk)
2977 T(YAFFS_TRACE_ERROR,
2978 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
2979 oldChunk,matchingChunk,tags.objectId, tags.chunkId));
2984 T(YAFFS_TRACE_ERROR,
2986 ("page %d in gc has no object: %d %d %d "
2988 tags.objectId, tags.chunkId, tags.byteCount));
2991 if (object && object->deleted
2992 && tags.chunkId != 0) {
2993 /* Data chunk in a deleted file, throw it away
2994 * It's a soft deleted data chunk,
2995 * No need to copy this, just forget about it and
2996 * fix up the object.
2999 object->nDataChunks--;
3001 if (object->nDataChunks <= 0) {
3002 /* remeber to clean up the object */
3003 dev->gcCleanupList[cleanups] =
3009 /* Todo object && object->deleted && object->nDataChunks == 0 */
3011 /* Deleted object header with no data chunks.
3012 * Can be discarded and the file deleted.
3014 object->chunkId = 0;
3015 yaffs_FreeTnode(object->myDev,
3018 object->variant.fileVariant.top = NULL;
3019 yaffs_DoGenericObjectDeletion(object);
3021 } else if (object) {
3022 /* It's either a data chunk in a live file or
3023 * an ObjectHeader, so we're interested in it.
3024 * NB Need to keep the ObjectHeaders of deleted files
3025 * until the whole file has been deleted off
3027 tags.serialNumber++;
3031 if (tags.chunkId == 0) {
3032 /* It is an object Id,
3033 * We need to nuke the shrinkheader flags first
3034 * We no longer want the shrinkHeader flag since its work is done
3035 * and if it is left in place it will mess up scanning.
3036 * Also, clear out any shadowing stuff
3039 yaffs_ObjectHeader *oh;
3040 oh = (yaffs_ObjectHeader *)buffer;
3042 oh->shadowsObject = -1;
3043 tags.extraShadows = 0;
3044 tags.extraIsShrinkHeader = 0;
3046 yaffs_VerifyObjectHeader(object,oh,&tags,1);
3050 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3053 retVal = YAFFS_FAIL;
3056 /* Ok, now fix up the Tnodes etc. */
3058 if (tags.chunkId == 0) {
3060 object->chunkId = newChunk;
3061 object->serial = tags.serialNumber;
3063 /* It's a data chunk */
3064 yaffs_PutChunkIntoFile
3072 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3077 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3080 /* Do any required cleanups */
3081 for (i = 0; i < cleanups; i++) {
3082 /* Time to delete the file too */
3084 yaffs_FindObjectByNumber(dev,
3085 dev->gcCleanupList[i]);
3087 yaffs_FreeTnode(dev,
3088 object->variant.fileVariant.
3090 object->variant.fileVariant.top = NULL;
3093 ("yaffs: About to finally delete object %d"
3094 TENDSTR), object->objectId));
3095 yaffs_DoGenericObjectDeletion(object);
3096 object->myDev->nDeletedFiles--;
3103 yaffs_VerifyCollectedBlock(dev,bi,block);
3105 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
3108 ("gc did not increase free chunks before %d after %d"
3109 TENDSTR), chunksBefore, chunksAfter));
3117 /* New garbage collector
3118 * If we're very low on erased blocks then we do aggressive garbage collection
3119 * otherwise we do "leasurely" garbage collection.
3120 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3121 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3123 * The idea is to help clear out space in a more spread-out manner.
3124 * Dunno if it really does anything useful.
3126 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
3130 int gcOk = YAFFS_OK;
3133 int checkpointBlockAdjust;
3135 if (dev->isDoingGC) {
3136 /* Bail out so we don't get recursive gc */
3140 /* This loop should pass the first time.
3141 * We'll only see looping here if the erase of the collected block fails.
3147 checkpointBlockAdjust = (dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint);
3148 if(checkpointBlockAdjust < 0)
3149 checkpointBlockAdjust = 0;
3151 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3152 /* We need a block soon...*/
3155 /* We're in no hurry */
3159 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3162 dev->garbageCollections++;
3164 dev->passiveGarbageCollections++;
3169 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3170 dev->nErasedBlocks, aggressive));
3172 gcOk = yaffs_GarbageCollectBlock(dev, block);
3175 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3178 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3179 TENDSTR), dev->nErasedBlocks, maxTries, block));
3181 } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
3184 return aggressive ? gcOk : YAFFS_OK;
3187 /*------------------------- TAGS --------------------------------*/
3189 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
3192 return (tags->chunkId == chunkInObject &&
3193 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3198 /*-------------------- Data file manipulation -----------------*/
3200 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
3201 yaffs_ExtendedTags * tags)
3203 /*Get the Tnode, then get the level 0 offset chunk offset */
3206 yaffs_ExtendedTags localTags;
3209 yaffs_Device *dev = in->myDev;
3212 /* Passed a NULL, so use our own tags space */
3216 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3219 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3222 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3228 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
3229 yaffs_ExtendedTags * tags)
3231 /* Get the Tnode, then get the level 0 offset chunk offset */
3234 yaffs_ExtendedTags localTags;
3236 yaffs_Device *dev = in->myDev;
3240 /* Passed a NULL, so use our own tags space */
3244 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3248 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3251 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3254 /* Delete the entry in the filestructure (if found) */
3256 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
3259 /*T(("No level 0 found for %d\n", chunkInInode)); */
3263 /* T(("Could not find %d to delete\n",chunkInInode)); */
3268 #ifdef YAFFS_PARANOID
3270 static int yaffs_CheckFileSanity(yaffs_Object * in)
3278 yaffs_Tags localTags;
3279 yaffs_Tags *tags = &localTags;
3283 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3284 /* T(("Object not a file\n")); */
3288 objId = in->objectId;
3289 fSize = in->variant.fileVariant.fileSize;
3291 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3293 for (chunk = 1; chunk <= nChunks; chunk++) {
3294 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3299 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
3301 if (yaffs_CheckChunkBits
3302 (dev, theChunk / dev->nChunksPerBlock,
3303 theChunk % dev->nChunksPerBlock)) {
3305 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3309 (tags, in->objectId, chunk, chunkDeleted)) {
3319 /* T(("No level 0 found for %d\n", chunk)); */
3323 return failed ? YAFFS_FAIL : YAFFS_OK;
3328 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
3329 int chunkInNAND, int inScan)
3331 /* NB inScan is zero unless scanning.
3332 * For forward scanning, inScan is > 0;
3333 * for backward scanning inScan is < 0
3337 yaffs_Device *dev = in->myDev;
3339 yaffs_ExtendedTags existingTags;
3340 yaffs_ExtendedTags newTags;
3341 unsigned existingSerial, newSerial;
3343 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3344 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3345 * If it is not during Scanning then something went wrong!
3348 T(YAFFS_TRACE_ERROR,
3350 ("yaffs tragedy:attempt to put data chunk into a non-file"
3355 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3359 tn = yaffs_AddOrFindLevel0Tnode(dev,
3360 &in->variant.fileVariant,
3367 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3370 /* If we're scanning then we need to test for duplicates
3371 * NB This does not need to be efficient since it should only ever
3372 * happen when the power fails during a write, then only one
3373 * chunk should ever be affected.
3375 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3376 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3379 if (existingChunk != 0) {
3380 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3381 * thus we have to do a FindChunkInFile to get the real chunk id.
3383 * We have a duplicate now we need to decide which one to use:
3385 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3386 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3387 * YAFFS1: Get both sets of tags and compare serial numbers.
3391 /* Only do this for forward scanning */
3392 yaffs_ReadChunkWithTagsFromNAND(dev,
3396 /* Do a proper find */
3398 yaffs_FindChunkInFile(in, chunkInInode,
3402 if (existingChunk <= 0) {
3403 /*Hoosterman - how did this happen? */
3405 T(YAFFS_TRACE_ERROR,
3407 ("yaffs tragedy: existing chunk < 0 in scan"
3412 /* NB The deleted flags should be false, otherwise the chunks will
3413 * not be loaded during a scan
3416 newSerial = newTags.serialNumber;
3417 existingSerial = existingTags.serialNumber;
3420 (in->myDev->isYaffs2 ||
3421 existingChunk <= 0 ||
3422 ((existingSerial + 1) & 3) == newSerial)) {
3423 /* Forward scanning.
3425 * Delete the old one and drop through to update the tnode
3427 yaffs_DeleteChunk(dev, existingChunk, 1,
3430 /* Backward scanning or we want to use the existing one
3432 * Delete the new one and return early so that the tnode isn't changed
3434 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3442 if (existingChunk == 0) {
3446 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
3451 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
3454 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3456 if (chunkInNAND >= 0) {
3457 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3460 T(YAFFS_TRACE_NANDACCESS,
3461 (TSTR("Chunk %d not found zero instead" TENDSTR),
3463 /* get sane (zero) data if you read a hole */
3464 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3470 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
3474 yaffs_ExtendedTags tags;
3475 yaffs_BlockInfo *bi;
3482 block = chunkId / dev->nChunksPerBlock;
3483 page = chunkId % dev->nChunksPerBlock;
3486 if(!yaffs_CheckChunkBit(dev,block,page))
3487 T(YAFFS_TRACE_VERIFY,
3488 (TSTR("Deleting invalid chunk %d"TENDSTR),
3491 bi = yaffs_GetBlockInfo(dev, block);
3493 T(YAFFS_TRACE_DELETION,
3494 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3497 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3499 yaffs_InitialiseTags(&tags);
3501 tags.chunkDeleted = 1;
3503 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3504 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3506 dev->nUnmarkedDeletions++;
3509 /* Pull out of the management area.
3510 * If the whole block became dirty, this will kick off an erasure.
3512 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3513 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3514 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3515 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3518 yaffs_ClearChunkBit(dev, block, page);
3522 if (bi->pagesInUse == 0 &&
3523 !bi->hasShrinkHeader &&
3524 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3525 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3526 yaffs_BlockBecameDirty(dev, block);
3530 /* T(("Bad news deleting chunk %d\n",chunkId)); */
3535 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
3536 const __u8 * buffer, int nBytes,
3539 /* Find old chunk Need to do this to get serial number
3540 * Write new one and patch into tree.
3541 * Invalidate old tags.
3545 yaffs_ExtendedTags prevTags;
3548 yaffs_ExtendedTags newTags;
3550 yaffs_Device *dev = in->myDev;
3552 yaffs_CheckGarbageCollection(dev);
3554 /* Get the previous chunk at this location in the file if it exists */
3555 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3557 /* Set up new tags */
3558 yaffs_InitialiseTags(&newTags);
3560 newTags.chunkId = chunkInInode;
3561 newTags.objectId = in->objectId;
3562 newTags.serialNumber =
3563 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
3564 newTags.byteCount = nBytes;
3567 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3570 if (newChunkId >= 0) {
3571 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3573 if (prevChunkId >= 0) {
3574 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3578 yaffs_CheckFileSanity(in);
3584 /* UpdateObjectHeader updates the header on NAND for an object.
3585 * If name is not NULL, then that new name is used.
3587 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
3588 int isShrink, int shadows)
3591 yaffs_BlockInfo *bi;
3593 yaffs_Device *dev = in->myDev;
3600 yaffs_ExtendedTags newTags;
3601 yaffs_ExtendedTags oldTags;
3603 __u8 *buffer = NULL;
3604 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3606 yaffs_ObjectHeader *oh = NULL;
3608 yaffs_strcpy(oldName,"silly old name");
3610 if (!in->fake || force) {
3612 yaffs_CheckGarbageCollection(dev);
3613 yaffs_CheckObjectDetailsLoaded(in);
3615 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3616 oh = (yaffs_ObjectHeader *) buffer;
3618 prevChunkId = in->chunkId;
3620 if (prevChunkId >= 0) {
3621 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3624 yaffs_VerifyObjectHeader(in,oh,&oldTags,0);
3626 memcpy(oldName, oh->name, sizeof(oh->name));
3629 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3631 oh->type = in->variantType;
3632 oh->yst_mode = in->yst_mode;
3633 oh->shadowsObject = shadows;
3635 #ifdef CONFIG_YAFFS_WINCE
3636 oh->win_atime[0] = in->win_atime[0];
3637 oh->win_ctime[0] = in->win_ctime[0];
3638 oh->win_mtime[0] = in->win_mtime[0];
3639 oh->win_atime[1] = in->win_atime[1];
3640 oh->win_ctime[1] = in->win_ctime[1];
3641 oh->win_mtime[1] = in->win_mtime[1];
3643 oh->yst_uid = in->yst_uid;
3644 oh->yst_gid = in->yst_gid;
3645 oh->yst_atime = in->yst_atime;
3646 oh->yst_mtime = in->yst_mtime;
3647 oh->yst_ctime = in->yst_ctime;
3648 oh->yst_rdev = in->yst_rdev;
3651 oh->parentObjectId = in->parent->objectId;
3653 oh->parentObjectId = 0;
3656 if (name && *name) {
3657 memset(oh->name, 0, sizeof(oh->name));
3658 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3659 } else if (prevChunkId>=0) {
3660 memcpy(oh->name, oldName, sizeof(oh->name));
3662 memset(oh->name, 0, sizeof(oh->name));
3665 oh->isShrink = isShrink;
3667 switch (in->variantType) {
3668 case YAFFS_OBJECT_TYPE_UNKNOWN:
3669 /* Should not happen */
3671 case YAFFS_OBJECT_TYPE_FILE:
3673 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3674 || oh->parentObjectId ==
3675 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3676 fileVariant.fileSize;
3678 case YAFFS_OBJECT_TYPE_HARDLINK:
3679 oh->equivalentObjectId =
3680 in->variant.hardLinkVariant.equivalentObjectId;
3682 case YAFFS_OBJECT_TYPE_SPECIAL:
3685 case YAFFS_OBJECT_TYPE_DIRECTORY:
3688 case YAFFS_OBJECT_TYPE_SYMLINK:
3689 yaffs_strncpy(oh->alias,
3690 in->variant.symLinkVariant.alias,
3691 YAFFS_MAX_ALIAS_LENGTH);
3692 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3697 yaffs_InitialiseTags(&newTags);
3699 newTags.chunkId = 0;
3700 newTags.objectId = in->objectId;
3701 newTags.serialNumber = in->serial;
3703 /* Add extra info for file header */
3705 newTags.extraHeaderInfoAvailable = 1;
3706 newTags.extraParentObjectId = oh->parentObjectId;
3707 newTags.extraFileLength = oh->fileSize;
3708 newTags.extraIsShrinkHeader = oh->isShrink;
3709 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3710 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3711 newTags.extraObjectType = in->variantType;
3713 yaffs_VerifyObjectHeader(in,oh,&newTags,1);
3715 /* Create new chunk in NAND */
3717 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3718 (prevChunkId >= 0) ? 1 : 0);
3720 if (newChunkId >= 0) {
3722 in->chunkId = newChunkId;
3724 if (prevChunkId >= 0) {
3725 yaffs_DeleteChunk(dev, prevChunkId, 1,
3729 if(!yaffs_ObjectHasCachedWriteData(in))
3732 /* If this was a shrink, then mark the block that the chunk lives on */
3734 bi = yaffs_GetBlockInfo(in->myDev,
3735 newChunkId /in->myDev-> nChunksPerBlock);
3736 bi->hasShrinkHeader = 1;
3741 retVal = newChunkId;
3746 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3751 /*------------------------ Short Operations Cache ----------------------------------------
3752 * In many situations where there is no high level buffering (eg WinCE) a lot of
3753 * reads might be short sequential reads, and a lot of writes may be short
3754 * sequential writes. eg. scanning/writing a jpeg file.
3755 * In these cases, a short read/write cache can provide a huge perfomance benefit
3756 * with dumb-as-a-rock code.
3757 * In Linux, the page cache provides read buffering aand the short op cache provides write
3760 * There are a limited number (~10) of cache chunks per device so that we don't
3761 * need a very intelligent search.
3764 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3766 yaffs_Device *dev = obj->myDev;
3768 yaffs_ChunkCache *cache;
3769 int nCaches = obj->myDev->nShortOpCaches;
3771 for(i = 0; i < nCaches; i++){
3772 cache = &dev->srCache[i];
3773 if (cache->object == obj &&
3782 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3784 yaffs_Device *dev = obj->myDev;
3785 int lowest = -99; /* Stop compiler whining. */
3787 yaffs_ChunkCache *cache;
3788 int chunkWritten = 0;
3789 int nCaches = obj->myDev->nShortOpCaches;
3795 /* Find the dirty cache for this object with the lowest chunk id. */
3796 for (i = 0; i < nCaches; i++) {
3797 if (dev->srCache[i].object == obj &&
3798 dev->srCache[i].dirty) {
3800 || dev->srCache[i].chunkId <
3802 cache = &dev->srCache[i];
3803 lowest = cache->chunkId;
3808 if (cache && !cache->locked) {
3809 /* Write it out and free it up */
3812 yaffs_WriteChunkDataToObject(cache->object,
3818 cache->object = NULL;
3821 } while (cache && chunkWritten > 0);
3824 /* Hoosterman, disk full while writing cache out. */
3825 T(YAFFS_TRACE_ERROR,
3826 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3833 /*yaffs_FlushEntireDeviceCache(dev)
3838 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3841 int nCaches = dev->nShortOpCaches;
3844 /* Find a dirty object in the cache and flush it...
3845 * until there are no further dirty objects.
3849 for( i = 0; i < nCaches && !obj; i++) {
3850 if (dev->srCache[i].object &&
3851 dev->srCache[i].dirty)
3852 obj = dev->srCache[i].object;
3856 yaffs_FlushFilesChunkCache(obj);
3863 /* Grab us a cache chunk for use.
3864 * First look for an empty one.
3865 * Then look for the least recently used non-dirty one.
3866 * Then look for the least recently used dirty one...., flush and look again.
3868 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
3874 if (dev->nShortOpCaches > 0) {
3875 for (i = 0; i < dev->nShortOpCaches; i++) {
3876 if (!dev->srCache[i].object)
3877 return &dev->srCache[i];
3883 usage = 0; /* just to stop the compiler grizzling */
3885 for (i = 0; i < dev->nShortOpCaches; i++) {
3886 if (!dev->srCache[i].dirty &&
3887 ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
3889 usage = dev->srCache[i].lastUse;
3895 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3902 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
3904 yaffs_ChunkCache *cache;
3905 yaffs_Object *theObj;
3910 if (dev->nShortOpCaches > 0) {
3911 /* Try find a non-dirty one... */
3913 cache = yaffs_GrabChunkCacheWorker(dev);
3916 /* They were all dirty, find the last recently used object and flush
3917 * its cache, then find again.
3918 * NB what's here is not very accurate, we actually flush the object
3919 * the last recently used page.
3922 /* With locking we can't assume we can use entry zero */
3929 for (i = 0; i < dev->nShortOpCaches; i++) {
3930 if (dev->srCache[i].object &&
3931 !dev->srCache[i].locked &&
3932 (dev->srCache[i].lastUse < usage || !cache))
3934 usage = dev->srCache[i].lastUse;
3935 theObj = dev->srCache[i].object;
3936 cache = &dev->srCache[i];
3941 if (!cache || cache->dirty) {
3942 /* Flush and try again */
3943 yaffs_FlushFilesChunkCache(theObj);
3944 cache = yaffs_GrabChunkCacheWorker(dev);
3954 /* Find a cached chunk */
3955 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
3958 yaffs_Device *dev = obj->myDev;
3960 if (dev->nShortOpCaches > 0) {
3961 for (i = 0; i < dev->nShortOpCaches; i++) {
3962 if (dev->srCache[i].object == obj &&
3963 dev->srCache[i].chunkId == chunkId) {
3966 return &dev->srCache[i];
3973 /* Mark the chunk for the least recently used algorithym */
3974 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
3978 if (dev->nShortOpCaches > 0) {
3979 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
3980 /* Reset the cache usages */
3982 for (i = 1; i < dev->nShortOpCaches; i++) {
3983 dev->srCache[i].lastUse = 0;
3990 cache->lastUse = dev->srLastUse;
3998 /* Invalidate a single cache page.
3999 * Do this when a whole page gets written,
4000 * ie the short cache for this page is no longer valid.
4002 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
4004 if (object->myDev->nShortOpCaches > 0) {
4005 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4008 cache->object = NULL;
4013 /* Invalidate all the cache pages associated with this object
4014 * Do this whenever ther file is deleted or resized.
4016 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
4019 yaffs_Device *dev = in->myDev;
4021 if (dev->nShortOpCaches > 0) {
4022 /* Invalidate it. */
4023 for (i = 0; i < dev->nShortOpCaches; i++) {
4024 if (dev->srCache[i].object == in) {
4025 dev->srCache[i].object = NULL;
4031 /*--------------------- Checkpointing --------------------*/
4034 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
4036 yaffs_CheckpointValidity cp;
4038 memset(&cp,0,sizeof(cp));
4040 cp.structType = sizeof(cp);
4041 cp.magic = YAFFS_MAGIC;
4042 cp.version = YAFFS_CHECKPOINT_VERSION;
4043 cp.head = (head) ? 1 : 0;
4045 return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
4049 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4051 yaffs_CheckpointValidity cp;
4054 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4057 ok = (cp.structType == sizeof(cp)) &&
4058 (cp.magic == YAFFS_MAGIC) &&
4059 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4060 (cp.head == ((head) ? 1 : 0));
4064 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4067 cp->nErasedBlocks = dev->nErasedBlocks;
4068 cp->allocationBlock = dev->allocationBlock;
4069 cp->allocationPage = dev->allocationPage;
4070 cp->nFreeChunks = dev->nFreeChunks;
4072 cp->nDeletedFiles = dev->nDeletedFiles;
4073 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4074 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4075 cp->sequenceNumber = dev->sequenceNumber;
4076 cp->oldestDirtySequence = dev->oldestDirtySequence;
4080 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4081 yaffs_CheckpointDevice *cp)
4083 dev->nErasedBlocks = cp->nErasedBlocks;
4084 dev->allocationBlock = cp->allocationBlock;
4085 dev->allocationPage = cp->allocationPage;
4086 dev->nFreeChunks = cp->nFreeChunks;
4088 dev->nDeletedFiles = cp->nDeletedFiles;
4089 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4090 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4091 dev->sequenceNumber = cp->sequenceNumber;
4092 dev->oldestDirtySequence = cp->oldestDirtySequence;
4096 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4098 yaffs_CheckpointDevice cp;
4100 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4104 /* Write device runtime values*/
4105 yaffs_DeviceToCheckpointDevice(&cp,dev);
4106 cp.structType = sizeof(cp);
4108 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4110 /* Write block info */
4112 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4113 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
4116 /* Write chunk bits */
4118 nBytes = nBlocks * dev->chunkBitmapStride;
4119 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
4125 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4127 yaffs_CheckpointDevice cp;
4129 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4133 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4137 if(cp.structType != sizeof(cp))
4141 yaffs_CheckpointDeviceToDevice(dev,&cp);
4143 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4145 ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
4149 nBytes = nBlocks * dev->chunkBitmapStride;
4151 ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
4156 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4160 cp->objectId = obj->objectId;
4161 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4162 cp->chunkId = obj->chunkId;
4163 cp->variantType = obj->variantType;
4164 cp->deleted = obj->deleted;
4165 cp->softDeleted = obj->softDeleted;
4166 cp->unlinked = obj->unlinked;
4167 cp->fake = obj->fake;
4168 cp->renameAllowed = obj->renameAllowed;
4169 cp->unlinkAllowed = obj->unlinkAllowed;
4170 cp->serial = obj->serial;
4171 cp->nDataChunks = obj->nDataChunks;
4173 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4174 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4175 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4176 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4179 static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
4182 yaffs_Object *parent;
4184 obj->objectId = cp->objectId;
4187 parent = yaffs_FindOrCreateObjectByNumber(
4190 YAFFS_OBJECT_TYPE_DIRECTORY);
4195 yaffs_AddObjectToDirectory(parent, obj);
4197 obj->chunkId = cp->chunkId;
4198 obj->variantType = cp->variantType;
4199 obj->deleted = cp->deleted;
4200 obj->softDeleted = cp->softDeleted;
4201 obj->unlinked = cp->unlinked;
4202 obj->fake = cp->fake;
4203 obj->renameAllowed = cp->renameAllowed;
4204 obj->unlinkAllowed = cp->unlinkAllowed;
4205 obj->serial = cp->serial;
4206 obj->nDataChunks = cp->nDataChunks;
4208 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4209 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4210 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4211 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4213 if(obj->objectId >= YAFFS_NOBJECT_BUCKETS)
4214 obj->lazyLoaded = 1;
4219 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
4220 __u32 level, int chunkOffset)
4223 yaffs_Device *dev = in->myDev;
4225 int nTnodeBytes = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4230 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
4231 if (tn->internal[i]) {
4232 ok = yaffs_CheckpointTnodeWorker(in,
4235 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4238 } else if (level == 0) {
4239 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4240 /* printf("write tnode at %d\n",baseOffset); */
4241 ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
4243 ok = (yaffs_CheckpointWrite(dev,tn,nTnodeBytes) == nTnodeBytes);
4251 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4253 __u32 endMarker = ~0;
4256 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4257 ok = yaffs_CheckpointTnodeWorker(obj,
4258 obj->variant.fileVariant.top,
4259 obj->variant.fileVariant.topLevel,
4262 ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) ==
4269 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4273 yaffs_Device *dev = obj->myDev;
4274 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4278 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4280 while(ok && (~baseChunk)){
4282 /* Read level 0 tnode */
4285 /* printf("read tnode at %d\n",baseChunk); */
4286 tn = yaffs_GetTnodeRaw(dev);
4288 ok = (yaffs_CheckpointRead(dev,tn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8) ==
4289 (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
4294 ok = yaffs_AddOrFindLevel0Tnode(dev,
4302 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4306 T(YAFFS_TRACE_CHECKPOINT,(
4307 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4308 nread,baseChunk,ok));
4314 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4317 yaffs_CheckpointObject cp;
4320 struct list_head *lh;
4323 /* Iterate through the objects in each hash entry,
4324 * dumping them to the checkpointing stream.
4327 for(i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++){
4328 list_for_each(lh, &dev->objectBucket[i].list) {
4330 obj = list_entry(lh, yaffs_Object, hashLink);
4331 if (!obj->deferedFree) {
4332 yaffs_ObjectToCheckpointObject(&cp,obj);
4333 cp.structType = sizeof(cp);
4335 T(YAFFS_TRACE_CHECKPOINT,(
4336 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
4337 cp.objectId,cp.parentId,cp.variantType,cp.chunkId,(unsigned) obj));
4339 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4341 if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4342 ok = yaffs_WriteCheckpointTnodes(obj);
4349 /* Dump end of list */
4350 memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
4351 cp.structType = sizeof(cp);
4354 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4359 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4362 yaffs_CheckpointObject cp;
4365 yaffs_Object *hardList = NULL;
4367 while(ok && !done) {
4368 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4369 if(cp.structType != sizeof(cp)) {
4370 T(YAFFS_TRACE_CHECKPOINT,(TSTR("struct size %d instead of %d ok %d"TENDSTR),
4371 cp.structType,sizeof(cp),ok));
4375 T(YAFFS_TRACE_CHECKPOINT,(TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4376 cp.objectId,cp.parentId,cp.variantType,cp.chunkId));
4378 if(ok && cp.objectId == ~0)
4381 obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
4383 yaffs_CheckpointObjectToObject(obj,&cp);
4384 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4385 ok = yaffs_ReadCheckpointTnodes(obj);
4386 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4387 obj->hardLinks.next =
4388 (struct list_head *)
4398 yaffs_HardlinkFixup(dev,hardList);
4403 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4405 __u32 checkpointSum;
4408 yaffs_GetCheckpointSum(dev,&checkpointSum);
4410 ok = (yaffs_CheckpointWrite(dev,&checkpointSum,sizeof(checkpointSum)) == sizeof(checkpointSum));
4418 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4420 __u32 checkpointSum0;
4421 __u32 checkpointSum1;
4424 yaffs_GetCheckpointSum(dev,&checkpointSum0);
4426 ok = (yaffs_CheckpointRead(dev,&checkpointSum1,sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4431 if(checkpointSum0 != checkpointSum1)
4438 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4443 if(dev->skipCheckpointWrite || !dev->isYaffs2){
4444 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint write" TENDSTR)));
4449 ok = yaffs_CheckpointOpen(dev,1);
4452 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4453 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
4456 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint device" TENDSTR)));
4457 ok = yaffs_WriteCheckpointDevice(dev);
4460 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint objects" TENDSTR)));
4461 ok = yaffs_WriteCheckpointObjects(dev);
4464 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4465 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
4469 ok = yaffs_WriteCheckpointSum(dev);
4473 if(!yaffs_CheckpointClose(dev))
4477 dev->isCheckpointed = 1;
4479 dev->isCheckpointed = 0;
4481 return dev->isCheckpointed;
4484 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4488 if(dev->skipCheckpointRead || !dev->isYaffs2){
4489 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint read" TENDSTR)));
4494 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
4497 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4498 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
4501 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint device" TENDSTR)));
4502 ok = yaffs_ReadCheckpointDevice(dev);
4505 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint objects" TENDSTR)));
4506 ok = yaffs_ReadCheckpointObjects(dev);
4509 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4510 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
4514 ok = yaffs_ReadCheckpointSum(dev);
4515 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint checksum %d" TENDSTR),ok));
4518 if(!yaffs_CheckpointClose(dev))
4522 dev->isCheckpointed = 1;
4524 dev->isCheckpointed = 0;
4530 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4532 if(dev->isCheckpointed ||
4533 dev->blocksInCheckpoint > 0){
4534 dev->isCheckpointed = 0;
4535 yaffs_CheckpointInvalidateStream(dev);
4536 if(dev->superBlock && dev->markSuperBlockDirty)
4537 dev->markSuperBlockDirty(dev->superBlock);
4542 int yaffs_CheckpointSave(yaffs_Device *dev)
4545 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4547 yaffs_VerifyObjects(dev);
4548 yaffs_VerifyBlocks(dev);
4549 yaffs_VerifyFreeChunks(dev);
4551 if(!dev->isCheckpointed) {
4552 yaffs_InvalidateCheckpoint(dev);
4553 yaffs_WriteCheckpointData(dev);
4556 T(YAFFS_TRACE_ALWAYS,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4558 return dev->isCheckpointed;
4561 int yaffs_CheckpointRestore(yaffs_Device *dev)
4564 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4566 retval = yaffs_ReadCheckpointData(dev);
4568 if(dev->isCheckpointed){
4569 yaffs_VerifyObjects(dev);
4570 yaffs_VerifyBlocks(dev);
4571 yaffs_VerifyFreeChunks(dev);
4574 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4579 /*--------------------- File read/write ------------------------
4580 * Read and write have very similar structures.
4581 * In general the read/write has three parts to it
4582 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4583 * Some complete chunks
4584 * An incomplete chunk to end off with
4586 * Curve-balls: the first chunk might also be the last chunk.
4589 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, loff_t offset,
4598 yaffs_ChunkCache *cache;
4605 //chunk = offset / dev->nDataBytesPerChunk + 1;
4606 //start = offset % dev->nDataBytesPerChunk;
4607 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4610 /* OK now check for the curveball where the start and end are in
4613 if ((start + n) < dev->nDataBytesPerChunk) {
4616 nToCopy = dev->nDataBytesPerChunk - start;
4619 cache = yaffs_FindChunkCache(in, chunk);
4621 /* If the chunk is already in the cache or it is less than a whole chunk
4622 * then use the cache (if there is caching)
4623 * else bypass the cache.
4625 if (cache || nToCopy != dev->nDataBytesPerChunk) {
4626 if (dev->nShortOpCaches > 0) {
4628 /* If we can't find the data in the cache, then load it up. */
4631 cache = yaffs_GrabChunkCache(in->myDev);
4633 cache->chunkId = chunk;
4636 yaffs_ReadChunkDataFromObject(in, chunk,
4642 yaffs_UseChunkCache(dev, cache, 0);
4646 #ifdef CONFIG_YAFFS_WINCE
4647 yfsd_UnlockYAFFS(TRUE);
4649 memcpy(buffer, &cache->data[start], nToCopy);
4651 #ifdef CONFIG_YAFFS_WINCE
4652 yfsd_LockYAFFS(TRUE);
4656 /* Read into the local buffer then copy..*/
4659 yaffs_GetTempBuffer(dev, __LINE__);
4660 yaffs_ReadChunkDataFromObject(in, chunk,
4662 #ifdef CONFIG_YAFFS_WINCE
4663 yfsd_UnlockYAFFS(TRUE);
4665 memcpy(buffer, &localBuffer[start], nToCopy);
4667 #ifdef CONFIG_YAFFS_WINCE
4668 yfsd_LockYAFFS(TRUE);
4670 yaffs_ReleaseTempBuffer(dev, localBuffer,
4675 #ifdef CONFIG_YAFFS_WINCE
4676 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4678 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4679 * This is because we otherwise screw up WinCE's memory mapper
4681 yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
4683 #ifdef CONFIG_YAFFS_WINCE
4684 yfsd_UnlockYAFFS(TRUE);
4686 memcpy(buffer, localBuffer, dev->nDataBytesPerChunk);
4688 #ifdef CONFIG_YAFFS_WINCE
4689 yfsd_LockYAFFS(TRUE);
4690 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4694 /* A full chunk. Read directly into the supplied buffer. */
4695 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4709 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, loff_t offset,
4710 int nBytes, int writeThrough)
4719 int startOfWrite = offset;
4720 int chunkWritten = 0;
4727 while (n > 0 && chunkWritten >= 0) {
4728 //chunk = offset / dev->nDataBytesPerChunk + 1;
4729 //start = offset % dev->nDataBytesPerChunk;
4730 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4733 /* OK now check for the curveball where the start and end are in
4737 if ((start + n) < dev->nDataBytesPerChunk) {
4740 /* Now folks, to calculate how many bytes to write back....
4741 * If we're overwriting and not writing to then end of file then
4742 * we need to write back as much as was there before.
4746 in->variant.fileVariant.fileSize -
4747 ((chunk - 1) * dev->nDataBytesPerChunk);
4749 if (nBytesRead > dev->nDataBytesPerChunk) {
4750 nBytesRead = dev->nDataBytesPerChunk;
4755 (start + n)) ? nBytesRead : (start + n);
4758 nToCopy = dev->nDataBytesPerChunk - start;
4759 nToWriteBack = dev->nDataBytesPerChunk;
4762 if (nToCopy != dev->nDataBytesPerChunk) {
4763 /* An incomplete start or end chunk (or maybe both start and end chunk) */
4764 if (dev->nShortOpCaches > 0) {
4765 yaffs_ChunkCache *cache;
4766 /* If we can't find the data in the cache, then load the cache */
4767 cache = yaffs_FindChunkCache(in, chunk);
4770 && yaffs_CheckSpaceForAllocation(in->
4772 cache = yaffs_GrabChunkCache(in->myDev);
4774 cache->chunkId = chunk;
4777 yaffs_ReadChunkDataFromObject(in, chunk,
4783 !yaffs_CheckSpaceForAllocation(in->myDev)){
4784 /* Drop the cache if it was a read cache item and
4785 * no space check has been made for it.
4791 yaffs_UseChunkCache(dev, cache, 1);
4793 #ifdef CONFIG_YAFFS_WINCE
4794 yfsd_UnlockYAFFS(TRUE);
4797 memcpy(&cache->data[start], buffer,
4800 #ifdef CONFIG_YAFFS_WINCE
4801 yfsd_LockYAFFS(TRUE);
4804 cache->nBytes = nToWriteBack;
4808 yaffs_WriteChunkDataToObject
4811 cache->data, cache->nBytes,
4817 chunkWritten = -1; /* fail the write */
4820 /* An incomplete start or end chunk (or maybe both start and end chunk)
4821 * Read into the local buffer then copy, then copy over and write back.
4825 yaffs_GetTempBuffer(dev, __LINE__);
4827 yaffs_ReadChunkDataFromObject(in, chunk,
4830 #ifdef CONFIG_YAFFS_WINCE
4831 yfsd_UnlockYAFFS(TRUE);
4834 memcpy(&localBuffer[start], buffer, nToCopy);
4836 #ifdef CONFIG_YAFFS_WINCE
4837 yfsd_LockYAFFS(TRUE);
4840 yaffs_WriteChunkDataToObject(in, chunk,
4845 yaffs_ReleaseTempBuffer(dev, localBuffer,
4852 #ifdef CONFIG_YAFFS_WINCE
4853 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4854 * This is because we otherwise screw up WinCE's memory mapper
4856 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4857 #ifdef CONFIG_YAFFS_WINCE
4858 yfsd_UnlockYAFFS(TRUE);
4860 memcpy(localBuffer, buffer, dev->nDataBytesPerChunk);
4861 #ifdef CONFIG_YAFFS_WINCE
4862 yfsd_LockYAFFS(TRUE);
4865 yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
4866 dev->nDataBytesPerChunk,
4868 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4870 /* A full chunk. Write directly from the supplied buffer. */
4872 yaffs_WriteChunkDataToObject(in, chunk, buffer,
4873 dev->nDataBytesPerChunk,
4876 /* Since we've overwritten the cached data, we better invalidate it. */
4877 yaffs_InvalidateChunkCache(in, chunk);
4880 if (chunkWritten >= 0) {
4889 /* Update file object */
4891 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
4892 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4901 /* ---------------------- File resizing stuff ------------------ */
4903 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
4906 yaffs_Device *dev = in->myDev;
4907 int oldFileSize = in->variant.fileVariant.fileSize;
4909 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
4911 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
4912 dev->nDataBytesPerChunk;
4916 /* Delete backwards so that we don't end up with holes if
4917 * power is lost part-way through the operation.
4919 for (i = lastDel; i >= startDel; i--) {
4920 /* NB this could be optimised somewhat,
4921 * eg. could retrieve the tags and write them without
4922 * using yaffs_DeleteChunk
4925 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
4928 (dev->internalStartBlock * dev->nChunksPerBlock)
4930 ((dev->internalEndBlock +
4931 1) * dev->nChunksPerBlock)) {
4932 T(YAFFS_TRACE_ALWAYS,
4933 (TSTR("Found daft chunkId %d for %d" TENDSTR),
4937 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
4944 int yaffs_ResizeFile(yaffs_Object * in, loff_t newSize)
4947 int oldFileSize = in->variant.fileVariant.fileSize;
4948 int newSizeOfPartialChunk;
4951 yaffs_Device *dev = in->myDev;
4953 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
4955 yaffs_FlushFilesChunkCache(in);
4956 yaffs_InvalidateWholeChunkCache(in);
4958 yaffs_CheckGarbageCollection(dev);
4960 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
4961 return yaffs_GetFileSize(in);
4964 if (newSize == oldFileSize) {
4968 if (newSize < oldFileSize) {
4970 yaffs_PruneResizedChunks(in, newSize);
4972 if (newSizeOfPartialChunk != 0) {
4973 int lastChunk = 1 + newFullChunks;
4975 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4977 /* Got to read and rewrite the last chunk with its new size and zero pad */
4978 yaffs_ReadChunkDataFromObject(in, lastChunk,
4981 memset(localBuffer + newSizeOfPartialChunk, 0,
4982 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
4984 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
4985 newSizeOfPartialChunk, 1);
4987 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4990 in->variant.fileVariant.fileSize = newSize;
4992 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
4994 /* newsSize > oldFileSize */
4995 in->variant.fileVariant.fileSize = newSize;
5000 /* Write a new object header.
5001 * show we've shrunk the file, if need be
5002 * Do this only if the file is not in the deleted directories.
5004 if (in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5005 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
5006 yaffs_UpdateObjectHeader(in, NULL, 0,
5007 (newSize < oldFileSize) ? 1 : 0, 0);
5013 loff_t yaffs_GetFileSize(yaffs_Object * obj)
5015 obj = yaffs_GetEquivalentObject(obj);
5017 switch (obj->variantType) {
5018 case YAFFS_OBJECT_TYPE_FILE:
5019 return obj->variant.fileVariant.fileSize;
5020 case YAFFS_OBJECT_TYPE_SYMLINK:
5021 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5029 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
5033 yaffs_FlushFilesChunkCache(in);
5035 #ifdef CONFIG_YAFFS_WINCE
5036 yfsd_WinFileTimeNow(in->win_mtime);
5039 in->yst_mtime = Y_CURRENT_TIME;
5045 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5046 0) ? YAFFS_OK : YAFFS_FAIL;
5055 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
5058 /* First off, invalidate the file's data in the cache, without flushing. */
5059 yaffs_InvalidateWholeChunkCache(in);
5061 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5062 /* Move to the unlinked directory so we have a record that it was deleted. */
5063 yaffs_ChangeObjectName(in, in->myDev->deletedDir,"deleted", 0, 0);
5067 yaffs_RemoveObjectFromDirectory(in);
5068 yaffs_DeleteChunk(in->myDev, in->chunkId, 1, __LINE__);
5071 yaffs_FreeObject(in);
5076 /* yaffs_DeleteFile deletes the whole file data
5077 * and the inode associated with the file.
5078 * It does not delete the links associated with the file.
5080 static int yaffs_UnlinkFile(yaffs_Object * in)
5084 int immediateDeletion = 0;
5089 immediateDeletion = 1;
5093 if (in->inUse <= 0) {
5094 immediateDeletion = 1;
5098 if (immediateDeletion) {
5100 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5102 T(YAFFS_TRACE_TRACING,
5103 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5106 in->myDev->nDeletedFiles++;
5107 if (0 && in->myDev->isYaffs2) {
5108 yaffs_ResizeFile(in, 0);
5110 yaffs_SoftDeleteFile(in);
5113 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5121 int yaffs_DeleteFile(yaffs_Object * in)
5123 int retVal = YAFFS_OK;
5125 if (in->nDataChunks > 0) {
5126 /* Use soft deletion if there is data in the file */
5127 if (!in->unlinked) {
5128 retVal = yaffs_UnlinkFile(in);
5130 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5132 in->myDev->nDeletedFiles++;
5133 yaffs_SoftDeleteFile(in);
5135 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
5137 /* The file has no data chunks so we toss it immediately */
5138 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5139 in->variant.fileVariant.top = NULL;
5140 yaffs_DoGenericObjectDeletion(in);
5146 static int yaffs_DeleteDirectory(yaffs_Object * in)
5148 /* First check that the directory is empty. */
5149 if (list_empty(&in->variant.directoryVariant.children)) {
5150 return yaffs_DoGenericObjectDeletion(in);
5157 static int yaffs_DeleteSymLink(yaffs_Object * in)
5159 YFREE(in->variant.symLinkVariant.alias);
5161 return yaffs_DoGenericObjectDeletion(in);
5164 static int yaffs_DeleteHardLink(yaffs_Object * in)
5166 /* remove this hardlink from the list assocaited with the equivalent
5169 list_del(&in->hardLinks);
5170 return yaffs_DoGenericObjectDeletion(in);
5173 static void yaffs_DestroyObject(yaffs_Object * obj)
5175 switch (obj->variantType) {
5176 case YAFFS_OBJECT_TYPE_FILE:
5177 yaffs_DeleteFile(obj);
5179 case YAFFS_OBJECT_TYPE_DIRECTORY:
5180 yaffs_DeleteDirectory(obj);
5182 case YAFFS_OBJECT_TYPE_SYMLINK:
5183 yaffs_DeleteSymLink(obj);
5185 case YAFFS_OBJECT_TYPE_HARDLINK:
5186 yaffs_DeleteHardLink(obj);
5188 case YAFFS_OBJECT_TYPE_SPECIAL:
5189 yaffs_DoGenericObjectDeletion(obj);
5191 case YAFFS_OBJECT_TYPE_UNKNOWN:
5192 break; /* should not happen. */
5196 static int yaffs_UnlinkWorker(yaffs_Object * obj)
5199 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5200 return yaffs_DeleteHardLink(obj);
5201 } else if (!list_empty(&obj->hardLinks)) {
5202 /* Curve ball: We're unlinking an object that has a hardlink.
5204 * This problem arises because we are not strictly following
5205 * The Linux link/inode model.
5207 * We can't really delete the object.
5208 * Instead, we do the following:
5209 * - Select a hardlink.
5210 * - Unhook it from the hard links
5211 * - Unhook it from its parent directory (so that the rename can work)
5212 * - Rename the object to the hardlink's name.
5213 * - Delete the hardlink
5218 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5220 hl = list_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5222 list_del_init(&hl->hardLinks);
5223 list_del_init(&hl->siblings);
5225 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5227 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
5229 if (retVal == YAFFS_OK) {
5230 retVal = yaffs_DoGenericObjectDeletion(hl);
5235 switch (obj->variantType) {
5236 case YAFFS_OBJECT_TYPE_FILE:
5237 return yaffs_UnlinkFile(obj);
5239 case YAFFS_OBJECT_TYPE_DIRECTORY:
5240 return yaffs_DeleteDirectory(obj);
5242 case YAFFS_OBJECT_TYPE_SYMLINK:
5243 return yaffs_DeleteSymLink(obj);
5245 case YAFFS_OBJECT_TYPE_SPECIAL:
5246 return yaffs_DoGenericObjectDeletion(obj);
5248 case YAFFS_OBJECT_TYPE_HARDLINK:
5249 case YAFFS_OBJECT_TYPE_UNKNOWN:
5257 static int yaffs_UnlinkObject( yaffs_Object *obj)
5260 if (obj && obj->unlinkAllowed) {
5261 return yaffs_UnlinkWorker(obj);
5267 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
5271 obj = yaffs_FindObjectByName(dir, name);
5272 return yaffs_UnlinkObject(obj);
5275 /*----------------------- Initialisation Scanning ---------------------- */
5277 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
5278 int backwardScanning)
5282 if (!backwardScanning) {
5283 /* Handle YAFFS1 forward scanning case
5284 * For YAFFS1 we always do the deletion
5288 /* Handle YAFFS2 case (backward scanning)
5289 * If the shadowed object exists then ignore.
5291 if (yaffs_FindObjectByNumber(dev, objId)) {
5296 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5297 * We put it in unlinked dir to be cleaned up after the scanning
5300 yaffs_FindOrCreateObjectByNumber(dev, objId,
5301 YAFFS_OBJECT_TYPE_FILE);
5302 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5303 obj->variant.fileVariant.shrinkSize = 0;
5304 obj->valid = 1; /* So that we don't read any other info for this file */
5314 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5321 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5323 in = yaffs_FindObjectByNumber(dev,
5324 hl->variant.hardLinkVariant.
5325 equivalentObjectId);
5328 /* Add the hardlink pointers */
5329 hl->variant.hardLinkVariant.equivalentObject = in;
5330 list_add(&hl->hardLinks, &in->hardLinks);
5332 /* Todo Need to report/handle this better.
5333 * Got a problem... hardlink to a non-existant object
5335 hl->variant.hardLinkVariant.equivalentObject = NULL;
5336 INIT_LIST_HEAD(&hl->hardLinks);
5348 static int ybicmp(const void *a, const void *b){
5349 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5350 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5351 register int ablock = ((yaffs_BlockIndex *)a)->block;
5352 register int bblock = ((yaffs_BlockIndex *)b)->block;
5354 return ablock - bblock;
5360 static int yaffs_Scan(yaffs_Device * dev)
5362 yaffs_ExtendedTags tags;
5367 int nBlocksToScan = 0;
5373 yaffs_BlockState state;
5374 yaffs_Object *hardList = NULL;
5375 yaffs_BlockInfo *bi;
5377 yaffs_ObjectHeader *oh;
5379 yaffs_Object *parent;
5380 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5382 int alloc_failed = 0;
5387 yaffs_BlockIndex *blockIndex = NULL;
5389 if (dev->isYaffs2) {
5391 (TSTR("yaffs_Scan is not for YAFFS2!" TENDSTR)));
5395 //TODO Throw all the yaffs2 stuuf out of yaffs_Scan since it is only for yaffs1 format.
5398 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5399 dev->internalStartBlock, dev->internalEndBlock));
5401 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5403 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5405 if (dev->isYaffs2) {
5406 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
5411 /* Scan all the blocks to determine their state */
5412 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5413 bi = yaffs_GetBlockInfo(dev, blk);
5414 yaffs_ClearChunkBits(dev, blk);
5416 bi->softDeletions = 0;
5418 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5420 bi->blockState = state;
5421 bi->sequenceNumber = sequenceNumber;
5423 T(YAFFS_TRACE_SCAN_DEBUG,
5424 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5425 state, sequenceNumber));
5427 if (state == YAFFS_BLOCK_STATE_DEAD) {
5428 T(YAFFS_TRACE_BAD_BLOCKS,
5429 (TSTR("block %d is bad" TENDSTR), blk));
5430 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5431 T(YAFFS_TRACE_SCAN_DEBUG,
5432 (TSTR("Block empty " TENDSTR)));
5433 dev->nErasedBlocks++;
5434 dev->nFreeChunks += dev->nChunksPerBlock;
5435 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5437 /* Determine the highest sequence number */
5438 if (dev->isYaffs2 &&
5439 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
5440 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
5442 blockIndex[nBlocksToScan].seq = sequenceNumber;
5443 blockIndex[nBlocksToScan].block = blk;
5447 if (sequenceNumber >= dev->sequenceNumber) {
5448 dev->sequenceNumber = sequenceNumber;
5450 } else if (dev->isYaffs2) {
5451 /* TODO: Nasty sequence number! */
5454 ("Block scanning block %d has bad sequence number %d"
5455 TENDSTR), blk, sequenceNumber));
5462 * Dungy old bubble sort for now...
5464 if (dev->isYaffs2) {
5465 yaffs_BlockIndex temp;
5469 for (i = 0; i < nBlocksToScan; i++)
5470 for (j = i + 1; j < nBlocksToScan; j++)
5471 if (blockIndex[i].seq > blockIndex[j].seq) {
5472 temp = blockIndex[j];
5473 blockIndex[j] = blockIndex[i];
5474 blockIndex[i] = temp;
5478 /* Now scan the blocks looking at the data. */
5479 if (dev->isYaffs2) {
5481 endIterator = nBlocksToScan - 1;
5482 T(YAFFS_TRACE_SCAN_DEBUG,
5483 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
5485 startIterator = dev->internalStartBlock;
5486 endIterator = dev->internalEndBlock;
5489 /* For each block.... */
5490 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5493 if (dev->isYaffs2) {
5494 /* get the block to scan in the correct order */
5495 blk = blockIndex[blockIterator].block;
5497 blk = blockIterator;
5500 bi = yaffs_GetBlockInfo(dev, blk);
5501 state = bi->blockState;
5505 /* For each chunk in each block that needs scanning....*/
5506 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5507 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5508 /* Read the tags and decide what to do */
5509 chunk = blk * dev->nChunksPerBlock + c;
5511 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5514 /* Let's have a good look at this chunk... */
5516 if (!dev->isYaffs2 && tags.chunkDeleted) {
5522 /*T((" %d %d deleted\n",blk,c)); */
5523 } else if (!tags.chunkUsed) {
5524 /* An unassigned chunk in the block
5525 * This means that either the block is empty or
5526 * this is the one being allocated from
5530 /* We're looking at the first chunk in the block so the block is unused */
5531 state = YAFFS_BLOCK_STATE_EMPTY;
5532 dev->nErasedBlocks++;
5534 /* this is the block being allocated from */
5537 (" Allocating from %d %d" TENDSTR),
5539 state = YAFFS_BLOCK_STATE_ALLOCATING;
5540 dev->allocationBlock = blk;
5541 dev->allocationPage = c;
5542 dev->allocationBlockFinder = blk;
5543 /* Set it to here to encourage the allocator to go forth from here. */
5545 /* Yaffs2 sanity check:
5546 * This should be the one with the highest sequence number
5549 && (dev->sequenceNumber !=
5550 bi->sequenceNumber)) {
5551 T(YAFFS_TRACE_ALWAYS,
5553 ("yaffs: Allocation block %d was not highest sequence id:"
5554 " block seq = %d, dev seq = %d"
5555 TENDSTR), blk,bi->sequenceNumber,dev->sequenceNumber));
5559 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5560 } else if (tags.chunkId > 0) {
5561 /* chunkId > 0 so it is a data chunk... */
5562 unsigned int endpos;
5564 yaffs_SetChunkBit(dev, blk, c);
5567 in = yaffs_FindOrCreateObjectByNumber(dev,
5570 YAFFS_OBJECT_TYPE_FILE);
5571 /* PutChunkIntoFile checks for a clash (two data chunks with
5572 * the same chunkId).
5579 if(!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,1))
5584 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5587 in->variantType == YAFFS_OBJECT_TYPE_FILE
5588 && in->variant.fileVariant.scannedFileSize <
5590 in->variant.fileVariant.
5591 scannedFileSize = endpos;
5592 if (!dev->useHeaderFileSize) {
5593 in->variant.fileVariant.
5595 in->variant.fileVariant.
5600 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
5602 /* chunkId == 0, so it is an ObjectHeader.
5603 * Thus, we read in the object header and make the object
5605 yaffs_SetChunkBit(dev, blk, c);
5608 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5612 oh = (yaffs_ObjectHeader *) chunkData;
5614 in = yaffs_FindObjectByNumber(dev,
5616 if (in && in->variantType != oh->type) {
5617 /* This should not happen, but somehow
5618 * Wev'e ended up with an objectId that has been reused but not yet
5619 * deleted, and worse still it has changed type. Delete the old object.
5622 yaffs_DestroyObject(in);
5627 in = yaffs_FindOrCreateObjectByNumber(dev,
5635 if (in && oh->shadowsObject > 0) {
5636 yaffs_HandleShadowedObject(dev,
5642 if (in && in->valid) {
5643 /* We have already filled this one. We have a duplicate and need to resolve it. */
5645 unsigned existingSerial = in->serial;
5646 unsigned newSerial = tags.serialNumber;
5648 if (dev->isYaffs2 ||
5649 ((existingSerial + 1) & 3) ==
5651 /* Use new one - destroy the exisiting one */
5652 yaffs_DeleteChunk(dev,
5657 /* Use existing - destroy this one. */
5658 yaffs_DeleteChunk(dev, chunk, 1,
5663 if (in && !in->valid &&
5664 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5665 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5666 /* We only load some info, don't fiddle with directory structure */
5668 in->variantType = oh->type;
5670 in->yst_mode = oh->yst_mode;
5671 #ifdef CONFIG_YAFFS_WINCE
5672 in->win_atime[0] = oh->win_atime[0];
5673 in->win_ctime[0] = oh->win_ctime[0];
5674 in->win_mtime[0] = oh->win_mtime[0];
5675 in->win_atime[1] = oh->win_atime[1];
5676 in->win_ctime[1] = oh->win_ctime[1];
5677 in->win_mtime[1] = oh->win_mtime[1];
5679 in->yst_uid = oh->yst_uid;
5680 in->yst_gid = oh->yst_gid;
5681 in->yst_atime = oh->yst_atime;
5682 in->yst_mtime = oh->yst_mtime;
5683 in->yst_ctime = oh->yst_ctime;
5684 in->yst_rdev = oh->yst_rdev;
5686 in->chunkId = chunk;
5688 } else if (in && !in->valid) {
5689 /* we need to load this info */
5692 in->variantType = oh->type;
5694 in->yst_mode = oh->yst_mode;
5695 #ifdef CONFIG_YAFFS_WINCE
5696 in->win_atime[0] = oh->win_atime[0];
5697 in->win_ctime[0] = oh->win_ctime[0];
5698 in->win_mtime[0] = oh->win_mtime[0];
5699 in->win_atime[1] = oh->win_atime[1];
5700 in->win_ctime[1] = oh->win_ctime[1];
5701 in->win_mtime[1] = oh->win_mtime[1];
5703 in->yst_uid = oh->yst_uid;
5704 in->yst_gid = oh->yst_gid;
5705 in->yst_atime = oh->yst_atime;
5706 in->yst_mtime = oh->yst_mtime;
5707 in->yst_ctime = oh->yst_ctime;
5708 in->yst_rdev = oh->yst_rdev;
5710 in->chunkId = chunk;
5712 yaffs_SetObjectName(in, oh->name);
5715 /* directory stuff...
5720 yaffs_FindOrCreateObjectByNumber
5721 (dev, oh->parentObjectId,
5722 YAFFS_OBJECT_TYPE_DIRECTORY);
5723 if (parent->variantType ==
5724 YAFFS_OBJECT_TYPE_UNKNOWN) {
5725 /* Set up as a directory */
5726 parent->variantType =
5727 YAFFS_OBJECT_TYPE_DIRECTORY;
5728 INIT_LIST_HEAD(&parent->variant.
5731 } else if (parent->variantType !=
5732 YAFFS_OBJECT_TYPE_DIRECTORY)
5734 /* Hoosterman, another problem....
5735 * We're trying to use a non-directory as a directory
5738 T(YAFFS_TRACE_ERROR,
5740 ("yaffs tragedy: attempting to use non-directory as"
5741 " a directory in scan. Put in lost+found."
5743 parent = dev->lostNFoundDir;
5746 yaffs_AddObjectToDirectory(parent, in);
5748 if (0 && (parent == dev->deletedDir ||
5749 parent == dev->unlinkedDir)) {
5750 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
5751 dev->nDeletedFiles++;
5753 /* Note re hardlinks.
5754 * Since we might scan a hardlink before its equivalent object is scanned
5755 * we put them all in a list.
5756 * After scanning is complete, we should have all the objects, so we run through this
5757 * list and fix up all the chains.
5760 switch (in->variantType) {
5761 case YAFFS_OBJECT_TYPE_UNKNOWN:
5762 /* Todo got a problem */
5764 case YAFFS_OBJECT_TYPE_FILE:
5767 /* Prune back the shrunken chunks */
5768 yaffs_PruneResizedChunks
5770 /* Mark the block as having a shrinkHeader */
5771 bi->hasShrinkHeader = 1;
5774 if (dev->useHeaderFileSize)
5776 in->variant.fileVariant.
5781 case YAFFS_OBJECT_TYPE_HARDLINK:
5782 in->variant.hardLinkVariant.
5783 equivalentObjectId =
5784 oh->equivalentObjectId;
5785 in->hardLinks.next =
5786 (struct list_head *)
5790 case YAFFS_OBJECT_TYPE_DIRECTORY:
5793 case YAFFS_OBJECT_TYPE_SPECIAL:
5796 case YAFFS_OBJECT_TYPE_SYMLINK:
5797 in->variant.symLinkVariant.alias =
5798 yaffs_CloneString(oh->alias);
5799 if(!in->variant.symLinkVariant.alias)
5804 if (parent == dev->deletedDir) {
5805 yaffs_DestroyObject(in);
5806 bi->hasShrinkHeader = 1;
5812 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5813 /* If we got this far while scanning, then the block is fully allocated.*/
5814 state = YAFFS_BLOCK_STATE_FULL;
5817 bi->blockState = state;
5819 /* Now let's see if it was dirty */
5820 if (bi->pagesInUse == 0 &&
5821 !bi->hasShrinkHeader &&
5822 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5823 yaffs_BlockBecameDirty(dev, blk);
5833 /* Ok, we've done all the scanning.
5834 * Fix up the hard link chains.
5835 * We should now have scanned all the objects, now it's time to add these
5839 yaffs_HardlinkFixup(dev,hardList);
5841 /* Handle the unlinked files. Since they were left in an unlinked state we should
5845 struct list_head *i;
5846 struct list_head *n;
5849 /* Soft delete all the unlinked files */
5850 list_for_each_safe(i, n,
5851 &dev->unlinkedDir->variant.directoryVariant.
5854 l = list_entry(i, yaffs_Object, siblings);
5855 yaffs_DestroyObject(l);
5860 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5866 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5872 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5875 yaffs_ObjectHeader *oh;
5876 yaffs_Device *dev = in->myDev;
5877 yaffs_ExtendedTags tags;
5879 int alloc_failed = 0;
5885 T(YAFFS_TRACE_SCAN,(TSTR("details for object %d %s loaded" TENDSTR),
5887 in->lazyLoaded ? "not yet" : "already"));
5892 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5894 result = yaffs_ReadChunkWithTagsFromNAND(dev,in->chunkId,chunkData,&tags);
5895 oh = (yaffs_ObjectHeader *) chunkData;
5897 in->yst_mode = oh->yst_mode;
5898 #ifdef CONFIG_YAFFS_WINCE
5899 in->win_atime[0] = oh->win_atime[0];
5900 in->win_ctime[0] = oh->win_ctime[0];
5901 in->win_mtime[0] = oh->win_mtime[0];
5902 in->win_atime[1] = oh->win_atime[1];
5903 in->win_ctime[1] = oh->win_ctime[1];
5904 in->win_mtime[1] = oh->win_mtime[1];
5906 in->yst_uid = oh->yst_uid;
5907 in->yst_gid = oh->yst_gid;
5908 in->yst_atime = oh->yst_atime;
5909 in->yst_mtime = oh->yst_mtime;
5910 in->yst_ctime = oh->yst_ctime;
5911 in->yst_rdev = oh->yst_rdev;
5914 yaffs_SetObjectName(in, oh->name);
5916 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
5917 in->variant.symLinkVariant.alias =
5918 yaffs_CloneString(oh->alias);
5919 if(!in->variant.symLinkVariant.alias)
5920 alloc_failed = 1; /* Not returned to caller */
5923 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
5927 static int yaffs_ScanBackwards(yaffs_Device * dev)
5929 yaffs_ExtendedTags tags;
5934 int nBlocksToScan = 0;
5940 yaffs_BlockState state;
5941 yaffs_Object *hardList = NULL;
5942 yaffs_BlockInfo *bi;
5944 yaffs_ObjectHeader *oh;
5946 yaffs_Object *parent;
5947 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5953 int foundChunksInBlock;
5954 int equivalentObjectId;
5955 int alloc_failed = 0;
5958 yaffs_BlockIndex *blockIndex = NULL;
5959 int altBlockIndex = 0;
5961 if (!dev->isYaffs2) {
5963 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
5969 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
5970 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
5973 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5975 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
5978 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
5984 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
5988 dev->blocksInCheckpoint = 0;
5990 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5992 /* Scan all the blocks to determine their state */
5993 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5994 bi = yaffs_GetBlockInfo(dev, blk);
5995 yaffs_ClearChunkBits(dev, blk);
5997 bi->softDeletions = 0;
5999 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6001 bi->blockState = state;
6002 bi->sequenceNumber = sequenceNumber;
6004 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6005 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6007 T(YAFFS_TRACE_SCAN_DEBUG,
6008 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6009 state, sequenceNumber));
6012 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
6013 dev->blocksInCheckpoint++;
6015 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6016 T(YAFFS_TRACE_BAD_BLOCKS,
6017 (TSTR("block %d is bad" TENDSTR), blk));
6018 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6019 T(YAFFS_TRACE_SCAN_DEBUG,
6020 (TSTR("Block empty " TENDSTR)));
6021 dev->nErasedBlocks++;
6022 dev->nFreeChunks += dev->nChunksPerBlock;
6023 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6025 /* Determine the highest sequence number */
6026 if (dev->isYaffs2 &&
6027 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6028 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6030 blockIndex[nBlocksToScan].seq = sequenceNumber;
6031 blockIndex[nBlocksToScan].block = blk;
6035 if (sequenceNumber >= dev->sequenceNumber) {
6036 dev->sequenceNumber = sequenceNumber;
6038 } else if (dev->isYaffs2) {
6039 /* TODO: Nasty sequence number! */
6042 ("Block scanning block %d has bad sequence number %d"
6043 TENDSTR), blk, sequenceNumber));
6050 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6056 /* Sort the blocks */
6057 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6059 /* Use qsort now. */
6060 qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6064 /* Dungy old bubble sort... */
6066 yaffs_BlockIndex temp;
6070 for (i = 0; i < nBlocksToScan; i++)
6071 for (j = i + 1; j < nBlocksToScan; j++)
6072 if (blockIndex[i].seq > blockIndex[j].seq) {
6073 temp = blockIndex[j];
6074 blockIndex[j] = blockIndex[i];
6075 blockIndex[i] = temp;
6082 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6084 /* Now scan the blocks looking at the data. */
6086 endIterator = nBlocksToScan - 1;
6087 T(YAFFS_TRACE_SCAN_DEBUG,
6088 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6090 /* For each block.... backwards */
6091 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6093 /* Cooperative multitasking! This loop can run for so
6094 long that watchdog timers expire. */
6097 /* get the block to scan in the correct order */
6098 blk = blockIndex[blockIterator].block;
6100 bi = yaffs_GetBlockInfo(dev, blk);
6103 state = bi->blockState;
6107 /* For each chunk in each block that needs scanning.... */
6108 foundChunksInBlock = 0;
6109 for (c = dev->nChunksPerBlock - 1;
6110 !alloc_failed && c >= 0 &&
6111 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6112 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6113 /* Scan backwards...
6114 * Read the tags and decide what to do
6117 chunk = blk * dev->nChunksPerBlock + c;
6119 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6122 /* Let's have a good look at this chunk... */
6124 if (!tags.chunkUsed) {
6125 /* An unassigned chunk in the block.
6126 * If there are used chunks after this one, then
6127 * it is a chunk that was skipped due to failing the erased
6128 * check. Just skip it so that it can be deleted.
6129 * But, more typically, We get here when this is an unallocated
6130 * chunk and his means that either the block is empty or
6131 * this is the one being allocated from
6134 if(foundChunksInBlock)
6136 /* This is a chunk that was skipped due to failing the erased check */
6138 } else if (c == 0) {
6139 /* We're looking at the first chunk in the block so the block is unused */
6140 state = YAFFS_BLOCK_STATE_EMPTY;
6141 dev->nErasedBlocks++;
6143 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6144 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6145 if(dev->sequenceNumber == bi->sequenceNumber) {
6146 /* this is the block being allocated from */
6150 (" Allocating from %d %d"
6153 state = YAFFS_BLOCK_STATE_ALLOCATING;
6154 dev->allocationBlock = blk;
6155 dev->allocationPage = c;
6156 dev->allocationBlockFinder = blk;
6159 /* This is a partially written block that is not
6160 * the current allocation block. This block must have
6161 * had a write failure, so set up for retirement.
6164 bi->needsRetiring = 1;
6165 bi->gcPrioritise = 1;
6167 T(YAFFS_TRACE_ALWAYS,
6168 (TSTR("Partially written block %d being set for retirement" TENDSTR),
6178 } else if (tags.chunkId > 0) {
6179 /* chunkId > 0 so it is a data chunk... */
6180 unsigned int endpos;
6182 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6184 foundChunksInBlock = 1;
6187 yaffs_SetChunkBit(dev, blk, c);
6190 in = yaffs_FindOrCreateObjectByNumber(dev,
6193 YAFFS_OBJECT_TYPE_FILE);
6200 in->variantType == YAFFS_OBJECT_TYPE_FILE
6202 in->variant.fileVariant.shrinkSize) {
6203 /* This has not been invalidated by a resize */
6204 if(!yaffs_PutChunkIntoFile(in, tags.chunkId,
6209 /* File size is calculated by looking at the data chunks if we have not
6210 * seen an object header yet. Stop this practice once we find an object header.
6214 1) * dev->nDataBytesPerChunk +
6217 if (!in->valid && /* have not got an object header yet */
6218 in->variant.fileVariant.
6219 scannedFileSize < endpos) {
6220 in->variant.fileVariant.
6221 scannedFileSize = endpos;
6222 in->variant.fileVariant.
6224 in->variant.fileVariant.
6229 /* This chunk has been invalidated by a resize, so delete */
6230 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6234 /* chunkId == 0, so it is an ObjectHeader.
6235 * Thus, we read in the object header and make the object
6237 foundChunksInBlock = 1;
6239 yaffs_SetChunkBit(dev, blk, c);
6245 if (tags.extraHeaderInfoAvailable) {
6246 in = yaffs_FindOrCreateObjectByNumber
6247 (dev, tags.objectId,
6248 tags.extraObjectType);
6252 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
6255 tags.extraShadows ||
6257 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6258 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
6261 /* If we don't have valid info then we need to read the chunk
6262 * TODO In future we can probably defer reading the chunk and
6263 * living with invalid data until needed.
6266 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6271 oh = (yaffs_ObjectHeader *) chunkData;
6274 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6279 /* TODO Hoosterman we have a problem! */
6280 T(YAFFS_TRACE_ERROR,
6282 ("yaffs tragedy: Could not make object for object %d "
6283 "at chunk %d during scan"
6284 TENDSTR), tags.objectId, chunk));
6289 /* We have already filled this one.
6290 * We have a duplicate that will be discarded, but
6291 * we first have to suck out resize info if it is a file.
6294 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6296 oh-> type == YAFFS_OBJECT_TYPE_FILE)||
6297 (tags.extraHeaderInfoAvailable &&
6298 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
6301 (oh) ? oh->fileSize : tags.
6303 __u32 parentObjectId =
6305 parentObjectId : tags.
6306 extraParentObjectId;
6308 (oh) ? oh->isShrink : tags.
6309 extraIsShrinkHeader;
6311 /* If it is deleted (unlinked at start also means deleted)
6312 * we treat the file size as being zeroed at this point.
6314 if (parentObjectId ==
6315 YAFFS_OBJECTID_DELETED
6316 || parentObjectId ==
6317 YAFFS_OBJECTID_UNLINKED) {
6323 in->variant.fileVariant.
6324 shrinkSize > thisSize) {
6325 in->variant.fileVariant.
6331 bi->hasShrinkHeader = 1;
6335 /* Use existing - destroy this one. */
6336 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6341 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6343 YAFFS_OBJECTID_LOSTNFOUND)) {
6344 /* We only load some info, don't fiddle with directory structure */
6348 in->variantType = oh->type;
6350 in->yst_mode = oh->yst_mode;
6351 #ifdef CONFIG_YAFFS_WINCE
6352 in->win_atime[0] = oh->win_atime[0];
6353 in->win_ctime[0] = oh->win_ctime[0];
6354 in->win_mtime[0] = oh->win_mtime[0];
6355 in->win_atime[1] = oh->win_atime[1];
6356 in->win_ctime[1] = oh->win_ctime[1];
6357 in->win_mtime[1] = oh->win_mtime[1];
6359 in->yst_uid = oh->yst_uid;
6360 in->yst_gid = oh->yst_gid;
6361 in->yst_atime = oh->yst_atime;
6362 in->yst_mtime = oh->yst_mtime;
6363 in->yst_ctime = oh->yst_ctime;
6364 in->yst_rdev = oh->yst_rdev;
6368 in->variantType = tags.extraObjectType;
6372 in->chunkId = chunk;
6374 } else if (!in->valid) {
6375 /* we need to load this info */
6378 in->chunkId = chunk;
6381 in->variantType = oh->type;
6383 in->yst_mode = oh->yst_mode;
6384 #ifdef CONFIG_YAFFS_WINCE
6385 in->win_atime[0] = oh->win_atime[0];
6386 in->win_ctime[0] = oh->win_ctime[0];
6387 in->win_mtime[0] = oh->win_mtime[0];
6388 in->win_atime[1] = oh->win_atime[1];
6389 in->win_ctime[1] = oh->win_ctime[1];
6390 in->win_mtime[1] = oh->win_mtime[1];
6392 in->yst_uid = oh->yst_uid;
6393 in->yst_gid = oh->yst_gid;
6394 in->yst_atime = oh->yst_atime;
6395 in->yst_mtime = oh->yst_mtime;
6396 in->yst_ctime = oh->yst_ctime;
6397 in->yst_rdev = oh->yst_rdev;
6400 if (oh->shadowsObject > 0)
6401 yaffs_HandleShadowedObject(dev,
6407 yaffs_SetObjectName(in, oh->name);
6409 yaffs_FindOrCreateObjectByNumber
6410 (dev, oh->parentObjectId,
6411 YAFFS_OBJECT_TYPE_DIRECTORY);
6413 fileSize = oh->fileSize;
6414 isShrink = oh->isShrink;
6415 equivalentObjectId = oh->equivalentObjectId;
6419 in->variantType = tags.extraObjectType;
6421 yaffs_FindOrCreateObjectByNumber
6422 (dev, tags.extraParentObjectId,
6423 YAFFS_OBJECT_TYPE_DIRECTORY);
6424 fileSize = tags.extraFileLength;
6425 isShrink = tags.extraIsShrinkHeader;
6426 equivalentObjectId = tags.extraEquivalentObjectId;
6432 /* directory stuff...
6436 if (parent->variantType ==
6437 YAFFS_OBJECT_TYPE_UNKNOWN) {
6438 /* Set up as a directory */
6439 parent->variantType =
6440 YAFFS_OBJECT_TYPE_DIRECTORY;
6441 INIT_LIST_HEAD(&parent->variant.
6444 } else if (parent->variantType !=
6445 YAFFS_OBJECT_TYPE_DIRECTORY)
6447 /* Hoosterman, another problem....
6448 * We're trying to use a non-directory as a directory
6451 T(YAFFS_TRACE_ERROR,
6453 ("yaffs tragedy: attempting to use non-directory as"
6454 " a directory in scan. Put in lost+found."
6456 parent = dev->lostNFoundDir;
6459 yaffs_AddObjectToDirectory(parent, in);
6461 itsUnlinked = (parent == dev->deletedDir) ||
6462 (parent == dev->unlinkedDir);
6465 /* Mark the block as having a shrinkHeader */
6466 bi->hasShrinkHeader = 1;
6469 /* Note re hardlinks.
6470 * Since we might scan a hardlink before its equivalent object is scanned
6471 * we put them all in a list.
6472 * After scanning is complete, we should have all the objects, so we run
6473 * through this list and fix up all the chains.
6476 switch (in->variantType) {
6477 case YAFFS_OBJECT_TYPE_UNKNOWN:
6478 /* Todo got a problem */
6480 case YAFFS_OBJECT_TYPE_FILE:
6482 if (in->variant.fileVariant.
6483 scannedFileSize < fileSize) {
6484 /* This covers the case where the file size is greater
6485 * than where the data is
6486 * This will happen if the file is resized to be larger
6487 * than its current data extents.
6489 in->variant.fileVariant.fileSize = fileSize;
6490 in->variant.fileVariant.scannedFileSize =
6491 in->variant.fileVariant.fileSize;
6495 in->variant.fileVariant.shrinkSize > fileSize) {
6496 in->variant.fileVariant.shrinkSize = fileSize;
6500 case YAFFS_OBJECT_TYPE_HARDLINK:
6502 in->variant.hardLinkVariant.equivalentObjectId =
6504 in->hardLinks.next =
6505 (struct list_head *) hardList;
6509 case YAFFS_OBJECT_TYPE_DIRECTORY:
6512 case YAFFS_OBJECT_TYPE_SPECIAL:
6515 case YAFFS_OBJECT_TYPE_SYMLINK:
6517 in->variant.symLinkVariant.alias =
6518 yaffs_CloneString(oh->
6520 if(!in->variant.symLinkVariant.alias)
6530 } /* End of scanning for each chunk */
6532 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6533 /* If we got this far while scanning, then the block is fully allocated. */
6534 state = YAFFS_BLOCK_STATE_FULL;
6537 bi->blockState = state;
6539 /* Now let's see if it was dirty */
6540 if (bi->pagesInUse == 0 &&
6541 !bi->hasShrinkHeader &&
6542 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6543 yaffs_BlockBecameDirty(dev, blk);
6549 YFREE_ALT(blockIndex);
6553 /* Ok, we've done all the scanning.
6554 * Fix up the hard link chains.
6555 * We should now have scanned all the objects, now it's time to add these
6558 yaffs_HardlinkFixup(dev,hardList);
6562 * Sort out state of unlinked and deleted objects.
6565 struct list_head *i;
6566 struct list_head *n;
6570 /* Soft delete all the unlinked files */
6571 list_for_each_safe(i, n,
6572 &dev->unlinkedDir->variant.directoryVariant.
6575 l = list_entry(i, yaffs_Object, siblings);
6576 yaffs_DestroyObject(l);
6580 /* Soft delete all the deletedDir files */
6581 list_for_each_safe(i, n,
6582 &dev->deletedDir->variant.directoryVariant.
6585 l = list_entry(i, yaffs_Object, siblings);
6586 yaffs_DestroyObject(l);
6592 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6598 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6603 /*------------------------------ Directory Functions ----------------------------- */
6605 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
6607 yaffs_Device *dev = obj->myDev;
6609 if(dev && dev->removeObjectCallback)
6610 dev->removeObjectCallback(obj);
6612 list_del_init(&obj->siblings);
6617 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
6622 T(YAFFS_TRACE_ALWAYS,
6624 ("tragedy: Trying to add an object to a null pointer directory"
6628 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6629 T(YAFFS_TRACE_ALWAYS,
6631 ("tragedy: Trying to add an object to a non-directory"
6636 if (obj->siblings.prev == NULL) {
6637 /* Not initialised */
6638 INIT_LIST_HEAD(&obj->siblings);
6640 } else if (!list_empty(&obj->siblings)) {
6641 /* If it is holed up somewhere else, un hook it */
6642 yaffs_RemoveObjectFromDirectory(obj);
6645 list_add(&obj->siblings, &directory->variant.directoryVariant.children);
6646 obj->parent = directory;
6648 if (directory == obj->myDev->unlinkedDir
6649 || directory == obj->myDev->deletedDir) {
6651 obj->myDev->nUnlinkedFiles++;
6652 obj->renameAllowed = 0;
6656 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
6661 struct list_head *i;
6662 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
6671 T(YAFFS_TRACE_ALWAYS,
6673 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6677 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6678 T(YAFFS_TRACE_ALWAYS,
6680 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6684 sum = yaffs_CalcNameSum(name);
6686 list_for_each(i, &directory->variant.directoryVariant.children) {
6688 l = list_entry(i, yaffs_Object, siblings);
6690 yaffs_CheckObjectDetailsLoaded(l);
6692 /* Special case for lost-n-found */
6693 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6694 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
6697 } else if (yaffs_SumCompare(l->sum, sum) || l->chunkId <= 0)
6699 /* LostnFound cunk called Objxxx
6702 yaffs_GetObjectName(l, buffer,
6703 YAFFS_MAX_NAME_LENGTH);
6704 if (yaffs_strncmp(name, buffer,YAFFS_MAX_NAME_LENGTH) == 0) {
6717 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
6718 int (*fn) (yaffs_Object *))
6720 struct list_head *i;
6724 T(YAFFS_TRACE_ALWAYS,
6726 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6730 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6731 T(YAFFS_TRACE_ALWAYS,
6733 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6737 list_for_each(i, &theDir->variant.directoryVariant.children) {
6739 l = list_entry(i, yaffs_Object, siblings);
6751 /* GetEquivalentObject dereferences any hard links to get to the
6755 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
6757 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
6758 /* We want the object id of the equivalent object, not this one */
6759 obj = obj->variant.hardLinkVariant.equivalentObject;
6760 yaffs_CheckObjectDetailsLoaded(obj);
6766 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
6768 memset(name, 0, buffSize * sizeof(YCHAR));
6770 yaffs_CheckObjectDetailsLoaded(obj);
6772 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6773 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
6774 } else if (obj->chunkId <= 0) {
6776 /* make up a name */
6777 yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX,
6779 yaffs_strncpy(name, locName, buffSize - 1);
6782 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
6783 else if (obj->shortName[0]) {
6784 yaffs_strcpy(name, obj->shortName);
6789 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
6791 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
6793 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
6795 if (obj->chunkId >= 0) {
6796 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
6797 obj->chunkId, buffer,
6800 yaffs_strncpy(name, oh->name, buffSize - 1);
6802 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
6805 return yaffs_strlen(name);
6808 int yaffs_GetObjectFileLength(yaffs_Object * obj)
6811 /* Dereference any hard linking */
6812 obj = yaffs_GetEquivalentObject(obj);
6814 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
6815 return obj->variant.fileVariant.fileSize;
6817 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6818 return yaffs_strlen(obj->variant.symLinkVariant.alias);
6820 /* Only a directory should drop through to here */
6821 return obj->myDev->nDataBytesPerChunk;
6825 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
6828 struct list_head *i;
6830 if (!obj->unlinked) {
6831 count++; /* the object itself */
6833 list_for_each(i, &obj->hardLinks) {
6834 count++; /* add the hard links; */
6840 int yaffs_GetObjectInode(yaffs_Object * obj)
6842 obj = yaffs_GetEquivalentObject(obj);
6844 return obj->objectId;
6847 unsigned yaffs_GetObjectType(yaffs_Object * obj)
6849 obj = yaffs_GetEquivalentObject(obj);
6851 switch (obj->variantType) {
6852 case YAFFS_OBJECT_TYPE_FILE:
6855 case YAFFS_OBJECT_TYPE_DIRECTORY:
6858 case YAFFS_OBJECT_TYPE_SYMLINK:
6861 case YAFFS_OBJECT_TYPE_HARDLINK:
6864 case YAFFS_OBJECT_TYPE_SPECIAL:
6865 if (S_ISFIFO(obj->yst_mode))
6867 if (S_ISCHR(obj->yst_mode))
6869 if (S_ISBLK(obj->yst_mode))
6871 if (S_ISSOCK(obj->yst_mode))
6879 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
6881 obj = yaffs_GetEquivalentObject(obj);
6882 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6883 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
6885 return yaffs_CloneString(_Y(""));
6889 #ifndef CONFIG_YAFFS_WINCE
6891 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
6893 unsigned int valid = attr->ia_valid;
6895 if (valid & ATTR_MODE)
6896 obj->yst_mode = attr->ia_mode;
6897 if (valid & ATTR_UID)
6898 obj->yst_uid = attr->ia_uid;
6899 if (valid & ATTR_GID)
6900 obj->yst_gid = attr->ia_gid;
6902 if (valid & ATTR_ATIME)
6903 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
6904 if (valid & ATTR_CTIME)
6905 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
6906 if (valid & ATTR_MTIME)
6907 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
6909 if (valid & ATTR_SIZE)
6910 yaffs_ResizeFile(obj, attr->ia_size);
6912 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6917 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
6919 unsigned int valid = 0;
6921 attr->ia_mode = obj->yst_mode;
6923 attr->ia_uid = obj->yst_uid;
6925 attr->ia_gid = obj->yst_gid;
6928 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
6929 valid |= ATTR_ATIME;
6930 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
6931 valid |= ATTR_CTIME;
6932 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
6933 valid |= ATTR_MTIME;
6935 attr->ia_size = yaffs_GetFileSize(obj);
6938 attr->ia_valid = valid;
6947 int yaffs_DumpObject(yaffs_Object * obj)
6951 yaffs_GetObjectName(obj, name, 256);
6953 T(YAFFS_TRACE_ALWAYS,
6955 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
6956 " chunk %d type %d size %d\n"
6957 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
6958 obj->dirty, obj->valid, obj->serial, obj->sum, obj->chunkId,
6959 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
6965 /*---------------------------- Initialisation code -------------------------------------- */
6967 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
6970 /* Common functions, gotta have */
6971 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
6974 #ifdef CONFIG_YAFFS_YAFFS2
6976 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
6977 if (dev->writeChunkWithTagsToNAND &&
6978 dev->readChunkWithTagsFromNAND &&
6979 !dev->writeChunkToNAND &&
6980 !dev->readChunkFromNAND &&
6981 dev->markNANDBlockBad && dev->queryNANDBlock)
6985 /* Can use the "spare" style interface for yaffs1 */
6986 if (!dev->isYaffs2 &&
6987 !dev->writeChunkWithTagsToNAND &&
6988 !dev->readChunkWithTagsFromNAND &&
6989 dev->writeChunkToNAND &&
6990 dev->readChunkFromNAND &&
6991 !dev->markNANDBlockBad && !dev->queryNANDBlock)
6998 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7000 /* Initialise the unlinked, deleted, root and lost and found directories */
7002 dev->lostNFoundDir = dev->rootDir = NULL;
7003 dev->unlinkedDir = dev->deletedDir = NULL;
7006 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7009 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7012 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7013 YAFFS_ROOT_MODE | S_IFDIR);
7014 dev->lostNFoundDir =
7015 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7016 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7018 if(dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir){
7019 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7026 int yaffs_GutsInitialise(yaffs_Device * dev)
7028 int init_failed = 0;
7032 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7034 /* Check stuff that must be set */
7037 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7041 dev->internalStartBlock = dev->startBlock;
7042 dev->internalEndBlock = dev->endBlock;
7043 dev->blockOffset = 0;
7044 dev->chunkOffset = 0;
7045 dev->nFreeChunks = 0;
7047 if (dev->startBlock == 0) {
7048 dev->internalStartBlock = dev->startBlock + 1;
7049 dev->internalEndBlock = dev->endBlock + 1;
7050 dev->blockOffset = 1;
7051 dev->chunkOffset = dev->nChunksPerBlock;
7054 /* Check geometry parameters. */
7056 if ((dev->isYaffs2 && dev->nDataBytesPerChunk < 1024) ||
7057 (!dev->isYaffs2 && dev->nDataBytesPerChunk != 512) ||
7058 dev->nChunksPerBlock < 2 ||
7059 dev->nReservedBlocks < 2 ||
7060 dev->internalStartBlock <= 0 ||
7061 dev->internalEndBlock <= 0 ||
7062 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
7064 T(YAFFS_TRACE_ALWAYS,
7066 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s "
7067 TENDSTR), dev->nDataBytesPerChunk, dev->isYaffs2 ? "2" : ""));
7071 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7072 T(YAFFS_TRACE_ALWAYS,
7073 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7077 /* Got the right mix of functions? */
7078 if (!yaffs_CheckDevFunctions(dev)) {
7079 /* Function missing */
7080 T(YAFFS_TRACE_ALWAYS,
7082 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7087 /* This is really a compilation check. */
7088 if (!yaffs_CheckStructures()) {
7089 T(YAFFS_TRACE_ALWAYS,
7090 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7094 if (dev->isMounted) {
7095 T(YAFFS_TRACE_ALWAYS,
7096 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7100 /* Finished with most checks. One or two more checks happen later on too. */
7106 /* OK now calculate a few things for the device */
7109 * Calculate all the chunk size manipulation numbers:
7111 /* Start off assuming it is a power of 2 */
7112 dev->chunkShift = ShiftDiv(dev->nDataBytesPerChunk);
7113 dev->chunkMask = (1<<dev->chunkShift) - 1;
7115 if(dev->nDataBytesPerChunk == (dev->chunkMask + 1)){
7116 /* Yes it is a power of 2, disable crumbs */
7118 dev->crumbShift = 0;
7119 dev->crumbsPerChunk = 0;
7121 /* Not a power of 2, use crumbs instead */
7122 dev->crumbShift = ShiftDiv(sizeof(yaffs_PackedTags2TagsPart));
7123 dev->crumbMask = (1<<dev->crumbShift)-1;
7124 dev->crumbsPerChunk = dev->nDataBytesPerChunk/(1 << dev->crumbShift);
7125 dev->chunkShift = 0;
7131 * Calculate chunkGroupBits.
7132 * We need to find the next power of 2 > than internalEndBlock
7135 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7139 /* Set up tnode width if wide tnodes are enabled. */
7140 if(!dev->wideTnodesDisabled){
7141 /* bits must be even so that we end up with 32-bit words */
7145 dev->tnodeWidth = 16;
7147 dev->tnodeWidth = bits;
7150 dev->tnodeWidth = 16;
7152 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7154 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7155 * so if the bitwidth of the
7156 * chunk range we're using is greater than 16 we need
7157 * to figure out chunk shift and chunkGroupSize
7160 if (bits <= dev->tnodeWidth)
7161 dev->chunkGroupBits = 0;
7163 dev->chunkGroupBits = bits - dev->tnodeWidth;
7166 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7168 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7169 /* We have a problem because the soft delete won't work if
7170 * the chunk group size > chunks per block.
7171 * This can be remedied by using larger "virtual blocks".
7173 T(YAFFS_TRACE_ALWAYS,
7174 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7179 /* OK, we've finished verifying the device, lets continue with initialisation */
7181 /* More device initialisation */
7182 dev->garbageCollections = 0;
7183 dev->passiveGarbageCollections = 0;
7184 dev->currentDirtyChecker = 0;
7185 dev->bufferedBlock = -1;
7186 dev->doingBufferedBlockRewrite = 0;
7187 dev->nDeletedFiles = 0;
7188 dev->nBackgroundDeletions = 0;
7189 dev->nUnlinkedFiles = 0;
7191 dev->eccUnfixed = 0;
7192 dev->tagsEccFixed = 0;
7193 dev->tagsEccUnfixed = 0;
7194 dev->nErasureFailures = 0;
7195 dev->nErasedBlocks = 0;
7197 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7199 /* Initialise temporary buffers and caches. */
7200 if(!yaffs_InitialiseTempBuffers(dev))
7203 dev->srCache = NULL;
7204 dev->gcCleanupList = NULL;
7208 dev->nShortOpCaches > 0) {
7211 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7213 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
7214 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7217 buf = dev->srCache = YMALLOC(srCacheBytes);
7220 memset(dev->srCache,0,srCacheBytes);
7222 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7223 dev->srCache[i].object = NULL;
7224 dev->srCache[i].lastUse = 0;
7225 dev->srCache[i].dirty = 0;
7226 dev->srCache[i].data = buf = YMALLOC_DMA(dev->nDataBytesPerChunk);
7237 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7238 if(!dev->gcCleanupList)
7242 if (dev->isYaffs2) {
7243 dev->useHeaderFileSize = 1;
7245 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7248 yaffs_InitialiseTnodes(dev);
7249 yaffs_InitialiseObjects(dev);
7251 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7256 /* Now scan the flash. */
7257 if (dev->isYaffs2) {
7258 if(yaffs_CheckpointRestore(dev)) {
7259 T(YAFFS_TRACE_ALWAYS,
7260 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7263 /* Clean up the mess caused by an aborted checkpoint load
7264 * and scan backwards.
7266 yaffs_DeinitialiseBlocks(dev);
7267 yaffs_DeinitialiseTnodes(dev);
7268 yaffs_DeinitialiseObjects(dev);
7271 dev->nErasedBlocks = 0;
7272 dev->nFreeChunks = 0;
7273 dev->allocationBlock = -1;
7274 dev->allocationPage = -1;
7275 dev->nDeletedFiles = 0;
7276 dev->nUnlinkedFiles = 0;
7277 dev->nBackgroundDeletions = 0;
7278 dev->oldestDirtySequence = 0;
7280 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7283 yaffs_InitialiseTnodes(dev);
7284 yaffs_InitialiseObjects(dev);
7286 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7289 if(!init_failed && !yaffs_ScanBackwards(dev))
7293 if(!yaffs_Scan(dev))
7298 /* Clean up the mess */
7299 T(YAFFS_TRACE_TRACING,
7300 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7302 yaffs_Deinitialise(dev);
7306 /* Zero out stats */
7307 dev->nPageReads = 0;
7308 dev->nPageWrites = 0;
7309 dev->nBlockErasures = 0;
7311 dev->nRetriedWrites = 0;
7313 dev->nRetiredBlocks = 0;
7315 yaffs_VerifyFreeChunks(dev);
7316 yaffs_VerifyBlocks(dev);
7319 T(YAFFS_TRACE_TRACING,
7320 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7325 void yaffs_Deinitialise(yaffs_Device * dev)
7327 if (dev->isMounted) {
7330 yaffs_DeinitialiseBlocks(dev);
7331 yaffs_DeinitialiseTnodes(dev);
7332 yaffs_DeinitialiseObjects(dev);
7333 if (dev->nShortOpCaches > 0 &&
7336 for (i = 0; i < dev->nShortOpCaches; i++) {
7337 if(dev->srCache[i].data)
7338 YFREE(dev->srCache[i].data);
7339 dev->srCache[i].data = NULL;
7342 YFREE(dev->srCache);
7343 dev->srCache = NULL;
7346 YFREE(dev->gcCleanupList);
7348 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
7349 YFREE(dev->tempBuffer[i].buffer);
7357 static int yaffs_CountFreeChunks(yaffs_Device * dev)
7362 yaffs_BlockInfo *blk;
7364 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7366 blk = yaffs_GetBlockInfo(dev, b);
7368 switch (blk->blockState) {
7369 case YAFFS_BLOCK_STATE_EMPTY:
7370 case YAFFS_BLOCK_STATE_ALLOCATING:
7371 case YAFFS_BLOCK_STATE_COLLECTING:
7372 case YAFFS_BLOCK_STATE_FULL:
7374 (dev->nChunksPerBlock - blk->pagesInUse +
7375 blk->softDeletions);
7386 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
7388 /* This is what we report to the outside world */
7391 int nDirtyCacheChunks;
7392 int blocksForCheckpoint;
7395 nFree = dev->nFreeChunks;
7397 nFree = yaffs_CountFreeChunks(dev);
7400 nFree += dev->nDeletedFiles;
7402 /* Now count the number of dirty chunks in the cache and subtract those */
7406 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7407 if (dev->srCache[i].dirty)
7408 nDirtyCacheChunks++;
7412 nFree -= nDirtyCacheChunks;
7414 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7416 /* Now we figure out how much to reserve for the checkpoint and report that... */
7417 blocksForCheckpoint = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
7418 if(blocksForCheckpoint < 0)
7419 blocksForCheckpoint = 0;
7421 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7430 static int yaffs_freeVerificationFailures;
7432 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
7437 if(yaffs_SkipVerification(dev))
7440 counted = yaffs_CountFreeChunks(dev);
7442 difference = dev->nFreeChunks - counted;
7445 T(YAFFS_TRACE_ALWAYS,
7446 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7447 dev->nFreeChunks, counted, difference));
7448 yaffs_freeVerificationFailures++;
7452 /*---------------------------------------- YAFFS test code ----------------------*/
7454 #define yaffs_CheckStruct(structure,syze, name) \
7455 if(sizeof(structure) != syze) \
7457 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
7458 name,syze,sizeof(structure))); \
7459 return YAFFS_FAIL; \
7462 static int yaffs_CheckStructures(void)
7464 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags") */
7465 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion") */
7466 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare") */
7467 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7468 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode")
7470 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader")