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.
17 const char *yaffs_guts_c_version =
18 "$Id: yaffs_guts.c,v 1.52 2007/10/16 00:45:05 charles Exp $";
21 #include "linux/stat.h"
23 #include "yaffsinterface.h"
25 #include "yaffs_guts.h"
26 #include "yaffs_tagsvalidity.h"
28 #include "yaffs_tagscompat.h"
29 #ifndef CONFIG_YAFFS_USE_OWN_SORT
30 #include "yaffs_qsort.h"
32 #include "yaffs_nand.h"
34 #include "yaffs_checkptrw.h"
36 #include "yaffs_nand.h"
37 #include "yaffs_packedtags2.h"
41 #ifdef CONFIG_YAFFS_WINCE
42 void yfsd_LockYAFFS(BOOL fsLockOnly);
43 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
46 #define YAFFS_PASSIVE_GC_CHUNKS 2
48 #include "yaffs_ecc.h"
51 /* Robustification (if it ever comes about...) */
52 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
53 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk);
54 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
56 const yaffs_ExtendedTags * tags);
57 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
58 const yaffs_ExtendedTags * tags);
60 /* Other local prototypes */
61 static int yaffs_UnlinkObject( yaffs_Object *obj);
62 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
64 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
66 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
68 yaffs_ExtendedTags * tags,
70 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
71 int chunkInNAND, int inScan);
73 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
74 yaffs_ObjectType type);
75 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
77 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
78 int force, int isShrink, int shadows);
79 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
80 static int yaffs_CheckStructures(void);
81 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
83 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
85 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo);
86 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
89 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
92 static int yaffs_UnlinkWorker(yaffs_Object * obj);
93 static void yaffs_DestroyObject(yaffs_Object * obj);
95 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
98 loff_t yaffs_GetFileSize(yaffs_Object * obj);
100 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr);
102 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
104 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
106 #ifdef YAFFS_PARANOID
107 static int yaffs_CheckFileSanity(yaffs_Object * in);
109 #define yaffs_CheckFileSanity(in)
112 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
113 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
115 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
117 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
118 yaffs_ExtendedTags * tags);
120 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos);
121 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
122 yaffs_FileStructure * fStruct,
126 /* Function to calculate chunk and offset */
128 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, __u32 *chunk, __u32 *offset)
131 /* Easy-peasy power of 2 case */
132 *chunk = (__u32)(addr >> dev->chunkShift);
133 *offset = (__u32)(addr & dev->chunkMask);
135 else if(dev->crumbsPerChunk)
137 /* Case where we're using "crumbs" */
138 *offset = (__u32)(addr & dev->crumbMask);
139 addr >>= dev->crumbShift;
140 *chunk = ((__u32)addr)/dev->crumbsPerChunk;
141 *offset += ((addr - (*chunk * dev->crumbsPerChunk)) << dev->crumbShift);
147 /* Function to return the number of shifts for a power of 2 greater than or equal
148 * to the given number
149 * Note we don't try to cater for all possible numbers and this does not have to
150 * be hellishly efficient.
153 static __u32 ShiftsGE(__u32 x)
158 nShifts = extraBits = 0;
161 if(x & 1) extraBits++;
172 /* Function to return the number of shifts to get a 1 in bit 0
175 static __u32 ShiftDiv(__u32 x)
194 * Temporary buffer manipulations.
197 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
200 __u8 *buf = (__u8 *)1;
202 memset(dev->tempBuffer,0,sizeof(dev->tempBuffer));
204 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
205 dev->tempBuffer[i].line = 0; /* not in use */
206 dev->tempBuffer[i].buffer = buf =
207 YMALLOC_DMA(dev->nDataBytesPerChunk);
210 return buf ? YAFFS_OK : YAFFS_FAIL;
214 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
217 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
218 if (dev->tempBuffer[i].line == 0) {
219 dev->tempBuffer[i].line = lineNo;
220 if ((i + 1) > dev->maxTemp) {
221 dev->maxTemp = i + 1;
222 for (j = 0; j <= i; j++)
223 dev->tempBuffer[j].maxLine =
224 dev->tempBuffer[j].line;
227 return dev->tempBuffer[i].buffer;
231 T(YAFFS_TRACE_BUFFERS,
232 (TSTR("Out of temp buffers at line %d, other held by lines:"),
234 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
235 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
237 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
240 * If we got here then we have to allocate an unmanaged one
244 dev->unmanagedTempAllocations++;
245 return YMALLOC(dev->nDataBytesPerChunk);
249 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
253 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
254 if (dev->tempBuffer[i].buffer == buffer) {
255 dev->tempBuffer[i].line = 0;
261 /* assume it is an unmanaged one. */
262 T(YAFFS_TRACE_BUFFERS,
263 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
266 dev->unmanagedTempDeallocations++;
272 * Determine if we have a managed buffer.
274 int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
277 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
278 if (dev->tempBuffer[i].buffer == buffer)
283 for (i = 0; i < dev->nShortOpCaches; i++) {
284 if( dev->srCache[i].data == buffer )
289 if (buffer == dev->checkpointBuffer)
292 T(YAFFS_TRACE_ALWAYS,
293 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
300 * Chunk bitmap manipulations
303 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
305 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
307 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
311 return dev->chunkBits +
312 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
315 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
317 if(blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
318 chunk < 0 || chunk >= dev->nChunksPerBlock) {
320 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),blk,chunk));
325 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
327 __u8 *blkBits = yaffs_BlockBits(dev, blk);
329 memset(blkBits, 0, dev->chunkBitmapStride);
332 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
334 __u8 *blkBits = yaffs_BlockBits(dev, blk);
336 yaffs_VerifyChunkBitId(dev,blk,chunk);
338 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
341 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
343 __u8 *blkBits = yaffs_BlockBits(dev, blk);
345 yaffs_VerifyChunkBitId(dev,blk,chunk);
347 blkBits[chunk / 8] |= (1 << (chunk & 7));
350 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
352 __u8 *blkBits = yaffs_BlockBits(dev, blk);
353 yaffs_VerifyChunkBitId(dev,blk,chunk);
355 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
358 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
360 __u8 *blkBits = yaffs_BlockBits(dev, blk);
362 for (i = 0; i < dev->chunkBitmapStride; i++) {
370 static int yaffs_CountChunkBits(yaffs_Device * dev, int blk)
372 __u8 *blkBits = yaffs_BlockBits(dev, blk);
375 for (i = 0; i < dev->chunkBitmapStride; i++) {
392 static Y_INLINE int yaffs_SkipVerification(yaffs_Device *dev)
394 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
397 static Y_INLINE int yaffs_SkipFullVerification(yaffs_Device *dev)
399 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
402 static Y_INLINE int yaffs_SkipNANDVerification(yaffs_Device *dev)
404 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
407 static const char * blockStateName[] = {
420 static void yaffs_VerifyBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
425 if(yaffs_SkipVerification(dev))
428 /* Report illegal runtime states */
429 if(bi->blockState <0 || bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
430 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has undefined state %d"TENDSTR),n,bi->blockState));
432 switch(bi->blockState){
433 case YAFFS_BLOCK_STATE_UNKNOWN:
434 case YAFFS_BLOCK_STATE_SCANNING:
435 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
436 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has bad run-state %s"TENDSTR),
437 n,blockStateName[bi->blockState]));
440 /* Check pages in use and soft deletions are legal */
442 actuallyUsed = bi->pagesInUse - bi->softDeletions;
444 if(bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
445 bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
446 actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock)
447 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
448 n,bi->pagesInUse,bi->softDeletions));
451 /* Check chunk bitmap legal */
452 inUse = yaffs_CountChunkBits(dev,n);
453 if(inUse != bi->pagesInUse)
454 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
455 n,bi->pagesInUse,inUse));
457 /* Check that the sequence number is valid.
458 * Ten million is legal, but is very unlikely
461 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
462 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000 ))
463 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has suspect sequence number of %d"TENDSTR),
464 n,bi->sequenceNumber));
468 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
470 yaffs_VerifyBlock(dev,bi,n);
472 /* After collection the block should be in the erased state */
473 /* TODO: This will need to change if we do partial gc */
475 if(bi->blockState != YAFFS_BLOCK_STATE_EMPTY){
476 T(YAFFS_TRACE_ERROR,(TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
481 static void yaffs_VerifyBlocks(yaffs_Device *dev)
484 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
485 int nIllegalBlockStates = 0;
488 if(yaffs_SkipVerification(dev))
491 memset(nBlocksPerState,0,sizeof(nBlocksPerState));
494 for(i = dev->internalStartBlock; i <= dev->internalEndBlock; i++){
495 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
496 yaffs_VerifyBlock(dev,bi,i);
498 if(bi->blockState >=0 && bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
499 nBlocksPerState[bi->blockState]++;
501 nIllegalBlockStates++;
505 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
506 T(YAFFS_TRACE_VERIFY,(TSTR("Block summary"TENDSTR)));
508 T(YAFFS_TRACE_VERIFY,(TSTR("%d blocks have illegal states"TENDSTR),nIllegalBlockStates));
509 if(nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
510 T(YAFFS_TRACE_VERIFY,(TSTR("Too many allocating blocks"TENDSTR)));
512 for(i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
513 T(YAFFS_TRACE_VERIFY,
514 (TSTR("%s %d blocks"TENDSTR),
515 blockStateName[i],nBlocksPerState[i]));
517 if(dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
518 T(YAFFS_TRACE_VERIFY,
519 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
520 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
522 if(dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
523 T(YAFFS_TRACE_VERIFY,
524 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
525 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
527 if(nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
528 T(YAFFS_TRACE_VERIFY,
529 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
530 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
532 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
537 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
538 * case those tests will not be performed.
540 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
542 if(yaffs_SkipVerification(obj->myDev))
545 if(!(tags && obj && oh)){
546 T(YAFFS_TRACE_VERIFY,
547 (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR),
548 (__u32)tags,(__u32)obj,(__u32)oh));
552 if(oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
553 oh->type > YAFFS_OBJECT_TYPE_MAX)
554 T(YAFFS_TRACE_VERIFY,
555 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
556 tags->objectId, oh->type));
558 if(tags->objectId != obj->objectId)
559 T(YAFFS_TRACE_VERIFY,
560 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
561 tags->objectId, obj->objectId));
565 * Check that the object's parent ids match if parentCheck requested.
567 * Tests do not apply to the root object.
570 if(parentCheck && tags->objectId > 1 && !obj->parent)
571 T(YAFFS_TRACE_VERIFY,
572 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
573 tags->objectId, oh->parentObjectId));
576 if(parentCheck && obj->parent &&
577 oh->parentObjectId != obj->parent->objectId &&
578 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
579 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
580 T(YAFFS_TRACE_VERIFY,
581 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
582 tags->objectId, oh->parentObjectId, obj->parent->objectId));
585 if(tags->objectId > 1 && oh->name[0] == 0) /* Null name */
586 T(YAFFS_TRACE_VERIFY,
587 (TSTR("Obj %d header name is NULL"TENDSTR),
590 if(tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
591 T(YAFFS_TRACE_VERIFY,
592 (TSTR("Obj %d header name is 0xFF"TENDSTR),
596 static void yaffs_VerifyFile(yaffs_Object *obj)
598 int requiredTallness;
604 yaffs_ExtendedTags tags;
608 if(obj && yaffs_SkipVerification(obj->myDev))
612 objectId = obj->objectId;
614 /* Check file size is consistent with tnode depth */
615 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
616 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
617 requiredTallness = 0;
619 x >>= YAFFS_TNODES_INTERNAL_BITS;
623 actualTallness = obj->variant.fileVariant.topLevel;
625 if(requiredTallness > actualTallness )
626 T(YAFFS_TRACE_VERIFY,
627 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
628 obj->objectId,actualTallness, requiredTallness));
631 /* Check that the chunks in the tnode tree are all correct.
632 * We do this by scanning through the tnode tree and
633 * checking the tags for every chunk match.
636 if(yaffs_SkipNANDVerification(dev))
639 for(i = 1; i <= lastChunk; i++){
640 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant,i);
643 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
645 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
646 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
647 if(tags.objectId != objectId || tags.chunkId != i){
648 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
649 objectId, i, theChunk,
650 tags.objectId, tags.chunkId));
659 static void yaffs_VerifyDirectory(yaffs_Object *obj)
661 if(obj && yaffs_SkipVerification(obj->myDev))
666 static void yaffs_VerifyHardLink(yaffs_Object *obj)
668 if(obj && yaffs_SkipVerification(obj->myDev))
671 /* Verify sane equivalent object */
674 static void yaffs_VerifySymlink(yaffs_Object *obj)
676 if(obj && yaffs_SkipVerification(obj->myDev))
679 /* Verify symlink string */
682 static void yaffs_VerifySpecial(yaffs_Object *obj)
684 if(obj && yaffs_SkipVerification(obj->myDev))
688 static void yaffs_VerifyObject(yaffs_Object *obj)
703 if(yaffs_SkipVerification(dev))
706 /* Check sane object header chunk */
708 chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
709 chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
711 chunkIdOk = (obj->chunkId >= chunkMin && obj->chunkId <= chunkMax);
712 chunkIsLive = chunkIdOk &&
713 yaffs_CheckChunkBit(dev,
714 obj->chunkId / dev->nChunksPerBlock,
715 obj->chunkId % dev->nChunksPerBlock);
717 (!chunkIdOk || !chunkIsLive)) {
718 T(YAFFS_TRACE_VERIFY,
719 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
720 obj->objectId,obj->chunkId,
721 chunkIdOk ? "" : ",out of range",
722 chunkIsLive || !chunkIdOk ? "" : ",marked as deleted"));
725 if(chunkIdOk && chunkIsLive &&!yaffs_SkipNANDVerification(dev)) {
726 yaffs_ExtendedTags tags;
727 yaffs_ObjectHeader *oh;
728 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
730 oh = (yaffs_ObjectHeader *)buffer;
732 yaffs_ReadChunkWithTagsFromNAND(dev, obj->chunkId,buffer, &tags);
734 yaffs_VerifyObjectHeader(obj,oh,&tags,1);
736 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
739 /* Verify it has a parent */
740 if(obj && !obj->fake &&
741 (!obj->parent || obj->parent->myDev != dev)){
742 T(YAFFS_TRACE_VERIFY,
743 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
744 obj->objectId,obj->parent));
747 /* Verify parent is a directory */
748 if(obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
749 T(YAFFS_TRACE_VERIFY,
750 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
751 obj->objectId,obj->parent->variantType));
754 switch(obj->variantType){
755 case YAFFS_OBJECT_TYPE_FILE:
756 yaffs_VerifyFile(obj);
758 case YAFFS_OBJECT_TYPE_SYMLINK:
759 yaffs_VerifySymlink(obj);
761 case YAFFS_OBJECT_TYPE_DIRECTORY:
762 yaffs_VerifyDirectory(obj);
764 case YAFFS_OBJECT_TYPE_HARDLINK:
765 yaffs_VerifyHardLink(obj);
767 case YAFFS_OBJECT_TYPE_SPECIAL:
768 yaffs_VerifySpecial(obj);
770 case YAFFS_OBJECT_TYPE_UNKNOWN:
772 T(YAFFS_TRACE_VERIFY,
773 (TSTR("Obj %d has illegaltype %d"TENDSTR),
774 obj->objectId,obj->variantType));
781 static void yaffs_VerifyObjects(yaffs_Device *dev)
785 struct list_head *lh;
787 if(yaffs_SkipVerification(dev))
790 /* Iterate through the objects in each hash entry */
792 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++){
793 list_for_each(lh, &dev->objectBucket[i].list) {
795 obj = list_entry(lh, yaffs_Object, hashLink);
796 yaffs_VerifyObject(obj);
805 * Simple hash function. Needs to have a reasonable spread
808 static Y_INLINE int yaffs_HashFunction(int n)
814 return (n % YAFFS_NOBJECT_BUCKETS);
818 * Access functions to useful fake objects
821 yaffs_Object *yaffs_Root(yaffs_Device * dev)
826 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
828 return dev->lostNFoundDir;
833 * Erased NAND checking functions
836 int yaffs_CheckFF(__u8 * buffer, int nBytes)
838 /* Horrible, slow implementation */
847 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
851 int retval = YAFFS_OK;
852 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
853 yaffs_ExtendedTags tags;
855 yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
857 if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
861 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
862 T(YAFFS_TRACE_NANDACCESS,
863 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
867 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
873 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
875 yaffs_ExtendedTags * tags,
882 yaffs_InvalidateCheckpoint(dev);
885 yaffs_BlockInfo *bi = 0;
888 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
894 /* First check this chunk is erased, if it needs
895 * checking. The checking policy (unless forced
896 * always on) is as follows:
898 * Check the first page we try to write in a block.
899 * If the check passes then we don't need to check any
900 * more. If the check fails, we check again...
901 * If the block has been erased, we don't need to check.
903 * However, if the block has been prioritised for gc,
904 * then we think there might be something odd about
905 * this block and stop using it.
907 * Rationale: We should only ever see chunks that have
908 * not been erased if there was a partially written
909 * chunk due to power loss. This checking policy should
910 * catch that case with very few checks and thus save a
911 * lot of checks that are most likely not needed.
913 if (bi->gcPrioritise) {
914 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
915 /* try another chunk */
919 /* let's give it a try */
922 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
923 bi->skipErasedCheck = 0;
925 if (!bi->skipErasedCheck) {
926 erasedOk = yaffs_CheckChunkErased(dev, chunk);
927 if (erasedOk != YAFFS_OK) {
929 (TSTR ("**>> yaffs chunk %d was not erased"
932 /* try another chunk */
935 bi->skipErasedCheck = 1;
938 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
940 if (writeOk != YAFFS_OK) {
941 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
942 /* try another chunk */
946 /* Copy the data into the robustification buffer */
947 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
949 } while (writeOk != YAFFS_OK &&
950 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
957 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
960 dev->nRetriedWrites += (attempts - 1);
967 * Block retiring for handling a broken block.
970 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
972 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
974 yaffs_InvalidateCheckpoint(dev);
976 yaffs_MarkBlockBad(dev, blockInNAND);
978 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
979 bi->gcPrioritise = 0;
980 bi->needsRetiring = 0;
982 dev->nRetiredBlocks++;
986 * Functions for robustisizing TODO
990 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
992 const yaffs_ExtendedTags * tags)
996 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
997 const yaffs_ExtendedTags * tags)
1001 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1003 if(!bi->gcPrioritise){
1004 bi->gcPrioritise = 1;
1005 dev->hasPendingPrioritisedGCs = 1;
1006 bi->chunkErrorStrikes ++;
1008 if(bi->chunkErrorStrikes > 3){
1009 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1010 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1017 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
1020 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1021 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1023 yaffs_HandleChunkError(dev,bi);
1027 /* Was an actual write failure, so mark the block for retirement */
1028 bi->needsRetiring = 1;
1029 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1030 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1035 /* Delete the chunk */
1036 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1040 /*---------------- Name handling functions ------------*/
1042 static __u16 yaffs_CalcNameSum(const YCHAR * name)
1047 YUCHAR *bname = (YUCHAR *) name;
1049 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1051 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1052 sum += yaffs_toupper(*bname) * i;
1054 sum += (*bname) * i;
1063 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
1065 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1066 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
1067 yaffs_strcpy(obj->shortName, name);
1069 obj->shortName[0] = _Y('\0');
1072 obj->sum = yaffs_CalcNameSum(name);
1075 /*-------------------- TNODES -------------------
1077 * List of spare tnodes
1078 * The list is hooked together using the first pointer
1082 /* yaffs_CreateTnodes creates a bunch more tnodes and
1083 * adds them to the tnode free list.
1084 * Don't use this function directly
1087 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
1091 yaffs_Tnode *newTnodes;
1095 yaffs_TnodeList *tnl;
1100 /* Calculate the tnode size in bytes for variable width tnode support.
1101 * Must be a multiple of 32-bits */
1102 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1104 /* make these things */
1106 newTnodes = YMALLOC(nTnodes * tnodeSize);
1107 mem = (__u8 *)newTnodes;
1110 T(YAFFS_TRACE_ERROR,
1111 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1115 /* Hook them into the free list */
1117 for (i = 0; i < nTnodes - 1; i++) {
1118 newTnodes[i].internal[0] = &newTnodes[i + 1];
1119 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1120 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1124 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1125 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1126 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1128 dev->freeTnodes = newTnodes;
1130 /* New hookup for wide tnodes */
1131 for(i = 0; i < nTnodes -1; i++) {
1132 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1133 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1134 curr->internal[0] = next;
1137 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1138 curr->internal[0] = dev->freeTnodes;
1139 dev->freeTnodes = (yaffs_Tnode *)mem;
1144 dev->nFreeTnodes += nTnodes;
1145 dev->nTnodesCreated += nTnodes;
1147 /* Now add this bunch of tnodes to a list for freeing up.
1148 * NB If we can't add this to the management list it isn't fatal
1149 * but it just means we can't free this bunch of tnodes later.
1152 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1154 T(YAFFS_TRACE_ERROR,
1156 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1160 tnl->tnodes = newTnodes;
1161 tnl->next = dev->allocatedTnodeList;
1162 dev->allocatedTnodeList = tnl;
1165 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1170 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1172 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
1174 yaffs_Tnode *tn = NULL;
1176 /* If there are none left make more */
1177 if (!dev->freeTnodes) {
1178 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1181 if (dev->freeTnodes) {
1182 tn = dev->freeTnodes;
1183 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1184 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1185 /* Hoosterman, this thing looks like it isn't in the list */
1186 T(YAFFS_TRACE_ALWAYS,
1187 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1190 dev->freeTnodes = dev->freeTnodes->internal[0];
1197 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
1199 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1202 memset(tn, 0, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1207 /* FreeTnode frees up a tnode and puts it back on the free list */
1208 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
1211 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1212 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1213 /* Hoosterman, this thing looks like it is already in the list */
1214 T(YAFFS_TRACE_ALWAYS,
1215 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1217 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1219 tn->internal[0] = dev->freeTnodes;
1220 dev->freeTnodes = tn;
1225 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
1227 /* Free the list of allocated tnodes */
1228 yaffs_TnodeList *tmp;
1230 while (dev->allocatedTnodeList) {
1231 tmp = dev->allocatedTnodeList->next;
1233 YFREE(dev->allocatedTnodeList->tnodes);
1234 YFREE(dev->allocatedTnodeList);
1235 dev->allocatedTnodeList = tmp;
1239 dev->freeTnodes = NULL;
1240 dev->nFreeTnodes = 0;
1243 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
1245 dev->allocatedTnodeList = NULL;
1246 dev->freeTnodes = NULL;
1247 dev->nFreeTnodes = 0;
1248 dev->nTnodesCreated = 0;
1253 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
1255 __u32 *map = (__u32 *)tn;
1261 pos &= YAFFS_TNODES_LEVEL0_MASK;
1262 val >>= dev->chunkGroupBits;
1264 bitInMap = pos * dev->tnodeWidth;
1265 wordInMap = bitInMap /32;
1266 bitInWord = bitInMap & (32 -1);
1268 mask = dev->tnodeMask << bitInWord;
1270 map[wordInMap] &= ~mask;
1271 map[wordInMap] |= (mask & (val << bitInWord));
1273 if(dev->tnodeWidth > (32-bitInWord)) {
1274 bitInWord = (32 - bitInWord);
1276 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1277 map[wordInMap] &= ~mask;
1278 map[wordInMap] |= (mask & (val >> bitInWord));
1282 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
1284 __u32 *map = (__u32 *)tn;
1290 pos &= YAFFS_TNODES_LEVEL0_MASK;
1292 bitInMap = pos * dev->tnodeWidth;
1293 wordInMap = bitInMap /32;
1294 bitInWord = bitInMap & (32 -1);
1296 val = map[wordInMap] >> bitInWord;
1298 if(dev->tnodeWidth > (32-bitInWord)) {
1299 bitInWord = (32 - bitInWord);
1301 val |= (map[wordInMap] << bitInWord);
1304 val &= dev->tnodeMask;
1305 val <<= dev->chunkGroupBits;
1310 /* ------------------- End of individual tnode manipulation -----------------*/
1312 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1313 * The look up tree is represented by the top tnode and the number of topLevel
1314 * in the tree. 0 means only the level 0 tnode is in the tree.
1317 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1318 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
1319 yaffs_FileStructure * fStruct,
1323 yaffs_Tnode *tn = fStruct->top;
1325 int requiredTallness;
1326 int level = fStruct->topLevel;
1328 /* Check sane level and chunk Id */
1329 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
1333 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1337 /* First check we're tall enough (ie enough topLevel) */
1339 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1340 requiredTallness = 0;
1342 i >>= YAFFS_TNODES_INTERNAL_BITS;
1346 if (requiredTallness > fStruct->topLevel) {
1347 /* Not tall enough, so we can't find it, return NULL. */
1351 /* Traverse down to level 0 */
1352 while (level > 0 && tn) {
1354 internal[(chunkId >>
1355 ( YAFFS_TNODES_LEVEL0_BITS +
1357 YAFFS_TNODES_INTERNAL_BITS)
1359 YAFFS_TNODES_INTERNAL_MASK];
1367 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1368 * This happens in two steps:
1369 * 1. If the tree isn't tall enough, then make it taller.
1370 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1372 * Used when modifying the tree.
1374 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1375 * be plugged into the ttree.
1378 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
1379 yaffs_FileStructure * fStruct,
1381 yaffs_Tnode *passedTn)
1384 int requiredTallness;
1392 /* Check sane level and page Id */
1393 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
1397 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1401 /* First check we're tall enough (ie enough topLevel) */
1403 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1404 requiredTallness = 0;
1406 x >>= YAFFS_TNODES_INTERNAL_BITS;
1411 if (requiredTallness > fStruct->topLevel) {
1412 /* Not tall enough,gotta make the tree taller */
1413 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1415 tn = yaffs_GetTnode(dev);
1418 tn->internal[0] = fStruct->top;
1421 T(YAFFS_TRACE_ERROR,
1422 (TSTR("yaffs: no more tnodes" TENDSTR)));
1426 fStruct->topLevel = requiredTallness;
1429 /* Traverse down to level 0, adding anything we need */
1431 l = fStruct->topLevel;
1435 while (l > 0 && tn) {
1437 ( YAFFS_TNODES_LEVEL0_BITS +
1438 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1439 YAFFS_TNODES_INTERNAL_MASK;
1442 if((l>1) && !tn->internal[x]){
1443 /* Add missing non-level-zero tnode */
1444 tn->internal[x] = yaffs_GetTnode(dev);
1447 /* Looking from level 1 at level 0 */
1449 /* If we already have one, then release it.*/
1451 yaffs_FreeTnode(dev,tn->internal[x]);
1452 tn->internal[x] = passedTn;
1454 } else if(!tn->internal[x]) {
1455 /* Don't have one, none passed in */
1456 tn->internal[x] = yaffs_GetTnode(dev);
1460 tn = tn->internal[x];
1464 /* top is level 0 */
1466 memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1467 yaffs_FreeTnode(dev,passedTn);
1474 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1475 yaffs_ExtendedTags * tags, int objectId,
1480 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1481 if (yaffs_CheckChunkBit
1482 (dev, theChunk / dev->nChunksPerBlock,
1483 theChunk % dev->nChunksPerBlock)) {
1484 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1486 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1497 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1500 yaffs_BlockInfo *theBlock;
1502 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1504 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1506 theBlock->softDeletions++;
1511 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1512 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1514 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1517 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1518 __u32 level, int chunkOffset)
1523 yaffs_Device *dev = in->myDev;
1528 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1530 if (tn->internal[i]) {
1532 yaffs_SoftDeleteWorker(in,
1538 YAFFS_TNODES_INTERNAL_BITS)
1541 yaffs_FreeTnode(dev,
1544 tn->internal[i] = NULL;
1546 /* Hoosterman... how could this happen? */
1550 return (allDone) ? 1 : 0;
1551 } else if (level == 0) {
1553 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1554 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1556 /* Note this does not find the real chunk, only the chunk group.
1557 * We make an assumption that a chunk group is not larger than
1560 yaffs_SoftDeleteChunk(dev, theChunk);
1561 yaffs_PutLevel0Tnode(dev,tn,i,0);
1575 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1578 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1579 if (obj->nDataChunks <= 0) {
1580 /* Empty file with no duplicate object headers, just delete it immediately */
1581 yaffs_FreeTnode(obj->myDev,
1582 obj->variant.fileVariant.top);
1583 obj->variant.fileVariant.top = NULL;
1584 T(YAFFS_TRACE_TRACING,
1585 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1587 yaffs_DoGenericObjectDeletion(obj);
1589 yaffs_SoftDeleteWorker(obj,
1590 obj->variant.fileVariant.top,
1591 obj->variant.fileVariant.
1593 obj->softDeleted = 1;
1598 /* Pruning removes any part of the file structure tree that is beyond the
1599 * bounds of the file (ie that does not point to chunks).
1601 * A file should only get pruned when its size is reduced.
1603 * Before pruning, the chunks must be pulled from the tree and the
1604 * level 0 tnode entries must be zeroed out.
1605 * Could also use this for file deletion, but that's probably better handled
1606 * by a special case.
1609 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1610 __u32 level, int del0)
1618 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1619 if (tn->internal[i] && level > 0) {
1621 yaffs_PruneWorker(dev, tn->internal[i],
1623 (i == 0) ? del0 : 1);
1626 if (tn->internal[i]) {
1631 if (hasData == 0 && del0) {
1632 /* Free and return NULL */
1634 yaffs_FreeTnode(dev, tn);
1644 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1645 yaffs_FileStructure * fStruct)
1652 if (fStruct->topLevel > 0) {
1654 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1656 /* Now we have a tree with all the non-zero branches NULL but the height
1657 * is the same as it was.
1658 * Let's see if we can trim internal tnodes to shorten the tree.
1659 * We can do this if only the 0th element in the tnode is in use
1660 * (ie all the non-zero are NULL)
1663 while (fStruct->topLevel && !done) {
1667 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1668 if (tn->internal[i]) {
1674 fStruct->top = tn->internal[0];
1675 fStruct->topLevel--;
1676 yaffs_FreeTnode(dev, tn);
1686 /*-------------------- End of File Structure functions.-------------------*/
1688 /* yaffs_CreateFreeObjects creates a bunch more objects and
1689 * adds them to the object free list.
1691 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1694 yaffs_Object *newObjects;
1695 yaffs_ObjectList *list;
1700 /* make these things */
1701 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1702 list = YMALLOC(sizeof(yaffs_ObjectList));
1704 if (!newObjects || !list) {
1709 T(YAFFS_TRACE_ALLOCATE,
1710 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1714 /* Hook them into the free list */
1715 for (i = 0; i < nObjects - 1; i++) {
1716 newObjects[i].siblings.next =
1717 (struct list_head *)(&newObjects[i + 1]);
1720 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1721 dev->freeObjects = newObjects;
1722 dev->nFreeObjects += nObjects;
1723 dev->nObjectsCreated += nObjects;
1725 /* Now add this bunch of Objects to a list for freeing up. */
1727 list->objects = newObjects;
1728 list->next = dev->allocatedObjectList;
1729 dev->allocatedObjectList = list;
1735 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1736 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1738 yaffs_Object *tn = NULL;
1740 /* If there are none left make more */
1741 if (!dev->freeObjects) {
1742 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1745 if (dev->freeObjects) {
1746 tn = dev->freeObjects;
1748 (yaffs_Object *) (dev->freeObjects->siblings.next);
1749 dev->nFreeObjects--;
1751 /* Now sweeten it up... */
1753 memset(tn, 0, sizeof(yaffs_Object));
1756 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1757 INIT_LIST_HEAD(&(tn->hardLinks));
1758 INIT_LIST_HEAD(&(tn->hashLink));
1759 INIT_LIST_HEAD(&tn->siblings);
1761 /* Add it to the lost and found directory.
1762 * NB Can't put root or lostNFound in lostNFound so
1763 * check if lostNFound exists first
1765 if (dev->lostNFoundDir) {
1766 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1773 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1778 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1780 obj->fake = 1; /* it is fake so it has no NAND presence... */
1781 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1782 obj->unlinkAllowed = 0; /* ... or unlink it */
1785 obj->yst_mode = mode;
1787 obj->chunkId = 0; /* Not a valid chunk. */
1794 static void yaffs_UnhashObject(yaffs_Object * tn)
1797 yaffs_Device *dev = tn->myDev;
1799 /* If it is still linked into the bucket list, free from the list */
1800 if (!list_empty(&tn->hashLink)) {
1801 list_del_init(&tn->hashLink);
1802 bucket = yaffs_HashFunction(tn->objectId);
1803 dev->objectBucket[bucket].count--;
1808 /* FreeObject frees up a Object and puts it back on the free list */
1809 static void yaffs_FreeObject(yaffs_Object * tn)
1812 yaffs_Device *dev = tn->myDev;
1814 /* XXX U-BOOT XXX */
1818 /* We're still hooked up to a cached inode.
1819 * Don't delete now, but mark for later deletion
1821 tn->deferedFree = 1;
1826 yaffs_UnhashObject(tn);
1828 /* Link into the free list. */
1829 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1830 dev->freeObjects = tn;
1831 dev->nFreeObjects++;
1834 /* XXX U-BOOT XXX */
1838 void yaffs_HandleDeferedFree(yaffs_Object * obj)
1840 if (obj->deferedFree) {
1841 yaffs_FreeObject(obj);
1848 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
1850 /* Free the list of allocated Objects */
1852 yaffs_ObjectList *tmp;
1854 while (dev->allocatedObjectList) {
1855 tmp = dev->allocatedObjectList->next;
1856 YFREE(dev->allocatedObjectList->objects);
1857 YFREE(dev->allocatedObjectList);
1859 dev->allocatedObjectList = tmp;
1862 dev->freeObjects = NULL;
1863 dev->nFreeObjects = 0;
1866 static void yaffs_InitialiseObjects(yaffs_Device * dev)
1870 dev->allocatedObjectList = NULL;
1871 dev->freeObjects = NULL;
1872 dev->nFreeObjects = 0;
1874 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
1875 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1876 dev->objectBucket[i].count = 0;
1881 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
1886 int lowest = 999999;
1888 /* First let's see if we can find one that's empty. */
1890 for (i = 0; i < 10 && lowest > 0; i++) {
1892 x %= YAFFS_NOBJECT_BUCKETS;
1893 if (dev->objectBucket[x].count < lowest) {
1894 lowest = dev->objectBucket[x].count;
1900 /* If we didn't find an empty list, then try
1901 * looking a bit further for a short one
1904 for (i = 0; i < 10 && lowest > 3; i++) {
1906 x %= YAFFS_NOBJECT_BUCKETS;
1907 if (dev->objectBucket[x].count < lowest) {
1908 lowest = dev->objectBucket[x].count;
1917 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
1919 int bucket = yaffs_FindNiceObjectBucket(dev);
1921 /* Now find an object value that has not already been taken
1922 * by scanning the list.
1926 struct list_head *i;
1928 __u32 n = (__u32) bucket;
1930 /* yaffs_CheckObjectHashSanity(); */
1934 n += YAFFS_NOBJECT_BUCKETS;
1935 if (1 || dev->objectBucket[bucket].count > 0) {
1936 list_for_each(i, &dev->objectBucket[bucket].list) {
1937 /* If there is already one in the list */
1939 && list_entry(i, yaffs_Object,
1940 hashLink)->objectId == n) {
1951 static void yaffs_HashObject(yaffs_Object * in)
1953 int bucket = yaffs_HashFunction(in->objectId);
1954 yaffs_Device *dev = in->myDev;
1956 list_add(&in->hashLink, &dev->objectBucket[bucket].list);
1957 dev->objectBucket[bucket].count++;
1961 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
1963 int bucket = yaffs_HashFunction(number);
1964 struct list_head *i;
1967 list_for_each(i, &dev->objectBucket[bucket].list) {
1968 /* Look if it is in the list */
1970 in = list_entry(i, yaffs_Object, hashLink);
1971 if (in->objectId == number) {
1972 /* XXX U-BOOT XXX */
1975 /* Don't tell the VFS about this one if it is defered free */
1976 if (in->deferedFree)
1988 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
1989 yaffs_ObjectType type)
1992 yaffs_Object *theObject;
1993 yaffs_Tnode *tn = NULL;
1996 number = yaffs_CreateNewObjectNumber(dev);
1999 theObject = yaffs_AllocateEmptyObject(dev);
2003 if(type == YAFFS_OBJECT_TYPE_FILE){
2004 tn = yaffs_GetTnode(dev);
2006 yaffs_FreeObject(theObject);
2014 theObject->fake = 0;
2015 theObject->renameAllowed = 1;
2016 theObject->unlinkAllowed = 1;
2017 theObject->objectId = number;
2018 yaffs_HashObject(theObject);
2019 theObject->variantType = type;
2020 #ifdef CONFIG_YAFFS_WINCE
2021 yfsd_WinFileTimeNow(theObject->win_atime);
2022 theObject->win_ctime[0] = theObject->win_mtime[0] =
2023 theObject->win_atime[0];
2024 theObject->win_ctime[1] = theObject->win_mtime[1] =
2025 theObject->win_atime[1];
2029 theObject->yst_atime = theObject->yst_mtime =
2030 theObject->yst_ctime = Y_CURRENT_TIME;
2033 case YAFFS_OBJECT_TYPE_FILE:
2034 theObject->variant.fileVariant.fileSize = 0;
2035 theObject->variant.fileVariant.scannedFileSize = 0;
2036 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2037 theObject->variant.fileVariant.topLevel = 0;
2038 theObject->variant.fileVariant.top = tn;
2040 case YAFFS_OBJECT_TYPE_DIRECTORY:
2041 INIT_LIST_HEAD(&theObject->variant.directoryVariant.
2044 case YAFFS_OBJECT_TYPE_SYMLINK:
2045 case YAFFS_OBJECT_TYPE_HARDLINK:
2046 case YAFFS_OBJECT_TYPE_SPECIAL:
2047 /* No action required */
2049 case YAFFS_OBJECT_TYPE_UNKNOWN:
2050 /* todo this should not happen */
2058 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
2060 yaffs_ObjectType type)
2062 yaffs_Object *theObject = NULL;
2065 theObject = yaffs_FindObjectByNumber(dev, number);
2069 theObject = yaffs_CreateNewObject(dev, number, type);
2077 static YCHAR *yaffs_CloneString(const YCHAR * str)
2079 YCHAR *newStr = NULL;
2082 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2084 yaffs_strcpy(newStr, str);
2092 * Mknod (create) a new object.
2093 * equivalentObject only has meaning for a hard link;
2094 * aliasString only has meaning for a sumlink.
2095 * rdev only has meaning for devices (a subset of special objects)
2098 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2099 yaffs_Object * parent,
2104 yaffs_Object * equivalentObject,
2105 const YCHAR * aliasString, __u32 rdev)
2110 yaffs_Device *dev = parent->myDev;
2112 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2113 if (yaffs_FindObjectByName(parent, name)) {
2117 in = yaffs_CreateNewObject(dev, -1, type);
2119 if(type == YAFFS_OBJECT_TYPE_SYMLINK){
2120 str = yaffs_CloneString(aliasString);
2122 yaffs_FreeObject(in);
2132 in->variantType = type;
2134 in->yst_mode = mode;
2136 #ifdef CONFIG_YAFFS_WINCE
2137 yfsd_WinFileTimeNow(in->win_atime);
2138 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2139 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2142 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2144 in->yst_rdev = rdev;
2148 in->nDataChunks = 0;
2150 yaffs_SetObjectName(in, name);
2153 yaffs_AddObjectToDirectory(parent, in);
2155 in->myDev = parent->myDev;
2158 case YAFFS_OBJECT_TYPE_SYMLINK:
2159 in->variant.symLinkVariant.alias = str;
2161 case YAFFS_OBJECT_TYPE_HARDLINK:
2162 in->variant.hardLinkVariant.equivalentObject =
2164 in->variant.hardLinkVariant.equivalentObjectId =
2165 equivalentObject->objectId;
2166 list_add(&in->hardLinks, &equivalentObject->hardLinks);
2168 case YAFFS_OBJECT_TYPE_FILE:
2169 case YAFFS_OBJECT_TYPE_DIRECTORY:
2170 case YAFFS_OBJECT_TYPE_SPECIAL:
2171 case YAFFS_OBJECT_TYPE_UNKNOWN:
2176 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2177 /* Could not create the object header, fail the creation */
2178 yaffs_DestroyObject(in);
2187 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
2188 __u32 mode, __u32 uid, __u32 gid)
2190 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2191 uid, gid, NULL, NULL, 0);
2194 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
2195 __u32 mode, __u32 uid, __u32 gid)
2197 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2198 mode, uid, gid, NULL, NULL, 0);
2201 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
2202 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2204 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2205 uid, gid, NULL, NULL, rdev);
2208 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
2209 __u32 mode, __u32 uid, __u32 gid,
2210 const YCHAR * alias)
2212 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2213 uid, gid, NULL, alias, 0);
2216 /* yaffs_Link returns the object id of the equivalent object.*/
2217 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
2218 yaffs_Object * equivalentObject)
2220 /* Get the real object in case we were fed a hard link as an equivalent object */
2221 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2223 if (yaffs_MknodObject
2224 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2225 equivalentObject, NULL, 0)) {
2226 return equivalentObject;
2233 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
2234 const YCHAR * newName, int force, int shadows)
2239 yaffs_Object *existingTarget;
2241 if (newDir == NULL) {
2242 newDir = obj->parent; /* use the old directory */
2245 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2246 T(YAFFS_TRACE_ALWAYS,
2248 ("tragendy: yaffs_ChangeObjectName: newDir is not a directory"
2253 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2254 if (obj->myDev->isYaffs2) {
2255 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2257 unlinkOp = (newDir == obj->myDev->unlinkedDir
2258 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2261 deleteOp = (newDir == obj->myDev->deletedDir);
2263 existingTarget = yaffs_FindObjectByName(newDir, newName);
2265 /* If the object is a file going into the unlinked directory,
2266 * then it is OK to just stuff it in since duplicate names are allowed.
2267 * else only proceed if the new name does not exist and if we're putting
2268 * it into a directory.
2275 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2276 yaffs_SetObjectName(obj, newName);
2279 yaffs_AddObjectToDirectory(newDir, obj);
2284 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2285 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
2292 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
2293 yaffs_Object * newDir, const YCHAR * newName)
2296 yaffs_Object *existingTarget;
2299 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2300 /* Special case for case insemsitive systems (eg. WinCE).
2301 * While look-up is case insensitive, the name isn't.
2302 * Therefore we might want to change x.txt to X.txt
2304 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
2309 obj = yaffs_FindObjectByName(oldDir, oldName);
2310 /* Check new name to long. */
2311 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK &&
2312 yaffs_strlen(newName) > YAFFS_MAX_ALIAS_LENGTH)
2315 else if (obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK &&
2316 yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2320 if (obj && obj->renameAllowed) {
2322 /* Now do the handling for an existing target, if there is one */
2324 existingTarget = yaffs_FindObjectByName(newDir, newName);
2325 if (existingTarget &&
2326 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2327 !list_empty(&existingTarget->variant.directoryVariant.children)) {
2328 /* There is a target that is a non-empty directory, so we fail */
2329 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2330 } else if (existingTarget && existingTarget != obj) {
2331 /* Nuke the target first, using shadowing,
2332 * but only if it isn't the same object
2334 yaffs_ChangeObjectName(obj, newDir, newName, force,
2335 existingTarget->objectId);
2336 yaffs_UnlinkObject(existingTarget);
2339 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2344 /*------------------------- Block Management and Page Allocation ----------------*/
2346 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
2348 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2350 dev->blockInfo = NULL;
2351 dev->chunkBits = NULL;
2353 dev->allocationBlock = -1; /* force it to get a new one */
2355 /* If the first allocation strategy fails, thry the alternate one */
2356 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2357 if(!dev->blockInfo){
2358 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2359 dev->blockInfoAlt = 1;
2362 dev->blockInfoAlt = 0;
2366 /* Set up dynamic blockinfo stuff. */
2367 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2368 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2369 if(!dev->chunkBits){
2370 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2371 dev->chunkBitsAlt = 1;
2374 dev->chunkBitsAlt = 0;
2377 if (dev->blockInfo && dev->chunkBits) {
2378 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2379 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2387 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
2389 if(dev->blockInfoAlt && dev->blockInfo)
2390 YFREE_ALT(dev->blockInfo);
2391 else if(dev->blockInfo)
2392 YFREE(dev->blockInfo);
2394 dev->blockInfoAlt = 0;
2396 dev->blockInfo = NULL;
2398 if(dev->chunkBitsAlt && dev->chunkBits)
2399 YFREE_ALT(dev->chunkBits);
2400 else if(dev->chunkBits)
2401 YFREE(dev->chunkBits);
2402 dev->chunkBitsAlt = 0;
2403 dev->chunkBits = NULL;
2406 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
2407 yaffs_BlockInfo * bi)
2414 return 1; /* disqualification only applies to yaffs2. */
2416 if (!bi->hasShrinkHeader)
2417 return 1; /* can gc */
2419 /* Find the oldest dirty sequence number if we don't know it and save it
2420 * so we don't have to keep recomputing it.
2422 if (!dev->oldestDirtySequence) {
2423 seq = dev->sequenceNumber;
2425 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2427 b = yaffs_GetBlockInfo(dev, i);
2428 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2429 (b->pagesInUse - b->softDeletions) <
2430 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2431 seq = b->sequenceNumber;
2434 dev->oldestDirtySequence = seq;
2437 /* Can't do gc of this block if there are any blocks older than this one that have
2440 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2444 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2445 * for garbage collection.
2448 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2452 int b = dev->currentDirtyChecker;
2459 yaffs_BlockInfo *bi;
2460 int pendingPrioritisedExist = 0;
2462 /* First let's see if we need to grab a prioritised block */
2463 if(dev->hasPendingPrioritisedGCs){
2464 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2466 bi = yaffs_GetBlockInfo(dev, i);
2467 //yaffs_VerifyBlock(dev,bi,i);
2469 if(bi->gcPrioritise) {
2470 pendingPrioritisedExist = 1;
2471 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2472 yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2473 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2476 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2481 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2482 dev->hasPendingPrioritisedGCs = 0;
2485 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2487 * else (we're doing a leasurely gc), then we only bother to do this if the
2488 * block has only a few pages in use.
2491 dev->nonAggressiveSkip--;
2493 if (!aggressive && (dev->nonAggressiveSkip > 0)) {
2499 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2503 dev->internalEndBlock - dev->internalStartBlock + 1;
2506 dev->internalEndBlock - dev->internalStartBlock + 1;
2507 iterations = iterations / 16;
2508 if (iterations > 200) {
2513 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2515 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2516 b = dev->internalStartBlock;
2519 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2520 T(YAFFS_TRACE_ERROR,
2521 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2525 bi = yaffs_GetBlockInfo(dev, b);
2528 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2535 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2536 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2537 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2539 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2543 dev->currentDirtyChecker = b;
2547 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2548 dev->nChunksPerBlock - pagesInUse,prioritised));
2551 dev->oldestDirtySequence = 0;
2554 dev->nonAggressiveSkip = 4;
2560 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2562 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2566 /* If the block is still healthy erase it and mark as clean.
2567 * If the block has had a data failure, then retire it.
2570 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2571 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2572 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2574 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2576 if (!bi->needsRetiring) {
2577 yaffs_InvalidateCheckpoint(dev);
2578 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2580 dev->nErasureFailures++;
2581 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2582 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2587 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2589 for (i = 0; i < dev->nChunksPerBlock; i++) {
2590 if (!yaffs_CheckChunkErased
2591 (dev, blockNo * dev->nChunksPerBlock + i)) {
2592 T(YAFFS_TRACE_ERROR,
2594 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2595 TENDSTR), blockNo, i));
2601 /* Clean it up... */
2602 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2603 dev->nErasedBlocks++;
2605 bi->softDeletions = 0;
2606 bi->hasShrinkHeader = 0;
2607 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2608 bi->gcPrioritise = 0;
2609 yaffs_ClearChunkBits(dev, blockNo);
2611 T(YAFFS_TRACE_ERASE,
2612 (TSTR("Erased block %d" TENDSTR), blockNo));
2614 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2616 yaffs_RetireBlock(dev, blockNo);
2617 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2618 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2622 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2626 yaffs_BlockInfo *bi;
2628 if (dev->nErasedBlocks < 1) {
2629 /* Hoosterman we've got a problem.
2630 * Can't get space to gc
2632 T(YAFFS_TRACE_ERROR,
2633 (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2638 /* Find an empty block. */
2640 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2641 dev->allocationBlockFinder++;
2642 if (dev->allocationBlockFinder < dev->internalStartBlock
2643 || dev->allocationBlockFinder > dev->internalEndBlock) {
2644 dev->allocationBlockFinder = dev->internalStartBlock;
2647 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2649 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2650 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2651 dev->sequenceNumber++;
2652 bi->sequenceNumber = dev->sequenceNumber;
2653 dev->nErasedBlocks--;
2654 T(YAFFS_TRACE_ALLOCATE,
2655 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2656 dev->allocationBlockFinder, dev->sequenceNumber,
2657 dev->nErasedBlocks));
2658 return dev->allocationBlockFinder;
2662 T(YAFFS_TRACE_ALWAYS,
2664 ("yaffs tragedy: no more eraased blocks, but there should have been %d"
2665 TENDSTR), dev->nErasedBlocks));
2671 // Check if there's space to allocate...
2672 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2673 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2676 int reservedBlocks = dev->nReservedBlocks;
2677 int checkpointBlocks;
2679 checkpointBlocks = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
2680 if(checkpointBlocks < 0)
2681 checkpointBlocks = 0;
2683 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2685 return (dev->nFreeChunks > reservedChunks);
2688 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2691 yaffs_BlockInfo *bi;
2693 if (dev->allocationBlock < 0) {
2694 /* Get next block to allocate off */
2695 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2696 dev->allocationPage = 0;
2699 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2700 /* Not enough space to allocate unless we're allowed to use the reserve. */
2704 if (dev->nErasedBlocks < dev->nReservedBlocks
2705 && dev->allocationPage == 0) {
2706 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2709 /* Next page please.... */
2710 if (dev->allocationBlock >= 0) {
2711 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2713 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2714 dev->allocationPage;
2716 yaffs_SetChunkBit(dev, dev->allocationBlock,
2717 dev->allocationPage);
2719 dev->allocationPage++;
2723 /* If the block is full set the state to full */
2724 if (dev->allocationPage >= dev->nChunksPerBlock) {
2725 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2726 dev->allocationBlock = -1;
2735 T(YAFFS_TRACE_ERROR,
2736 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2741 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2745 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2747 if (dev->allocationBlock > 0) {
2748 n += (dev->nChunksPerBlock - dev->allocationPage);
2755 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2761 int retVal = YAFFS_OK;
2764 int isCheckpointBlock;
2767 int chunksBefore = yaffs_GetErasedChunks(dev);
2770 yaffs_ExtendedTags tags;
2772 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2774 yaffs_Object *object;
2776 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2778 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2780 T(YAFFS_TRACE_TRACING,
2781 (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2782 bi->pagesInUse, bi->hasShrinkHeader));
2784 /*yaffs_VerifyFreeChunks(dev); */
2786 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2788 /* Take off the number of soft deleted entries because
2789 * they're going to get really deleted during GC.
2791 dev->nFreeChunks -= bi->softDeletions;
2795 if (isCheckpointBlock ||
2796 !yaffs_StillSomeChunkBits(dev, block)) {
2797 T(YAFFS_TRACE_TRACING,
2799 ("Collecting block %d that has no chunks in use" TENDSTR),
2801 yaffs_BlockBecameDirty(dev, block);
2804 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2806 yaffs_VerifyBlock(dev,bi,block);
2808 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
2809 chunkInBlock < dev->nChunksPerBlock
2810 && yaffs_StillSomeChunkBits(dev, block);
2811 chunkInBlock++, oldChunk++) {
2812 if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
2814 /* This page is in use and might need to be copied off */
2818 yaffs_InitialiseTags(&tags);
2820 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2824 yaffs_FindObjectByNumber(dev,
2827 T(YAFFS_TRACE_GC_DETAIL,
2829 ("Collecting page %d, %d %d %d " TENDSTR),
2830 chunkInBlock, tags.objectId, tags.chunkId,
2833 if(object && !yaffs_SkipVerification(dev)){
2834 if(tags.chunkId == 0)
2835 matchingChunk = object->chunkId;
2836 else if(object->softDeleted)
2837 matchingChunk = oldChunk; /* Defeat the test */
2839 matchingChunk = yaffs_FindChunkInFile(object,tags.chunkId,NULL);
2841 if(oldChunk != matchingChunk)
2842 T(YAFFS_TRACE_ERROR,
2843 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
2844 oldChunk,matchingChunk,tags.objectId, tags.chunkId));
2849 T(YAFFS_TRACE_ERROR,
2851 ("page %d in gc has no object: %d %d %d "
2853 tags.objectId, tags.chunkId, tags.byteCount));
2856 if (object && object->deleted
2857 && tags.chunkId != 0) {
2858 /* Data chunk in a deleted file, throw it away
2859 * It's a soft deleted data chunk,
2860 * No need to copy this, just forget about it and
2861 * fix up the object.
2864 object->nDataChunks--;
2866 if (object->nDataChunks <= 0) {
2867 /* remeber to clean up the object */
2868 dev->gcCleanupList[cleanups] =
2874 /* Todo object && object->deleted && object->nDataChunks == 0 */
2876 /* Deleted object header with no data chunks.
2877 * Can be discarded and the file deleted.
2879 object->chunkId = 0;
2880 yaffs_FreeTnode(object->myDev,
2883 object->variant.fileVariant.top = NULL;
2884 yaffs_DoGenericObjectDeletion(object);
2886 } else if (object) {
2887 /* It's either a data chunk in a live file or
2888 * an ObjectHeader, so we're interested in it.
2889 * NB Need to keep the ObjectHeaders of deleted files
2890 * until the whole file has been deleted off
2892 tags.serialNumber++;
2896 if (tags.chunkId == 0) {
2897 /* It is an object Id,
2898 * We need to nuke the shrinkheader flags first
2899 * We no longer want the shrinkHeader flag since its work is done
2900 * and if it is left in place it will mess up scanning.
2901 * Also, clear out any shadowing stuff
2904 yaffs_ObjectHeader *oh;
2905 oh = (yaffs_ObjectHeader *)buffer;
2907 oh->shadowsObject = -1;
2908 tags.extraShadows = 0;
2909 tags.extraIsShrinkHeader = 0;
2911 yaffs_VerifyObjectHeader(object,oh,&tags,1);
2915 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
2918 retVal = YAFFS_FAIL;
2921 /* Ok, now fix up the Tnodes etc. */
2923 if (tags.chunkId == 0) {
2925 object->chunkId = newChunk;
2926 object->serial = tags.serialNumber;
2928 /* It's a data chunk */
2929 yaffs_PutChunkIntoFile
2937 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
2942 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2945 /* Do any required cleanups */
2946 for (i = 0; i < cleanups; i++) {
2947 /* Time to delete the file too */
2949 yaffs_FindObjectByNumber(dev,
2950 dev->gcCleanupList[i]);
2952 yaffs_FreeTnode(dev,
2953 object->variant.fileVariant.
2955 object->variant.fileVariant.top = NULL;
2958 ("yaffs: About to finally delete object %d"
2959 TENDSTR), object->objectId));
2960 yaffs_DoGenericObjectDeletion(object);
2961 object->myDev->nDeletedFiles--;
2968 yaffs_VerifyCollectedBlock(dev,bi,block);
2970 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
2973 ("gc did not increase free chunks before %d after %d"
2974 TENDSTR), chunksBefore, chunksAfter));
2982 /* New garbage collector
2983 * If we're very low on erased blocks then we do aggressive garbage collection
2984 * otherwise we do "leasurely" garbage collection.
2985 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2986 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2988 * The idea is to help clear out space in a more spread-out manner.
2989 * Dunno if it really does anything useful.
2991 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
2995 int gcOk = YAFFS_OK;
2998 int checkpointBlockAdjust;
3000 if (dev->isDoingGC) {
3001 /* Bail out so we don't get recursive gc */
3005 /* This loop should pass the first time.
3006 * We'll only see looping here if the erase of the collected block fails.
3012 checkpointBlockAdjust = (dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint);
3013 if(checkpointBlockAdjust < 0)
3014 checkpointBlockAdjust = 0;
3016 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3017 /* We need a block soon...*/
3020 /* We're in no hurry */
3024 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3027 dev->garbageCollections++;
3029 dev->passiveGarbageCollections++;
3034 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3035 dev->nErasedBlocks, aggressive));
3037 gcOk = yaffs_GarbageCollectBlock(dev, block);
3040 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3043 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3044 TENDSTR), dev->nErasedBlocks, maxTries, block));
3046 } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
3049 return aggressive ? gcOk : YAFFS_OK;
3052 /*------------------------- TAGS --------------------------------*/
3054 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
3057 return (tags->chunkId == chunkInObject &&
3058 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3063 /*-------------------- Data file manipulation -----------------*/
3065 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
3066 yaffs_ExtendedTags * tags)
3068 /*Get the Tnode, then get the level 0 offset chunk offset */
3071 yaffs_ExtendedTags localTags;
3074 yaffs_Device *dev = in->myDev;
3077 /* Passed a NULL, so use our own tags space */
3081 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3084 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3087 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3093 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
3094 yaffs_ExtendedTags * tags)
3096 /* Get the Tnode, then get the level 0 offset chunk offset */
3099 yaffs_ExtendedTags localTags;
3101 yaffs_Device *dev = in->myDev;
3105 /* Passed a NULL, so use our own tags space */
3109 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3113 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3116 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3119 /* Delete the entry in the filestructure (if found) */
3121 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
3124 /*T(("No level 0 found for %d\n", chunkInInode)); */
3128 /* T(("Could not find %d to delete\n",chunkInInode)); */
3133 #ifdef YAFFS_PARANOID
3135 static int yaffs_CheckFileSanity(yaffs_Object * in)
3143 yaffs_Tags localTags;
3144 yaffs_Tags *tags = &localTags;
3148 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3149 /* T(("Object not a file\n")); */
3153 objId = in->objectId;
3154 fSize = in->variant.fileVariant.fileSize;
3156 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3158 for (chunk = 1; chunk <= nChunks; chunk++) {
3159 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3164 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
3166 if (yaffs_CheckChunkBits
3167 (dev, theChunk / dev->nChunksPerBlock,
3168 theChunk % dev->nChunksPerBlock)) {
3170 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3174 (tags, in->objectId, chunk, chunkDeleted)) {
3184 /* T(("No level 0 found for %d\n", chunk)); */
3188 return failed ? YAFFS_FAIL : YAFFS_OK;
3193 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
3194 int chunkInNAND, int inScan)
3196 /* NB inScan is zero unless scanning.
3197 * For forward scanning, inScan is > 0;
3198 * for backward scanning inScan is < 0
3202 yaffs_Device *dev = in->myDev;
3204 yaffs_ExtendedTags existingTags;
3205 yaffs_ExtendedTags newTags;
3206 unsigned existingSerial, newSerial;
3208 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3209 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3210 * If it is not during Scanning then something went wrong!
3213 T(YAFFS_TRACE_ERROR,
3215 ("yaffs tragedy:attempt to put data chunk into a non-file"
3220 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3224 tn = yaffs_AddOrFindLevel0Tnode(dev,
3225 &in->variant.fileVariant,
3232 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3235 /* If we're scanning then we need to test for duplicates
3236 * NB This does not need to be efficient since it should only ever
3237 * happen when the power fails during a write, then only one
3238 * chunk should ever be affected.
3240 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3241 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3244 if (existingChunk != 0) {
3245 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3246 * thus we have to do a FindChunkInFile to get the real chunk id.
3248 * We have a duplicate now we need to decide which one to use:
3250 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3251 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3252 * YAFFS1: Get both sets of tags and compare serial numbers.
3256 /* Only do this for forward scanning */
3257 yaffs_ReadChunkWithTagsFromNAND(dev,
3261 /* Do a proper find */
3263 yaffs_FindChunkInFile(in, chunkInInode,
3267 if (existingChunk <= 0) {
3268 /*Hoosterman - how did this happen? */
3270 T(YAFFS_TRACE_ERROR,
3272 ("yaffs tragedy: existing chunk < 0 in scan"
3277 /* NB The deleted flags should be false, otherwise the chunks will
3278 * not be loaded during a scan
3281 newSerial = newTags.serialNumber;
3282 existingSerial = existingTags.serialNumber;
3285 (in->myDev->isYaffs2 ||
3286 existingChunk <= 0 ||
3287 ((existingSerial + 1) & 3) == newSerial)) {
3288 /* Forward scanning.
3290 * Delete the old one and drop through to update the tnode
3292 yaffs_DeleteChunk(dev, existingChunk, 1,
3295 /* Backward scanning or we want to use the existing one
3297 * Delete the new one and return early so that the tnode isn't changed
3299 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3307 if (existingChunk == 0) {
3311 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
3316 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
3319 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3321 if (chunkInNAND >= 0) {
3322 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3325 T(YAFFS_TRACE_NANDACCESS,
3326 (TSTR("Chunk %d not found zero instead" TENDSTR),
3328 /* get sane (zero) data if you read a hole */
3329 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3335 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
3339 yaffs_ExtendedTags tags;
3340 yaffs_BlockInfo *bi;
3347 block = chunkId / dev->nChunksPerBlock;
3348 page = chunkId % dev->nChunksPerBlock;
3351 if(!yaffs_CheckChunkBit(dev,block,page))
3352 T(YAFFS_TRACE_VERIFY,
3353 (TSTR("Deleting invalid chunk %d"TENDSTR),
3356 bi = yaffs_GetBlockInfo(dev, block);
3358 T(YAFFS_TRACE_DELETION,
3359 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3362 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3364 yaffs_InitialiseTags(&tags);
3366 tags.chunkDeleted = 1;
3368 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3369 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3371 dev->nUnmarkedDeletions++;
3374 /* Pull out of the management area.
3375 * If the whole block became dirty, this will kick off an erasure.
3377 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3378 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3379 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3380 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3383 yaffs_ClearChunkBit(dev, block, page);
3387 if (bi->pagesInUse == 0 &&
3388 !bi->hasShrinkHeader &&
3389 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3390 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3391 yaffs_BlockBecameDirty(dev, block);
3395 /* T(("Bad news deleting chunk %d\n",chunkId)); */
3400 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
3401 const __u8 * buffer, int nBytes,
3404 /* Find old chunk Need to do this to get serial number
3405 * Write new one and patch into tree.
3406 * Invalidate old tags.
3410 yaffs_ExtendedTags prevTags;
3413 yaffs_ExtendedTags newTags;
3415 yaffs_Device *dev = in->myDev;
3417 yaffs_CheckGarbageCollection(dev);
3419 /* Get the previous chunk at this location in the file if it exists */
3420 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3422 /* Set up new tags */
3423 yaffs_InitialiseTags(&newTags);
3425 newTags.chunkId = chunkInInode;
3426 newTags.objectId = in->objectId;
3427 newTags.serialNumber =
3428 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
3429 newTags.byteCount = nBytes;
3432 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3435 if (newChunkId >= 0) {
3436 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3438 if (prevChunkId >= 0) {
3439 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3443 yaffs_CheckFileSanity(in);
3449 /* UpdateObjectHeader updates the header on NAND for an object.
3450 * If name is not NULL, then that new name is used.
3452 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
3453 int isShrink, int shadows)
3456 yaffs_BlockInfo *bi;
3458 yaffs_Device *dev = in->myDev;
3464 yaffs_ExtendedTags newTags;
3465 yaffs_ExtendedTags oldTags;
3467 __u8 *buffer = NULL;
3468 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3470 yaffs_ObjectHeader *oh = NULL;
3472 yaffs_strcpy(oldName,"silly old name");
3474 if (!in->fake || force) {
3476 yaffs_CheckGarbageCollection(dev);
3477 yaffs_CheckObjectDetailsLoaded(in);
3479 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3480 oh = (yaffs_ObjectHeader *) buffer;
3482 prevChunkId = in->chunkId;
3484 if (prevChunkId >= 0) {
3485 yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3488 yaffs_VerifyObjectHeader(in,oh,&oldTags,0);
3490 memcpy(oldName, oh->name, sizeof(oh->name));
3493 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3495 oh->type = in->variantType;
3496 oh->yst_mode = in->yst_mode;
3497 oh->shadowsObject = shadows;
3499 #ifdef CONFIG_YAFFS_WINCE
3500 oh->win_atime[0] = in->win_atime[0];
3501 oh->win_ctime[0] = in->win_ctime[0];
3502 oh->win_mtime[0] = in->win_mtime[0];
3503 oh->win_atime[1] = in->win_atime[1];
3504 oh->win_ctime[1] = in->win_ctime[1];
3505 oh->win_mtime[1] = in->win_mtime[1];
3507 oh->yst_uid = in->yst_uid;
3508 oh->yst_gid = in->yst_gid;
3509 oh->yst_atime = in->yst_atime;
3510 oh->yst_mtime = in->yst_mtime;
3511 oh->yst_ctime = in->yst_ctime;
3512 oh->yst_rdev = in->yst_rdev;
3515 oh->parentObjectId = in->parent->objectId;
3517 oh->parentObjectId = 0;
3520 if (name && *name) {
3521 memset(oh->name, 0, sizeof(oh->name));
3522 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3523 } else if (prevChunkId>=0) {
3524 memcpy(oh->name, oldName, sizeof(oh->name));
3526 memset(oh->name, 0, sizeof(oh->name));
3529 oh->isShrink = isShrink;
3531 switch (in->variantType) {
3532 case YAFFS_OBJECT_TYPE_UNKNOWN:
3533 /* Should not happen */
3535 case YAFFS_OBJECT_TYPE_FILE:
3537 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3538 || oh->parentObjectId ==
3539 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3540 fileVariant.fileSize;
3542 case YAFFS_OBJECT_TYPE_HARDLINK:
3543 oh->equivalentObjectId =
3544 in->variant.hardLinkVariant.equivalentObjectId;
3546 case YAFFS_OBJECT_TYPE_SPECIAL:
3549 case YAFFS_OBJECT_TYPE_DIRECTORY:
3552 case YAFFS_OBJECT_TYPE_SYMLINK:
3553 yaffs_strncpy(oh->alias,
3554 in->variant.symLinkVariant.alias,
3555 YAFFS_MAX_ALIAS_LENGTH);
3556 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3561 yaffs_InitialiseTags(&newTags);
3563 newTags.chunkId = 0;
3564 newTags.objectId = in->objectId;
3565 newTags.serialNumber = in->serial;
3567 /* Add extra info for file header */
3569 newTags.extraHeaderInfoAvailable = 1;
3570 newTags.extraParentObjectId = oh->parentObjectId;
3571 newTags.extraFileLength = oh->fileSize;
3572 newTags.extraIsShrinkHeader = oh->isShrink;
3573 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3574 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3575 newTags.extraObjectType = in->variantType;
3577 yaffs_VerifyObjectHeader(in,oh,&newTags,1);
3579 /* Create new chunk in NAND */
3581 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3582 (prevChunkId >= 0) ? 1 : 0);
3584 if (newChunkId >= 0) {
3586 in->chunkId = newChunkId;
3588 if (prevChunkId >= 0) {
3589 yaffs_DeleteChunk(dev, prevChunkId, 1,
3593 if(!yaffs_ObjectHasCachedWriteData(in))
3596 /* If this was a shrink, then mark the block that the chunk lives on */
3598 bi = yaffs_GetBlockInfo(in->myDev,
3599 newChunkId /in->myDev-> nChunksPerBlock);
3600 bi->hasShrinkHeader = 1;
3605 retVal = newChunkId;
3610 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3615 /*------------------------ Short Operations Cache ----------------------------------------
3616 * In many situations where there is no high level buffering (eg WinCE) a lot of
3617 * reads might be short sequential reads, and a lot of writes may be short
3618 * sequential writes. eg. scanning/writing a jpeg file.
3619 * In these cases, a short read/write cache can provide a huge perfomance benefit
3620 * with dumb-as-a-rock code.
3621 * In Linux, the page cache provides read buffering aand the short op cache provides write
3624 * There are a limited number (~10) of cache chunks per device so that we don't
3625 * need a very intelligent search.
3628 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3630 yaffs_Device *dev = obj->myDev;
3632 yaffs_ChunkCache *cache;
3633 int nCaches = obj->myDev->nShortOpCaches;
3635 for(i = 0; i < nCaches; i++){
3636 cache = &dev->srCache[i];
3637 if (cache->object == obj &&
3646 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3648 yaffs_Device *dev = obj->myDev;
3649 int lowest = -99; /* Stop compiler whining. */
3651 yaffs_ChunkCache *cache;
3652 int chunkWritten = 0;
3653 int nCaches = obj->myDev->nShortOpCaches;
3659 /* Find the dirty cache for this object with the lowest chunk id. */
3660 for (i = 0; i < nCaches; i++) {
3661 if (dev->srCache[i].object == obj &&
3662 dev->srCache[i].dirty) {
3664 || dev->srCache[i].chunkId <
3666 cache = &dev->srCache[i];
3667 lowest = cache->chunkId;
3672 if (cache && !cache->locked) {
3673 /* Write it out and free it up */
3676 yaffs_WriteChunkDataToObject(cache->object,
3682 cache->object = NULL;
3685 } while (cache && chunkWritten > 0);
3688 /* Hoosterman, disk full while writing cache out. */
3689 T(YAFFS_TRACE_ERROR,
3690 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3697 /*yaffs_FlushEntireDeviceCache(dev)
3702 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3705 int nCaches = dev->nShortOpCaches;
3708 /* Find a dirty object in the cache and flush it...
3709 * until there are no further dirty objects.
3713 for( i = 0; i < nCaches && !obj; i++) {
3714 if (dev->srCache[i].object &&
3715 dev->srCache[i].dirty)
3716 obj = dev->srCache[i].object;
3720 yaffs_FlushFilesChunkCache(obj);
3727 /* Grab us a cache chunk for use.
3728 * First look for an empty one.
3729 * Then look for the least recently used non-dirty one.
3730 * Then look for the least recently used dirty one...., flush and look again.
3732 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
3738 if (dev->nShortOpCaches > 0) {
3739 for (i = 0; i < dev->nShortOpCaches; i++) {
3740 if (!dev->srCache[i].object)
3741 return &dev->srCache[i];
3747 usage = 0; /* just to stop the compiler grizzling */
3749 for (i = 0; i < dev->nShortOpCaches; i++) {
3750 if (!dev->srCache[i].dirty &&
3751 ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
3753 usage = dev->srCache[i].lastUse;
3759 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3766 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
3768 yaffs_ChunkCache *cache;
3769 yaffs_Object *theObj;
3773 if (dev->nShortOpCaches > 0) {
3774 /* Try find a non-dirty one... */
3776 cache = yaffs_GrabChunkCacheWorker(dev);
3779 /* They were all dirty, find the last recently used object and flush
3780 * its cache, then find again.
3781 * NB what's here is not very accurate, we actually flush the object
3782 * the last recently used page.
3785 /* With locking we can't assume we can use entry zero */
3791 for (i = 0; i < dev->nShortOpCaches; i++) {
3792 if (dev->srCache[i].object &&
3793 !dev->srCache[i].locked &&
3794 (dev->srCache[i].lastUse < usage || !cache))
3796 usage = dev->srCache[i].lastUse;
3797 theObj = dev->srCache[i].object;
3798 cache = &dev->srCache[i];
3802 if (!cache || cache->dirty) {
3803 /* Flush and try again */
3804 yaffs_FlushFilesChunkCache(theObj);
3805 cache = yaffs_GrabChunkCacheWorker(dev);
3815 /* Find a cached chunk */
3816 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
3819 yaffs_Device *dev = obj->myDev;
3821 if (dev->nShortOpCaches > 0) {
3822 for (i = 0; i < dev->nShortOpCaches; i++) {
3823 if (dev->srCache[i].object == obj &&
3824 dev->srCache[i].chunkId == chunkId) {
3827 return &dev->srCache[i];
3834 /* Mark the chunk for the least recently used algorithym */
3835 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
3839 if (dev->nShortOpCaches > 0) {
3840 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
3841 /* Reset the cache usages */
3843 for (i = 1; i < dev->nShortOpCaches; i++) {
3844 dev->srCache[i].lastUse = 0;
3851 cache->lastUse = dev->srLastUse;
3859 /* Invalidate a single cache page.
3860 * Do this when a whole page gets written,
3861 * ie the short cache for this page is no longer valid.
3863 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
3865 if (object->myDev->nShortOpCaches > 0) {
3866 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
3869 cache->object = NULL;
3874 /* Invalidate all the cache pages associated with this object
3875 * Do this whenever ther file is deleted or resized.
3877 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
3880 yaffs_Device *dev = in->myDev;
3882 if (dev->nShortOpCaches > 0) {
3883 /* Invalidate it. */
3884 for (i = 0; i < dev->nShortOpCaches; i++) {
3885 if (dev->srCache[i].object == in) {
3886 dev->srCache[i].object = NULL;
3892 /*--------------------- Checkpointing --------------------*/
3895 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
3897 yaffs_CheckpointValidity cp;
3899 memset(&cp,0,sizeof(cp));
3901 cp.structType = sizeof(cp);
3902 cp.magic = YAFFS_MAGIC;
3903 cp.version = YAFFS_CHECKPOINT_VERSION;
3904 cp.head = (head) ? 1 : 0;
3906 return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
3910 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
3912 yaffs_CheckpointValidity cp;
3915 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3918 ok = (cp.structType == sizeof(cp)) &&
3919 (cp.magic == YAFFS_MAGIC) &&
3920 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
3921 (cp.head == ((head) ? 1 : 0));
3925 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
3928 cp->nErasedBlocks = dev->nErasedBlocks;
3929 cp->allocationBlock = dev->allocationBlock;
3930 cp->allocationPage = dev->allocationPage;
3931 cp->nFreeChunks = dev->nFreeChunks;
3933 cp->nDeletedFiles = dev->nDeletedFiles;
3934 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
3935 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
3936 cp->sequenceNumber = dev->sequenceNumber;
3937 cp->oldestDirtySequence = dev->oldestDirtySequence;
3941 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
3942 yaffs_CheckpointDevice *cp)
3944 dev->nErasedBlocks = cp->nErasedBlocks;
3945 dev->allocationBlock = cp->allocationBlock;
3946 dev->allocationPage = cp->allocationPage;
3947 dev->nFreeChunks = cp->nFreeChunks;
3949 dev->nDeletedFiles = cp->nDeletedFiles;
3950 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
3951 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
3952 dev->sequenceNumber = cp->sequenceNumber;
3953 dev->oldestDirtySequence = cp->oldestDirtySequence;
3957 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
3959 yaffs_CheckpointDevice cp;
3961 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
3965 /* Write device runtime values*/
3966 yaffs_DeviceToCheckpointDevice(&cp,dev);
3967 cp.structType = sizeof(cp);
3969 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3971 /* Write block info */
3973 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
3974 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
3977 /* Write chunk bits */
3979 nBytes = nBlocks * dev->chunkBitmapStride;
3980 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
3986 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
3988 yaffs_CheckpointDevice cp;
3990 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
3994 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3998 if(cp.structType != sizeof(cp))
4002 yaffs_CheckpointDeviceToDevice(dev,&cp);
4004 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4006 ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
4010 nBytes = nBlocks * dev->chunkBitmapStride;
4012 ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
4017 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4021 cp->objectId = obj->objectId;
4022 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4023 cp->chunkId = obj->chunkId;
4024 cp->variantType = obj->variantType;
4025 cp->deleted = obj->deleted;
4026 cp->softDeleted = obj->softDeleted;
4027 cp->unlinked = obj->unlinked;
4028 cp->fake = obj->fake;
4029 cp->renameAllowed = obj->renameAllowed;
4030 cp->unlinkAllowed = obj->unlinkAllowed;
4031 cp->serial = obj->serial;
4032 cp->nDataChunks = obj->nDataChunks;
4034 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4035 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4036 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4037 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4040 static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
4043 yaffs_Object *parent;
4045 obj->objectId = cp->objectId;
4048 parent = yaffs_FindOrCreateObjectByNumber(
4051 YAFFS_OBJECT_TYPE_DIRECTORY);
4056 yaffs_AddObjectToDirectory(parent, obj);
4058 obj->chunkId = cp->chunkId;
4059 obj->variantType = cp->variantType;
4060 obj->deleted = cp->deleted;
4061 obj->softDeleted = cp->softDeleted;
4062 obj->unlinked = cp->unlinked;
4063 obj->fake = cp->fake;
4064 obj->renameAllowed = cp->renameAllowed;
4065 obj->unlinkAllowed = cp->unlinkAllowed;
4066 obj->serial = cp->serial;
4067 obj->nDataChunks = cp->nDataChunks;
4069 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4070 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4071 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4072 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4074 if(obj->objectId >= YAFFS_NOBJECT_BUCKETS)
4075 obj->lazyLoaded = 1;
4080 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
4081 __u32 level, int chunkOffset)
4084 yaffs_Device *dev = in->myDev;
4086 int nTnodeBytes = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4091 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
4092 if (tn->internal[i]) {
4093 ok = yaffs_CheckpointTnodeWorker(in,
4096 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4099 } else if (level == 0) {
4100 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4101 /* printf("write tnode at %d\n",baseOffset); */
4102 ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
4104 ok = (yaffs_CheckpointWrite(dev,tn,nTnodeBytes) == nTnodeBytes);
4112 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4114 __u32 endMarker = ~0;
4117 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4118 ok = yaffs_CheckpointTnodeWorker(obj,
4119 obj->variant.fileVariant.top,
4120 obj->variant.fileVariant.topLevel,
4123 ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) ==
4130 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4134 yaffs_Device *dev = obj->myDev;
4135 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4139 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4141 while(ok && (~baseChunk)){
4143 /* Read level 0 tnode */
4146 /* printf("read tnode at %d\n",baseChunk); */
4147 tn = yaffs_GetTnodeRaw(dev);
4149 ok = (yaffs_CheckpointRead(dev,tn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8) ==
4150 (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
4155 ok = yaffs_AddOrFindLevel0Tnode(dev,
4163 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4167 T(YAFFS_TRACE_CHECKPOINT,(
4168 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4169 nread,baseChunk,ok));
4175 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4178 yaffs_CheckpointObject cp;
4181 struct list_head *lh;
4184 /* Iterate through the objects in each hash entry,
4185 * dumping them to the checkpointing stream.
4188 for(i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++){
4189 list_for_each(lh, &dev->objectBucket[i].list) {
4191 obj = list_entry(lh, yaffs_Object, hashLink);
4192 if (!obj->deferedFree) {
4193 yaffs_ObjectToCheckpointObject(&cp,obj);
4194 cp.structType = sizeof(cp);
4196 T(YAFFS_TRACE_CHECKPOINT,(
4197 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
4198 cp.objectId,cp.parentId,cp.variantType,cp.chunkId,(unsigned) obj));
4200 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4202 if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4203 ok = yaffs_WriteCheckpointTnodes(obj);
4210 /* Dump end of list */
4211 memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
4212 cp.structType = sizeof(cp);
4215 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4220 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4223 yaffs_CheckpointObject cp;
4226 yaffs_Object *hardList = NULL;
4228 while(ok && !done) {
4229 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4230 if(cp.structType != sizeof(cp)) {
4231 T(YAFFS_TRACE_CHECKPOINT,(TSTR("struct size %d instead of %d ok %d"TENDSTR),
4232 cp.structType,sizeof(cp),ok));
4236 T(YAFFS_TRACE_CHECKPOINT,(TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4237 cp.objectId,cp.parentId,cp.variantType,cp.chunkId));
4239 if(ok && cp.objectId == ~0)
4242 obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
4244 yaffs_CheckpointObjectToObject(obj,&cp);
4245 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4246 ok = yaffs_ReadCheckpointTnodes(obj);
4247 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4248 obj->hardLinks.next =
4249 (struct list_head *)
4259 yaffs_HardlinkFixup(dev,hardList);
4264 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4266 __u32 checkpointSum;
4269 yaffs_GetCheckpointSum(dev,&checkpointSum);
4271 ok = (yaffs_CheckpointWrite(dev,&checkpointSum,sizeof(checkpointSum)) == sizeof(checkpointSum));
4279 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4281 __u32 checkpointSum0;
4282 __u32 checkpointSum1;
4285 yaffs_GetCheckpointSum(dev,&checkpointSum0);
4287 ok = (yaffs_CheckpointRead(dev,&checkpointSum1,sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4292 if(checkpointSum0 != checkpointSum1)
4299 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4304 if(dev->skipCheckpointWrite || !dev->isYaffs2){
4305 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint write" TENDSTR)));
4310 ok = yaffs_CheckpointOpen(dev,1);
4313 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4314 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
4317 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint device" TENDSTR)));
4318 ok = yaffs_WriteCheckpointDevice(dev);
4321 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint objects" TENDSTR)));
4322 ok = yaffs_WriteCheckpointObjects(dev);
4325 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4326 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
4330 ok = yaffs_WriteCheckpointSum(dev);
4334 if(!yaffs_CheckpointClose(dev))
4338 dev->isCheckpointed = 1;
4340 dev->isCheckpointed = 0;
4342 return dev->isCheckpointed;
4345 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4349 if(dev->skipCheckpointRead || !dev->isYaffs2){
4350 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint read" TENDSTR)));
4355 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
4358 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4359 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
4362 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint device" TENDSTR)));
4363 ok = yaffs_ReadCheckpointDevice(dev);
4366 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint objects" TENDSTR)));
4367 ok = yaffs_ReadCheckpointObjects(dev);
4370 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4371 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
4375 ok = yaffs_ReadCheckpointSum(dev);
4376 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint checksum %d" TENDSTR),ok));
4379 if(!yaffs_CheckpointClose(dev))
4383 dev->isCheckpointed = 1;
4385 dev->isCheckpointed = 0;
4391 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4393 if(dev->isCheckpointed ||
4394 dev->blocksInCheckpoint > 0){
4395 dev->isCheckpointed = 0;
4396 yaffs_CheckpointInvalidateStream(dev);
4397 if(dev->superBlock && dev->markSuperBlockDirty)
4398 dev->markSuperBlockDirty(dev->superBlock);
4403 int yaffs_CheckpointSave(yaffs_Device *dev)
4406 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4408 yaffs_VerifyObjects(dev);
4409 yaffs_VerifyBlocks(dev);
4410 yaffs_VerifyFreeChunks(dev);
4412 if(!dev->isCheckpointed) {
4413 yaffs_InvalidateCheckpoint(dev);
4414 yaffs_WriteCheckpointData(dev);
4417 T(YAFFS_TRACE_ALWAYS,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4419 return dev->isCheckpointed;
4422 int yaffs_CheckpointRestore(yaffs_Device *dev)
4425 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4427 retval = yaffs_ReadCheckpointData(dev);
4429 if(dev->isCheckpointed){
4430 yaffs_VerifyObjects(dev);
4431 yaffs_VerifyBlocks(dev);
4432 yaffs_VerifyFreeChunks(dev);
4435 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4440 /*--------------------- File read/write ------------------------
4441 * Read and write have very similar structures.
4442 * In general the read/write has three parts to it
4443 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4444 * Some complete chunks
4445 * An incomplete chunk to end off with
4447 * Curve-balls: the first chunk might also be the last chunk.
4450 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, loff_t offset,
4459 yaffs_ChunkCache *cache;
4466 //chunk = offset / dev->nDataBytesPerChunk + 1;
4467 //start = offset % dev->nDataBytesPerChunk;
4468 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4471 /* OK now check for the curveball where the start and end are in
4474 if ((start + n) < dev->nDataBytesPerChunk) {
4477 nToCopy = dev->nDataBytesPerChunk - start;
4480 cache = yaffs_FindChunkCache(in, chunk);
4482 /* If the chunk is already in the cache or it is less than a whole chunk
4483 * then use the cache (if there is caching)
4484 * else bypass the cache.
4486 if (cache || nToCopy != dev->nDataBytesPerChunk) {
4487 if (dev->nShortOpCaches > 0) {
4489 /* If we can't find the data in the cache, then load it up. */
4492 cache = yaffs_GrabChunkCache(in->myDev);
4494 cache->chunkId = chunk;
4497 yaffs_ReadChunkDataFromObject(in, chunk,
4503 yaffs_UseChunkCache(dev, cache, 0);
4507 #ifdef CONFIG_YAFFS_WINCE
4508 yfsd_UnlockYAFFS(TRUE);
4510 memcpy(buffer, &cache->data[start], nToCopy);
4512 #ifdef CONFIG_YAFFS_WINCE
4513 yfsd_LockYAFFS(TRUE);
4517 /* Read into the local buffer then copy..*/
4520 yaffs_GetTempBuffer(dev, __LINE__);
4521 yaffs_ReadChunkDataFromObject(in, chunk,
4523 #ifdef CONFIG_YAFFS_WINCE
4524 yfsd_UnlockYAFFS(TRUE);
4526 memcpy(buffer, &localBuffer[start], nToCopy);
4528 #ifdef CONFIG_YAFFS_WINCE
4529 yfsd_LockYAFFS(TRUE);
4531 yaffs_ReleaseTempBuffer(dev, localBuffer,
4536 #ifdef CONFIG_YAFFS_WINCE
4537 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4539 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4540 * This is because we otherwise screw up WinCE's memory mapper
4542 yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
4544 #ifdef CONFIG_YAFFS_WINCE
4545 yfsd_UnlockYAFFS(TRUE);
4547 memcpy(buffer, localBuffer, dev->nDataBytesPerChunk);
4549 #ifdef CONFIG_YAFFS_WINCE
4550 yfsd_LockYAFFS(TRUE);
4551 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4555 /* A full chunk. Read directly into the supplied buffer. */
4556 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4570 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, loff_t offset,
4571 int nBytes, int writeThrough)
4580 int startOfWrite = offset;
4581 int chunkWritten = 0;
4588 while (n > 0 && chunkWritten >= 0) {
4589 //chunk = offset / dev->nDataBytesPerChunk + 1;
4590 //start = offset % dev->nDataBytesPerChunk;
4591 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4594 /* OK now check for the curveball where the start and end are in
4598 if ((start + n) < dev->nDataBytesPerChunk) {
4601 /* Now folks, to calculate how many bytes to write back....
4602 * If we're overwriting and not writing to then end of file then
4603 * we need to write back as much as was there before.
4607 in->variant.fileVariant.fileSize -
4608 ((chunk - 1) * dev->nDataBytesPerChunk);
4610 if (nBytesRead > dev->nDataBytesPerChunk) {
4611 nBytesRead = dev->nDataBytesPerChunk;
4616 (start + n)) ? nBytesRead : (start + n);
4619 nToCopy = dev->nDataBytesPerChunk - start;
4620 nToWriteBack = dev->nDataBytesPerChunk;
4623 if (nToCopy != dev->nDataBytesPerChunk) {
4624 /* An incomplete start or end chunk (or maybe both start and end chunk) */
4625 if (dev->nShortOpCaches > 0) {
4626 yaffs_ChunkCache *cache;
4627 /* If we can't find the data in the cache, then load the cache */
4628 cache = yaffs_FindChunkCache(in, chunk);
4631 && yaffs_CheckSpaceForAllocation(in->
4633 cache = yaffs_GrabChunkCache(in->myDev);
4635 cache->chunkId = chunk;
4638 yaffs_ReadChunkDataFromObject(in, chunk,
4644 !yaffs_CheckSpaceForAllocation(in->myDev)){
4645 /* Drop the cache if it was a read cache item and
4646 * no space check has been made for it.
4652 yaffs_UseChunkCache(dev, cache, 1);
4654 #ifdef CONFIG_YAFFS_WINCE
4655 yfsd_UnlockYAFFS(TRUE);
4658 memcpy(&cache->data[start], buffer,
4661 #ifdef CONFIG_YAFFS_WINCE
4662 yfsd_LockYAFFS(TRUE);
4665 cache->nBytes = nToWriteBack;
4669 yaffs_WriteChunkDataToObject
4672 cache->data, cache->nBytes,
4678 chunkWritten = -1; /* fail the write */
4681 /* An incomplete start or end chunk (or maybe both start and end chunk)
4682 * Read into the local buffer then copy, then copy over and write back.
4686 yaffs_GetTempBuffer(dev, __LINE__);
4688 yaffs_ReadChunkDataFromObject(in, chunk,
4691 #ifdef CONFIG_YAFFS_WINCE
4692 yfsd_UnlockYAFFS(TRUE);
4695 memcpy(&localBuffer[start], buffer, nToCopy);
4697 #ifdef CONFIG_YAFFS_WINCE
4698 yfsd_LockYAFFS(TRUE);
4701 yaffs_WriteChunkDataToObject(in, chunk,
4706 yaffs_ReleaseTempBuffer(dev, localBuffer,
4713 #ifdef CONFIG_YAFFS_WINCE
4714 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4715 * This is because we otherwise screw up WinCE's memory mapper
4717 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4718 #ifdef CONFIG_YAFFS_WINCE
4719 yfsd_UnlockYAFFS(TRUE);
4721 memcpy(localBuffer, buffer, dev->nDataBytesPerChunk);
4722 #ifdef CONFIG_YAFFS_WINCE
4723 yfsd_LockYAFFS(TRUE);
4726 yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
4727 dev->nDataBytesPerChunk,
4729 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4731 /* A full chunk. Write directly from the supplied buffer. */
4733 yaffs_WriteChunkDataToObject(in, chunk, buffer,
4734 dev->nDataBytesPerChunk,
4737 /* Since we've overwritten the cached data, we better invalidate it. */
4738 yaffs_InvalidateChunkCache(in, chunk);
4741 if (chunkWritten >= 0) {
4750 /* Update file object */
4752 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
4753 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4762 /* ---------------------- File resizing stuff ------------------ */
4764 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
4767 yaffs_Device *dev = in->myDev;
4768 int oldFileSize = in->variant.fileVariant.fileSize;
4770 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
4772 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
4773 dev->nDataBytesPerChunk;
4777 /* Delete backwards so that we don't end up with holes if
4778 * power is lost part-way through the operation.
4780 for (i = lastDel; i >= startDel; i--) {
4781 /* NB this could be optimised somewhat,
4782 * eg. could retrieve the tags and write them without
4783 * using yaffs_DeleteChunk
4786 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
4789 (dev->internalStartBlock * dev->nChunksPerBlock)
4791 ((dev->internalEndBlock +
4792 1) * dev->nChunksPerBlock)) {
4793 T(YAFFS_TRACE_ALWAYS,
4794 (TSTR("Found daft chunkId %d for %d" TENDSTR),
4798 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
4805 int yaffs_ResizeFile(yaffs_Object * in, loff_t newSize)
4808 int oldFileSize = in->variant.fileVariant.fileSize;
4809 __u32 newSizeOfPartialChunk = 0;
4810 __u32 newFullChunks = 0;
4812 yaffs_Device *dev = in->myDev;
4814 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
4816 yaffs_FlushFilesChunkCache(in);
4817 yaffs_InvalidateWholeChunkCache(in);
4819 yaffs_CheckGarbageCollection(dev);
4821 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
4822 return yaffs_GetFileSize(in);
4825 if (newSize == oldFileSize) {
4829 if (newSize < oldFileSize) {
4831 yaffs_PruneResizedChunks(in, newSize);
4833 if (newSizeOfPartialChunk != 0) {
4834 int lastChunk = 1 + newFullChunks;
4836 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4838 /* Got to read and rewrite the last chunk with its new size and zero pad */
4839 yaffs_ReadChunkDataFromObject(in, lastChunk,
4842 memset(localBuffer + newSizeOfPartialChunk, 0,
4843 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
4845 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
4846 newSizeOfPartialChunk, 1);
4848 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4851 in->variant.fileVariant.fileSize = newSize;
4853 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
4855 /* newsSize > oldFileSize */
4856 in->variant.fileVariant.fileSize = newSize;
4861 /* Write a new object header.
4862 * show we've shrunk the file, if need be
4863 * Do this only if the file is not in the deleted directories.
4865 if (in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
4866 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
4867 yaffs_UpdateObjectHeader(in, NULL, 0,
4868 (newSize < oldFileSize) ? 1 : 0, 0);
4874 loff_t yaffs_GetFileSize(yaffs_Object * obj)
4876 obj = yaffs_GetEquivalentObject(obj);
4878 switch (obj->variantType) {
4879 case YAFFS_OBJECT_TYPE_FILE:
4880 return obj->variant.fileVariant.fileSize;
4881 case YAFFS_OBJECT_TYPE_SYMLINK:
4882 return yaffs_strlen(obj->variant.symLinkVariant.alias);
4890 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
4894 yaffs_FlushFilesChunkCache(in);
4896 #ifdef CONFIG_YAFFS_WINCE
4897 yfsd_WinFileTimeNow(in->win_mtime);
4900 in->yst_mtime = Y_CURRENT_TIME;
4906 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
4907 0) ? YAFFS_OK : YAFFS_FAIL;
4916 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
4919 /* First off, invalidate the file's data in the cache, without flushing. */
4920 yaffs_InvalidateWholeChunkCache(in);
4922 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
4923 /* Move to the unlinked directory so we have a record that it was deleted. */
4924 yaffs_ChangeObjectName(in, in->myDev->deletedDir,"deleted", 0, 0);
4928 yaffs_RemoveObjectFromDirectory(in);
4929 yaffs_DeleteChunk(in->myDev, in->chunkId, 1, __LINE__);
4932 yaffs_FreeObject(in);
4937 /* yaffs_DeleteFile deletes the whole file data
4938 * and the inode associated with the file.
4939 * It does not delete the links associated with the file.
4941 static int yaffs_UnlinkFile(yaffs_Object * in)
4945 int immediateDeletion = 0;
4948 /* XXX U-BOOT XXX */
4952 immediateDeletion = 1;
4957 if (in->inUse <= 0) {
4958 immediateDeletion = 1;
4962 if (immediateDeletion) {
4964 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
4966 T(YAFFS_TRACE_TRACING,
4967 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
4970 in->myDev->nDeletedFiles++;
4971 if (0 && in->myDev->isYaffs2) {
4972 yaffs_ResizeFile(in, 0);
4974 yaffs_SoftDeleteFile(in);
4977 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
4985 int yaffs_DeleteFile(yaffs_Object * in)
4987 int retVal = YAFFS_OK;
4989 if (in->nDataChunks > 0) {
4990 /* Use soft deletion if there is data in the file */
4991 if (!in->unlinked) {
4992 retVal = yaffs_UnlinkFile(in);
4994 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
4996 in->myDev->nDeletedFiles++;
4997 yaffs_SoftDeleteFile(in);
4999 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
5001 /* The file has no data chunks so we toss it immediately */
5002 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5003 in->variant.fileVariant.top = NULL;
5004 yaffs_DoGenericObjectDeletion(in);
5010 static int yaffs_DeleteDirectory(yaffs_Object * in)
5012 /* First check that the directory is empty. */
5013 if (list_empty(&in->variant.directoryVariant.children)) {
5014 return yaffs_DoGenericObjectDeletion(in);
5021 static int yaffs_DeleteSymLink(yaffs_Object * in)
5023 YFREE(in->variant.symLinkVariant.alias);
5025 return yaffs_DoGenericObjectDeletion(in);
5028 static int yaffs_DeleteHardLink(yaffs_Object * in)
5030 /* remove this hardlink from the list assocaited with the equivalent
5033 list_del(&in->hardLinks);
5034 return yaffs_DoGenericObjectDeletion(in);
5037 static void yaffs_DestroyObject(yaffs_Object * obj)
5039 switch (obj->variantType) {
5040 case YAFFS_OBJECT_TYPE_FILE:
5041 yaffs_DeleteFile(obj);
5043 case YAFFS_OBJECT_TYPE_DIRECTORY:
5044 yaffs_DeleteDirectory(obj);
5046 case YAFFS_OBJECT_TYPE_SYMLINK:
5047 yaffs_DeleteSymLink(obj);
5049 case YAFFS_OBJECT_TYPE_HARDLINK:
5050 yaffs_DeleteHardLink(obj);
5052 case YAFFS_OBJECT_TYPE_SPECIAL:
5053 yaffs_DoGenericObjectDeletion(obj);
5055 case YAFFS_OBJECT_TYPE_UNKNOWN:
5056 break; /* should not happen. */
5060 static int yaffs_UnlinkWorker(yaffs_Object * obj)
5063 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5064 return yaffs_DeleteHardLink(obj);
5065 } else if (!list_empty(&obj->hardLinks)) {
5066 /* Curve ball: We're unlinking an object that has a hardlink.
5068 * This problem arises because we are not strictly following
5069 * The Linux link/inode model.
5071 * We can't really delete the object.
5072 * Instead, we do the following:
5073 * - Select a hardlink.
5074 * - Unhook it from the hard links
5075 * - Unhook it from its parent directory (so that the rename can work)
5076 * - Rename the object to the hardlink's name.
5077 * - Delete the hardlink
5082 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5084 hl = list_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5086 list_del_init(&hl->hardLinks);
5087 list_del_init(&hl->siblings);
5089 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5091 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
5093 if (retVal == YAFFS_OK) {
5094 retVal = yaffs_DoGenericObjectDeletion(hl);
5099 switch (obj->variantType) {
5100 case YAFFS_OBJECT_TYPE_FILE:
5101 return yaffs_UnlinkFile(obj);
5103 case YAFFS_OBJECT_TYPE_DIRECTORY:
5104 return yaffs_DeleteDirectory(obj);
5106 case YAFFS_OBJECT_TYPE_SYMLINK:
5107 return yaffs_DeleteSymLink(obj);
5109 case YAFFS_OBJECT_TYPE_SPECIAL:
5110 return yaffs_DoGenericObjectDeletion(obj);
5112 case YAFFS_OBJECT_TYPE_HARDLINK:
5113 case YAFFS_OBJECT_TYPE_UNKNOWN:
5121 static int yaffs_UnlinkObject( yaffs_Object *obj)
5124 if (obj && obj->unlinkAllowed) {
5125 return yaffs_UnlinkWorker(obj);
5131 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
5135 obj = yaffs_FindObjectByName(dir, name);
5136 return yaffs_UnlinkObject(obj);
5139 /*----------------------- Initialisation Scanning ---------------------- */
5141 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
5142 int backwardScanning)
5146 if (!backwardScanning) {
5147 /* Handle YAFFS1 forward scanning case
5148 * For YAFFS1 we always do the deletion
5152 /* Handle YAFFS2 case (backward scanning)
5153 * If the shadowed object exists then ignore.
5155 if (yaffs_FindObjectByNumber(dev, objId)) {
5160 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5161 * We put it in unlinked dir to be cleaned up after the scanning
5164 yaffs_FindOrCreateObjectByNumber(dev, objId,
5165 YAFFS_OBJECT_TYPE_FILE);
5166 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5167 obj->variant.fileVariant.shrinkSize = 0;
5168 obj->valid = 1; /* So that we don't read any other info for this file */
5178 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5185 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5187 in = yaffs_FindObjectByNumber(dev,
5188 hl->variant.hardLinkVariant.
5189 equivalentObjectId);
5192 /* Add the hardlink pointers */
5193 hl->variant.hardLinkVariant.equivalentObject = in;
5194 list_add(&hl->hardLinks, &in->hardLinks);
5196 /* Todo Need to report/handle this better.
5197 * Got a problem... hardlink to a non-existant object
5199 hl->variant.hardLinkVariant.equivalentObject = NULL;
5200 INIT_LIST_HEAD(&hl->hardLinks);
5212 static int ybicmp(const void *a, const void *b){
5213 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5214 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5215 register int ablock = ((yaffs_BlockIndex *)a)->block;
5216 register int bblock = ((yaffs_BlockIndex *)b)->block;
5218 return ablock - bblock;
5224 static int yaffs_Scan(yaffs_Device * dev)
5226 yaffs_ExtendedTags tags;
5231 int nBlocksToScan = 0;
5236 yaffs_BlockState state;
5237 yaffs_Object *hardList = NULL;
5238 yaffs_BlockInfo *bi;
5240 yaffs_ObjectHeader *oh;
5242 yaffs_Object *parent;
5243 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5245 int alloc_failed = 0;
5250 yaffs_BlockIndex *blockIndex = NULL;
5252 if (dev->isYaffs2) {
5254 (TSTR("yaffs_Scan is not for YAFFS2!" TENDSTR)));
5258 //TODO Throw all the yaffs2 stuuf out of yaffs_Scan since it is only for yaffs1 format.
5261 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5262 dev->internalStartBlock, dev->internalEndBlock));
5264 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5266 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5268 if (dev->isYaffs2) {
5269 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
5274 /* Scan all the blocks to determine their state */
5275 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5276 bi = yaffs_GetBlockInfo(dev, blk);
5277 yaffs_ClearChunkBits(dev, blk);
5279 bi->softDeletions = 0;
5281 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5283 bi->blockState = state;
5284 bi->sequenceNumber = sequenceNumber;
5286 T(YAFFS_TRACE_SCAN_DEBUG,
5287 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5288 state, sequenceNumber));
5290 if (state == YAFFS_BLOCK_STATE_DEAD) {
5291 T(YAFFS_TRACE_BAD_BLOCKS,
5292 (TSTR("block %d is bad" TENDSTR), blk));
5293 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5294 T(YAFFS_TRACE_SCAN_DEBUG,
5295 (TSTR("Block empty " TENDSTR)));
5296 dev->nErasedBlocks++;
5297 dev->nFreeChunks += dev->nChunksPerBlock;
5298 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5300 /* Determine the highest sequence number */
5301 if (dev->isYaffs2 &&
5302 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
5303 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
5305 blockIndex[nBlocksToScan].seq = sequenceNumber;
5306 blockIndex[nBlocksToScan].block = blk;
5310 if (sequenceNumber >= dev->sequenceNumber) {
5311 dev->sequenceNumber = sequenceNumber;
5313 } else if (dev->isYaffs2) {
5314 /* TODO: Nasty sequence number! */
5317 ("Block scanning block %d has bad sequence number %d"
5318 TENDSTR), blk, sequenceNumber));
5325 * Dungy old bubble sort for now...
5327 if (dev->isYaffs2) {
5328 yaffs_BlockIndex temp;
5332 for (i = 0; i < nBlocksToScan; i++)
5333 for (j = i + 1; j < nBlocksToScan; j++)
5334 if (blockIndex[i].seq > blockIndex[j].seq) {
5335 temp = blockIndex[j];
5336 blockIndex[j] = blockIndex[i];
5337 blockIndex[i] = temp;
5341 /* Now scan the blocks looking at the data. */
5342 if (dev->isYaffs2) {
5344 endIterator = nBlocksToScan - 1;
5345 T(YAFFS_TRACE_SCAN_DEBUG,
5346 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
5348 startIterator = dev->internalStartBlock;
5349 endIterator = dev->internalEndBlock;
5352 /* For each block.... */
5353 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5356 if (dev->isYaffs2) {
5357 /* get the block to scan in the correct order */
5358 blk = blockIndex[blockIterator].block;
5360 blk = blockIterator;
5363 bi = yaffs_GetBlockInfo(dev, blk);
5364 state = bi->blockState;
5368 /* For each chunk in each block that needs scanning....*/
5369 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5370 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5371 /* Read the tags and decide what to do */
5372 chunk = blk * dev->nChunksPerBlock + c;
5374 yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5377 /* Let's have a good look at this chunk... */
5379 if (!dev->isYaffs2 && tags.chunkDeleted) {
5385 /*T((" %d %d deleted\n",blk,c)); */
5386 } else if (!tags.chunkUsed) {
5387 /* An unassigned chunk in the block
5388 * This means that either the block is empty or
5389 * this is the one being allocated from
5393 /* We're looking at the first chunk in the block so the block is unused */
5394 state = YAFFS_BLOCK_STATE_EMPTY;
5395 dev->nErasedBlocks++;
5397 /* this is the block being allocated from */
5400 (" Allocating from %d %d" TENDSTR),
5402 state = YAFFS_BLOCK_STATE_ALLOCATING;
5403 dev->allocationBlock = blk;
5404 dev->allocationPage = c;
5405 dev->allocationBlockFinder = blk;
5406 /* Set it to here to encourage the allocator to go forth from here. */
5408 /* Yaffs2 sanity check:
5409 * This should be the one with the highest sequence number
5412 && (dev->sequenceNumber !=
5413 bi->sequenceNumber)) {
5414 T(YAFFS_TRACE_ALWAYS,
5416 ("yaffs: Allocation block %d was not highest sequence id:"
5417 " block seq = %d, dev seq = %d"
5418 TENDSTR), blk,bi->sequenceNumber,dev->sequenceNumber));
5422 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5423 } else if (tags.chunkId > 0) {
5424 /* chunkId > 0 so it is a data chunk... */
5425 unsigned int endpos;
5427 yaffs_SetChunkBit(dev, blk, c);
5430 in = yaffs_FindOrCreateObjectByNumber(dev,
5433 YAFFS_OBJECT_TYPE_FILE);
5434 /* PutChunkIntoFile checks for a clash (two data chunks with
5435 * the same chunkId).
5442 if(!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,1))
5447 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5450 in->variantType == YAFFS_OBJECT_TYPE_FILE
5451 && in->variant.fileVariant.scannedFileSize <
5453 in->variant.fileVariant.
5454 scannedFileSize = endpos;
5455 if (!dev->useHeaderFileSize) {
5456 in->variant.fileVariant.
5458 in->variant.fileVariant.
5463 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
5465 /* chunkId == 0, so it is an ObjectHeader.
5466 * Thus, we read in the object header and make the object
5468 yaffs_SetChunkBit(dev, blk, c);
5471 yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5475 oh = (yaffs_ObjectHeader *) chunkData;
5477 in = yaffs_FindObjectByNumber(dev,
5479 if (in && in->variantType != oh->type) {
5480 /* This should not happen, but somehow
5481 * Wev'e ended up with an objectId that has been reused but not yet
5482 * deleted, and worse still it has changed type. Delete the old object.
5485 yaffs_DestroyObject(in);
5490 in = yaffs_FindOrCreateObjectByNumber(dev,
5498 if (in && oh->shadowsObject > 0) {
5499 yaffs_HandleShadowedObject(dev,
5505 if (in && in->valid) {
5506 /* We have already filled this one. We have a duplicate and need to resolve it. */
5508 unsigned existingSerial = in->serial;
5509 unsigned newSerial = tags.serialNumber;
5511 if (dev->isYaffs2 ||
5512 ((existingSerial + 1) & 3) ==
5514 /* Use new one - destroy the exisiting one */
5515 yaffs_DeleteChunk(dev,
5520 /* Use existing - destroy this one. */
5521 yaffs_DeleteChunk(dev, chunk, 1,
5526 if (in && !in->valid &&
5527 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5528 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5529 /* We only load some info, don't fiddle with directory structure */
5531 in->variantType = oh->type;
5533 in->yst_mode = oh->yst_mode;
5534 #ifdef CONFIG_YAFFS_WINCE
5535 in->win_atime[0] = oh->win_atime[0];
5536 in->win_ctime[0] = oh->win_ctime[0];
5537 in->win_mtime[0] = oh->win_mtime[0];
5538 in->win_atime[1] = oh->win_atime[1];
5539 in->win_ctime[1] = oh->win_ctime[1];
5540 in->win_mtime[1] = oh->win_mtime[1];
5542 in->yst_uid = oh->yst_uid;
5543 in->yst_gid = oh->yst_gid;
5544 in->yst_atime = oh->yst_atime;
5545 in->yst_mtime = oh->yst_mtime;
5546 in->yst_ctime = oh->yst_ctime;
5547 in->yst_rdev = oh->yst_rdev;
5549 in->chunkId = chunk;
5551 } else if (in && !in->valid) {
5552 /* we need to load this info */
5555 in->variantType = oh->type;
5557 in->yst_mode = oh->yst_mode;
5558 #ifdef CONFIG_YAFFS_WINCE
5559 in->win_atime[0] = oh->win_atime[0];
5560 in->win_ctime[0] = oh->win_ctime[0];
5561 in->win_mtime[0] = oh->win_mtime[0];
5562 in->win_atime[1] = oh->win_atime[1];
5563 in->win_ctime[1] = oh->win_ctime[1];
5564 in->win_mtime[1] = oh->win_mtime[1];
5566 in->yst_uid = oh->yst_uid;
5567 in->yst_gid = oh->yst_gid;
5568 in->yst_atime = oh->yst_atime;
5569 in->yst_mtime = oh->yst_mtime;
5570 in->yst_ctime = oh->yst_ctime;
5571 in->yst_rdev = oh->yst_rdev;
5573 in->chunkId = chunk;
5575 yaffs_SetObjectName(in, oh->name);
5578 /* directory stuff...
5583 yaffs_FindOrCreateObjectByNumber
5584 (dev, oh->parentObjectId,
5585 YAFFS_OBJECT_TYPE_DIRECTORY);
5586 if (parent->variantType ==
5587 YAFFS_OBJECT_TYPE_UNKNOWN) {
5588 /* Set up as a directory */
5589 parent->variantType =
5590 YAFFS_OBJECT_TYPE_DIRECTORY;
5591 INIT_LIST_HEAD(&parent->variant.
5594 } else if (parent->variantType !=
5595 YAFFS_OBJECT_TYPE_DIRECTORY)
5597 /* Hoosterman, another problem....
5598 * We're trying to use a non-directory as a directory
5601 T(YAFFS_TRACE_ERROR,
5603 ("yaffs tragedy: attempting to use non-directory as"
5604 " a directory in scan. Put in lost+found."
5606 parent = dev->lostNFoundDir;
5609 yaffs_AddObjectToDirectory(parent, in);
5611 if (0 && (parent == dev->deletedDir ||
5612 parent == dev->unlinkedDir)) {
5613 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
5614 dev->nDeletedFiles++;
5616 /* Note re hardlinks.
5617 * Since we might scan a hardlink before its equivalent object is scanned
5618 * we put them all in a list.
5619 * After scanning is complete, we should have all the objects, so we run through this
5620 * list and fix up all the chains.
5623 switch (in->variantType) {
5624 case YAFFS_OBJECT_TYPE_UNKNOWN:
5625 /* Todo got a problem */
5627 case YAFFS_OBJECT_TYPE_FILE:
5630 /* Prune back the shrunken chunks */
5631 yaffs_PruneResizedChunks
5633 /* Mark the block as having a shrinkHeader */
5634 bi->hasShrinkHeader = 1;
5637 if (dev->useHeaderFileSize)
5639 in->variant.fileVariant.
5644 case YAFFS_OBJECT_TYPE_HARDLINK:
5645 in->variant.hardLinkVariant.
5646 equivalentObjectId =
5647 oh->equivalentObjectId;
5648 in->hardLinks.next =
5649 (struct list_head *)
5653 case YAFFS_OBJECT_TYPE_DIRECTORY:
5656 case YAFFS_OBJECT_TYPE_SPECIAL:
5659 case YAFFS_OBJECT_TYPE_SYMLINK:
5660 in->variant.symLinkVariant.alias =
5661 yaffs_CloneString(oh->alias);
5662 if(!in->variant.symLinkVariant.alias)
5667 if (parent == dev->deletedDir) {
5668 yaffs_DestroyObject(in);
5669 bi->hasShrinkHeader = 1;
5675 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5676 /* If we got this far while scanning, then the block is fully allocated.*/
5677 state = YAFFS_BLOCK_STATE_FULL;
5680 bi->blockState = state;
5682 /* Now let's see if it was dirty */
5683 if (bi->pagesInUse == 0 &&
5684 !bi->hasShrinkHeader &&
5685 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5686 yaffs_BlockBecameDirty(dev, blk);
5696 /* Ok, we've done all the scanning.
5697 * Fix up the hard link chains.
5698 * We should now have scanned all the objects, now it's time to add these
5702 yaffs_HardlinkFixup(dev,hardList);
5704 /* Handle the unlinked files. Since they were left in an unlinked state we should
5708 struct list_head *i;
5709 struct list_head *n;
5712 /* Soft delete all the unlinked files */
5713 list_for_each_safe(i, n,
5714 &dev->unlinkedDir->variant.directoryVariant.
5717 l = list_entry(i, yaffs_Object, siblings);
5718 yaffs_DestroyObject(l);
5723 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5729 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5735 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5738 yaffs_ObjectHeader *oh;
5739 yaffs_Device *dev = in->myDev;
5740 yaffs_ExtendedTags tags;
5746 T(YAFFS_TRACE_SCAN,(TSTR("details for object %d %s loaded" TENDSTR),
5748 in->lazyLoaded ? "not yet" : "already"));
5753 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5755 yaffs_ReadChunkWithTagsFromNAND(dev, in->chunkId,
5757 oh = (yaffs_ObjectHeader *) chunkData;
5759 in->yst_mode = oh->yst_mode;
5760 #ifdef CONFIG_YAFFS_WINCE
5761 in->win_atime[0] = oh->win_atime[0];
5762 in->win_ctime[0] = oh->win_ctime[0];
5763 in->win_mtime[0] = oh->win_mtime[0];
5764 in->win_atime[1] = oh->win_atime[1];
5765 in->win_ctime[1] = oh->win_ctime[1];
5766 in->win_mtime[1] = oh->win_mtime[1];
5768 in->yst_uid = oh->yst_uid;
5769 in->yst_gid = oh->yst_gid;
5770 in->yst_atime = oh->yst_atime;
5771 in->yst_mtime = oh->yst_mtime;
5772 in->yst_ctime = oh->yst_ctime;
5773 in->yst_rdev = oh->yst_rdev;
5776 yaffs_SetObjectName(in, oh->name);
5778 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
5779 in->variant.symLinkVariant.alias =
5780 yaffs_CloneString(oh->alias);
5783 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
5787 static int yaffs_ScanBackwards(yaffs_Device * dev)
5789 yaffs_ExtendedTags tags;
5794 int nBlocksToScan = 0;
5798 yaffs_BlockState state;
5799 yaffs_Object *hardList = NULL;
5800 yaffs_BlockInfo *bi;
5802 yaffs_ObjectHeader *oh;
5804 yaffs_Object *parent;
5805 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5811 int foundChunksInBlock;
5812 int equivalentObjectId;
5813 int alloc_failed = 0;
5816 yaffs_BlockIndex *blockIndex = NULL;
5817 int altBlockIndex = 0;
5819 if (!dev->isYaffs2) {
5821 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
5827 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
5828 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
5831 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5833 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
5836 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
5842 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
5846 dev->blocksInCheckpoint = 0;
5848 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5850 /* Scan all the blocks to determine their state */
5851 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5852 bi = yaffs_GetBlockInfo(dev, blk);
5853 yaffs_ClearChunkBits(dev, blk);
5855 bi->softDeletions = 0;
5857 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5859 bi->blockState = state;
5860 bi->sequenceNumber = sequenceNumber;
5862 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
5863 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
5865 T(YAFFS_TRACE_SCAN_DEBUG,
5866 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5867 state, sequenceNumber));
5870 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
5871 dev->blocksInCheckpoint++;
5873 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
5874 T(YAFFS_TRACE_BAD_BLOCKS,
5875 (TSTR("block %d is bad" TENDSTR), blk));
5876 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5877 T(YAFFS_TRACE_SCAN_DEBUG,
5878 (TSTR("Block empty " TENDSTR)));
5879 dev->nErasedBlocks++;
5880 dev->nFreeChunks += dev->nChunksPerBlock;
5881 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5883 /* Determine the highest sequence number */
5884 if (dev->isYaffs2 &&
5885 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
5886 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
5888 blockIndex[nBlocksToScan].seq = sequenceNumber;
5889 blockIndex[nBlocksToScan].block = blk;
5893 if (sequenceNumber >= dev->sequenceNumber) {
5894 dev->sequenceNumber = sequenceNumber;
5896 } else if (dev->isYaffs2) {
5897 /* TODO: Nasty sequence number! */
5900 ("Block scanning block %d has bad sequence number %d"
5901 TENDSTR), blk, sequenceNumber));
5908 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
5914 /* Sort the blocks */
5915 #ifndef CONFIG_YAFFS_USE_OWN_SORT
5917 /* Use qsort now. */
5918 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
5922 /* Dungy old bubble sort... */
5924 yaffs_BlockIndex temp;
5928 for (i = 0; i < nBlocksToScan; i++)
5929 for (j = i + 1; j < nBlocksToScan; j++)
5930 if (blockIndex[i].seq > blockIndex[j].seq) {
5931 temp = blockIndex[j];
5932 blockIndex[j] = blockIndex[i];
5933 blockIndex[i] = temp;
5940 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
5942 /* Now scan the blocks looking at the data. */
5944 endIterator = nBlocksToScan - 1;
5945 T(YAFFS_TRACE_SCAN_DEBUG,
5946 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
5948 /* For each block.... backwards */
5949 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
5951 /* Cooperative multitasking! This loop can run for so
5952 long that watchdog timers expire. */
5955 /* get the block to scan in the correct order */
5956 blk = blockIndex[blockIterator].block;
5958 bi = yaffs_GetBlockInfo(dev, blk);
5961 state = bi->blockState;
5963 /* For each chunk in each block that needs scanning.... */
5964 foundChunksInBlock = 0;
5965 for (c = dev->nChunksPerBlock - 1;
5966 !alloc_failed && c >= 0 &&
5967 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
5968 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
5969 /* Scan backwards...
5970 * Read the tags and decide what to do
5973 chunk = blk * dev->nChunksPerBlock + c;
5975 yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5978 /* Let's have a good look at this chunk... */
5980 if (!tags.chunkUsed) {
5981 /* An unassigned chunk in the block.
5982 * If there are used chunks after this one, then
5983 * it is a chunk that was skipped due to failing the erased
5984 * check. Just skip it so that it can be deleted.
5985 * But, more typically, We get here when this is an unallocated
5986 * chunk and his means that either the block is empty or
5987 * this is the one being allocated from
5990 if(foundChunksInBlock)
5992 /* This is a chunk that was skipped due to failing the erased check */
5994 } else if (c == 0) {
5995 /* We're looking at the first chunk in the block so the block is unused */
5996 state = YAFFS_BLOCK_STATE_EMPTY;
5997 dev->nErasedBlocks++;
5999 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6000 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6001 if(dev->sequenceNumber == bi->sequenceNumber) {
6002 /* this is the block being allocated from */
6006 (" Allocating from %d %d"
6009 state = YAFFS_BLOCK_STATE_ALLOCATING;
6010 dev->allocationBlock = blk;
6011 dev->allocationPage = c;
6012 dev->allocationBlockFinder = blk;
6015 /* This is a partially written block that is not
6016 * the current allocation block. This block must have
6017 * had a write failure, so set up for retirement.
6020 bi->needsRetiring = 1;
6021 bi->gcPrioritise = 1;
6023 T(YAFFS_TRACE_ALWAYS,
6024 (TSTR("Partially written block %d being set for retirement" TENDSTR),
6034 } else if (tags.chunkId > 0) {
6035 /* chunkId > 0 so it is a data chunk... */
6036 unsigned int endpos;
6038 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6040 foundChunksInBlock = 1;
6043 yaffs_SetChunkBit(dev, blk, c);
6046 in = yaffs_FindOrCreateObjectByNumber(dev,
6049 YAFFS_OBJECT_TYPE_FILE);
6056 in->variantType == YAFFS_OBJECT_TYPE_FILE
6058 in->variant.fileVariant.shrinkSize) {
6059 /* This has not been invalidated by a resize */
6060 if(!yaffs_PutChunkIntoFile(in, tags.chunkId,
6065 /* File size is calculated by looking at the data chunks if we have not
6066 * seen an object header yet. Stop this practice once we find an object header.
6070 1) * dev->nDataBytesPerChunk +
6073 if (!in->valid && /* have not got an object header yet */
6074 in->variant.fileVariant.
6075 scannedFileSize < endpos) {
6076 in->variant.fileVariant.
6077 scannedFileSize = endpos;
6078 in->variant.fileVariant.
6080 in->variant.fileVariant.
6085 /* This chunk has been invalidated by a resize, so delete */
6086 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6090 /* chunkId == 0, so it is an ObjectHeader.
6091 * Thus, we read in the object header and make the object
6093 foundChunksInBlock = 1;
6095 yaffs_SetChunkBit(dev, blk, c);
6101 if (tags.extraHeaderInfoAvailable) {
6102 in = yaffs_FindOrCreateObjectByNumber
6103 (dev, tags.objectId,
6104 tags.extraObjectType);
6108 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
6111 tags.extraShadows ||
6113 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6114 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
6117 /* If we don't have valid info then we need to read the chunk
6118 * TODO In future we can probably defer reading the chunk and
6119 * living with invalid data until needed.
6122 yaffs_ReadChunkWithTagsFromNAND(dev,
6127 oh = (yaffs_ObjectHeader *) chunkData;
6130 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6135 /* TODO Hoosterman we have a problem! */
6136 T(YAFFS_TRACE_ERROR,
6138 ("yaffs tragedy: Could not make object for object %d "
6139 "at chunk %d during scan"
6140 TENDSTR), tags.objectId, chunk));
6145 /* We have already filled this one.
6146 * We have a duplicate that will be discarded, but
6147 * we first have to suck out resize info if it is a file.
6150 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6152 oh-> type == YAFFS_OBJECT_TYPE_FILE)||
6153 (tags.extraHeaderInfoAvailable &&
6154 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
6157 (oh) ? oh->fileSize : tags.
6159 __u32 parentObjectId =
6161 parentObjectId : tags.
6162 extraParentObjectId;
6164 (oh) ? oh->isShrink : tags.
6165 extraIsShrinkHeader;
6167 /* If it is deleted (unlinked at start also means deleted)
6168 * we treat the file size as being zeroed at this point.
6170 if (parentObjectId ==
6171 YAFFS_OBJECTID_DELETED
6172 || parentObjectId ==
6173 YAFFS_OBJECTID_UNLINKED) {
6179 in->variant.fileVariant.
6180 shrinkSize > thisSize) {
6181 in->variant.fileVariant.
6187 bi->hasShrinkHeader = 1;
6191 /* Use existing - destroy this one. */
6192 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6197 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6199 YAFFS_OBJECTID_LOSTNFOUND)) {
6200 /* We only load some info, don't fiddle with directory structure */
6204 in->variantType = oh->type;
6206 in->yst_mode = oh->yst_mode;
6207 #ifdef CONFIG_YAFFS_WINCE
6208 in->win_atime[0] = oh->win_atime[0];
6209 in->win_ctime[0] = oh->win_ctime[0];
6210 in->win_mtime[0] = oh->win_mtime[0];
6211 in->win_atime[1] = oh->win_atime[1];
6212 in->win_ctime[1] = oh->win_ctime[1];
6213 in->win_mtime[1] = oh->win_mtime[1];
6215 in->yst_uid = oh->yst_uid;
6216 in->yst_gid = oh->yst_gid;
6217 in->yst_atime = oh->yst_atime;
6218 in->yst_mtime = oh->yst_mtime;
6219 in->yst_ctime = oh->yst_ctime;
6220 in->yst_rdev = oh->yst_rdev;
6224 in->variantType = tags.extraObjectType;
6228 in->chunkId = chunk;
6230 } else if (!in->valid) {
6231 /* we need to load this info */
6234 in->chunkId = chunk;
6237 in->variantType = oh->type;
6239 in->yst_mode = oh->yst_mode;
6240 #ifdef CONFIG_YAFFS_WINCE
6241 in->win_atime[0] = oh->win_atime[0];
6242 in->win_ctime[0] = oh->win_ctime[0];
6243 in->win_mtime[0] = oh->win_mtime[0];
6244 in->win_atime[1] = oh->win_atime[1];
6245 in->win_ctime[1] = oh->win_ctime[1];
6246 in->win_mtime[1] = oh->win_mtime[1];
6248 in->yst_uid = oh->yst_uid;
6249 in->yst_gid = oh->yst_gid;
6250 in->yst_atime = oh->yst_atime;
6251 in->yst_mtime = oh->yst_mtime;
6252 in->yst_ctime = oh->yst_ctime;
6253 in->yst_rdev = oh->yst_rdev;
6256 if (oh->shadowsObject > 0)
6257 yaffs_HandleShadowedObject(dev,
6263 yaffs_SetObjectName(in, oh->name);
6265 yaffs_FindOrCreateObjectByNumber
6266 (dev, oh->parentObjectId,
6267 YAFFS_OBJECT_TYPE_DIRECTORY);
6269 fileSize = oh->fileSize;
6270 isShrink = oh->isShrink;
6271 equivalentObjectId = oh->equivalentObjectId;
6275 in->variantType = tags.extraObjectType;
6277 yaffs_FindOrCreateObjectByNumber
6278 (dev, tags.extraParentObjectId,
6279 YAFFS_OBJECT_TYPE_DIRECTORY);
6280 fileSize = tags.extraFileLength;
6281 isShrink = tags.extraIsShrinkHeader;
6282 equivalentObjectId = tags.extraEquivalentObjectId;
6288 /* directory stuff...
6292 if (parent->variantType ==
6293 YAFFS_OBJECT_TYPE_UNKNOWN) {
6294 /* Set up as a directory */
6295 parent->variantType =
6296 YAFFS_OBJECT_TYPE_DIRECTORY;
6297 INIT_LIST_HEAD(&parent->variant.
6300 } else if (parent->variantType !=
6301 YAFFS_OBJECT_TYPE_DIRECTORY)
6303 /* Hoosterman, another problem....
6304 * We're trying to use a non-directory as a directory
6307 T(YAFFS_TRACE_ERROR,
6309 ("yaffs tragedy: attempting to use non-directory as"
6310 " a directory in scan. Put in lost+found."
6312 parent = dev->lostNFoundDir;
6315 yaffs_AddObjectToDirectory(parent, in);
6317 itsUnlinked = (parent == dev->deletedDir) ||
6318 (parent == dev->unlinkedDir);
6321 /* Mark the block as having a shrinkHeader */
6322 bi->hasShrinkHeader = 1;
6325 /* Note re hardlinks.
6326 * Since we might scan a hardlink before its equivalent object is scanned
6327 * we put them all in a list.
6328 * After scanning is complete, we should have all the objects, so we run
6329 * through this list and fix up all the chains.
6332 switch (in->variantType) {
6333 case YAFFS_OBJECT_TYPE_UNKNOWN:
6334 /* Todo got a problem */
6336 case YAFFS_OBJECT_TYPE_FILE:
6338 if (in->variant.fileVariant.
6339 scannedFileSize < fileSize) {
6340 /* This covers the case where the file size is greater
6341 * than where the data is
6342 * This will happen if the file is resized to be larger
6343 * than its current data extents.
6345 in->variant.fileVariant.fileSize = fileSize;
6346 in->variant.fileVariant.scannedFileSize =
6347 in->variant.fileVariant.fileSize;
6351 in->variant.fileVariant.shrinkSize > fileSize) {
6352 in->variant.fileVariant.shrinkSize = fileSize;
6356 case YAFFS_OBJECT_TYPE_HARDLINK:
6358 in->variant.hardLinkVariant.equivalentObjectId =
6360 in->hardLinks.next =
6361 (struct list_head *) hardList;
6365 case YAFFS_OBJECT_TYPE_DIRECTORY:
6368 case YAFFS_OBJECT_TYPE_SPECIAL:
6371 case YAFFS_OBJECT_TYPE_SYMLINK:
6373 in->variant.symLinkVariant.alias =
6374 yaffs_CloneString(oh->
6376 if(!in->variant.symLinkVariant.alias)
6386 } /* End of scanning for each chunk */
6388 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6389 /* If we got this far while scanning, then the block is fully allocated. */
6390 state = YAFFS_BLOCK_STATE_FULL;
6393 bi->blockState = state;
6395 /* Now let's see if it was dirty */
6396 if (bi->pagesInUse == 0 &&
6397 !bi->hasShrinkHeader &&
6398 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6399 yaffs_BlockBecameDirty(dev, blk);
6405 YFREE_ALT(blockIndex);
6409 /* Ok, we've done all the scanning.
6410 * Fix up the hard link chains.
6411 * We should now have scanned all the objects, now it's time to add these
6414 yaffs_HardlinkFixup(dev,hardList);
6418 * Sort out state of unlinked and deleted objects.
6421 struct list_head *i;
6422 struct list_head *n;
6426 /* Soft delete all the unlinked files */
6427 list_for_each_safe(i, n,
6428 &dev->unlinkedDir->variant.directoryVariant.
6431 l = list_entry(i, yaffs_Object, siblings);
6432 yaffs_DestroyObject(l);
6436 /* Soft delete all the deletedDir files */
6437 list_for_each_safe(i, n,
6438 &dev->deletedDir->variant.directoryVariant.
6441 l = list_entry(i, yaffs_Object, siblings);
6442 yaffs_DestroyObject(l);
6448 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6454 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6459 /*------------------------------ Directory Functions ----------------------------- */
6461 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
6463 yaffs_Device *dev = obj->myDev;
6465 if(dev && dev->removeObjectCallback)
6466 dev->removeObjectCallback(obj);
6468 list_del_init(&obj->siblings);
6473 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
6478 T(YAFFS_TRACE_ALWAYS,
6480 ("tragedy: Trying to add an object to a null pointer directory"
6484 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6485 T(YAFFS_TRACE_ALWAYS,
6487 ("tragedy: Trying to add an object to a non-directory"
6492 if (obj->siblings.prev == NULL) {
6493 /* Not initialised */
6494 INIT_LIST_HEAD(&obj->siblings);
6496 } else if (!list_empty(&obj->siblings)) {
6497 /* If it is holed up somewhere else, un hook it */
6498 yaffs_RemoveObjectFromDirectory(obj);
6501 list_add(&obj->siblings, &directory->variant.directoryVariant.children);
6502 obj->parent = directory;
6504 if (directory == obj->myDev->unlinkedDir
6505 || directory == obj->myDev->deletedDir) {
6507 obj->myDev->nUnlinkedFiles++;
6508 obj->renameAllowed = 0;
6512 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
6517 struct list_head *i;
6518 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
6527 T(YAFFS_TRACE_ALWAYS,
6529 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6533 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6534 T(YAFFS_TRACE_ALWAYS,
6536 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6540 sum = yaffs_CalcNameSum(name);
6542 list_for_each(i, &directory->variant.directoryVariant.children) {
6544 l = list_entry(i, yaffs_Object, siblings);
6546 yaffs_CheckObjectDetailsLoaded(l);
6548 /* Special case for lost-n-found */
6549 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6550 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
6553 } else if (yaffs_SumCompare(l->sum, sum) || l->chunkId <= 0)
6555 /* LostnFound cunk called Objxxx
6558 yaffs_GetObjectName(l, buffer,
6559 YAFFS_MAX_NAME_LENGTH);
6560 if (yaffs_strncmp(name, buffer,YAFFS_MAX_NAME_LENGTH) == 0) {
6573 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
6574 int (*fn) (yaffs_Object *))
6576 struct list_head *i;
6580 T(YAFFS_TRACE_ALWAYS,
6582 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6586 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6587 T(YAFFS_TRACE_ALWAYS,
6589 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6593 list_for_each(i, &theDir->variant.directoryVariant.children) {
6595 l = list_entry(i, yaffs_Object, siblings);
6607 /* GetEquivalentObject dereferences any hard links to get to the
6611 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
6613 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
6614 /* We want the object id of the equivalent object, not this one */
6615 obj = obj->variant.hardLinkVariant.equivalentObject;
6616 yaffs_CheckObjectDetailsLoaded(obj);
6622 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
6624 memset(name, 0, buffSize * sizeof(YCHAR));
6626 yaffs_CheckObjectDetailsLoaded(obj);
6628 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6629 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
6630 } else if (obj->chunkId <= 0) {
6632 /* make up a name */
6633 yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX,
6635 yaffs_strncpy(name, locName, buffSize - 1);
6638 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
6639 else if (obj->shortName[0]) {
6640 yaffs_strcpy(name, obj->shortName);
6644 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
6646 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
6648 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
6650 if (obj->chunkId >= 0) {
6651 yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
6652 obj->chunkId, buffer,
6655 yaffs_strncpy(name, oh->name, buffSize - 1);
6657 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
6660 return yaffs_strlen(name);
6663 int yaffs_GetObjectFileLength(yaffs_Object * obj)
6666 /* Dereference any hard linking */
6667 obj = yaffs_GetEquivalentObject(obj);
6669 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
6670 return obj->variant.fileVariant.fileSize;
6672 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6673 return yaffs_strlen(obj->variant.symLinkVariant.alias);
6675 /* Only a directory should drop through to here */
6676 return obj->myDev->nDataBytesPerChunk;
6680 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
6683 struct list_head *i;
6685 if (!obj->unlinked) {
6686 count++; /* the object itself */
6688 list_for_each(i, &obj->hardLinks) {
6689 count++; /* add the hard links; */
6695 int yaffs_GetObjectInode(yaffs_Object * obj)
6697 obj = yaffs_GetEquivalentObject(obj);
6699 return obj->objectId;
6702 unsigned yaffs_GetObjectType(yaffs_Object * obj)
6704 obj = yaffs_GetEquivalentObject(obj);
6706 switch (obj->variantType) {
6707 case YAFFS_OBJECT_TYPE_FILE:
6710 case YAFFS_OBJECT_TYPE_DIRECTORY:
6713 case YAFFS_OBJECT_TYPE_SYMLINK:
6716 case YAFFS_OBJECT_TYPE_HARDLINK:
6719 case YAFFS_OBJECT_TYPE_SPECIAL:
6720 if (S_ISFIFO(obj->yst_mode))
6722 if (S_ISCHR(obj->yst_mode))
6724 if (S_ISBLK(obj->yst_mode))
6726 if (S_ISSOCK(obj->yst_mode))
6734 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
6736 obj = yaffs_GetEquivalentObject(obj);
6737 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6738 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
6740 return yaffs_CloneString(_Y(""));
6744 #ifndef CONFIG_YAFFS_WINCE
6746 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
6748 unsigned int valid = attr->ia_valid;
6750 if (valid & ATTR_MODE)
6751 obj->yst_mode = attr->ia_mode;
6752 if (valid & ATTR_UID)
6753 obj->yst_uid = attr->ia_uid;
6754 if (valid & ATTR_GID)
6755 obj->yst_gid = attr->ia_gid;
6757 if (valid & ATTR_ATIME)
6758 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
6759 if (valid & ATTR_CTIME)
6760 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
6761 if (valid & ATTR_MTIME)
6762 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
6764 if (valid & ATTR_SIZE)
6765 yaffs_ResizeFile(obj, attr->ia_size);
6767 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6772 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
6774 unsigned int valid = 0;
6776 attr->ia_mode = obj->yst_mode;
6778 attr->ia_uid = obj->yst_uid;
6780 attr->ia_gid = obj->yst_gid;
6783 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
6784 valid |= ATTR_ATIME;
6785 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
6786 valid |= ATTR_CTIME;
6787 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
6788 valid |= ATTR_MTIME;
6790 attr->ia_size = yaffs_GetFileSize(obj);
6793 attr->ia_valid = valid;
6802 int yaffs_DumpObject(yaffs_Object * obj)
6806 yaffs_GetObjectName(obj, name, 256);
6808 T(YAFFS_TRACE_ALWAYS,
6810 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
6811 " chunk %d type %d size %d\n"
6812 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
6813 obj->dirty, obj->valid, obj->serial, obj->sum, obj->chunkId,
6814 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
6820 /*---------------------------- Initialisation code -------------------------------------- */
6822 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
6825 /* Common functions, gotta have */
6826 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
6829 #ifdef CONFIG_YAFFS_YAFFS2
6831 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
6832 if (dev->writeChunkWithTagsToNAND &&
6833 dev->readChunkWithTagsFromNAND &&
6834 !dev->writeChunkToNAND &&
6835 !dev->readChunkFromNAND &&
6836 dev->markNANDBlockBad && dev->queryNANDBlock)
6840 /* Can use the "spare" style interface for yaffs1 */
6841 if (!dev->isYaffs2 &&
6842 !dev->writeChunkWithTagsToNAND &&
6843 !dev->readChunkWithTagsFromNAND &&
6844 dev->writeChunkToNAND &&
6845 dev->readChunkFromNAND &&
6846 !dev->markNANDBlockBad && !dev->queryNANDBlock)
6853 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
6855 /* Initialise the unlinked, deleted, root and lost and found directories */
6857 dev->lostNFoundDir = dev->rootDir = NULL;
6858 dev->unlinkedDir = dev->deletedDir = NULL;
6861 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
6864 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
6867 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
6868 YAFFS_ROOT_MODE | S_IFDIR);
6869 dev->lostNFoundDir =
6870 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
6871 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
6873 if(dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir){
6874 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
6881 int yaffs_GutsInitialise(yaffs_Device * dev)
6883 int init_failed = 0;
6887 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
6889 /* Check stuff that must be set */
6892 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
6896 dev->internalStartBlock = dev->startBlock;
6897 dev->internalEndBlock = dev->endBlock;
6898 dev->blockOffset = 0;
6899 dev->chunkOffset = 0;
6900 dev->nFreeChunks = 0;
6902 if (dev->startBlock == 0) {
6903 dev->internalStartBlock = dev->startBlock + 1;
6904 dev->internalEndBlock = dev->endBlock + 1;
6905 dev->blockOffset = 1;
6906 dev->chunkOffset = dev->nChunksPerBlock;
6909 /* Check geometry parameters. */
6911 if ((dev->isYaffs2 && dev->nDataBytesPerChunk < 1024) ||
6912 (!dev->isYaffs2 && dev->nDataBytesPerChunk != 512) ||
6913 dev->nChunksPerBlock < 2 ||
6914 dev->nReservedBlocks < 2 ||
6915 dev->internalStartBlock <= 0 ||
6916 dev->internalEndBlock <= 0 ||
6917 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
6919 T(YAFFS_TRACE_ALWAYS,
6921 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s "
6922 TENDSTR), dev->nDataBytesPerChunk, dev->isYaffs2 ? "2" : ""));
6926 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
6927 T(YAFFS_TRACE_ALWAYS,
6928 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
6932 /* Got the right mix of functions? */
6933 if (!yaffs_CheckDevFunctions(dev)) {
6934 /* Function missing */
6935 T(YAFFS_TRACE_ALWAYS,
6937 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
6942 /* This is really a compilation check. */
6943 if (!yaffs_CheckStructures()) {
6944 T(YAFFS_TRACE_ALWAYS,
6945 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
6949 if (dev->isMounted) {
6950 T(YAFFS_TRACE_ALWAYS,
6951 (TSTR("yaffs: device already mounted\n" TENDSTR)));
6955 /* Finished with most checks. One or two more checks happen later on too. */
6961 /* OK now calculate a few things for the device */
6964 * Calculate all the chunk size manipulation numbers:
6966 /* Start off assuming it is a power of 2 */
6967 dev->chunkShift = ShiftDiv(dev->nDataBytesPerChunk);
6968 dev->chunkMask = (1<<dev->chunkShift) - 1;
6970 if(dev->nDataBytesPerChunk == (dev->chunkMask + 1)){
6971 /* Yes it is a power of 2, disable crumbs */
6973 dev->crumbShift = 0;
6974 dev->crumbsPerChunk = 0;
6976 /* Not a power of 2, use crumbs instead */
6977 dev->crumbShift = ShiftDiv(sizeof(yaffs_PackedTags2TagsPart));
6978 dev->crumbMask = (1<<dev->crumbShift)-1;
6979 dev->crumbsPerChunk = dev->nDataBytesPerChunk/(1 << dev->crumbShift);
6980 dev->chunkShift = 0;
6986 * Calculate chunkGroupBits.
6987 * We need to find the next power of 2 > than internalEndBlock
6990 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
6994 /* Set up tnode width if wide tnodes are enabled. */
6995 if(!dev->wideTnodesDisabled){
6996 /* bits must be even so that we end up with 32-bit words */
7000 dev->tnodeWidth = 16;
7002 dev->tnodeWidth = bits;
7005 dev->tnodeWidth = 16;
7007 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7009 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7010 * so if the bitwidth of the
7011 * chunk range we're using is greater than 16 we need
7012 * to figure out chunk shift and chunkGroupSize
7015 if (bits <= dev->tnodeWidth)
7016 dev->chunkGroupBits = 0;
7018 dev->chunkGroupBits = bits - dev->tnodeWidth;
7021 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7023 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7024 /* We have a problem because the soft delete won't work if
7025 * the chunk group size > chunks per block.
7026 * This can be remedied by using larger "virtual blocks".
7028 T(YAFFS_TRACE_ALWAYS,
7029 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7034 /* OK, we've finished verifying the device, lets continue with initialisation */
7036 /* More device initialisation */
7037 dev->garbageCollections = 0;
7038 dev->passiveGarbageCollections = 0;
7039 dev->currentDirtyChecker = 0;
7040 dev->bufferedBlock = -1;
7041 dev->doingBufferedBlockRewrite = 0;
7042 dev->nDeletedFiles = 0;
7043 dev->nBackgroundDeletions = 0;
7044 dev->nUnlinkedFiles = 0;
7046 dev->eccUnfixed = 0;
7047 dev->tagsEccFixed = 0;
7048 dev->tagsEccUnfixed = 0;
7049 dev->nErasureFailures = 0;
7050 dev->nErasedBlocks = 0;
7052 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7054 /* Initialise temporary buffers and caches. */
7055 if(!yaffs_InitialiseTempBuffers(dev))
7058 dev->srCache = NULL;
7059 dev->gcCleanupList = NULL;
7063 dev->nShortOpCaches > 0) {
7066 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7068 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
7069 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7072 dev->srCache = YMALLOC(srCacheBytes);
7073 buf = (__u8 *)dev->srCache;
7076 memset(dev->srCache,0,srCacheBytes);
7078 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7079 dev->srCache[i].object = NULL;
7080 dev->srCache[i].lastUse = 0;
7081 dev->srCache[i].dirty = 0;
7082 dev->srCache[i].data = buf = YMALLOC_DMA(dev->nDataBytesPerChunk);
7093 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7094 if(!dev->gcCleanupList)
7098 if (dev->isYaffs2) {
7099 dev->useHeaderFileSize = 1;
7101 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7104 yaffs_InitialiseTnodes(dev);
7105 yaffs_InitialiseObjects(dev);
7107 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7112 /* Now scan the flash. */
7113 if (dev->isYaffs2) {
7114 if(yaffs_CheckpointRestore(dev)) {
7115 T(YAFFS_TRACE_ALWAYS,
7116 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7119 /* Clean up the mess caused by an aborted checkpoint load
7120 * and scan backwards.
7122 yaffs_DeinitialiseBlocks(dev);
7123 yaffs_DeinitialiseTnodes(dev);
7124 yaffs_DeinitialiseObjects(dev);
7127 dev->nErasedBlocks = 0;
7128 dev->nFreeChunks = 0;
7129 dev->allocationBlock = -1;
7130 dev->allocationPage = -1;
7131 dev->nDeletedFiles = 0;
7132 dev->nUnlinkedFiles = 0;
7133 dev->nBackgroundDeletions = 0;
7134 dev->oldestDirtySequence = 0;
7136 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7139 yaffs_InitialiseTnodes(dev);
7140 yaffs_InitialiseObjects(dev);
7142 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7145 if(!init_failed && !yaffs_ScanBackwards(dev))
7149 if(!yaffs_Scan(dev))
7154 /* Clean up the mess */
7155 T(YAFFS_TRACE_TRACING,
7156 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7158 yaffs_Deinitialise(dev);
7162 /* Zero out stats */
7163 dev->nPageReads = 0;
7164 dev->nPageWrites = 0;
7165 dev->nBlockErasures = 0;
7167 dev->nRetriedWrites = 0;
7169 dev->nRetiredBlocks = 0;
7171 yaffs_VerifyFreeChunks(dev);
7172 yaffs_VerifyBlocks(dev);
7175 T(YAFFS_TRACE_TRACING,
7176 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7181 void yaffs_Deinitialise(yaffs_Device * dev)
7183 if (dev->isMounted) {
7186 yaffs_DeinitialiseBlocks(dev);
7187 yaffs_DeinitialiseTnodes(dev);
7188 yaffs_DeinitialiseObjects(dev);
7189 if (dev->nShortOpCaches > 0 &&
7192 for (i = 0; i < dev->nShortOpCaches; i++) {
7193 if(dev->srCache[i].data)
7194 YFREE(dev->srCache[i].data);
7195 dev->srCache[i].data = NULL;
7198 YFREE(dev->srCache);
7199 dev->srCache = NULL;
7202 YFREE(dev->gcCleanupList);
7204 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
7205 YFREE(dev->tempBuffer[i].buffer);
7213 static int yaffs_CountFreeChunks(yaffs_Device * dev)
7218 yaffs_BlockInfo *blk;
7220 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7222 blk = yaffs_GetBlockInfo(dev, b);
7224 switch (blk->blockState) {
7225 case YAFFS_BLOCK_STATE_EMPTY:
7226 case YAFFS_BLOCK_STATE_ALLOCATING:
7227 case YAFFS_BLOCK_STATE_COLLECTING:
7228 case YAFFS_BLOCK_STATE_FULL:
7230 (dev->nChunksPerBlock - blk->pagesInUse +
7231 blk->softDeletions);
7242 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
7244 /* This is what we report to the outside world */
7247 int nDirtyCacheChunks;
7248 int blocksForCheckpoint;
7251 nFree = dev->nFreeChunks;
7253 nFree = yaffs_CountFreeChunks(dev);
7256 nFree += dev->nDeletedFiles;
7258 /* Now count the number of dirty chunks in the cache and subtract those */
7262 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7263 if (dev->srCache[i].dirty)
7264 nDirtyCacheChunks++;
7268 nFree -= nDirtyCacheChunks;
7270 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7272 /* Now we figure out how much to reserve for the checkpoint and report that... */
7273 blocksForCheckpoint = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
7274 if(blocksForCheckpoint < 0)
7275 blocksForCheckpoint = 0;
7277 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7286 static int yaffs_freeVerificationFailures;
7288 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
7293 if(yaffs_SkipVerification(dev))
7296 counted = yaffs_CountFreeChunks(dev);
7298 difference = dev->nFreeChunks - counted;
7301 T(YAFFS_TRACE_ALWAYS,
7302 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7303 dev->nFreeChunks, counted, difference));
7304 yaffs_freeVerificationFailures++;
7308 /*---------------------------------------- YAFFS test code ----------------------*/
7310 #define yaffs_CheckStruct(structure,syze, name) \
7311 if(sizeof(structure) != syze) \
7313 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
7314 name,syze,sizeof(structure))); \
7315 return YAFFS_FAIL; \
7318 static int yaffs_CheckStructures(void)
7320 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags") */
7321 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion") */
7322 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare") */
7323 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7324 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode")
7326 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader")