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 =
18 #include "yaffsinterface.h"
19 #include "yaffs_guts.h"
20 #include "yaffs_tagsvalidity.h"
22 #include "yaffs_tagscompat.h"
23 #ifndef CONFIG_YAFFS_USE_OWN_SORT
24 #include "yaffs_qsort.h"
26 #include "yaffs_nand.h"
28 #include "yaffs_checkptrw.h"
30 #include "yaffs_nand.h"
31 #include "yaffs_packedtags2.h"
34 #ifdef CONFIG_YAFFS_WINCE
35 void yfsd_LockYAFFS(BOOL fsLockOnly);
36 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
39 #define YAFFS_PASSIVE_GC_CHUNKS 2
41 #include "yaffs_ecc.h"
44 /* Robustification (if it ever comes about...) */
45 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
46 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk);
47 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
49 const yaffs_ExtendedTags * tags);
50 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
51 const yaffs_ExtendedTags * tags);
53 /* Other local prototypes */
54 static int yaffs_UnlinkObject( yaffs_Object *obj);
55 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
57 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
59 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
61 yaffs_ExtendedTags * tags,
63 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
64 int chunkInNAND, int inScan);
66 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
67 yaffs_ObjectType type);
68 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
70 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
71 int force, int isShrink, int shadows);
72 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
73 static int yaffs_CheckStructures(void);
74 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
75 int chunkOffset, int *limit);
76 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
78 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
80 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo);
81 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
84 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
87 static int yaffs_UnlinkWorker(yaffs_Object * obj);
88 static void yaffs_DestroyObject(yaffs_Object * obj);
90 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
93 loff_t yaffs_GetFileSize(yaffs_Object * obj);
95 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr);
97 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
99 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
101 #ifdef YAFFS_PARANOID
102 static int yaffs_CheckFileSanity(yaffs_Object * in);
104 #define yaffs_CheckFileSanity(in)
107 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
108 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
110 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
112 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
113 yaffs_ExtendedTags * tags);
115 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos);
116 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
117 yaffs_FileStructure * fStruct,
121 /* Function to calculate chunk and offset */
123 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, __u32 *chunk, __u32 *offset)
126 /* Easy-peasy power of 2 case */
127 *chunk = (__u32)(addr >> dev->chunkShift);
128 *offset = (__u32)(addr & dev->chunkMask);
130 else if(dev->crumbsPerChunk)
132 /* Case where we're using "crumbs" */
133 *offset = (__u32)(addr & dev->crumbMask);
134 addr >>= dev->crumbShift;
135 *chunk = ((__u32)addr)/dev->crumbsPerChunk;
136 *offset += ((addr - (*chunk * dev->crumbsPerChunk)) << dev->crumbShift);
142 /* Function to return the number of shifts for a power of 2 greater than or equal
143 * to the given number
144 * Note we don't try to cater for all possible numbers and this does not have to
145 * be hellishly efficient.
148 static __u32 ShiftsGE(__u32 x)
153 nShifts = extraBits = 0;
156 if(x & 1) extraBits++;
167 /* Function to return the number of shifts to get a 1 in bit 0
170 static __u32 ShiftDiv(__u32 x)
189 * Temporary buffer manipulations.
192 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
195 __u8 *buf = (__u8 *)1;
197 memset(dev->tempBuffer,0,sizeof(dev->tempBuffer));
199 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
200 dev->tempBuffer[i].line = 0; /* not in use */
201 dev->tempBuffer[i].buffer = buf =
202 YMALLOC_DMA(dev->nDataBytesPerChunk);
205 return buf ? YAFFS_OK : YAFFS_FAIL;
209 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
212 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
213 if (dev->tempBuffer[i].line == 0) {
214 dev->tempBuffer[i].line = lineNo;
215 if ((i + 1) > dev->maxTemp) {
216 dev->maxTemp = i + 1;
217 for (j = 0; j <= i; j++)
218 dev->tempBuffer[j].maxLine =
219 dev->tempBuffer[j].line;
222 return dev->tempBuffer[i].buffer;
226 T(YAFFS_TRACE_BUFFERS,
227 (TSTR("Out of temp buffers at line %d, other held by lines:"),
229 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
230 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
232 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
235 * If we got here then we have to allocate an unmanaged one
239 dev->unmanagedTempAllocations++;
240 return YMALLOC(dev->nDataBytesPerChunk);
244 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
248 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
249 if (dev->tempBuffer[i].buffer == buffer) {
250 dev->tempBuffer[i].line = 0;
256 /* assume it is an unmanaged one. */
257 T(YAFFS_TRACE_BUFFERS,
258 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
261 dev->unmanagedTempDeallocations++;
267 * Determine if we have a managed buffer.
269 int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
272 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
273 if (dev->tempBuffer[i].buffer == buffer)
278 for (i = 0; i < dev->nShortOpCaches; i++) {
279 if( dev->srCache[i].data == buffer )
284 if (buffer == dev->checkpointBuffer)
287 T(YAFFS_TRACE_ALWAYS,
288 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
295 * Chunk bitmap manipulations
298 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
300 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
302 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
306 return dev->chunkBits +
307 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
310 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
312 if(blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
313 chunk < 0 || chunk >= dev->nChunksPerBlock) {
315 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),blk,chunk));
320 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
322 __u8 *blkBits = yaffs_BlockBits(dev, blk);
324 memset(blkBits, 0, dev->chunkBitmapStride);
327 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
329 __u8 *blkBits = yaffs_BlockBits(dev, blk);
331 yaffs_VerifyChunkBitId(dev,blk,chunk);
333 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
336 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
338 __u8 *blkBits = yaffs_BlockBits(dev, blk);
340 yaffs_VerifyChunkBitId(dev,blk,chunk);
342 blkBits[chunk / 8] |= (1 << (chunk & 7));
345 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
347 __u8 *blkBits = yaffs_BlockBits(dev, blk);
348 yaffs_VerifyChunkBitId(dev,blk,chunk);
350 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
353 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
355 __u8 *blkBits = yaffs_BlockBits(dev, blk);
357 for (i = 0; i < dev->chunkBitmapStride; i++) {
365 static int yaffs_CountChunkBits(yaffs_Device * dev, int blk)
367 __u8 *blkBits = yaffs_BlockBits(dev, blk);
370 for (i = 0; i < dev->chunkBitmapStride; i++) {
387 static int yaffs_SkipVerification(yaffs_Device *dev)
389 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
392 static int yaffs_SkipFullVerification(yaffs_Device *dev)
394 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
397 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
399 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
402 static const char * blockStateName[] = {
415 static void yaffs_VerifyBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
420 if(yaffs_SkipVerification(dev))
423 /* Report illegal runtime states */
424 if(bi->blockState <0 || bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
425 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has undefined state %d"TENDSTR),n,bi->blockState));
427 switch(bi->blockState){
428 case YAFFS_BLOCK_STATE_UNKNOWN:
429 case YAFFS_BLOCK_STATE_SCANNING:
430 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
431 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has bad run-state %s"TENDSTR),
432 n,blockStateName[bi->blockState]));
435 /* Check pages in use and soft deletions are legal */
437 actuallyUsed = bi->pagesInUse - bi->softDeletions;
439 if(bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
440 bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
441 actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock)
442 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
443 n,bi->pagesInUse,bi->softDeletions));
446 /* Check chunk bitmap legal */
447 inUse = yaffs_CountChunkBits(dev,n);
448 if(inUse != bi->pagesInUse)
449 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
450 n,bi->pagesInUse,inUse));
452 /* Check that the sequence number is valid.
453 * Ten million is legal, but is very unlikely
456 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
457 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000 ))
458 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has suspect sequence number of %d"TENDSTR),
459 n,bi->sequenceNumber));
463 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
465 yaffs_VerifyBlock(dev,bi,n);
467 /* After collection the block should be in the erased state */
468 /* TODO: This will need to change if we do partial gc */
470 if(bi->blockState != YAFFS_BLOCK_STATE_EMPTY){
471 T(YAFFS_TRACE_ERROR,(TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
476 static void yaffs_VerifyBlocks(yaffs_Device *dev)
479 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
480 int nIllegalBlockStates = 0;
483 if(yaffs_SkipVerification(dev))
486 memset(nBlocksPerState,0,sizeof(nBlocksPerState));
489 for(i = dev->internalStartBlock; i <= dev->internalEndBlock; i++){
490 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
491 yaffs_VerifyBlock(dev,bi,i);
493 if(bi->blockState >=0 && bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
494 nBlocksPerState[bi->blockState]++;
496 nIllegalBlockStates++;
500 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
501 T(YAFFS_TRACE_VERIFY,(TSTR("Block summary"TENDSTR)));
503 T(YAFFS_TRACE_VERIFY,(TSTR("%d blocks have illegal states"TENDSTR),nIllegalBlockStates));
504 if(nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
505 T(YAFFS_TRACE_VERIFY,(TSTR("Too many allocating blocks"TENDSTR)));
507 for(i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
508 T(YAFFS_TRACE_VERIFY,
509 (TSTR("%s %d blocks"TENDSTR),
510 blockStateName[i],nBlocksPerState[i]));
512 if(dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
513 T(YAFFS_TRACE_VERIFY,
514 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
515 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
517 if(dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
518 T(YAFFS_TRACE_VERIFY,
519 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
520 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
522 if(nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
523 T(YAFFS_TRACE_VERIFY,
524 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
525 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
527 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
532 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
533 * case those tests will not be performed.
535 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
537 if(yaffs_SkipVerification(obj->myDev))
540 if(!(tags && obj && oh)){
541 T(YAFFS_TRACE_VERIFY,
542 (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR),
543 (__u32)tags,(__u32)obj,(__u32)oh));
547 if(oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
548 oh->type > YAFFS_OBJECT_TYPE_MAX)
549 T(YAFFS_TRACE_VERIFY,
550 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
551 tags->objectId, oh->type));
553 if(tags->objectId != obj->objectId)
554 T(YAFFS_TRACE_VERIFY,
555 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
556 tags->objectId, obj->objectId));
560 * Check that the object's parent ids match if parentCheck requested.
562 * Tests do not apply to the root object.
565 if(parentCheck && tags->objectId > 1 && !obj->parent)
566 T(YAFFS_TRACE_VERIFY,
567 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
568 tags->objectId, oh->parentObjectId));
571 if(parentCheck && obj->parent &&
572 oh->parentObjectId != obj->parent->objectId &&
573 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
574 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
575 T(YAFFS_TRACE_VERIFY,
576 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
577 tags->objectId, oh->parentObjectId, obj->parent->objectId));
580 if(tags->objectId > 1 && oh->name[0] == 0) /* Null name */
581 T(YAFFS_TRACE_VERIFY,
582 (TSTR("Obj %d header name is NULL"TENDSTR),
585 if(tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
586 T(YAFFS_TRACE_VERIFY,
587 (TSTR("Obj %d header name is 0xFF"TENDSTR),
593 static int yaffs_VerifyTnodeWorker(yaffs_Object * obj, yaffs_Tnode * tn,
594 __u32 level, int chunkOffset)
597 yaffs_Device *dev = obj->myDev;
599 int nTnodeBytes = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
604 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
605 if (tn->internal[i]) {
606 ok = yaffs_VerifyTnodeWorker(obj,
609 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
612 } else if (level == 0) {
614 yaffs_ExtendedTags tags;
615 __u32 objectId = obj->objectId;
617 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
619 for(i = 0; i < YAFFS_NTNODES_LEVEL0; i++){
620 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
623 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
624 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
625 if(tags.objectId != objectId || tags.chunkId != chunkOffset){
626 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
627 objectId, chunkOffset, theChunk,
628 tags.objectId, tags.chunkId));
641 static void yaffs_VerifyFile(yaffs_Object *obj)
643 int requiredTallness;
650 yaffs_ExtendedTags tags;
654 if(obj && yaffs_SkipVerification(obj->myDev))
658 objectId = obj->objectId;
660 /* Check file size is consistent with tnode depth */
661 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
662 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
663 requiredTallness = 0;
665 x >>= YAFFS_TNODES_INTERNAL_BITS;
669 actualTallness = obj->variant.fileVariant.topLevel;
671 if(requiredTallness > actualTallness )
672 T(YAFFS_TRACE_VERIFY,
673 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
674 obj->objectId,actualTallness, requiredTallness));
677 /* Check that the chunks in the tnode tree are all correct.
678 * We do this by scanning through the tnode tree and
679 * checking the tags for every chunk match.
682 if(yaffs_SkipNANDVerification(dev))
685 for(i = 1; i <= lastChunk; i++){
686 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant,i);
689 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
691 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
692 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
693 if(tags.objectId != objectId || tags.chunkId != i){
694 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
695 objectId, i, theChunk,
696 tags.objectId, tags.chunkId));
705 static void yaffs_VerifyDirectory(yaffs_Object *obj)
707 if(obj && yaffs_SkipVerification(obj->myDev))
712 static void yaffs_VerifyHardLink(yaffs_Object *obj)
714 if(obj && yaffs_SkipVerification(obj->myDev))
717 /* Verify sane equivalent object */
720 static void yaffs_VerifySymlink(yaffs_Object *obj)
722 if(obj && yaffs_SkipVerification(obj->myDev))
725 /* Verify symlink string */
728 static void yaffs_VerifySpecial(yaffs_Object *obj)
730 if(obj && yaffs_SkipVerification(obj->myDev))
734 static void yaffs_VerifyObject(yaffs_Object *obj)
749 if(yaffs_SkipVerification(dev))
752 /* Check sane object header chunk */
754 chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
755 chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
757 chunkIdOk = (obj->chunkId >= chunkMin && obj->chunkId <= chunkMax);
758 chunkIsLive = chunkIdOk &&
759 yaffs_CheckChunkBit(dev,
760 obj->chunkId / dev->nChunksPerBlock,
761 obj->chunkId % dev->nChunksPerBlock);
763 (!chunkIdOk || !chunkIsLive)) {
764 T(YAFFS_TRACE_VERIFY,
765 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
766 obj->objectId,obj->chunkId,
767 chunkIdOk ? "" : ",out of range",
768 chunkIsLive || !chunkIdOk ? "" : ",marked as deleted"));
771 if(chunkIdOk && chunkIsLive &&!yaffs_SkipNANDVerification(dev)) {
772 yaffs_ExtendedTags tags;
773 yaffs_ObjectHeader *oh;
774 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
776 oh = (yaffs_ObjectHeader *)buffer;
778 yaffs_ReadChunkWithTagsFromNAND(dev, obj->chunkId,buffer, &tags);
780 yaffs_VerifyObjectHeader(obj,oh,&tags,1);
782 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
785 /* Verify it has a parent */
786 if(obj && !obj->fake &&
787 (!obj->parent || obj->parent->myDev != dev)){
788 T(YAFFS_TRACE_VERIFY,
789 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
790 obj->objectId,obj->parent));
793 /* Verify parent is a directory */
794 if(obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
795 T(YAFFS_TRACE_VERIFY,
796 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
797 obj->objectId,obj->parent->variantType));
800 switch(obj->variantType){
801 case YAFFS_OBJECT_TYPE_FILE:
802 yaffs_VerifyFile(obj);
804 case YAFFS_OBJECT_TYPE_SYMLINK:
805 yaffs_VerifySymlink(obj);
807 case YAFFS_OBJECT_TYPE_DIRECTORY:
808 yaffs_VerifyDirectory(obj);
810 case YAFFS_OBJECT_TYPE_HARDLINK:
811 yaffs_VerifyHardLink(obj);
813 case YAFFS_OBJECT_TYPE_SPECIAL:
814 yaffs_VerifySpecial(obj);
816 case YAFFS_OBJECT_TYPE_UNKNOWN:
818 T(YAFFS_TRACE_VERIFY,
819 (TSTR("Obj %d has illegaltype %d"TENDSTR),
820 obj->objectId,obj->variantType));
827 static void yaffs_VerifyObjects(yaffs_Device *dev)
831 struct list_head *lh;
833 if(yaffs_SkipVerification(dev))
836 /* Iterate through the objects in each hash entry */
838 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++){
839 list_for_each(lh, &dev->objectBucket[i].list) {
841 obj = list_entry(lh, yaffs_Object, hashLink);
842 yaffs_VerifyObject(obj);
851 * Simple hash function. Needs to have a reasonable spread
854 static Y_INLINE int yaffs_HashFunction(int n)
857 return (n % YAFFS_NOBJECT_BUCKETS);
861 * Access functions to useful fake objects
864 yaffs_Object *yaffs_Root(yaffs_Device * dev)
869 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
871 return dev->lostNFoundDir;
876 * Erased NAND checking functions
879 int yaffs_CheckFF(__u8 * buffer, int nBytes)
881 /* Horrible, slow implementation */
890 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
894 int retval = YAFFS_OK;
895 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
896 yaffs_ExtendedTags tags;
899 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
901 if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
905 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
906 T(YAFFS_TRACE_NANDACCESS,
907 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
911 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
918 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
920 yaffs_ExtendedTags * tags,
927 yaffs_InvalidateCheckpoint(dev);
930 yaffs_BlockInfo *bi = 0;
933 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
939 /* First check this chunk is erased, if it needs
940 * checking. The checking policy (unless forced
941 * always on) is as follows:
943 * Check the first page we try to write in a block.
944 * If the check passes then we don't need to check any
945 * more. If the check fails, we check again...
946 * If the block has been erased, we don't need to check.
948 * However, if the block has been prioritised for gc,
949 * then we think there might be something odd about
950 * this block and stop using it.
952 * Rationale: We should only ever see chunks that have
953 * not been erased if there was a partially written
954 * chunk due to power loss. This checking policy should
955 * catch that case with very few checks and thus save a
956 * lot of checks that are most likely not needed.
958 if (bi->gcPrioritise) {
959 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
960 /* try another chunk */
964 /* let's give it a try */
967 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
968 bi->skipErasedCheck = 0;
970 if (!bi->skipErasedCheck) {
971 erasedOk = yaffs_CheckChunkErased(dev, chunk);
972 if (erasedOk != YAFFS_OK) {
974 (TSTR ("**>> yaffs chunk %d was not erased"
977 /* try another chunk */
980 bi->skipErasedCheck = 1;
983 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
985 if (writeOk != YAFFS_OK) {
986 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
987 /* try another chunk */
991 /* Copy the data into the robustification buffer */
992 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
994 } while (writeOk != YAFFS_OK && attempts < yaffs_wr_attempts);
998 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1001 dev->nRetriedWrites += (attempts - 1);
1008 * Block retiring for handling a broken block.
1011 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
1013 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1015 yaffs_InvalidateCheckpoint(dev);
1017 yaffs_MarkBlockBad(dev, blockInNAND);
1019 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1020 bi->gcPrioritise = 0;
1021 bi->needsRetiring = 0;
1023 dev->nRetiredBlocks++;
1027 * Functions for robustisizing TODO
1031 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
1033 const yaffs_ExtendedTags * tags)
1037 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
1038 const yaffs_ExtendedTags * tags)
1042 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1044 if(!bi->gcPrioritise){
1045 bi->gcPrioritise = 1;
1046 dev->hasPendingPrioritisedGCs = 1;
1047 bi->chunkErrorStrikes ++;
1049 if(bi->chunkErrorStrikes > 3){
1050 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1051 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1058 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
1061 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1062 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1064 yaffs_HandleChunkError(dev,bi);
1068 /* Was an actual write failure, so mark the block for retirement */
1069 bi->needsRetiring = 1;
1070 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1071 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1076 /* Delete the chunk */
1077 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1081 /*---------------- Name handling functions ------------*/
1083 static __u16 yaffs_CalcNameSum(const YCHAR * name)
1088 YUCHAR *bname = (YUCHAR *) name;
1090 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1092 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1093 sum += yaffs_toupper(*bname) * i;
1095 sum += (*bname) * i;
1104 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
1106 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1107 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
1108 yaffs_strcpy(obj->shortName, name);
1110 obj->shortName[0] = _Y('\0');
1113 obj->sum = yaffs_CalcNameSum(name);
1116 /*-------------------- TNODES -------------------
1118 * List of spare tnodes
1119 * The list is hooked together using the first pointer
1123 /* yaffs_CreateTnodes creates a bunch more tnodes and
1124 * adds them to the tnode free list.
1125 * Don't use this function directly
1128 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
1132 yaffs_Tnode *newTnodes;
1136 yaffs_TnodeList *tnl;
1141 /* Calculate the tnode size in bytes for variable width tnode support.
1142 * Must be a multiple of 32-bits */
1143 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1145 /* make these things */
1147 newTnodes = YMALLOC(nTnodes * tnodeSize);
1148 mem = (__u8 *)newTnodes;
1151 T(YAFFS_TRACE_ERROR,
1152 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1156 /* Hook them into the free list */
1158 for (i = 0; i < nTnodes - 1; i++) {
1159 newTnodes[i].internal[0] = &newTnodes[i + 1];
1160 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1161 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1165 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1166 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1167 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1169 dev->freeTnodes = newTnodes;
1171 /* New hookup for wide tnodes */
1172 for(i = 0; i < nTnodes -1; i++) {
1173 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1174 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1175 curr->internal[0] = next;
1178 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1179 curr->internal[0] = dev->freeTnodes;
1180 dev->freeTnodes = (yaffs_Tnode *)mem;
1185 dev->nFreeTnodes += nTnodes;
1186 dev->nTnodesCreated += nTnodes;
1188 /* Now add this bunch of tnodes to a list for freeing up.
1189 * NB If we can't add this to the management list it isn't fatal
1190 * but it just means we can't free this bunch of tnodes later.
1193 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1195 T(YAFFS_TRACE_ERROR,
1197 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1201 tnl->tnodes = newTnodes;
1202 tnl->next = dev->allocatedTnodeList;
1203 dev->allocatedTnodeList = tnl;
1206 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1211 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1213 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
1215 yaffs_Tnode *tn = NULL;
1217 /* If there are none left make more */
1218 if (!dev->freeTnodes) {
1219 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1222 if (dev->freeTnodes) {
1223 tn = dev->freeTnodes;
1224 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1225 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1226 /* Hoosterman, this thing looks like it isn't in the list */
1227 T(YAFFS_TRACE_ALWAYS,
1228 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1231 dev->freeTnodes = dev->freeTnodes->internal[0];
1238 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
1240 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1243 memset(tn, 0, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1248 /* FreeTnode frees up a tnode and puts it back on the free list */
1249 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
1252 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1253 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1254 /* Hoosterman, this thing looks like it is already in the list */
1255 T(YAFFS_TRACE_ALWAYS,
1256 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1258 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1260 tn->internal[0] = dev->freeTnodes;
1261 dev->freeTnodes = tn;
1266 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
1268 /* Free the list of allocated tnodes */
1269 yaffs_TnodeList *tmp;
1271 while (dev->allocatedTnodeList) {
1272 tmp = dev->allocatedTnodeList->next;
1274 YFREE(dev->allocatedTnodeList->tnodes);
1275 YFREE(dev->allocatedTnodeList);
1276 dev->allocatedTnodeList = tmp;
1280 dev->freeTnodes = NULL;
1281 dev->nFreeTnodes = 0;
1284 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
1286 dev->allocatedTnodeList = NULL;
1287 dev->freeTnodes = NULL;
1288 dev->nFreeTnodes = 0;
1289 dev->nTnodesCreated = 0;
1294 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
1296 __u32 *map = (__u32 *)tn;
1302 pos &= YAFFS_TNODES_LEVEL0_MASK;
1303 val >>= dev->chunkGroupBits;
1305 bitInMap = pos * dev->tnodeWidth;
1306 wordInMap = bitInMap /32;
1307 bitInWord = bitInMap & (32 -1);
1309 mask = dev->tnodeMask << bitInWord;
1311 map[wordInMap] &= ~mask;
1312 map[wordInMap] |= (mask & (val << bitInWord));
1314 if(dev->tnodeWidth > (32-bitInWord)) {
1315 bitInWord = (32 - bitInWord);
1317 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1318 map[wordInMap] &= ~mask;
1319 map[wordInMap] |= (mask & (val >> bitInWord));
1323 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
1325 __u32 *map = (__u32 *)tn;
1331 pos &= YAFFS_TNODES_LEVEL0_MASK;
1333 bitInMap = pos * dev->tnodeWidth;
1334 wordInMap = bitInMap /32;
1335 bitInWord = bitInMap & (32 -1);
1337 val = map[wordInMap] >> bitInWord;
1339 if(dev->tnodeWidth > (32-bitInWord)) {
1340 bitInWord = (32 - bitInWord);
1342 val |= (map[wordInMap] << bitInWord);
1345 val &= dev->tnodeMask;
1346 val <<= dev->chunkGroupBits;
1351 /* ------------------- End of individual tnode manipulation -----------------*/
1353 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1354 * The look up tree is represented by the top tnode and the number of topLevel
1355 * in the tree. 0 means only the level 0 tnode is in the tree.
1358 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1359 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
1360 yaffs_FileStructure * fStruct,
1364 yaffs_Tnode *tn = fStruct->top;
1366 int requiredTallness;
1367 int level = fStruct->topLevel;
1369 /* Check sane level and chunk Id */
1370 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
1374 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1378 /* First check we're tall enough (ie enough topLevel) */
1380 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1381 requiredTallness = 0;
1383 i >>= YAFFS_TNODES_INTERNAL_BITS;
1387 if (requiredTallness > fStruct->topLevel) {
1388 /* Not tall enough, so we can't find it, return NULL. */
1392 /* Traverse down to level 0 */
1393 while (level > 0 && tn) {
1395 internal[(chunkId >>
1396 ( YAFFS_TNODES_LEVEL0_BITS +
1398 YAFFS_TNODES_INTERNAL_BITS)
1400 YAFFS_TNODES_INTERNAL_MASK];
1408 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1409 * This happens in two steps:
1410 * 1. If the tree isn't tall enough, then make it taller.
1411 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1413 * Used when modifying the tree.
1415 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1416 * be plugged into the ttree.
1419 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
1420 yaffs_FileStructure * fStruct,
1422 yaffs_Tnode *passedTn)
1425 int requiredTallness;
1433 /* Check sane level and page Id */
1434 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
1438 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1442 /* First check we're tall enough (ie enough topLevel) */
1444 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1445 requiredTallness = 0;
1447 x >>= YAFFS_TNODES_INTERNAL_BITS;
1452 if (requiredTallness > fStruct->topLevel) {
1453 /* Not tall enough,gotta make the tree taller */
1454 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1456 tn = yaffs_GetTnode(dev);
1459 tn->internal[0] = fStruct->top;
1462 T(YAFFS_TRACE_ERROR,
1463 (TSTR("yaffs: no more tnodes" TENDSTR)));
1467 fStruct->topLevel = requiredTallness;
1470 /* Traverse down to level 0, adding anything we need */
1472 l = fStruct->topLevel;
1476 while (l > 0 && tn) {
1478 ( YAFFS_TNODES_LEVEL0_BITS +
1479 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1480 YAFFS_TNODES_INTERNAL_MASK;
1483 if((l>1) && !tn->internal[x]){
1484 /* Add missing non-level-zero tnode */
1485 tn->internal[x] = yaffs_GetTnode(dev);
1488 /* Looking from level 1 at level 0 */
1490 /* If we already have one, then release it.*/
1492 yaffs_FreeTnode(dev,tn->internal[x]);
1493 tn->internal[x] = passedTn;
1495 } else if(!tn->internal[x]) {
1496 /* Don't have one, none passed in */
1497 tn->internal[x] = yaffs_GetTnode(dev);
1501 tn = tn->internal[x];
1505 /* top is level 0 */
1507 memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1508 yaffs_FreeTnode(dev,passedTn);
1515 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1516 yaffs_ExtendedTags * tags, int objectId,
1521 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1522 if (yaffs_CheckChunkBit
1523 (dev, theChunk / dev->nChunksPerBlock,
1524 theChunk % dev->nChunksPerBlock)) {
1525 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1527 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1539 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1540 * chunks and tnodes in the file
1541 * Returns 1 if the tree was deleted.
1542 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1545 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1546 int chunkOffset, int *limit)
1551 yaffs_ExtendedTags tags;
1553 yaffs_Device *dev = in->myDev;
1560 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1562 if (tn->internal[i]) {
1563 if (limit && (*limit) < 0) {
1567 yaffs_DeleteWorker(in,
1575 YAFFS_TNODES_INTERNAL_BITS)
1580 yaffs_FreeTnode(dev,
1583 tn->internal[i] = NULL;
1588 return (allDone) ? 1 : 0;
1589 } else if (level == 0) {
1592 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1594 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1599 YAFFS_TNODES_LEVEL0_BITS) + i;
1602 yaffs_FindChunkInGroup(dev,
1608 if (foundChunk > 0) {
1609 yaffs_DeleteChunk(dev,
1614 *limit = *limit - 1;
1622 yaffs_PutLevel0Tnode(dev,tn,i,0);
1626 return (i < 0) ? 1 : 0;
1636 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1639 yaffs_BlockInfo *theBlock;
1641 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1643 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1645 theBlock->softDeletions++;
1650 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1651 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1653 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1656 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1657 __u32 level, int chunkOffset)
1662 yaffs_Device *dev = in->myDev;
1667 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1669 if (tn->internal[i]) {
1671 yaffs_SoftDeleteWorker(in,
1677 YAFFS_TNODES_INTERNAL_BITS)
1680 yaffs_FreeTnode(dev,
1683 tn->internal[i] = NULL;
1685 /* Hoosterman... how could this happen? */
1689 return (allDone) ? 1 : 0;
1690 } else if (level == 0) {
1692 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1693 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1695 /* Note this does not find the real chunk, only the chunk group.
1696 * We make an assumption that a chunk group is not larger than
1699 yaffs_SoftDeleteChunk(dev, theChunk);
1700 yaffs_PutLevel0Tnode(dev,tn,i,0);
1714 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1717 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1718 if (obj->nDataChunks <= 0) {
1719 /* Empty file with no duplicate object headers, just delete it immediately */
1720 yaffs_FreeTnode(obj->myDev,
1721 obj->variant.fileVariant.top);
1722 obj->variant.fileVariant.top = NULL;
1723 T(YAFFS_TRACE_TRACING,
1724 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1726 yaffs_DoGenericObjectDeletion(obj);
1728 yaffs_SoftDeleteWorker(obj,
1729 obj->variant.fileVariant.top,
1730 obj->variant.fileVariant.
1732 obj->softDeleted = 1;
1737 /* Pruning removes any part of the file structure tree that is beyond the
1738 * bounds of the file (ie that does not point to chunks).
1740 * A file should only get pruned when its size is reduced.
1742 * Before pruning, the chunks must be pulled from the tree and the
1743 * level 0 tnode entries must be zeroed out.
1744 * Could also use this for file deletion, but that's probably better handled
1745 * by a special case.
1748 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1749 __u32 level, int del0)
1757 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1758 if (tn->internal[i] && level > 0) {
1760 yaffs_PruneWorker(dev, tn->internal[i],
1762 (i == 0) ? del0 : 1);
1765 if (tn->internal[i]) {
1770 if (hasData == 0 && del0) {
1771 /* Free and return NULL */
1773 yaffs_FreeTnode(dev, tn);
1783 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1784 yaffs_FileStructure * fStruct)
1791 if (fStruct->topLevel > 0) {
1793 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1795 /* Now we have a tree with all the non-zero branches NULL but the height
1796 * is the same as it was.
1797 * Let's see if we can trim internal tnodes to shorten the tree.
1798 * We can do this if only the 0th element in the tnode is in use
1799 * (ie all the non-zero are NULL)
1802 while (fStruct->topLevel && !done) {
1806 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1807 if (tn->internal[i]) {
1813 fStruct->top = tn->internal[0];
1814 fStruct->topLevel--;
1815 yaffs_FreeTnode(dev, tn);
1825 /*-------------------- End of File Structure functions.-------------------*/
1827 /* yaffs_CreateFreeObjects creates a bunch more objects and
1828 * adds them to the object free list.
1830 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1833 yaffs_Object *newObjects;
1834 yaffs_ObjectList *list;
1839 /* make these things */
1840 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1841 list = YMALLOC(sizeof(yaffs_ObjectList));
1843 if (!newObjects || !list) {
1848 T(YAFFS_TRACE_ALLOCATE,
1849 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1853 /* Hook them into the free list */
1854 for (i = 0; i < nObjects - 1; i++) {
1855 newObjects[i].siblings.next =
1856 (struct list_head *)(&newObjects[i + 1]);
1859 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1860 dev->freeObjects = newObjects;
1861 dev->nFreeObjects += nObjects;
1862 dev->nObjectsCreated += nObjects;
1864 /* Now add this bunch of Objects to a list for freeing up. */
1866 list->objects = newObjects;
1867 list->next = dev->allocatedObjectList;
1868 dev->allocatedObjectList = list;
1874 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1875 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1877 yaffs_Object *tn = NULL;
1879 /* If there are none left make more */
1880 if (!dev->freeObjects) {
1881 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1884 if (dev->freeObjects) {
1885 tn = dev->freeObjects;
1887 (yaffs_Object *) (dev->freeObjects->siblings.next);
1888 dev->nFreeObjects--;
1890 /* Now sweeten it up... */
1892 memset(tn, 0, sizeof(yaffs_Object));
1895 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1896 INIT_LIST_HEAD(&(tn->hardLinks));
1897 INIT_LIST_HEAD(&(tn->hashLink));
1898 INIT_LIST_HEAD(&tn->siblings);
1900 /* Add it to the lost and found directory.
1901 * NB Can't put root or lostNFound in lostNFound so
1902 * check if lostNFound exists first
1904 if (dev->lostNFoundDir) {
1905 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1912 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1917 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1919 obj->fake = 1; /* it is fake so it has no NAND presence... */
1920 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1921 obj->unlinkAllowed = 0; /* ... or unlink it */
1924 obj->yst_mode = mode;
1926 obj->chunkId = 0; /* Not a valid chunk. */
1933 static void yaffs_UnhashObject(yaffs_Object * tn)
1936 yaffs_Device *dev = tn->myDev;
1938 /* If it is still linked into the bucket list, free from the list */
1939 if (!list_empty(&tn->hashLink)) {
1940 list_del_init(&tn->hashLink);
1941 bucket = yaffs_HashFunction(tn->objectId);
1942 dev->objectBucket[bucket].count--;
1947 /* FreeObject frees up a Object and puts it back on the free list */
1948 static void yaffs_FreeObject(yaffs_Object * tn)
1951 yaffs_Device *dev = tn->myDev;
1955 /* We're still hooked up to a cached inode.
1956 * Don't delete now, but mark for later deletion
1958 tn->deferedFree = 1;
1963 yaffs_UnhashObject(tn);
1965 /* Link into the free list. */
1966 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1967 dev->freeObjects = tn;
1968 dev->nFreeObjects++;
1973 void yaffs_HandleDeferedFree(yaffs_Object * obj)
1975 if (obj->deferedFree) {
1976 yaffs_FreeObject(obj);
1982 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
1984 /* Free the list of allocated Objects */
1986 yaffs_ObjectList *tmp;
1988 while (dev->allocatedObjectList) {
1989 tmp = dev->allocatedObjectList->next;
1990 YFREE(dev->allocatedObjectList->objects);
1991 YFREE(dev->allocatedObjectList);
1993 dev->allocatedObjectList = tmp;
1996 dev->freeObjects = NULL;
1997 dev->nFreeObjects = 0;
2000 static void yaffs_InitialiseObjects(yaffs_Device * dev)
2004 dev->allocatedObjectList = NULL;
2005 dev->freeObjects = NULL;
2006 dev->nFreeObjects = 0;
2008 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2009 INIT_LIST_HEAD(&dev->objectBucket[i].list);
2010 dev->objectBucket[i].count = 0;
2015 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
2020 int lowest = 999999;
2022 /* First let's see if we can find one that's empty. */
2024 for (i = 0; i < 10 && lowest > 0; i++) {
2026 x %= YAFFS_NOBJECT_BUCKETS;
2027 if (dev->objectBucket[x].count < lowest) {
2028 lowest = dev->objectBucket[x].count;
2034 /* If we didn't find an empty list, then try
2035 * looking a bit further for a short one
2038 for (i = 0; i < 10 && lowest > 3; i++) {
2040 x %= YAFFS_NOBJECT_BUCKETS;
2041 if (dev->objectBucket[x].count < lowest) {
2042 lowest = dev->objectBucket[x].count;
2051 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
2053 int bucket = yaffs_FindNiceObjectBucket(dev);
2055 /* Now find an object value that has not already been taken
2056 * by scanning the list.
2060 struct list_head *i;
2062 __u32 n = (__u32) bucket;
2064 /* yaffs_CheckObjectHashSanity(); */
2068 n += YAFFS_NOBJECT_BUCKETS;
2069 if (1 || dev->objectBucket[bucket].count > 0) {
2070 list_for_each(i, &dev->objectBucket[bucket].list) {
2071 /* If there is already one in the list */
2073 && list_entry(i, yaffs_Object,
2074 hashLink)->objectId == n) {
2085 static void yaffs_HashObject(yaffs_Object * in)
2087 int bucket = yaffs_HashFunction(in->objectId);
2088 yaffs_Device *dev = in->myDev;
2090 list_add(&in->hashLink, &dev->objectBucket[bucket].list);
2091 dev->objectBucket[bucket].count++;
2095 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
2097 int bucket = yaffs_HashFunction(number);
2098 struct list_head *i;
2101 list_for_each(i, &dev->objectBucket[bucket].list) {
2102 /* Look if it is in the list */
2104 in = list_entry(i, yaffs_Object, hashLink);
2105 if (in->objectId == number) {
2107 /* Don't tell the VFS about this one if it is defered free */
2108 if (in->deferedFree)
2120 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
2121 yaffs_ObjectType type)
2124 yaffs_Object *theObject;
2128 number = yaffs_CreateNewObjectNumber(dev);
2131 theObject = yaffs_AllocateEmptyObject(dev);
2135 if(type == YAFFS_OBJECT_TYPE_FILE){
2136 tn = yaffs_GetTnode(dev);
2138 yaffs_FreeObject(theObject);
2146 theObject->fake = 0;
2147 theObject->renameAllowed = 1;
2148 theObject->unlinkAllowed = 1;
2149 theObject->objectId = number;
2150 yaffs_HashObject(theObject);
2151 theObject->variantType = type;
2152 #ifdef CONFIG_YAFFS_WINCE
2153 yfsd_WinFileTimeNow(theObject->win_atime);
2154 theObject->win_ctime[0] = theObject->win_mtime[0] =
2155 theObject->win_atime[0];
2156 theObject->win_ctime[1] = theObject->win_mtime[1] =
2157 theObject->win_atime[1];
2161 theObject->yst_atime = theObject->yst_mtime =
2162 theObject->yst_ctime = Y_CURRENT_TIME;
2165 case YAFFS_OBJECT_TYPE_FILE:
2166 theObject->variant.fileVariant.fileSize = 0;
2167 theObject->variant.fileVariant.scannedFileSize = 0;
2168 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2169 theObject->variant.fileVariant.topLevel = 0;
2170 theObject->variant.fileVariant.top = tn;
2172 case YAFFS_OBJECT_TYPE_DIRECTORY:
2173 INIT_LIST_HEAD(&theObject->variant.directoryVariant.
2176 case YAFFS_OBJECT_TYPE_SYMLINK:
2177 case YAFFS_OBJECT_TYPE_HARDLINK:
2178 case YAFFS_OBJECT_TYPE_SPECIAL:
2179 /* No action required */
2181 case YAFFS_OBJECT_TYPE_UNKNOWN:
2182 /* todo this should not happen */
2190 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
2192 yaffs_ObjectType type)
2194 yaffs_Object *theObject = NULL;
2197 theObject = yaffs_FindObjectByNumber(dev, number);
2201 theObject = yaffs_CreateNewObject(dev, number, type);
2209 static YCHAR *yaffs_CloneString(const YCHAR * str)
2211 YCHAR *newStr = NULL;
2214 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2216 yaffs_strcpy(newStr, str);
2224 * Mknod (create) a new object.
2225 * equivalentObject only has meaning for a hard link;
2226 * aliasString only has meaning for a sumlink.
2227 * rdev only has meaning for devices (a subset of special objects)
2230 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2231 yaffs_Object * parent,
2236 yaffs_Object * equivalentObject,
2237 const YCHAR * aliasString, __u32 rdev)
2242 yaffs_Device *dev = parent->myDev;
2244 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2245 if (yaffs_FindObjectByName(parent, name)) {
2249 in = yaffs_CreateNewObject(dev, -1, type);
2251 if(type == YAFFS_OBJECT_TYPE_SYMLINK){
2252 str = yaffs_CloneString(aliasString);
2254 yaffs_FreeObject(in);
2264 in->variantType = type;
2266 in->yst_mode = mode;
2268 #ifdef CONFIG_YAFFS_WINCE
2269 yfsd_WinFileTimeNow(in->win_atime);
2270 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2271 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2274 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2276 in->yst_rdev = rdev;
2280 in->nDataChunks = 0;
2282 yaffs_SetObjectName(in, name);
2285 yaffs_AddObjectToDirectory(parent, in);
2287 in->myDev = parent->myDev;
2290 case YAFFS_OBJECT_TYPE_SYMLINK:
2291 in->variant.symLinkVariant.alias = str;
2293 case YAFFS_OBJECT_TYPE_HARDLINK:
2294 in->variant.hardLinkVariant.equivalentObject =
2296 in->variant.hardLinkVariant.equivalentObjectId =
2297 equivalentObject->objectId;
2298 list_add(&in->hardLinks, &equivalentObject->hardLinks);
2300 case YAFFS_OBJECT_TYPE_FILE:
2301 case YAFFS_OBJECT_TYPE_DIRECTORY:
2302 case YAFFS_OBJECT_TYPE_SPECIAL:
2303 case YAFFS_OBJECT_TYPE_UNKNOWN:
2308 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2309 /* Could not create the object header, fail the creation */
2310 yaffs_DestroyObject(in);
2319 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
2320 __u32 mode, __u32 uid, __u32 gid)
2322 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2323 uid, gid, NULL, NULL, 0);
2326 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
2327 __u32 mode, __u32 uid, __u32 gid)
2329 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2330 mode, uid, gid, NULL, NULL, 0);
2333 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
2334 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2336 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2337 uid, gid, NULL, NULL, rdev);
2340 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
2341 __u32 mode, __u32 uid, __u32 gid,
2342 const YCHAR * alias)
2344 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2345 uid, gid, NULL, alias, 0);
2348 /* yaffs_Link returns the object id of the equivalent object.*/
2349 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
2350 yaffs_Object * equivalentObject)
2352 /* Get the real object in case we were fed a hard link as an equivalent object */
2353 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2355 if (yaffs_MknodObject
2356 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2357 equivalentObject, NULL, 0)) {
2358 return equivalentObject;
2365 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
2366 const YCHAR * newName, int force, int shadows)
2371 yaffs_Object *existingTarget;
2373 if (newDir == NULL) {
2374 newDir = obj->parent; /* use the old directory */
2377 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2378 T(YAFFS_TRACE_ALWAYS,
2380 ("tragendy: yaffs_ChangeObjectName: newDir is not a directory"
2385 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2386 if (obj->myDev->isYaffs2) {
2387 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2389 unlinkOp = (newDir == obj->myDev->unlinkedDir
2390 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2393 deleteOp = (newDir == obj->myDev->deletedDir);
2395 existingTarget = yaffs_FindObjectByName(newDir, newName);
2397 /* If the object is a file going into the unlinked directory,
2398 * then it is OK to just stuff it in since duplicate names are allowed.
2399 * else only proceed if the new name does not exist and if we're putting
2400 * it into a directory.
2407 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2408 yaffs_SetObjectName(obj, newName);
2411 yaffs_AddObjectToDirectory(newDir, obj);
2416 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2417 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
2424 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
2425 yaffs_Object * newDir, const YCHAR * newName)
2428 yaffs_Object *existingTarget;
2431 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2432 /* Special case for case insemsitive systems (eg. WinCE).
2433 * While look-up is case insensitive, the name isn't.
2434 * Therefore we might want to change x.txt to X.txt
2436 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
2441 obj = yaffs_FindObjectByName(oldDir, oldName);
2442 /* Check new name to long. */
2443 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK &&
2444 yaffs_strlen(newName) > YAFFS_MAX_ALIAS_LENGTH)
2447 else if (obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK &&
2448 yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2452 if (obj && obj->renameAllowed) {
2454 /* Now do the handling for an existing target, if there is one */
2456 existingTarget = yaffs_FindObjectByName(newDir, newName);
2457 if (existingTarget &&
2458 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2459 !list_empty(&existingTarget->variant.directoryVariant.children)) {
2460 /* There is a target that is a non-empty directory, so we fail */
2461 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2462 } else if (existingTarget && existingTarget != obj) {
2463 /* Nuke the target first, using shadowing,
2464 * but only if it isn't the same object
2466 yaffs_ChangeObjectName(obj, newDir, newName, force,
2467 existingTarget->objectId);
2468 yaffs_UnlinkObject(existingTarget);
2471 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2476 /*------------------------- Block Management and Page Allocation ----------------*/
2478 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
2480 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2482 dev->blockInfo = NULL;
2483 dev->chunkBits = NULL;
2485 dev->allocationBlock = -1; /* force it to get a new one */
2487 /* If the first allocation strategy fails, thry the alternate one */
2488 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2489 if(!dev->blockInfo){
2490 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2491 dev->blockInfoAlt = 1;
2494 dev->blockInfoAlt = 0;
2498 /* Set up dynamic blockinfo stuff. */
2499 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2500 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2501 if(!dev->chunkBits){
2502 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2503 dev->chunkBitsAlt = 1;
2506 dev->chunkBitsAlt = 0;
2509 if (dev->blockInfo && dev->chunkBits) {
2510 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2511 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2519 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
2521 if(dev->blockInfoAlt && dev->blockInfo)
2522 YFREE_ALT(dev->blockInfo);
2523 else if(dev->blockInfo)
2524 YFREE(dev->blockInfo);
2526 dev->blockInfoAlt = 0;
2528 dev->blockInfo = NULL;
2530 if(dev->chunkBitsAlt && dev->chunkBits)
2531 YFREE_ALT(dev->chunkBits);
2532 else if(dev->chunkBits)
2533 YFREE(dev->chunkBits);
2534 dev->chunkBitsAlt = 0;
2535 dev->chunkBits = NULL;
2538 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
2539 yaffs_BlockInfo * bi)
2546 return 1; /* disqualification only applies to yaffs2. */
2548 if (!bi->hasShrinkHeader)
2549 return 1; /* can gc */
2551 /* Find the oldest dirty sequence number if we don't know it and save it
2552 * so we don't have to keep recomputing it.
2554 if (!dev->oldestDirtySequence) {
2555 seq = dev->sequenceNumber;
2557 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2559 b = yaffs_GetBlockInfo(dev, i);
2560 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2561 (b->pagesInUse - b->softDeletions) <
2562 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2563 seq = b->sequenceNumber;
2566 dev->oldestDirtySequence = seq;
2569 /* Can't do gc of this block if there are any blocks older than this one that have
2572 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2576 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2577 * for garbage collection.
2580 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2584 int b = dev->currentDirtyChecker;
2591 yaffs_BlockInfo *bi;
2592 int pendingPrioritisedExist = 0;
2594 /* First let's see if we need to grab a prioritised block */
2595 if(dev->hasPendingPrioritisedGCs){
2596 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2598 bi = yaffs_GetBlockInfo(dev, i);
2599 //yaffs_VerifyBlock(dev,bi,i);
2601 if(bi->gcPrioritise) {
2602 pendingPrioritisedExist = 1;
2603 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2604 yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2605 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2608 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2613 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2614 dev->hasPendingPrioritisedGCs = 0;
2617 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2619 * else (we're doing a leasurely gc), then we only bother to do this if the
2620 * block has only a few pages in use.
2623 dev->nonAggressiveSkip--;
2625 if (!aggressive && (dev->nonAggressiveSkip > 0)) {
2631 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2635 dev->internalEndBlock - dev->internalStartBlock + 1;
2638 dev->internalEndBlock - dev->internalStartBlock + 1;
2639 iterations = iterations / 16;
2640 if (iterations > 200) {
2645 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2647 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2648 b = dev->internalStartBlock;
2651 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2652 T(YAFFS_TRACE_ERROR,
2653 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2657 bi = yaffs_GetBlockInfo(dev, b);
2660 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2667 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2668 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2669 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2671 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2675 dev->currentDirtyChecker = b;
2679 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2680 dev->nChunksPerBlock - pagesInUse,prioritised));
2683 dev->oldestDirtySequence = 0;
2686 dev->nonAggressiveSkip = 4;
2692 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2694 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2698 /* If the block is still healthy erase it and mark as clean.
2699 * If the block has had a data failure, then retire it.
2702 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2703 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2704 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2706 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2708 if (!bi->needsRetiring) {
2709 yaffs_InvalidateCheckpoint(dev);
2710 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2712 dev->nErasureFailures++;
2713 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2714 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2719 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2721 for (i = 0; i < dev->nChunksPerBlock; i++) {
2722 if (!yaffs_CheckChunkErased
2723 (dev, blockNo * dev->nChunksPerBlock + i)) {
2724 T(YAFFS_TRACE_ERROR,
2726 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2727 TENDSTR), blockNo, i));
2733 /* Clean it up... */
2734 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2735 dev->nErasedBlocks++;
2737 bi->softDeletions = 0;
2738 bi->hasShrinkHeader = 0;
2739 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2740 bi->gcPrioritise = 0;
2741 yaffs_ClearChunkBits(dev, blockNo);
2743 T(YAFFS_TRACE_ERASE,
2744 (TSTR("Erased block %d" TENDSTR), blockNo));
2746 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2748 yaffs_RetireBlock(dev, blockNo);
2749 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2750 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2754 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2758 yaffs_BlockInfo *bi;
2760 if (dev->nErasedBlocks < 1) {
2761 /* Hoosterman we've got a problem.
2762 * Can't get space to gc
2764 T(YAFFS_TRACE_ERROR,
2765 (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2770 /* Find an empty block. */
2772 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2773 dev->allocationBlockFinder++;
2774 if (dev->allocationBlockFinder < dev->internalStartBlock
2775 || dev->allocationBlockFinder > dev->internalEndBlock) {
2776 dev->allocationBlockFinder = dev->internalStartBlock;
2779 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2781 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2782 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2783 dev->sequenceNumber++;
2784 bi->sequenceNumber = dev->sequenceNumber;
2785 dev->nErasedBlocks--;
2786 T(YAFFS_TRACE_ALLOCATE,
2787 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2788 dev->allocationBlockFinder, dev->sequenceNumber,
2789 dev->nErasedBlocks));
2790 return dev->allocationBlockFinder;
2794 T(YAFFS_TRACE_ALWAYS,
2796 ("yaffs tragedy: no more eraased blocks, but there should have been %d"
2797 TENDSTR), dev->nErasedBlocks));
2803 // Check if there's space to allocate...
2804 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2805 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2808 int reservedBlocks = dev->nReservedBlocks;
2809 int checkpointBlocks;
2811 checkpointBlocks = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
2812 if(checkpointBlocks < 0)
2813 checkpointBlocks = 0;
2815 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2817 return (dev->nFreeChunks > reservedChunks);
2820 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2823 yaffs_BlockInfo *bi;
2825 if (dev->allocationBlock < 0) {
2826 /* Get next block to allocate off */
2827 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2828 dev->allocationPage = 0;
2831 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2832 /* Not enough space to allocate unless we're allowed to use the reserve. */
2836 if (dev->nErasedBlocks < dev->nReservedBlocks
2837 && dev->allocationPage == 0) {
2838 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2841 /* Next page please.... */
2842 if (dev->allocationBlock >= 0) {
2843 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2845 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2846 dev->allocationPage;
2848 yaffs_SetChunkBit(dev, dev->allocationBlock,
2849 dev->allocationPage);
2851 dev->allocationPage++;
2855 /* If the block is full set the state to full */
2856 if (dev->allocationPage >= dev->nChunksPerBlock) {
2857 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2858 dev->allocationBlock = -1;
2867 T(YAFFS_TRACE_ERROR,
2868 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2873 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2877 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2879 if (dev->allocationBlock > 0) {
2880 n += (dev->nChunksPerBlock - dev->allocationPage);
2887 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2893 int retVal = YAFFS_OK;
2896 int isCheckpointBlock;
2899 int chunksBefore = yaffs_GetErasedChunks(dev);
2902 yaffs_ExtendedTags tags;
2904 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2906 yaffs_Object *object;
2908 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2910 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2912 T(YAFFS_TRACE_TRACING,
2913 (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2914 bi->pagesInUse, bi->hasShrinkHeader));
2916 /*yaffs_VerifyFreeChunks(dev); */
2918 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2920 /* Take off the number of soft deleted entries because
2921 * they're going to get really deleted during GC.
2923 dev->nFreeChunks -= bi->softDeletions;
2927 if (isCheckpointBlock ||
2928 !yaffs_StillSomeChunkBits(dev, block)) {
2929 T(YAFFS_TRACE_TRACING,
2931 ("Collecting block %d that has no chunks in use" TENDSTR),
2933 yaffs_BlockBecameDirty(dev, block);
2936 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2938 yaffs_VerifyBlock(dev,bi,block);
2940 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
2941 chunkInBlock < dev->nChunksPerBlock
2942 && yaffs_StillSomeChunkBits(dev, block);
2943 chunkInBlock++, oldChunk++) {
2944 if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
2946 /* This page is in use and might need to be copied off */
2950 yaffs_InitialiseTags(&tags);
2952 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2956 yaffs_FindObjectByNumber(dev,
2959 T(YAFFS_TRACE_GC_DETAIL,
2961 ("Collecting page %d, %d %d %d " TENDSTR),
2962 chunkInBlock, tags.objectId, tags.chunkId,
2965 if(object && !yaffs_SkipVerification(dev)){
2966 if(tags.chunkId == 0)
2967 matchingChunk = object->chunkId;
2968 else if(object->softDeleted)
2969 matchingChunk = oldChunk; /* Defeat the test */
2971 matchingChunk = yaffs_FindChunkInFile(object,tags.chunkId,NULL);
2973 if(oldChunk != matchingChunk)
2974 T(YAFFS_TRACE_ERROR,
2975 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
2976 oldChunk,matchingChunk,tags.objectId, tags.chunkId));
2981 T(YAFFS_TRACE_ERROR,
2983 ("page %d in gc has no object: %d %d %d "
2985 tags.objectId, tags.chunkId, tags.byteCount));
2988 if (object && object->deleted
2989 && tags.chunkId != 0) {
2990 /* Data chunk in a deleted file, throw it away
2991 * It's a soft deleted data chunk,
2992 * No need to copy this, just forget about it and
2993 * fix up the object.
2996 object->nDataChunks--;
2998 if (object->nDataChunks <= 0) {
2999 /* remeber to clean up the object */
3000 dev->gcCleanupList[cleanups] =
3006 /* Todo object && object->deleted && object->nDataChunks == 0 */
3008 /* Deleted object header with no data chunks.
3009 * Can be discarded and the file deleted.
3011 object->chunkId = 0;
3012 yaffs_FreeTnode(object->myDev,
3015 object->variant.fileVariant.top = NULL;
3016 yaffs_DoGenericObjectDeletion(object);
3018 } else if (object) {
3019 /* It's either a data chunk in a live file or
3020 * an ObjectHeader, so we're interested in it.
3021 * NB Need to keep the ObjectHeaders of deleted files
3022 * until the whole file has been deleted off
3024 tags.serialNumber++;
3028 if (tags.chunkId == 0) {
3029 /* It is an object Id,
3030 * We need to nuke the shrinkheader flags first
3031 * We no longer want the shrinkHeader flag since its work is done
3032 * and if it is left in place it will mess up scanning.
3033 * Also, clear out any shadowing stuff
3036 yaffs_ObjectHeader *oh;
3037 oh = (yaffs_ObjectHeader *)buffer;
3039 oh->shadowsObject = -1;
3040 tags.extraShadows = 0;
3041 tags.extraIsShrinkHeader = 0;
3043 yaffs_VerifyObjectHeader(object,oh,&tags,1);
3047 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3050 retVal = YAFFS_FAIL;
3053 /* Ok, now fix up the Tnodes etc. */
3055 if (tags.chunkId == 0) {
3057 object->chunkId = newChunk;
3058 object->serial = tags.serialNumber;
3060 /* It's a data chunk */
3061 yaffs_PutChunkIntoFile
3069 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3074 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3077 /* Do any required cleanups */
3078 for (i = 0; i < cleanups; i++) {
3079 /* Time to delete the file too */
3081 yaffs_FindObjectByNumber(dev,
3082 dev->gcCleanupList[i]);
3084 yaffs_FreeTnode(dev,
3085 object->variant.fileVariant.
3087 object->variant.fileVariant.top = NULL;
3090 ("yaffs: About to finally delete object %d"
3091 TENDSTR), object->objectId));
3092 yaffs_DoGenericObjectDeletion(object);
3093 object->myDev->nDeletedFiles--;
3100 yaffs_VerifyCollectedBlock(dev,bi,block);
3102 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
3105 ("gc did not increase free chunks before %d after %d"
3106 TENDSTR), chunksBefore, chunksAfter));
3114 /* New garbage collector
3115 * If we're very low on erased blocks then we do aggressive garbage collection
3116 * otherwise we do "leasurely" garbage collection.
3117 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3118 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3120 * The idea is to help clear out space in a more spread-out manner.
3121 * Dunno if it really does anything useful.
3123 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
3127 int gcOk = YAFFS_OK;
3130 int checkpointBlockAdjust;
3132 if (dev->isDoingGC) {
3133 /* Bail out so we don't get recursive gc */
3137 /* This loop should pass the first time.
3138 * We'll only see looping here if the erase of the collected block fails.
3144 checkpointBlockAdjust = (dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint);
3145 if(checkpointBlockAdjust < 0)
3146 checkpointBlockAdjust = 0;
3148 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3149 /* We need a block soon...*/
3152 /* We're in no hurry */
3156 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3159 dev->garbageCollections++;
3161 dev->passiveGarbageCollections++;
3166 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3167 dev->nErasedBlocks, aggressive));
3169 gcOk = yaffs_GarbageCollectBlock(dev, block);
3172 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3175 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3176 TENDSTR), dev->nErasedBlocks, maxTries, block));
3178 } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
3181 return aggressive ? gcOk : YAFFS_OK;
3184 /*------------------------- TAGS --------------------------------*/
3186 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
3189 return (tags->chunkId == chunkInObject &&
3190 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3195 /*-------------------- Data file manipulation -----------------*/
3197 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
3198 yaffs_ExtendedTags * tags)
3200 /*Get the Tnode, then get the level 0 offset chunk offset */
3203 yaffs_ExtendedTags localTags;
3206 yaffs_Device *dev = in->myDev;
3209 /* Passed a NULL, so use our own tags space */
3213 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3216 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3219 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3225 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
3226 yaffs_ExtendedTags * tags)
3228 /* Get the Tnode, then get the level 0 offset chunk offset */
3231 yaffs_ExtendedTags localTags;
3233 yaffs_Device *dev = in->myDev;
3237 /* Passed a NULL, so use our own tags space */
3241 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3245 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3248 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3251 /* Delete the entry in the filestructure (if found) */
3253 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
3256 /*T(("No level 0 found for %d\n", chunkInInode)); */
3260 /* T(("Could not find %d to delete\n",chunkInInode)); */
3265 #ifdef YAFFS_PARANOID
3267 static int yaffs_CheckFileSanity(yaffs_Object * in)
3275 yaffs_Tags localTags;
3276 yaffs_Tags *tags = &localTags;
3280 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3281 /* T(("Object not a file\n")); */
3285 objId = in->objectId;
3286 fSize = in->variant.fileVariant.fileSize;
3288 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3290 for (chunk = 1; chunk <= nChunks; chunk++) {
3291 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3296 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
3298 if (yaffs_CheckChunkBits
3299 (dev, theChunk / dev->nChunksPerBlock,
3300 theChunk % dev->nChunksPerBlock)) {
3302 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3306 (tags, in->objectId, chunk, chunkDeleted)) {
3316 /* T(("No level 0 found for %d\n", chunk)); */
3320 return failed ? YAFFS_FAIL : YAFFS_OK;
3325 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
3326 int chunkInNAND, int inScan)
3328 /* NB inScan is zero unless scanning.
3329 * For forward scanning, inScan is > 0;
3330 * for backward scanning inScan is < 0
3334 yaffs_Device *dev = in->myDev;
3336 yaffs_ExtendedTags existingTags;
3337 yaffs_ExtendedTags newTags;
3338 unsigned existingSerial, newSerial;
3340 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3341 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3342 * If it is not during Scanning then something went wrong!
3345 T(YAFFS_TRACE_ERROR,
3347 ("yaffs tragedy:attempt to put data chunk into a non-file"
3352 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3356 tn = yaffs_AddOrFindLevel0Tnode(dev,
3357 &in->variant.fileVariant,
3364 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3367 /* If we're scanning then we need to test for duplicates
3368 * NB This does not need to be efficient since it should only ever
3369 * happen when the power fails during a write, then only one
3370 * chunk should ever be affected.
3372 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3373 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3376 if (existingChunk != 0) {
3377 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3378 * thus we have to do a FindChunkInFile to get the real chunk id.
3380 * We have a duplicate now we need to decide which one to use:
3382 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3383 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3384 * YAFFS1: Get both sets of tags and compare serial numbers.
3388 /* Only do this for forward scanning */
3389 yaffs_ReadChunkWithTagsFromNAND(dev,
3393 /* Do a proper find */
3395 yaffs_FindChunkInFile(in, chunkInInode,
3399 if (existingChunk <= 0) {
3400 /*Hoosterman - how did this happen? */
3402 T(YAFFS_TRACE_ERROR,
3404 ("yaffs tragedy: existing chunk < 0 in scan"
3409 /* NB The deleted flags should be false, otherwise the chunks will
3410 * not be loaded during a scan
3413 newSerial = newTags.serialNumber;
3414 existingSerial = existingTags.serialNumber;
3417 (in->myDev->isYaffs2 ||
3418 existingChunk <= 0 ||
3419 ((existingSerial + 1) & 3) == newSerial)) {
3420 /* Forward scanning.
3422 * Delete the old one and drop through to update the tnode
3424 yaffs_DeleteChunk(dev, existingChunk, 1,
3427 /* Backward scanning or we want to use the existing one
3429 * Delete the new one and return early so that the tnode isn't changed
3431 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3439 if (existingChunk == 0) {
3443 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
3448 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
3451 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3453 if (chunkInNAND >= 0) {
3454 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3457 T(YAFFS_TRACE_NANDACCESS,
3458 (TSTR("Chunk %d not found zero instead" TENDSTR),
3460 /* get sane (zero) data if you read a hole */
3461 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3467 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
3471 yaffs_ExtendedTags tags;
3472 yaffs_BlockInfo *bi;
3479 block = chunkId / dev->nChunksPerBlock;
3480 page = chunkId % dev->nChunksPerBlock;
3483 if(!yaffs_CheckChunkBit(dev,block,page))
3484 T(YAFFS_TRACE_VERIFY,
3485 (TSTR("Deleting invalid chunk %d"TENDSTR),
3488 bi = yaffs_GetBlockInfo(dev, block);
3490 T(YAFFS_TRACE_DELETION,
3491 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3494 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3496 yaffs_InitialiseTags(&tags);
3498 tags.chunkDeleted = 1;
3500 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3501 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3503 dev->nUnmarkedDeletions++;
3506 /* Pull out of the management area.
3507 * If the whole block became dirty, this will kick off an erasure.
3509 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3510 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3511 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3512 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3515 yaffs_ClearChunkBit(dev, block, page);
3519 if (bi->pagesInUse == 0 &&
3520 !bi->hasShrinkHeader &&
3521 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3522 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3523 yaffs_BlockBecameDirty(dev, block);
3527 /* T(("Bad news deleting chunk %d\n",chunkId)); */
3532 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
3533 const __u8 * buffer, int nBytes,
3536 /* Find old chunk Need to do this to get serial number
3537 * Write new one and patch into tree.
3538 * Invalidate old tags.
3542 yaffs_ExtendedTags prevTags;
3545 yaffs_ExtendedTags newTags;
3547 yaffs_Device *dev = in->myDev;
3549 yaffs_CheckGarbageCollection(dev);
3551 /* Get the previous chunk at this location in the file if it exists */
3552 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3554 /* Set up new tags */
3555 yaffs_InitialiseTags(&newTags);
3557 newTags.chunkId = chunkInInode;
3558 newTags.objectId = in->objectId;
3559 newTags.serialNumber =
3560 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
3561 newTags.byteCount = nBytes;
3564 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3567 if (newChunkId >= 0) {
3568 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3570 if (prevChunkId >= 0) {
3571 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3575 yaffs_CheckFileSanity(in);
3581 /* UpdateObjectHeader updates the header on NAND for an object.
3582 * If name is not NULL, then that new name is used.
3584 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
3585 int isShrink, int shadows)
3588 yaffs_BlockInfo *bi;
3590 yaffs_Device *dev = in->myDev;
3597 yaffs_ExtendedTags newTags;
3598 yaffs_ExtendedTags oldTags;
3600 __u8 *buffer = NULL;
3601 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3603 yaffs_ObjectHeader *oh = NULL;
3605 yaffs_strcpy(oldName,"silly old name");
3607 if (!in->fake || force) {
3609 yaffs_CheckGarbageCollection(dev);
3610 yaffs_CheckObjectDetailsLoaded(in);
3612 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3613 oh = (yaffs_ObjectHeader *) buffer;
3615 prevChunkId = in->chunkId;
3617 if (prevChunkId >= 0) {
3618 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3621 yaffs_VerifyObjectHeader(in,oh,&oldTags,0);
3623 memcpy(oldName, oh->name, sizeof(oh->name));
3626 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3628 oh->type = in->variantType;
3629 oh->yst_mode = in->yst_mode;
3630 oh->shadowsObject = shadows;
3632 #ifdef CONFIG_YAFFS_WINCE
3633 oh->win_atime[0] = in->win_atime[0];
3634 oh->win_ctime[0] = in->win_ctime[0];
3635 oh->win_mtime[0] = in->win_mtime[0];
3636 oh->win_atime[1] = in->win_atime[1];
3637 oh->win_ctime[1] = in->win_ctime[1];
3638 oh->win_mtime[1] = in->win_mtime[1];
3640 oh->yst_uid = in->yst_uid;
3641 oh->yst_gid = in->yst_gid;
3642 oh->yst_atime = in->yst_atime;
3643 oh->yst_mtime = in->yst_mtime;
3644 oh->yst_ctime = in->yst_ctime;
3645 oh->yst_rdev = in->yst_rdev;
3648 oh->parentObjectId = in->parent->objectId;
3650 oh->parentObjectId = 0;
3653 if (name && *name) {
3654 memset(oh->name, 0, sizeof(oh->name));
3655 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3656 } else if (prevChunkId>=0) {
3657 memcpy(oh->name, oldName, sizeof(oh->name));
3659 memset(oh->name, 0, sizeof(oh->name));
3662 oh->isShrink = isShrink;
3664 switch (in->variantType) {
3665 case YAFFS_OBJECT_TYPE_UNKNOWN:
3666 /* Should not happen */
3668 case YAFFS_OBJECT_TYPE_FILE:
3670 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3671 || oh->parentObjectId ==
3672 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3673 fileVariant.fileSize;
3675 case YAFFS_OBJECT_TYPE_HARDLINK:
3676 oh->equivalentObjectId =
3677 in->variant.hardLinkVariant.equivalentObjectId;
3679 case YAFFS_OBJECT_TYPE_SPECIAL:
3682 case YAFFS_OBJECT_TYPE_DIRECTORY:
3685 case YAFFS_OBJECT_TYPE_SYMLINK:
3686 yaffs_strncpy(oh->alias,
3687 in->variant.symLinkVariant.alias,
3688 YAFFS_MAX_ALIAS_LENGTH);
3689 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3694 yaffs_InitialiseTags(&newTags);
3696 newTags.chunkId = 0;
3697 newTags.objectId = in->objectId;
3698 newTags.serialNumber = in->serial;
3700 /* Add extra info for file header */
3702 newTags.extraHeaderInfoAvailable = 1;
3703 newTags.extraParentObjectId = oh->parentObjectId;
3704 newTags.extraFileLength = oh->fileSize;
3705 newTags.extraIsShrinkHeader = oh->isShrink;
3706 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3707 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3708 newTags.extraObjectType = in->variantType;
3710 yaffs_VerifyObjectHeader(in,oh,&newTags,1);
3712 /* Create new chunk in NAND */
3714 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3715 (prevChunkId >= 0) ? 1 : 0);
3717 if (newChunkId >= 0) {
3719 in->chunkId = newChunkId;
3721 if (prevChunkId >= 0) {
3722 yaffs_DeleteChunk(dev, prevChunkId, 1,
3726 if(!yaffs_ObjectHasCachedWriteData(in))
3729 /* If this was a shrink, then mark the block that the chunk lives on */
3731 bi = yaffs_GetBlockInfo(in->myDev,
3732 newChunkId /in->myDev-> nChunksPerBlock);
3733 bi->hasShrinkHeader = 1;
3738 retVal = newChunkId;
3743 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3748 /*------------------------ Short Operations Cache ----------------------------------------
3749 * In many situations where there is no high level buffering (eg WinCE) a lot of
3750 * reads might be short sequential reads, and a lot of writes may be short
3751 * sequential writes. eg. scanning/writing a jpeg file.
3752 * In these cases, a short read/write cache can provide a huge perfomance benefit
3753 * with dumb-as-a-rock code.
3754 * In Linux, the page cache provides read buffering aand the short op cache provides write
3757 * There are a limited number (~10) of cache chunks per device so that we don't
3758 * need a very intelligent search.
3761 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3763 yaffs_Device *dev = obj->myDev;
3765 yaffs_ChunkCache *cache;
3766 int nCaches = obj->myDev->nShortOpCaches;
3768 for(i = 0; i < nCaches; i++){
3769 cache = &dev->srCache[i];
3770 if (cache->object == obj &&
3779 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3781 yaffs_Device *dev = obj->myDev;
3782 int lowest = -99; /* Stop compiler whining. */
3784 yaffs_ChunkCache *cache;
3785 int chunkWritten = 0;
3786 int nCaches = obj->myDev->nShortOpCaches;
3792 /* Find the dirty cache for this object with the lowest chunk id. */
3793 for (i = 0; i < nCaches; i++) {
3794 if (dev->srCache[i].object == obj &&
3795 dev->srCache[i].dirty) {
3797 || dev->srCache[i].chunkId <
3799 cache = &dev->srCache[i];
3800 lowest = cache->chunkId;
3805 if (cache && !cache->locked) {
3806 /* Write it out and free it up */
3809 yaffs_WriteChunkDataToObject(cache->object,
3815 cache->object = NULL;
3818 } while (cache && chunkWritten > 0);
3821 /* Hoosterman, disk full while writing cache out. */
3822 T(YAFFS_TRACE_ERROR,
3823 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3830 /*yaffs_FlushEntireDeviceCache(dev)
3835 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3838 int nCaches = dev->nShortOpCaches;
3841 /* Find a dirty object in the cache and flush it...
3842 * until there are no further dirty objects.
3846 for( i = 0; i < nCaches && !obj; i++) {
3847 if (dev->srCache[i].object &&
3848 dev->srCache[i].dirty)
3849 obj = dev->srCache[i].object;
3853 yaffs_FlushFilesChunkCache(obj);
3860 /* Grab us a cache chunk for use.
3861 * First look for an empty one.
3862 * Then look for the least recently used non-dirty one.
3863 * Then look for the least recently used dirty one...., flush and look again.
3865 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
3871 if (dev->nShortOpCaches > 0) {
3872 for (i = 0; i < dev->nShortOpCaches; i++) {
3873 if (!dev->srCache[i].object)
3874 return &dev->srCache[i];
3880 usage = 0; /* just to stop the compiler grizzling */
3882 for (i = 0; i < dev->nShortOpCaches; i++) {
3883 if (!dev->srCache[i].dirty &&
3884 ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
3886 usage = dev->srCache[i].lastUse;
3892 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3899 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
3901 yaffs_ChunkCache *cache;
3902 yaffs_Object *theObj;
3907 if (dev->nShortOpCaches > 0) {
3908 /* Try find a non-dirty one... */
3910 cache = yaffs_GrabChunkCacheWorker(dev);
3913 /* They were all dirty, find the last recently used object and flush
3914 * its cache, then find again.
3915 * NB what's here is not very accurate, we actually flush the object
3916 * the last recently used page.
3919 /* With locking we can't assume we can use entry zero */
3926 for (i = 0; i < dev->nShortOpCaches; i++) {
3927 if (dev->srCache[i].object &&
3928 !dev->srCache[i].locked &&
3929 (dev->srCache[i].lastUse < usage || !cache))
3931 usage = dev->srCache[i].lastUse;
3932 theObj = dev->srCache[i].object;
3933 cache = &dev->srCache[i];
3938 if (!cache || cache->dirty) {
3939 /* Flush and try again */
3940 yaffs_FlushFilesChunkCache(theObj);
3941 cache = yaffs_GrabChunkCacheWorker(dev);
3951 /* Find a cached chunk */
3952 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
3955 yaffs_Device *dev = obj->myDev;
3957 if (dev->nShortOpCaches > 0) {
3958 for (i = 0; i < dev->nShortOpCaches; i++) {
3959 if (dev->srCache[i].object == obj &&
3960 dev->srCache[i].chunkId == chunkId) {
3963 return &dev->srCache[i];
3970 /* Mark the chunk for the least recently used algorithym */
3971 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
3975 if (dev->nShortOpCaches > 0) {
3976 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
3977 /* Reset the cache usages */
3979 for (i = 1; i < dev->nShortOpCaches; i++) {
3980 dev->srCache[i].lastUse = 0;
3987 cache->lastUse = dev->srLastUse;
3995 /* Invalidate a single cache page.
3996 * Do this when a whole page gets written,
3997 * ie the short cache for this page is no longer valid.
3999 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
4001 if (object->myDev->nShortOpCaches > 0) {
4002 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4005 cache->object = NULL;
4010 /* Invalidate all the cache pages associated with this object
4011 * Do this whenever ther file is deleted or resized.
4013 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
4016 yaffs_Device *dev = in->myDev;
4018 if (dev->nShortOpCaches > 0) {
4019 /* Invalidate it. */
4020 for (i = 0; i < dev->nShortOpCaches; i++) {
4021 if (dev->srCache[i].object == in) {
4022 dev->srCache[i].object = NULL;
4028 /*--------------------- Checkpointing --------------------*/
4031 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
4033 yaffs_CheckpointValidity cp;
4035 memset(&cp,0,sizeof(cp));
4037 cp.structType = sizeof(cp);
4038 cp.magic = YAFFS_MAGIC;
4039 cp.version = YAFFS_CHECKPOINT_VERSION;
4040 cp.head = (head) ? 1 : 0;
4042 return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
4046 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4048 yaffs_CheckpointValidity cp;
4051 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4054 ok = (cp.structType == sizeof(cp)) &&
4055 (cp.magic == YAFFS_MAGIC) &&
4056 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4057 (cp.head == ((head) ? 1 : 0));
4061 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4064 cp->nErasedBlocks = dev->nErasedBlocks;
4065 cp->allocationBlock = dev->allocationBlock;
4066 cp->allocationPage = dev->allocationPage;
4067 cp->nFreeChunks = dev->nFreeChunks;
4069 cp->nDeletedFiles = dev->nDeletedFiles;
4070 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4071 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4072 cp->sequenceNumber = dev->sequenceNumber;
4073 cp->oldestDirtySequence = dev->oldestDirtySequence;
4077 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4078 yaffs_CheckpointDevice *cp)
4080 dev->nErasedBlocks = cp->nErasedBlocks;
4081 dev->allocationBlock = cp->allocationBlock;
4082 dev->allocationPage = cp->allocationPage;
4083 dev->nFreeChunks = cp->nFreeChunks;
4085 dev->nDeletedFiles = cp->nDeletedFiles;
4086 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4087 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4088 dev->sequenceNumber = cp->sequenceNumber;
4089 dev->oldestDirtySequence = cp->oldestDirtySequence;
4093 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4095 yaffs_CheckpointDevice cp;
4097 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4101 /* Write device runtime values*/
4102 yaffs_DeviceToCheckpointDevice(&cp,dev);
4103 cp.structType = sizeof(cp);
4105 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4107 /* Write block info */
4109 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4110 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
4113 /* Write chunk bits */
4115 nBytes = nBlocks * dev->chunkBitmapStride;
4116 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
4122 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4124 yaffs_CheckpointDevice cp;
4126 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4130 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4134 if(cp.structType != sizeof(cp))
4138 yaffs_CheckpointDeviceToDevice(dev,&cp);
4140 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4142 ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
4146 nBytes = nBlocks * dev->chunkBitmapStride;
4148 ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
4153 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4157 cp->objectId = obj->objectId;
4158 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4159 cp->chunkId = obj->chunkId;
4160 cp->variantType = obj->variantType;
4161 cp->deleted = obj->deleted;
4162 cp->softDeleted = obj->softDeleted;
4163 cp->unlinked = obj->unlinked;
4164 cp->fake = obj->fake;
4165 cp->renameAllowed = obj->renameAllowed;
4166 cp->unlinkAllowed = obj->unlinkAllowed;
4167 cp->serial = obj->serial;
4168 cp->nDataChunks = obj->nDataChunks;
4170 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4171 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4172 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4173 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4176 static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
4179 yaffs_Object *parent;
4181 obj->objectId = cp->objectId;
4184 parent = yaffs_FindOrCreateObjectByNumber(
4187 YAFFS_OBJECT_TYPE_DIRECTORY);
4192 yaffs_AddObjectToDirectory(parent, obj);
4194 obj->chunkId = cp->chunkId;
4195 obj->variantType = cp->variantType;
4196 obj->deleted = cp->deleted;
4197 obj->softDeleted = cp->softDeleted;
4198 obj->unlinked = cp->unlinked;
4199 obj->fake = cp->fake;
4200 obj->renameAllowed = cp->renameAllowed;
4201 obj->unlinkAllowed = cp->unlinkAllowed;
4202 obj->serial = cp->serial;
4203 obj->nDataChunks = cp->nDataChunks;
4205 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4206 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4207 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4208 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4210 if(obj->objectId >= YAFFS_NOBJECT_BUCKETS)
4211 obj->lazyLoaded = 1;
4216 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
4217 __u32 level, int chunkOffset)
4220 yaffs_Device *dev = in->myDev;
4222 int nTnodeBytes = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4227 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
4228 if (tn->internal[i]) {
4229 ok = yaffs_CheckpointTnodeWorker(in,
4232 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4235 } else if (level == 0) {
4236 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4237 /* printf("write tnode at %d\n",baseOffset); */
4238 ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
4240 ok = (yaffs_CheckpointWrite(dev,tn,nTnodeBytes) == nTnodeBytes);
4248 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4250 __u32 endMarker = ~0;
4253 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4254 ok = yaffs_CheckpointTnodeWorker(obj,
4255 obj->variant.fileVariant.top,
4256 obj->variant.fileVariant.topLevel,
4259 ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) ==
4266 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4270 yaffs_Device *dev = obj->myDev;
4271 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4275 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4277 while(ok && (~baseChunk)){
4279 /* Read level 0 tnode */
4282 /* printf("read tnode at %d\n",baseChunk); */
4283 tn = yaffs_GetTnodeRaw(dev);
4285 ok = (yaffs_CheckpointRead(dev,tn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8) ==
4286 (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
4291 ok = yaffs_AddOrFindLevel0Tnode(dev,
4299 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4303 T(YAFFS_TRACE_CHECKPOINT,(
4304 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4305 nread,baseChunk,ok));
4311 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4314 yaffs_CheckpointObject cp;
4317 struct list_head *lh;
4320 /* Iterate through the objects in each hash entry,
4321 * dumping them to the checkpointing stream.
4324 for(i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++){
4325 list_for_each(lh, &dev->objectBucket[i].list) {
4327 obj = list_entry(lh, yaffs_Object, hashLink);
4328 if (!obj->deferedFree) {
4329 yaffs_ObjectToCheckpointObject(&cp,obj);
4330 cp.structType = sizeof(cp);
4332 T(YAFFS_TRACE_CHECKPOINT,(
4333 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
4334 cp.objectId,cp.parentId,cp.variantType,cp.chunkId,(unsigned) obj));
4336 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4338 if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4339 ok = yaffs_WriteCheckpointTnodes(obj);
4346 /* Dump end of list */
4347 memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
4348 cp.structType = sizeof(cp);
4351 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4356 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4359 yaffs_CheckpointObject cp;
4362 yaffs_Object *hardList = NULL;
4364 while(ok && !done) {
4365 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4366 if(cp.structType != sizeof(cp)) {
4367 T(YAFFS_TRACE_CHECKPOINT,(TSTR("struct size %d instead of %d ok %d"TENDSTR),
4368 cp.structType,sizeof(cp),ok));
4372 T(YAFFS_TRACE_CHECKPOINT,(TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4373 cp.objectId,cp.parentId,cp.variantType,cp.chunkId));
4375 if(ok && cp.objectId == ~0)
4378 obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
4380 yaffs_CheckpointObjectToObject(obj,&cp);
4381 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4382 ok = yaffs_ReadCheckpointTnodes(obj);
4383 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4384 obj->hardLinks.next =
4385 (struct list_head *)
4395 yaffs_HardlinkFixup(dev,hardList);
4400 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4402 __u32 checkpointSum;
4405 yaffs_GetCheckpointSum(dev,&checkpointSum);
4407 ok = (yaffs_CheckpointWrite(dev,&checkpointSum,sizeof(checkpointSum)) == sizeof(checkpointSum));
4415 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4417 __u32 checkpointSum0;
4418 __u32 checkpointSum1;
4421 yaffs_GetCheckpointSum(dev,&checkpointSum0);
4423 ok = (yaffs_CheckpointRead(dev,&checkpointSum1,sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4428 if(checkpointSum0 != checkpointSum1)
4435 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4440 if(dev->skipCheckpointWrite || !dev->isYaffs2){
4441 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint write" TENDSTR)));
4446 ok = yaffs_CheckpointOpen(dev,1);
4449 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4450 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
4453 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint device" TENDSTR)));
4454 ok = yaffs_WriteCheckpointDevice(dev);
4457 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint objects" TENDSTR)));
4458 ok = yaffs_WriteCheckpointObjects(dev);
4461 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4462 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
4466 ok = yaffs_WriteCheckpointSum(dev);
4470 if(!yaffs_CheckpointClose(dev))
4474 dev->isCheckpointed = 1;
4476 dev->isCheckpointed = 0;
4478 return dev->isCheckpointed;
4481 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4485 if(dev->skipCheckpointRead || !dev->isYaffs2){
4486 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint read" TENDSTR)));
4491 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
4494 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4495 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
4498 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint device" TENDSTR)));
4499 ok = yaffs_ReadCheckpointDevice(dev);
4502 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint objects" TENDSTR)));
4503 ok = yaffs_ReadCheckpointObjects(dev);
4506 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4507 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
4511 ok = yaffs_ReadCheckpointSum(dev);
4512 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint checksum %d" TENDSTR),ok));
4515 if(!yaffs_CheckpointClose(dev))
4519 dev->isCheckpointed = 1;
4521 dev->isCheckpointed = 0;
4527 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4529 if(dev->isCheckpointed ||
4530 dev->blocksInCheckpoint > 0){
4531 dev->isCheckpointed = 0;
4532 yaffs_CheckpointInvalidateStream(dev);
4533 if(dev->superBlock && dev->markSuperBlockDirty)
4534 dev->markSuperBlockDirty(dev->superBlock);
4539 int yaffs_CheckpointSave(yaffs_Device *dev)
4542 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4544 yaffs_VerifyObjects(dev);
4545 yaffs_VerifyBlocks(dev);
4546 yaffs_VerifyFreeChunks(dev);
4548 if(!dev->isCheckpointed) {
4549 yaffs_InvalidateCheckpoint(dev);
4550 yaffs_WriteCheckpointData(dev);
4553 T(YAFFS_TRACE_ALWAYS,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4555 return dev->isCheckpointed;
4558 int yaffs_CheckpointRestore(yaffs_Device *dev)
4561 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4563 retval = yaffs_ReadCheckpointData(dev);
4565 if(dev->isCheckpointed){
4566 yaffs_VerifyObjects(dev);
4567 yaffs_VerifyBlocks(dev);
4568 yaffs_VerifyFreeChunks(dev);
4571 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4576 /*--------------------- File read/write ------------------------
4577 * Read and write have very similar structures.
4578 * In general the read/write has three parts to it
4579 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4580 * Some complete chunks
4581 * An incomplete chunk to end off with
4583 * Curve-balls: the first chunk might also be the last chunk.
4586 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, loff_t offset,
4595 yaffs_ChunkCache *cache;
4602 //chunk = offset / dev->nDataBytesPerChunk + 1;
4603 //start = offset % dev->nDataBytesPerChunk;
4604 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4607 /* OK now check for the curveball where the start and end are in
4610 if ((start + n) < dev->nDataBytesPerChunk) {
4613 nToCopy = dev->nDataBytesPerChunk - start;
4616 cache = yaffs_FindChunkCache(in, chunk);
4618 /* If the chunk is already in the cache or it is less than a whole chunk
4619 * then use the cache (if there is caching)
4620 * else bypass the cache.
4622 if (cache || nToCopy != dev->nDataBytesPerChunk) {
4623 if (dev->nShortOpCaches > 0) {
4625 /* If we can't find the data in the cache, then load it up. */
4628 cache = yaffs_GrabChunkCache(in->myDev);
4630 cache->chunkId = chunk;
4633 yaffs_ReadChunkDataFromObject(in, chunk,
4639 yaffs_UseChunkCache(dev, cache, 0);
4643 #ifdef CONFIG_YAFFS_WINCE
4644 yfsd_UnlockYAFFS(TRUE);
4646 memcpy(buffer, &cache->data[start], nToCopy);
4648 #ifdef CONFIG_YAFFS_WINCE
4649 yfsd_LockYAFFS(TRUE);
4653 /* Read into the local buffer then copy..*/
4656 yaffs_GetTempBuffer(dev, __LINE__);
4657 yaffs_ReadChunkDataFromObject(in, chunk,
4659 #ifdef CONFIG_YAFFS_WINCE
4660 yfsd_UnlockYAFFS(TRUE);
4662 memcpy(buffer, &localBuffer[start], nToCopy);
4664 #ifdef CONFIG_YAFFS_WINCE
4665 yfsd_LockYAFFS(TRUE);
4667 yaffs_ReleaseTempBuffer(dev, localBuffer,
4672 #ifdef CONFIG_YAFFS_WINCE
4673 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4675 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4676 * This is because we otherwise screw up WinCE's memory mapper
4678 yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
4680 #ifdef CONFIG_YAFFS_WINCE
4681 yfsd_UnlockYAFFS(TRUE);
4683 memcpy(buffer, localBuffer, dev->nDataBytesPerChunk);
4685 #ifdef CONFIG_YAFFS_WINCE
4686 yfsd_LockYAFFS(TRUE);
4687 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4691 /* A full chunk. Read directly into the supplied buffer. */
4692 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4706 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, loff_t offset,
4707 int nBytes, int writeThrough)
4716 int startOfWrite = offset;
4717 int chunkWritten = 0;
4724 while (n > 0 && chunkWritten >= 0) {
4725 //chunk = offset / dev->nDataBytesPerChunk + 1;
4726 //start = offset % dev->nDataBytesPerChunk;
4727 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4730 /* OK now check for the curveball where the start and end are in
4734 if ((start + n) < dev->nDataBytesPerChunk) {
4737 /* Now folks, to calculate how many bytes to write back....
4738 * If we're overwriting and not writing to then end of file then
4739 * we need to write back as much as was there before.
4743 in->variant.fileVariant.fileSize -
4744 ((chunk - 1) * dev->nDataBytesPerChunk);
4746 if (nBytesRead > dev->nDataBytesPerChunk) {
4747 nBytesRead = dev->nDataBytesPerChunk;
4752 (start + n)) ? nBytesRead : (start + n);
4755 nToCopy = dev->nDataBytesPerChunk - start;
4756 nToWriteBack = dev->nDataBytesPerChunk;
4759 if (nToCopy != dev->nDataBytesPerChunk) {
4760 /* An incomplete start or end chunk (or maybe both start and end chunk) */
4761 if (dev->nShortOpCaches > 0) {
4762 yaffs_ChunkCache *cache;
4763 /* If we can't find the data in the cache, then load the cache */
4764 cache = yaffs_FindChunkCache(in, chunk);
4767 && yaffs_CheckSpaceForAllocation(in->
4769 cache = yaffs_GrabChunkCache(in->myDev);
4771 cache->chunkId = chunk;
4774 yaffs_ReadChunkDataFromObject(in, chunk,
4780 !yaffs_CheckSpaceForAllocation(in->myDev)){
4781 /* Drop the cache if it was a read cache item and
4782 * no space check has been made for it.
4788 yaffs_UseChunkCache(dev, cache, 1);
4790 #ifdef CONFIG_YAFFS_WINCE
4791 yfsd_UnlockYAFFS(TRUE);
4794 memcpy(&cache->data[start], buffer,
4797 #ifdef CONFIG_YAFFS_WINCE
4798 yfsd_LockYAFFS(TRUE);
4801 cache->nBytes = nToWriteBack;
4805 yaffs_WriteChunkDataToObject
4808 cache->data, cache->nBytes,
4814 chunkWritten = -1; /* fail the write */
4817 /* An incomplete start or end chunk (or maybe both start and end chunk)
4818 * Read into the local buffer then copy, then copy over and write back.
4822 yaffs_GetTempBuffer(dev, __LINE__);
4824 yaffs_ReadChunkDataFromObject(in, chunk,
4827 #ifdef CONFIG_YAFFS_WINCE
4828 yfsd_UnlockYAFFS(TRUE);
4831 memcpy(&localBuffer[start], buffer, nToCopy);
4833 #ifdef CONFIG_YAFFS_WINCE
4834 yfsd_LockYAFFS(TRUE);
4837 yaffs_WriteChunkDataToObject(in, chunk,
4842 yaffs_ReleaseTempBuffer(dev, localBuffer,
4849 #ifdef CONFIG_YAFFS_WINCE
4850 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4851 * This is because we otherwise screw up WinCE's memory mapper
4853 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4854 #ifdef CONFIG_YAFFS_WINCE
4855 yfsd_UnlockYAFFS(TRUE);
4857 memcpy(localBuffer, buffer, dev->nDataBytesPerChunk);
4858 #ifdef CONFIG_YAFFS_WINCE
4859 yfsd_LockYAFFS(TRUE);
4862 yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
4863 dev->nDataBytesPerChunk,
4865 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4867 /* A full chunk. Write directly from the supplied buffer. */
4869 yaffs_WriteChunkDataToObject(in, chunk, buffer,
4870 dev->nDataBytesPerChunk,
4873 /* Since we've overwritten the cached data, we better invalidate it. */
4874 yaffs_InvalidateChunkCache(in, chunk);
4877 if (chunkWritten >= 0) {
4886 /* Update file object */
4888 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
4889 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4898 /* ---------------------- File resizing stuff ------------------ */
4900 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
4903 yaffs_Device *dev = in->myDev;
4904 int oldFileSize = in->variant.fileVariant.fileSize;
4906 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
4908 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
4909 dev->nDataBytesPerChunk;
4913 /* Delete backwards so that we don't end up with holes if
4914 * power is lost part-way through the operation.
4916 for (i = lastDel; i >= startDel; i--) {
4917 /* NB this could be optimised somewhat,
4918 * eg. could retrieve the tags and write them without
4919 * using yaffs_DeleteChunk
4922 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
4925 (dev->internalStartBlock * dev->nChunksPerBlock)
4927 ((dev->internalEndBlock +
4928 1) * dev->nChunksPerBlock)) {
4929 T(YAFFS_TRACE_ALWAYS,
4930 (TSTR("Found daft chunkId %d for %d" TENDSTR),
4934 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
4941 int yaffs_ResizeFile(yaffs_Object * in, loff_t newSize)
4944 int oldFileSize = in->variant.fileVariant.fileSize;
4945 int newSizeOfPartialChunk;
4948 yaffs_Device *dev = in->myDev;
4950 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
4952 yaffs_FlushFilesChunkCache(in);
4953 yaffs_InvalidateWholeChunkCache(in);
4955 yaffs_CheckGarbageCollection(dev);
4957 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
4958 return yaffs_GetFileSize(in);
4961 if (newSize == oldFileSize) {
4965 if (newSize < oldFileSize) {
4967 yaffs_PruneResizedChunks(in, newSize);
4969 if (newSizeOfPartialChunk != 0) {
4970 int lastChunk = 1 + newFullChunks;
4972 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4974 /* Got to read and rewrite the last chunk with its new size and zero pad */
4975 yaffs_ReadChunkDataFromObject(in, lastChunk,
4978 memset(localBuffer + newSizeOfPartialChunk, 0,
4979 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
4981 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
4982 newSizeOfPartialChunk, 1);
4984 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4987 in->variant.fileVariant.fileSize = newSize;
4989 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
4991 /* newsSize > oldFileSize */
4992 in->variant.fileVariant.fileSize = newSize;
4997 /* Write a new object header.
4998 * show we've shrunk the file, if need be
4999 * Do this only if the file is not in the deleted directories.
5001 if (in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5002 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
5003 yaffs_UpdateObjectHeader(in, NULL, 0,
5004 (newSize < oldFileSize) ? 1 : 0, 0);
5010 loff_t yaffs_GetFileSize(yaffs_Object * obj)
5012 obj = yaffs_GetEquivalentObject(obj);
5014 switch (obj->variantType) {
5015 case YAFFS_OBJECT_TYPE_FILE:
5016 return obj->variant.fileVariant.fileSize;
5017 case YAFFS_OBJECT_TYPE_SYMLINK:
5018 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5026 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
5030 yaffs_FlushFilesChunkCache(in);
5032 #ifdef CONFIG_YAFFS_WINCE
5033 yfsd_WinFileTimeNow(in->win_mtime);
5036 in->yst_mtime = Y_CURRENT_TIME;
5042 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5043 0) ? YAFFS_OK : YAFFS_FAIL;
5052 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
5055 /* First off, invalidate the file's data in the cache, without flushing. */
5056 yaffs_InvalidateWholeChunkCache(in);
5058 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5059 /* Move to the unlinked directory so we have a record that it was deleted. */
5060 yaffs_ChangeObjectName(in, in->myDev->deletedDir,"deleted", 0, 0);
5064 yaffs_RemoveObjectFromDirectory(in);
5065 yaffs_DeleteChunk(in->myDev, in->chunkId, 1, __LINE__);
5068 yaffs_FreeObject(in);
5073 /* yaffs_DeleteFile deletes the whole file data
5074 * and the inode associated with the file.
5075 * It does not delete the links associated with the file.
5077 static int yaffs_UnlinkFile(yaffs_Object * in)
5081 int immediateDeletion = 0;
5086 immediateDeletion = 1;
5090 if (in->inUse <= 0) {
5091 immediateDeletion = 1;
5095 if (immediateDeletion) {
5097 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5099 T(YAFFS_TRACE_TRACING,
5100 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5103 in->myDev->nDeletedFiles++;
5104 if (0 && in->myDev->isYaffs2) {
5105 yaffs_ResizeFile(in, 0);
5107 yaffs_SoftDeleteFile(in);
5110 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5118 int yaffs_DeleteFile(yaffs_Object * in)
5120 int retVal = YAFFS_OK;
5122 if (in->nDataChunks > 0) {
5123 /* Use soft deletion if there is data in the file */
5124 if (!in->unlinked) {
5125 retVal = yaffs_UnlinkFile(in);
5127 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5129 in->myDev->nDeletedFiles++;
5130 yaffs_SoftDeleteFile(in);
5132 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
5134 /* The file has no data chunks so we toss it immediately */
5135 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5136 in->variant.fileVariant.top = NULL;
5137 yaffs_DoGenericObjectDeletion(in);
5143 static int yaffs_DeleteDirectory(yaffs_Object * in)
5145 /* First check that the directory is empty. */
5146 if (list_empty(&in->variant.directoryVariant.children)) {
5147 return yaffs_DoGenericObjectDeletion(in);
5154 static int yaffs_DeleteSymLink(yaffs_Object * in)
5156 YFREE(in->variant.symLinkVariant.alias);
5158 return yaffs_DoGenericObjectDeletion(in);
5161 static int yaffs_DeleteHardLink(yaffs_Object * in)
5163 /* remove this hardlink from the list assocaited with the equivalent
5166 list_del(&in->hardLinks);
5167 return yaffs_DoGenericObjectDeletion(in);
5170 static void yaffs_DestroyObject(yaffs_Object * obj)
5172 switch (obj->variantType) {
5173 case YAFFS_OBJECT_TYPE_FILE:
5174 yaffs_DeleteFile(obj);
5176 case YAFFS_OBJECT_TYPE_DIRECTORY:
5177 yaffs_DeleteDirectory(obj);
5179 case YAFFS_OBJECT_TYPE_SYMLINK:
5180 yaffs_DeleteSymLink(obj);
5182 case YAFFS_OBJECT_TYPE_HARDLINK:
5183 yaffs_DeleteHardLink(obj);
5185 case YAFFS_OBJECT_TYPE_SPECIAL:
5186 yaffs_DoGenericObjectDeletion(obj);
5188 case YAFFS_OBJECT_TYPE_UNKNOWN:
5189 break; /* should not happen. */
5193 static int yaffs_UnlinkWorker(yaffs_Object * obj)
5196 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5197 return yaffs_DeleteHardLink(obj);
5198 } else if (!list_empty(&obj->hardLinks)) {
5199 /* Curve ball: We're unlinking an object that has a hardlink.
5201 * This problem arises because we are not strictly following
5202 * The Linux link/inode model.
5204 * We can't really delete the object.
5205 * Instead, we do the following:
5206 * - Select a hardlink.
5207 * - Unhook it from the hard links
5208 * - Unhook it from its parent directory (so that the rename can work)
5209 * - Rename the object to the hardlink's name.
5210 * - Delete the hardlink
5215 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5217 hl = list_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5219 list_del_init(&hl->hardLinks);
5220 list_del_init(&hl->siblings);
5222 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5224 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
5226 if (retVal == YAFFS_OK) {
5227 retVal = yaffs_DoGenericObjectDeletion(hl);
5232 switch (obj->variantType) {
5233 case YAFFS_OBJECT_TYPE_FILE:
5234 return yaffs_UnlinkFile(obj);
5236 case YAFFS_OBJECT_TYPE_DIRECTORY:
5237 return yaffs_DeleteDirectory(obj);
5239 case YAFFS_OBJECT_TYPE_SYMLINK:
5240 return yaffs_DeleteSymLink(obj);
5242 case YAFFS_OBJECT_TYPE_SPECIAL:
5243 return yaffs_DoGenericObjectDeletion(obj);
5245 case YAFFS_OBJECT_TYPE_HARDLINK:
5246 case YAFFS_OBJECT_TYPE_UNKNOWN:
5254 static int yaffs_UnlinkObject( yaffs_Object *obj)
5257 if (obj && obj->unlinkAllowed) {
5258 return yaffs_UnlinkWorker(obj);
5264 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
5268 obj = yaffs_FindObjectByName(dir, name);
5269 return yaffs_UnlinkObject(obj);
5272 /*----------------------- Initialisation Scanning ---------------------- */
5274 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
5275 int backwardScanning)
5279 if (!backwardScanning) {
5280 /* Handle YAFFS1 forward scanning case
5281 * For YAFFS1 we always do the deletion
5285 /* Handle YAFFS2 case (backward scanning)
5286 * If the shadowed object exists then ignore.
5288 if (yaffs_FindObjectByNumber(dev, objId)) {
5293 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5294 * We put it in unlinked dir to be cleaned up after the scanning
5297 yaffs_FindOrCreateObjectByNumber(dev, objId,
5298 YAFFS_OBJECT_TYPE_FILE);
5299 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5300 obj->variant.fileVariant.shrinkSize = 0;
5301 obj->valid = 1; /* So that we don't read any other info for this file */
5311 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5318 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5320 in = yaffs_FindObjectByNumber(dev,
5321 hl->variant.hardLinkVariant.
5322 equivalentObjectId);
5325 /* Add the hardlink pointers */
5326 hl->variant.hardLinkVariant.equivalentObject = in;
5327 list_add(&hl->hardLinks, &in->hardLinks);
5329 /* Todo Need to report/handle this better.
5330 * Got a problem... hardlink to a non-existant object
5332 hl->variant.hardLinkVariant.equivalentObject = NULL;
5333 INIT_LIST_HEAD(&hl->hardLinks);
5345 static int ybicmp(const void *a, const void *b){
5346 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5347 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5348 register int ablock = ((yaffs_BlockIndex *)a)->block;
5349 register int bblock = ((yaffs_BlockIndex *)b)->block;
5351 return ablock - bblock;
5357 static int yaffs_Scan(yaffs_Device * dev)
5359 yaffs_ExtendedTags tags;
5364 int nBlocksToScan = 0;
5370 yaffs_BlockState state;
5371 yaffs_Object *hardList = NULL;
5372 yaffs_BlockInfo *bi;
5374 yaffs_ObjectHeader *oh;
5376 yaffs_Object *parent;
5377 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5379 int alloc_failed = 0;
5384 yaffs_BlockIndex *blockIndex = NULL;
5386 if (dev->isYaffs2) {
5388 (TSTR("yaffs_Scan is not for YAFFS2!" TENDSTR)));
5392 //TODO Throw all the yaffs2 stuuf out of yaffs_Scan since it is only for yaffs1 format.
5395 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5396 dev->internalStartBlock, dev->internalEndBlock));
5398 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5400 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5402 if (dev->isYaffs2) {
5403 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
5408 /* Scan all the blocks to determine their state */
5409 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5410 bi = yaffs_GetBlockInfo(dev, blk);
5411 yaffs_ClearChunkBits(dev, blk);
5413 bi->softDeletions = 0;
5415 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5417 bi->blockState = state;
5418 bi->sequenceNumber = sequenceNumber;
5420 T(YAFFS_TRACE_SCAN_DEBUG,
5421 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5422 state, sequenceNumber));
5424 if (state == YAFFS_BLOCK_STATE_DEAD) {
5425 T(YAFFS_TRACE_BAD_BLOCKS,
5426 (TSTR("block %d is bad" TENDSTR), blk));
5427 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5428 T(YAFFS_TRACE_SCAN_DEBUG,
5429 (TSTR("Block empty " TENDSTR)));
5430 dev->nErasedBlocks++;
5431 dev->nFreeChunks += dev->nChunksPerBlock;
5432 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5434 /* Determine the highest sequence number */
5435 if (dev->isYaffs2 &&
5436 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
5437 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
5439 blockIndex[nBlocksToScan].seq = sequenceNumber;
5440 blockIndex[nBlocksToScan].block = blk;
5444 if (sequenceNumber >= dev->sequenceNumber) {
5445 dev->sequenceNumber = sequenceNumber;
5447 } else if (dev->isYaffs2) {
5448 /* TODO: Nasty sequence number! */
5451 ("Block scanning block %d has bad sequence number %d"
5452 TENDSTR), blk, sequenceNumber));
5459 * Dungy old bubble sort for now...
5461 if (dev->isYaffs2) {
5462 yaffs_BlockIndex temp;
5466 for (i = 0; i < nBlocksToScan; i++)
5467 for (j = i + 1; j < nBlocksToScan; j++)
5468 if (blockIndex[i].seq > blockIndex[j].seq) {
5469 temp = blockIndex[j];
5470 blockIndex[j] = blockIndex[i];
5471 blockIndex[i] = temp;
5475 /* Now scan the blocks looking at the data. */
5476 if (dev->isYaffs2) {
5478 endIterator = nBlocksToScan - 1;
5479 T(YAFFS_TRACE_SCAN_DEBUG,
5480 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
5482 startIterator = dev->internalStartBlock;
5483 endIterator = dev->internalEndBlock;
5486 /* For each block.... */
5487 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5490 if (dev->isYaffs2) {
5491 /* get the block to scan in the correct order */
5492 blk = blockIndex[blockIterator].block;
5494 blk = blockIterator;
5497 bi = yaffs_GetBlockInfo(dev, blk);
5498 state = bi->blockState;
5502 /* For each chunk in each block that needs scanning....*/
5503 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5504 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5505 /* Read the tags and decide what to do */
5506 chunk = blk * dev->nChunksPerBlock + c;
5508 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5511 /* Let's have a good look at this chunk... */
5513 if (!dev->isYaffs2 && tags.chunkDeleted) {
5519 /*T((" %d %d deleted\n",blk,c)); */
5520 } else if (!tags.chunkUsed) {
5521 /* An unassigned chunk in the block
5522 * This means that either the block is empty or
5523 * this is the one being allocated from
5527 /* We're looking at the first chunk in the block so the block is unused */
5528 state = YAFFS_BLOCK_STATE_EMPTY;
5529 dev->nErasedBlocks++;
5531 /* this is the block being allocated from */
5534 (" Allocating from %d %d" TENDSTR),
5536 state = YAFFS_BLOCK_STATE_ALLOCATING;
5537 dev->allocationBlock = blk;
5538 dev->allocationPage = c;
5539 dev->allocationBlockFinder = blk;
5540 /* Set it to here to encourage the allocator to go forth from here. */
5542 /* Yaffs2 sanity check:
5543 * This should be the one with the highest sequence number
5546 && (dev->sequenceNumber !=
5547 bi->sequenceNumber)) {
5548 T(YAFFS_TRACE_ALWAYS,
5550 ("yaffs: Allocation block %d was not highest sequence id:"
5551 " block seq = %d, dev seq = %d"
5552 TENDSTR), blk,bi->sequenceNumber,dev->sequenceNumber));
5556 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5557 } else if (tags.chunkId > 0) {
5558 /* chunkId > 0 so it is a data chunk... */
5559 unsigned int endpos;
5561 yaffs_SetChunkBit(dev, blk, c);
5564 in = yaffs_FindOrCreateObjectByNumber(dev,
5567 YAFFS_OBJECT_TYPE_FILE);
5568 /* PutChunkIntoFile checks for a clash (two data chunks with
5569 * the same chunkId).
5576 if(!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,1))
5581 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5584 in->variantType == YAFFS_OBJECT_TYPE_FILE
5585 && in->variant.fileVariant.scannedFileSize <
5587 in->variant.fileVariant.
5588 scannedFileSize = endpos;
5589 if (!dev->useHeaderFileSize) {
5590 in->variant.fileVariant.
5592 in->variant.fileVariant.
5597 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
5599 /* chunkId == 0, so it is an ObjectHeader.
5600 * Thus, we read in the object header and make the object
5602 yaffs_SetChunkBit(dev, blk, c);
5605 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5609 oh = (yaffs_ObjectHeader *) chunkData;
5611 in = yaffs_FindObjectByNumber(dev,
5613 if (in && in->variantType != oh->type) {
5614 /* This should not happen, but somehow
5615 * Wev'e ended up with an objectId that has been reused but not yet
5616 * deleted, and worse still it has changed type. Delete the old object.
5619 yaffs_DestroyObject(in);
5624 in = yaffs_FindOrCreateObjectByNumber(dev,
5632 if (in && oh->shadowsObject > 0) {
5633 yaffs_HandleShadowedObject(dev,
5639 if (in && in->valid) {
5640 /* We have already filled this one. We have a duplicate and need to resolve it. */
5642 unsigned existingSerial = in->serial;
5643 unsigned newSerial = tags.serialNumber;
5645 if (dev->isYaffs2 ||
5646 ((existingSerial + 1) & 3) ==
5648 /* Use new one - destroy the exisiting one */
5649 yaffs_DeleteChunk(dev,
5654 /* Use existing - destroy this one. */
5655 yaffs_DeleteChunk(dev, chunk, 1,
5660 if (in && !in->valid &&
5661 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5662 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5663 /* We only load some info, don't fiddle with directory structure */
5665 in->variantType = oh->type;
5667 in->yst_mode = oh->yst_mode;
5668 #ifdef CONFIG_YAFFS_WINCE
5669 in->win_atime[0] = oh->win_atime[0];
5670 in->win_ctime[0] = oh->win_ctime[0];
5671 in->win_mtime[0] = oh->win_mtime[0];
5672 in->win_atime[1] = oh->win_atime[1];
5673 in->win_ctime[1] = oh->win_ctime[1];
5674 in->win_mtime[1] = oh->win_mtime[1];
5676 in->yst_uid = oh->yst_uid;
5677 in->yst_gid = oh->yst_gid;
5678 in->yst_atime = oh->yst_atime;
5679 in->yst_mtime = oh->yst_mtime;
5680 in->yst_ctime = oh->yst_ctime;
5681 in->yst_rdev = oh->yst_rdev;
5683 in->chunkId = chunk;
5685 } else if (in && !in->valid) {
5686 /* we need to load this info */
5689 in->variantType = oh->type;
5691 in->yst_mode = oh->yst_mode;
5692 #ifdef CONFIG_YAFFS_WINCE
5693 in->win_atime[0] = oh->win_atime[0];
5694 in->win_ctime[0] = oh->win_ctime[0];
5695 in->win_mtime[0] = oh->win_mtime[0];
5696 in->win_atime[1] = oh->win_atime[1];
5697 in->win_ctime[1] = oh->win_ctime[1];
5698 in->win_mtime[1] = oh->win_mtime[1];
5700 in->yst_uid = oh->yst_uid;
5701 in->yst_gid = oh->yst_gid;
5702 in->yst_atime = oh->yst_atime;
5703 in->yst_mtime = oh->yst_mtime;
5704 in->yst_ctime = oh->yst_ctime;
5705 in->yst_rdev = oh->yst_rdev;
5707 in->chunkId = chunk;
5709 yaffs_SetObjectName(in, oh->name);
5712 /* directory stuff...
5717 yaffs_FindOrCreateObjectByNumber
5718 (dev, oh->parentObjectId,
5719 YAFFS_OBJECT_TYPE_DIRECTORY);
5720 if (parent->variantType ==
5721 YAFFS_OBJECT_TYPE_UNKNOWN) {
5722 /* Set up as a directory */
5723 parent->variantType =
5724 YAFFS_OBJECT_TYPE_DIRECTORY;
5725 INIT_LIST_HEAD(&parent->variant.
5728 } else if (parent->variantType !=
5729 YAFFS_OBJECT_TYPE_DIRECTORY)
5731 /* Hoosterman, another problem....
5732 * We're trying to use a non-directory as a directory
5735 T(YAFFS_TRACE_ERROR,
5737 ("yaffs tragedy: attempting to use non-directory as"
5738 " a directory in scan. Put in lost+found."
5740 parent = dev->lostNFoundDir;
5743 yaffs_AddObjectToDirectory(parent, in);
5745 if (0 && (parent == dev->deletedDir ||
5746 parent == dev->unlinkedDir)) {
5747 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
5748 dev->nDeletedFiles++;
5750 /* Note re hardlinks.
5751 * Since we might scan a hardlink before its equivalent object is scanned
5752 * we put them all in a list.
5753 * After scanning is complete, we should have all the objects, so we run through this
5754 * list and fix up all the chains.
5757 switch (in->variantType) {
5758 case YAFFS_OBJECT_TYPE_UNKNOWN:
5759 /* Todo got a problem */
5761 case YAFFS_OBJECT_TYPE_FILE:
5764 /* Prune back the shrunken chunks */
5765 yaffs_PruneResizedChunks
5767 /* Mark the block as having a shrinkHeader */
5768 bi->hasShrinkHeader = 1;
5771 if (dev->useHeaderFileSize)
5773 in->variant.fileVariant.
5778 case YAFFS_OBJECT_TYPE_HARDLINK:
5779 in->variant.hardLinkVariant.
5780 equivalentObjectId =
5781 oh->equivalentObjectId;
5782 in->hardLinks.next =
5783 (struct list_head *)
5787 case YAFFS_OBJECT_TYPE_DIRECTORY:
5790 case YAFFS_OBJECT_TYPE_SPECIAL:
5793 case YAFFS_OBJECT_TYPE_SYMLINK:
5794 in->variant.symLinkVariant.alias =
5795 yaffs_CloneString(oh->alias);
5796 if(!in->variant.symLinkVariant.alias)
5801 if (parent == dev->deletedDir) {
5802 yaffs_DestroyObject(in);
5803 bi->hasShrinkHeader = 1;
5809 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5810 /* If we got this far while scanning, then the block is fully allocated.*/
5811 state = YAFFS_BLOCK_STATE_FULL;
5814 bi->blockState = state;
5816 /* Now let's see if it was dirty */
5817 if (bi->pagesInUse == 0 &&
5818 !bi->hasShrinkHeader &&
5819 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5820 yaffs_BlockBecameDirty(dev, blk);
5830 /* Ok, we've done all the scanning.
5831 * Fix up the hard link chains.
5832 * We should now have scanned all the objects, now it's time to add these
5836 yaffs_HardlinkFixup(dev,hardList);
5838 /* Handle the unlinked files. Since they were left in an unlinked state we should
5842 struct list_head *i;
5843 struct list_head *n;
5846 /* Soft delete all the unlinked files */
5847 list_for_each_safe(i, n,
5848 &dev->unlinkedDir->variant.directoryVariant.
5851 l = list_entry(i, yaffs_Object, siblings);
5852 yaffs_DestroyObject(l);
5857 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5863 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5869 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5872 yaffs_ObjectHeader *oh;
5873 yaffs_Device *dev = in->myDev;
5874 yaffs_ExtendedTags tags;
5876 int alloc_failed = 0;
5882 T(YAFFS_TRACE_SCAN,(TSTR("details for object %d %s loaded" TENDSTR),
5884 in->lazyLoaded ? "not yet" : "already"));
5889 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5891 result = yaffs_ReadChunkWithTagsFromNAND(dev,in->chunkId,chunkData,&tags);
5892 oh = (yaffs_ObjectHeader *) chunkData;
5894 in->yst_mode = oh->yst_mode;
5895 #ifdef CONFIG_YAFFS_WINCE
5896 in->win_atime[0] = oh->win_atime[0];
5897 in->win_ctime[0] = oh->win_ctime[0];
5898 in->win_mtime[0] = oh->win_mtime[0];
5899 in->win_atime[1] = oh->win_atime[1];
5900 in->win_ctime[1] = oh->win_ctime[1];
5901 in->win_mtime[1] = oh->win_mtime[1];
5903 in->yst_uid = oh->yst_uid;
5904 in->yst_gid = oh->yst_gid;
5905 in->yst_atime = oh->yst_atime;
5906 in->yst_mtime = oh->yst_mtime;
5907 in->yst_ctime = oh->yst_ctime;
5908 in->yst_rdev = oh->yst_rdev;
5911 yaffs_SetObjectName(in, oh->name);
5913 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
5914 in->variant.symLinkVariant.alias =
5915 yaffs_CloneString(oh->alias);
5916 if(!in->variant.symLinkVariant.alias)
5917 alloc_failed = 1; /* Not returned to caller */
5920 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
5924 static int yaffs_ScanBackwards(yaffs_Device * dev)
5926 yaffs_ExtendedTags tags;
5931 int nBlocksToScan = 0;
5937 yaffs_BlockState state;
5938 yaffs_Object *hardList = NULL;
5939 yaffs_BlockInfo *bi;
5941 yaffs_ObjectHeader *oh;
5943 yaffs_Object *parent;
5944 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5950 int foundChunksInBlock;
5951 int equivalentObjectId;
5952 int alloc_failed = 0;
5955 yaffs_BlockIndex *blockIndex = NULL;
5956 int altBlockIndex = 0;
5958 if (!dev->isYaffs2) {
5960 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
5966 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
5967 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
5970 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5972 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
5975 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
5981 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
5985 dev->blocksInCheckpoint = 0;
5987 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5989 /* Scan all the blocks to determine their state */
5990 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5991 bi = yaffs_GetBlockInfo(dev, blk);
5992 yaffs_ClearChunkBits(dev, blk);
5994 bi->softDeletions = 0;
5996 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5998 bi->blockState = state;
5999 bi->sequenceNumber = sequenceNumber;
6001 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6002 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6004 T(YAFFS_TRACE_SCAN_DEBUG,
6005 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6006 state, sequenceNumber));
6009 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
6010 dev->blocksInCheckpoint++;
6012 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6013 T(YAFFS_TRACE_BAD_BLOCKS,
6014 (TSTR("block %d is bad" TENDSTR), blk));
6015 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6016 T(YAFFS_TRACE_SCAN_DEBUG,
6017 (TSTR("Block empty " TENDSTR)));
6018 dev->nErasedBlocks++;
6019 dev->nFreeChunks += dev->nChunksPerBlock;
6020 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6022 /* Determine the highest sequence number */
6023 if (dev->isYaffs2 &&
6024 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6025 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6027 blockIndex[nBlocksToScan].seq = sequenceNumber;
6028 blockIndex[nBlocksToScan].block = blk;
6032 if (sequenceNumber >= dev->sequenceNumber) {
6033 dev->sequenceNumber = sequenceNumber;
6035 } else if (dev->isYaffs2) {
6036 /* TODO: Nasty sequence number! */
6039 ("Block scanning block %d has bad sequence number %d"
6040 TENDSTR), blk, sequenceNumber));
6047 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6053 /* Sort the blocks */
6054 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6055 yaffs_qsort(blockIndex, nBlocksToScan,
6056 sizeof(yaffs_BlockIndex), ybicmp);
6059 /* Dungy old bubble sort... */
6061 yaffs_BlockIndex temp;
6065 for (i = 0; i < nBlocksToScan; i++)
6066 for (j = i + 1; j < nBlocksToScan; j++)
6067 if (blockIndex[i].seq > blockIndex[j].seq) {
6068 temp = blockIndex[j];
6069 blockIndex[j] = blockIndex[i];
6070 blockIndex[i] = temp;
6077 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6079 /* Now scan the blocks looking at the data. */
6081 endIterator = nBlocksToScan - 1;
6082 T(YAFFS_TRACE_SCAN_DEBUG,
6083 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6085 /* For each block.... backwards */
6086 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6088 /* Cooperative multitasking! This loop can run for so
6089 long that watchdog timers expire. */
6092 /* get the block to scan in the correct order */
6093 blk = blockIndex[blockIterator].block;
6095 bi = yaffs_GetBlockInfo(dev, blk);
6098 state = bi->blockState;
6102 /* For each chunk in each block that needs scanning.... */
6103 foundChunksInBlock = 0;
6104 for (c = dev->nChunksPerBlock - 1;
6105 !alloc_failed && c >= 0 &&
6106 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6107 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6108 /* Scan backwards...
6109 * Read the tags and decide what to do
6112 chunk = blk * dev->nChunksPerBlock + c;
6114 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6117 /* Let's have a good look at this chunk... */
6119 if (!tags.chunkUsed) {
6120 /* An unassigned chunk in the block.
6121 * If there are used chunks after this one, then
6122 * it is a chunk that was skipped due to failing the erased
6123 * check. Just skip it so that it can be deleted.
6124 * But, more typically, We get here when this is an unallocated
6125 * chunk and his means that either the block is empty or
6126 * this is the one being allocated from
6129 if(foundChunksInBlock)
6131 /* This is a chunk that was skipped due to failing the erased check */
6133 } else if (c == 0) {
6134 /* We're looking at the first chunk in the block so the block is unused */
6135 state = YAFFS_BLOCK_STATE_EMPTY;
6136 dev->nErasedBlocks++;
6138 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6139 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6140 if(dev->sequenceNumber == bi->sequenceNumber) {
6141 /* this is the block being allocated from */
6145 (" Allocating from %d %d"
6148 state = YAFFS_BLOCK_STATE_ALLOCATING;
6149 dev->allocationBlock = blk;
6150 dev->allocationPage = c;
6151 dev->allocationBlockFinder = blk;
6154 /* This is a partially written block that is not
6155 * the current allocation block. This block must have
6156 * had a write failure, so set up for retirement.
6159 bi->needsRetiring = 1;
6160 bi->gcPrioritise = 1;
6162 T(YAFFS_TRACE_ALWAYS,
6163 (TSTR("Partially written block %d being set for retirement" TENDSTR),
6173 } else if (tags.chunkId > 0) {
6174 /* chunkId > 0 so it is a data chunk... */
6175 unsigned int endpos;
6177 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6179 foundChunksInBlock = 1;
6182 yaffs_SetChunkBit(dev, blk, c);
6185 in = yaffs_FindOrCreateObjectByNumber(dev,
6188 YAFFS_OBJECT_TYPE_FILE);
6195 in->variantType == YAFFS_OBJECT_TYPE_FILE
6197 in->variant.fileVariant.shrinkSize) {
6198 /* This has not been invalidated by a resize */
6199 if(!yaffs_PutChunkIntoFile(in, tags.chunkId,
6204 /* File size is calculated by looking at the data chunks if we have not
6205 * seen an object header yet. Stop this practice once we find an object header.
6209 1) * dev->nDataBytesPerChunk +
6212 if (!in->valid && /* have not got an object header yet */
6213 in->variant.fileVariant.
6214 scannedFileSize < endpos) {
6215 in->variant.fileVariant.
6216 scannedFileSize = endpos;
6217 in->variant.fileVariant.
6219 in->variant.fileVariant.
6224 /* This chunk has been invalidated by a resize, so delete */
6225 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6229 /* chunkId == 0, so it is an ObjectHeader.
6230 * Thus, we read in the object header and make the object
6232 foundChunksInBlock = 1;
6234 yaffs_SetChunkBit(dev, blk, c);
6240 if (tags.extraHeaderInfoAvailable) {
6241 in = yaffs_FindOrCreateObjectByNumber
6242 (dev, tags.objectId,
6243 tags.extraObjectType);
6247 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
6250 tags.extraShadows ||
6252 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6253 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
6256 /* If we don't have valid info then we need to read the chunk
6257 * TODO In future we can probably defer reading the chunk and
6258 * living with invalid data until needed.
6261 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6266 oh = (yaffs_ObjectHeader *) chunkData;
6269 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6274 /* TODO Hoosterman we have a problem! */
6275 T(YAFFS_TRACE_ERROR,
6277 ("yaffs tragedy: Could not make object for object %d "
6278 "at chunk %d during scan"
6279 TENDSTR), tags.objectId, chunk));
6284 /* We have already filled this one.
6285 * We have a duplicate that will be discarded, but
6286 * we first have to suck out resize info if it is a file.
6289 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6291 oh-> type == YAFFS_OBJECT_TYPE_FILE)||
6292 (tags.extraHeaderInfoAvailable &&
6293 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
6296 (oh) ? oh->fileSize : tags.
6298 __u32 parentObjectId =
6300 parentObjectId : tags.
6301 extraParentObjectId;
6303 (oh) ? oh->isShrink : tags.
6304 extraIsShrinkHeader;
6306 /* If it is deleted (unlinked at start also means deleted)
6307 * we treat the file size as being zeroed at this point.
6309 if (parentObjectId ==
6310 YAFFS_OBJECTID_DELETED
6311 || parentObjectId ==
6312 YAFFS_OBJECTID_UNLINKED) {
6318 in->variant.fileVariant.
6319 shrinkSize > thisSize) {
6320 in->variant.fileVariant.
6326 bi->hasShrinkHeader = 1;
6330 /* Use existing - destroy this one. */
6331 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6336 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6338 YAFFS_OBJECTID_LOSTNFOUND)) {
6339 /* We only load some info, don't fiddle with directory structure */
6343 in->variantType = oh->type;
6345 in->yst_mode = oh->yst_mode;
6346 #ifdef CONFIG_YAFFS_WINCE
6347 in->win_atime[0] = oh->win_atime[0];
6348 in->win_ctime[0] = oh->win_ctime[0];
6349 in->win_mtime[0] = oh->win_mtime[0];
6350 in->win_atime[1] = oh->win_atime[1];
6351 in->win_ctime[1] = oh->win_ctime[1];
6352 in->win_mtime[1] = oh->win_mtime[1];
6354 in->yst_uid = oh->yst_uid;
6355 in->yst_gid = oh->yst_gid;
6356 in->yst_atime = oh->yst_atime;
6357 in->yst_mtime = oh->yst_mtime;
6358 in->yst_ctime = oh->yst_ctime;
6359 in->yst_rdev = oh->yst_rdev;
6363 in->variantType = tags.extraObjectType;
6367 in->chunkId = chunk;
6369 } else if (!in->valid) {
6370 /* we need to load this info */
6373 in->chunkId = chunk;
6376 in->variantType = oh->type;
6378 in->yst_mode = oh->yst_mode;
6379 #ifdef CONFIG_YAFFS_WINCE
6380 in->win_atime[0] = oh->win_atime[0];
6381 in->win_ctime[0] = oh->win_ctime[0];
6382 in->win_mtime[0] = oh->win_mtime[0];
6383 in->win_atime[1] = oh->win_atime[1];
6384 in->win_ctime[1] = oh->win_ctime[1];
6385 in->win_mtime[1] = oh->win_mtime[1];
6387 in->yst_uid = oh->yst_uid;
6388 in->yst_gid = oh->yst_gid;
6389 in->yst_atime = oh->yst_atime;
6390 in->yst_mtime = oh->yst_mtime;
6391 in->yst_ctime = oh->yst_ctime;
6392 in->yst_rdev = oh->yst_rdev;
6395 if (oh->shadowsObject > 0)
6396 yaffs_HandleShadowedObject(dev,
6402 yaffs_SetObjectName(in, oh->name);
6404 yaffs_FindOrCreateObjectByNumber
6405 (dev, oh->parentObjectId,
6406 YAFFS_OBJECT_TYPE_DIRECTORY);
6408 fileSize = oh->fileSize;
6409 isShrink = oh->isShrink;
6410 equivalentObjectId = oh->equivalentObjectId;
6414 in->variantType = tags.extraObjectType;
6416 yaffs_FindOrCreateObjectByNumber
6417 (dev, tags.extraParentObjectId,
6418 YAFFS_OBJECT_TYPE_DIRECTORY);
6419 fileSize = tags.extraFileLength;
6420 isShrink = tags.extraIsShrinkHeader;
6421 equivalentObjectId = tags.extraEquivalentObjectId;
6427 /* directory stuff...
6431 if (parent->variantType ==
6432 YAFFS_OBJECT_TYPE_UNKNOWN) {
6433 /* Set up as a directory */
6434 parent->variantType =
6435 YAFFS_OBJECT_TYPE_DIRECTORY;
6436 INIT_LIST_HEAD(&parent->variant.
6439 } else if (parent->variantType !=
6440 YAFFS_OBJECT_TYPE_DIRECTORY)
6442 /* Hoosterman, another problem....
6443 * We're trying to use a non-directory as a directory
6446 T(YAFFS_TRACE_ERROR,
6448 ("yaffs tragedy: attempting to use non-directory as"
6449 " a directory in scan. Put in lost+found."
6451 parent = dev->lostNFoundDir;
6454 yaffs_AddObjectToDirectory(parent, in);
6456 itsUnlinked = (parent == dev->deletedDir) ||
6457 (parent == dev->unlinkedDir);
6460 /* Mark the block as having a shrinkHeader */
6461 bi->hasShrinkHeader = 1;
6464 /* Note re hardlinks.
6465 * Since we might scan a hardlink before its equivalent object is scanned
6466 * we put them all in a list.
6467 * After scanning is complete, we should have all the objects, so we run
6468 * through this list and fix up all the chains.
6471 switch (in->variantType) {
6472 case YAFFS_OBJECT_TYPE_UNKNOWN:
6473 /* Todo got a problem */
6475 case YAFFS_OBJECT_TYPE_FILE:
6477 if (in->variant.fileVariant.
6478 scannedFileSize < fileSize) {
6479 /* This covers the case where the file size is greater
6480 * than where the data is
6481 * This will happen if the file is resized to be larger
6482 * than its current data extents.
6484 in->variant.fileVariant.fileSize = fileSize;
6485 in->variant.fileVariant.scannedFileSize =
6486 in->variant.fileVariant.fileSize;
6490 in->variant.fileVariant.shrinkSize > fileSize) {
6491 in->variant.fileVariant.shrinkSize = fileSize;
6495 case YAFFS_OBJECT_TYPE_HARDLINK:
6497 in->variant.hardLinkVariant.equivalentObjectId =
6499 in->hardLinks.next =
6500 (struct list_head *) hardList;
6504 case YAFFS_OBJECT_TYPE_DIRECTORY:
6507 case YAFFS_OBJECT_TYPE_SPECIAL:
6510 case YAFFS_OBJECT_TYPE_SYMLINK:
6512 in->variant.symLinkVariant.alias =
6513 yaffs_CloneString(oh->
6515 if(!in->variant.symLinkVariant.alias)
6525 } /* End of scanning for each chunk */
6527 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6528 /* If we got this far while scanning, then the block is fully allocated. */
6529 state = YAFFS_BLOCK_STATE_FULL;
6532 bi->blockState = state;
6534 /* Now let's see if it was dirty */
6535 if (bi->pagesInUse == 0 &&
6536 !bi->hasShrinkHeader &&
6537 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6538 yaffs_BlockBecameDirty(dev, blk);
6544 YFREE_ALT(blockIndex);
6548 /* Ok, we've done all the scanning.
6549 * Fix up the hard link chains.
6550 * We should now have scanned all the objects, now it's time to add these
6553 yaffs_HardlinkFixup(dev,hardList);
6557 * Sort out state of unlinked and deleted objects.
6560 struct list_head *i;
6561 struct list_head *n;
6565 /* Soft delete all the unlinked files */
6566 list_for_each_safe(i, n,
6567 &dev->unlinkedDir->variant.directoryVariant.
6570 l = list_entry(i, yaffs_Object, siblings);
6571 yaffs_DestroyObject(l);
6575 /* Soft delete all the deletedDir files */
6576 list_for_each_safe(i, n,
6577 &dev->deletedDir->variant.directoryVariant.
6580 l = list_entry(i, yaffs_Object, siblings);
6581 yaffs_DestroyObject(l);
6587 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6593 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6598 /*------------------------------ Directory Functions ----------------------------- */
6600 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
6602 yaffs_Device *dev = obj->myDev;
6604 if(dev && dev->removeObjectCallback)
6605 dev->removeObjectCallback(obj);
6607 list_del_init(&obj->siblings);
6612 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
6617 T(YAFFS_TRACE_ALWAYS,
6619 ("tragedy: Trying to add an object to a null pointer directory"
6623 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6624 T(YAFFS_TRACE_ALWAYS,
6626 ("tragedy: Trying to add an object to a non-directory"
6631 if (obj->siblings.prev == NULL) {
6632 /* Not initialised */
6633 INIT_LIST_HEAD(&obj->siblings);
6635 } else if (!list_empty(&obj->siblings)) {
6636 /* If it is holed up somewhere else, un hook it */
6637 yaffs_RemoveObjectFromDirectory(obj);
6640 list_add(&obj->siblings, &directory->variant.directoryVariant.children);
6641 obj->parent = directory;
6643 if (directory == obj->myDev->unlinkedDir
6644 || directory == obj->myDev->deletedDir) {
6646 obj->myDev->nUnlinkedFiles++;
6647 obj->renameAllowed = 0;
6651 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
6656 struct list_head *i;
6657 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
6666 T(YAFFS_TRACE_ALWAYS,
6668 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6672 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6673 T(YAFFS_TRACE_ALWAYS,
6675 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6679 sum = yaffs_CalcNameSum(name);
6681 list_for_each(i, &directory->variant.directoryVariant.children) {
6683 l = list_entry(i, yaffs_Object, siblings);
6685 yaffs_CheckObjectDetailsLoaded(l);
6687 /* Special case for lost-n-found */
6688 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6689 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
6692 } else if (yaffs_SumCompare(l->sum, sum) || l->chunkId <= 0)
6694 /* LostnFound cunk called Objxxx
6697 yaffs_GetObjectName(l, buffer,
6698 YAFFS_MAX_NAME_LENGTH);
6699 if (yaffs_strncmp(name, buffer,YAFFS_MAX_NAME_LENGTH) == 0) {
6712 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
6713 int (*fn) (yaffs_Object *))
6715 struct list_head *i;
6719 T(YAFFS_TRACE_ALWAYS,
6721 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6725 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6726 T(YAFFS_TRACE_ALWAYS,
6728 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6732 list_for_each(i, &theDir->variant.directoryVariant.children) {
6734 l = list_entry(i, yaffs_Object, siblings);
6746 /* GetEquivalentObject dereferences any hard links to get to the
6750 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
6752 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
6753 /* We want the object id of the equivalent object, not this one */
6754 obj = obj->variant.hardLinkVariant.equivalentObject;
6755 yaffs_CheckObjectDetailsLoaded(obj);
6761 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
6763 memset(name, 0, buffSize * sizeof(YCHAR));
6765 yaffs_CheckObjectDetailsLoaded(obj);
6767 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6768 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
6769 } else if (obj->chunkId <= 0) {
6771 /* make up a name */
6772 yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX,
6774 yaffs_strncpy(name, locName, buffSize - 1);
6777 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
6778 else if (obj->shortName[0]) {
6779 yaffs_strcpy(name, obj->shortName);
6784 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
6786 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
6788 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
6790 if (obj->chunkId >= 0) {
6791 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
6792 obj->chunkId, buffer,
6795 yaffs_strncpy(name, oh->name, buffSize - 1);
6797 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
6800 return yaffs_strlen(name);
6803 int yaffs_GetObjectFileLength(yaffs_Object * obj)
6806 /* Dereference any hard linking */
6807 obj = yaffs_GetEquivalentObject(obj);
6809 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
6810 return obj->variant.fileVariant.fileSize;
6812 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6813 return yaffs_strlen(obj->variant.symLinkVariant.alias);
6815 /* Only a directory should drop through to here */
6816 return obj->myDev->nDataBytesPerChunk;
6820 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
6823 struct list_head *i;
6825 if (!obj->unlinked) {
6826 count++; /* the object itself */
6828 list_for_each(i, &obj->hardLinks) {
6829 count++; /* add the hard links; */
6835 int yaffs_GetObjectInode(yaffs_Object * obj)
6837 obj = yaffs_GetEquivalentObject(obj);
6839 return obj->objectId;
6842 unsigned yaffs_GetObjectType(yaffs_Object * obj)
6844 obj = yaffs_GetEquivalentObject(obj);
6846 switch (obj->variantType) {
6847 case YAFFS_OBJECT_TYPE_FILE:
6850 case YAFFS_OBJECT_TYPE_DIRECTORY:
6853 case YAFFS_OBJECT_TYPE_SYMLINK:
6856 case YAFFS_OBJECT_TYPE_HARDLINK:
6859 case YAFFS_OBJECT_TYPE_SPECIAL:
6860 if (S_ISFIFO(obj->yst_mode))
6862 if (S_ISCHR(obj->yst_mode))
6864 if (S_ISBLK(obj->yst_mode))
6866 if (S_ISSOCK(obj->yst_mode))
6874 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
6876 obj = yaffs_GetEquivalentObject(obj);
6877 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6878 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
6880 return yaffs_CloneString(_Y(""));
6884 #ifndef CONFIG_YAFFS_WINCE
6886 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
6888 unsigned int valid = attr->ia_valid;
6890 if (valid & ATTR_MODE)
6891 obj->yst_mode = attr->ia_mode;
6892 if (valid & ATTR_UID)
6893 obj->yst_uid = attr->ia_uid;
6894 if (valid & ATTR_GID)
6895 obj->yst_gid = attr->ia_gid;
6897 if (valid & ATTR_ATIME)
6898 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
6899 if (valid & ATTR_CTIME)
6900 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
6901 if (valid & ATTR_MTIME)
6902 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
6904 if (valid & ATTR_SIZE)
6905 yaffs_ResizeFile(obj, attr->ia_size);
6907 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6912 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
6914 unsigned int valid = 0;
6916 attr->ia_mode = obj->yst_mode;
6918 attr->ia_uid = obj->yst_uid;
6920 attr->ia_gid = obj->yst_gid;
6923 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
6924 valid |= ATTR_ATIME;
6925 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
6926 valid |= ATTR_CTIME;
6927 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
6928 valid |= ATTR_MTIME;
6930 attr->ia_size = yaffs_GetFileSize(obj);
6933 attr->ia_valid = valid;
6942 int yaffs_DumpObject(yaffs_Object * obj)
6946 yaffs_GetObjectName(obj, name, 256);
6948 T(YAFFS_TRACE_ALWAYS,
6950 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
6951 " chunk %d type %d size %d\n"
6952 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
6953 obj->dirty, obj->valid, obj->serial, obj->sum, obj->chunkId,
6954 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
6960 /*---------------------------- Initialisation code -------------------------------------- */
6962 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
6965 /* Common functions, gotta have */
6966 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
6969 #ifdef CONFIG_YAFFS_YAFFS2
6971 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
6972 if (dev->writeChunkWithTagsToNAND &&
6973 dev->readChunkWithTagsFromNAND &&
6974 !dev->writeChunkToNAND &&
6975 !dev->readChunkFromNAND &&
6976 dev->markNANDBlockBad && dev->queryNANDBlock)
6980 /* Can use the "spare" style interface for yaffs1 */
6981 if (!dev->isYaffs2 &&
6982 !dev->writeChunkWithTagsToNAND &&
6983 !dev->readChunkWithTagsFromNAND &&
6984 dev->writeChunkToNAND &&
6985 dev->readChunkFromNAND &&
6986 !dev->markNANDBlockBad && !dev->queryNANDBlock)
6993 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
6995 /* Initialise the unlinked, deleted, root and lost and found directories */
6997 dev->lostNFoundDir = dev->rootDir = NULL;
6998 dev->unlinkedDir = dev->deletedDir = NULL;
7001 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7004 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7007 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7008 YAFFS_ROOT_MODE | S_IFDIR);
7009 dev->lostNFoundDir =
7010 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7011 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7013 if(dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir){
7014 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7021 int yaffs_GutsInitialise(yaffs_Device * dev)
7023 int init_failed = 0;
7027 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7029 /* Check stuff that must be set */
7032 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7036 dev->internalStartBlock = dev->startBlock;
7037 dev->internalEndBlock = dev->endBlock;
7038 dev->blockOffset = 0;
7039 dev->chunkOffset = 0;
7040 dev->nFreeChunks = 0;
7042 if (dev->startBlock == 0) {
7043 dev->internalStartBlock = dev->startBlock + 1;
7044 dev->internalEndBlock = dev->endBlock + 1;
7045 dev->blockOffset = 1;
7046 dev->chunkOffset = dev->nChunksPerBlock;
7049 /* Check geometry parameters. */
7051 if ((dev->isYaffs2 && dev->nDataBytesPerChunk < 1024) ||
7052 (!dev->isYaffs2 && dev->nDataBytesPerChunk != 512) ||
7053 dev->nChunksPerBlock < 2 ||
7054 dev->nReservedBlocks < 2 ||
7055 dev->internalStartBlock <= 0 ||
7056 dev->internalEndBlock <= 0 ||
7057 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
7059 T(YAFFS_TRACE_ALWAYS,
7061 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s "
7062 TENDSTR), dev->nDataBytesPerChunk, dev->isYaffs2 ? "2" : ""));
7066 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7067 T(YAFFS_TRACE_ALWAYS,
7068 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7072 /* Got the right mix of functions? */
7073 if (!yaffs_CheckDevFunctions(dev)) {
7074 /* Function missing */
7075 T(YAFFS_TRACE_ALWAYS,
7077 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7082 /* This is really a compilation check. */
7083 if (!yaffs_CheckStructures()) {
7084 T(YAFFS_TRACE_ALWAYS,
7085 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7089 if (dev->isMounted) {
7090 T(YAFFS_TRACE_ALWAYS,
7091 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7095 /* Finished with most checks. One or two more checks happen later on too. */
7101 /* OK now calculate a few things for the device */
7104 * Calculate all the chunk size manipulation numbers:
7106 /* Start off assuming it is a power of 2 */
7107 dev->chunkShift = ShiftDiv(dev->nDataBytesPerChunk);
7108 dev->chunkMask = (1<<dev->chunkShift) - 1;
7110 if(dev->nDataBytesPerChunk == (dev->chunkMask + 1)){
7111 /* Yes it is a power of 2, disable crumbs */
7113 dev->crumbShift = 0;
7114 dev->crumbsPerChunk = 0;
7116 /* Not a power of 2, use crumbs instead */
7117 dev->crumbShift = ShiftDiv(sizeof(yaffs_PackedTags2TagsPart));
7118 dev->crumbMask = (1<<dev->crumbShift)-1;
7119 dev->crumbsPerChunk = dev->nDataBytesPerChunk/(1 << dev->crumbShift);
7120 dev->chunkShift = 0;
7126 * Calculate chunkGroupBits.
7127 * We need to find the next power of 2 > than internalEndBlock
7130 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7134 /* Set up tnode width if wide tnodes are enabled. */
7135 if(!dev->wideTnodesDisabled){
7136 /* bits must be even so that we end up with 32-bit words */
7140 dev->tnodeWidth = 16;
7142 dev->tnodeWidth = bits;
7145 dev->tnodeWidth = 16;
7147 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7149 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7150 * so if the bitwidth of the
7151 * chunk range we're using is greater than 16 we need
7152 * to figure out chunk shift and chunkGroupSize
7155 if (bits <= dev->tnodeWidth)
7156 dev->chunkGroupBits = 0;
7158 dev->chunkGroupBits = bits - dev->tnodeWidth;
7161 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7163 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7164 /* We have a problem because the soft delete won't work if
7165 * the chunk group size > chunks per block.
7166 * This can be remedied by using larger "virtual blocks".
7168 T(YAFFS_TRACE_ALWAYS,
7169 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7174 /* OK, we've finished verifying the device, lets continue with initialisation */
7176 /* More device initialisation */
7177 dev->garbageCollections = 0;
7178 dev->passiveGarbageCollections = 0;
7179 dev->currentDirtyChecker = 0;
7180 dev->bufferedBlock = -1;
7181 dev->doingBufferedBlockRewrite = 0;
7182 dev->nDeletedFiles = 0;
7183 dev->nBackgroundDeletions = 0;
7184 dev->nUnlinkedFiles = 0;
7186 dev->eccUnfixed = 0;
7187 dev->tagsEccFixed = 0;
7188 dev->tagsEccUnfixed = 0;
7189 dev->nErasureFailures = 0;
7190 dev->nErasedBlocks = 0;
7192 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7194 /* Initialise temporary buffers and caches. */
7195 if(!yaffs_InitialiseTempBuffers(dev))
7198 dev->srCache = NULL;
7199 dev->gcCleanupList = NULL;
7203 dev->nShortOpCaches > 0) {
7206 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7208 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
7209 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7212 buf = dev->srCache = YMALLOC(srCacheBytes);
7215 memset(dev->srCache,0,srCacheBytes);
7217 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7218 dev->srCache[i].object = NULL;
7219 dev->srCache[i].lastUse = 0;
7220 dev->srCache[i].dirty = 0;
7221 dev->srCache[i].data = buf = YMALLOC_DMA(dev->nDataBytesPerChunk);
7232 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7233 if(!dev->gcCleanupList)
7237 if (dev->isYaffs2) {
7238 dev->useHeaderFileSize = 1;
7240 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7243 yaffs_InitialiseTnodes(dev);
7244 yaffs_InitialiseObjects(dev);
7246 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7251 /* Now scan the flash. */
7252 if (dev->isYaffs2) {
7253 if(yaffs_CheckpointRestore(dev)) {
7254 T(YAFFS_TRACE_ALWAYS,
7255 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7258 /* Clean up the mess caused by an aborted checkpoint load
7259 * and scan backwards.
7261 yaffs_DeinitialiseBlocks(dev);
7262 yaffs_DeinitialiseTnodes(dev);
7263 yaffs_DeinitialiseObjects(dev);
7266 dev->nErasedBlocks = 0;
7267 dev->nFreeChunks = 0;
7268 dev->allocationBlock = -1;
7269 dev->allocationPage = -1;
7270 dev->nDeletedFiles = 0;
7271 dev->nUnlinkedFiles = 0;
7272 dev->nBackgroundDeletions = 0;
7273 dev->oldestDirtySequence = 0;
7275 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7278 yaffs_InitialiseTnodes(dev);
7279 yaffs_InitialiseObjects(dev);
7281 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7284 if(!init_failed && !yaffs_ScanBackwards(dev))
7288 if(!yaffs_Scan(dev))
7293 /* Clean up the mess */
7294 T(YAFFS_TRACE_TRACING,
7295 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7297 yaffs_Deinitialise(dev);
7301 /* Zero out stats */
7302 dev->nPageReads = 0;
7303 dev->nPageWrites = 0;
7304 dev->nBlockErasures = 0;
7306 dev->nRetriedWrites = 0;
7308 dev->nRetiredBlocks = 0;
7310 yaffs_VerifyFreeChunks(dev);
7311 yaffs_VerifyBlocks(dev);
7314 T(YAFFS_TRACE_TRACING,
7315 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7320 void yaffs_Deinitialise(yaffs_Device * dev)
7322 if (dev->isMounted) {
7325 yaffs_DeinitialiseBlocks(dev);
7326 yaffs_DeinitialiseTnodes(dev);
7327 yaffs_DeinitialiseObjects(dev);
7328 if (dev->nShortOpCaches > 0 &&
7331 for (i = 0; i < dev->nShortOpCaches; i++) {
7332 if(dev->srCache[i].data)
7333 YFREE(dev->srCache[i].data);
7334 dev->srCache[i].data = NULL;
7337 YFREE(dev->srCache);
7338 dev->srCache = NULL;
7341 YFREE(dev->gcCleanupList);
7343 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
7344 YFREE(dev->tempBuffer[i].buffer);
7352 static int yaffs_CountFreeChunks(yaffs_Device * dev)
7357 yaffs_BlockInfo *blk;
7359 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7361 blk = yaffs_GetBlockInfo(dev, b);
7363 switch (blk->blockState) {
7364 case YAFFS_BLOCK_STATE_EMPTY:
7365 case YAFFS_BLOCK_STATE_ALLOCATING:
7366 case YAFFS_BLOCK_STATE_COLLECTING:
7367 case YAFFS_BLOCK_STATE_FULL:
7369 (dev->nChunksPerBlock - blk->pagesInUse +
7370 blk->softDeletions);
7381 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
7383 /* This is what we report to the outside world */
7386 int nDirtyCacheChunks;
7387 int blocksForCheckpoint;
7390 nFree = dev->nFreeChunks;
7392 nFree = yaffs_CountFreeChunks(dev);
7395 nFree += dev->nDeletedFiles;
7397 /* Now count the number of dirty chunks in the cache and subtract those */
7401 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7402 if (dev->srCache[i].dirty)
7403 nDirtyCacheChunks++;
7407 nFree -= nDirtyCacheChunks;
7409 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7411 /* Now we figure out how much to reserve for the checkpoint and report that... */
7412 blocksForCheckpoint = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
7413 if(blocksForCheckpoint < 0)
7414 blocksForCheckpoint = 0;
7416 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7425 static int yaffs_freeVerificationFailures;
7427 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
7432 if(yaffs_SkipVerification(dev))
7435 counted = yaffs_CountFreeChunks(dev);
7437 difference = dev->nFreeChunks - counted;
7440 T(YAFFS_TRACE_ALWAYS,
7441 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7442 dev->nFreeChunks, counted, difference));
7443 yaffs_freeVerificationFailures++;
7447 /*---------------------------------------- YAFFS test code ----------------------*/
7449 #define yaffs_CheckStruct(structure,syze, name) \
7450 if(sizeof(structure) != syze) \
7452 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
7453 name,syze,sizeof(structure))); \
7454 return YAFFS_FAIL; \
7457 static int yaffs_CheckStructures(void)
7459 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags") */
7460 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion") */
7461 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare") */
7462 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7463 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode")
7465 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader")