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.
15 const char *yaffs_guts_c_version =
16 "$Id: yaffs_guts.c,v 1.75 2009-01-23 00:31:01 charles Exp $";
20 #include "yaffsinterface.h"
21 #include "yaffs_guts.h"
22 #include "yaffs_tagsvalidity.h"
23 #include "yaffs_getblockinfo.h"
25 #include "yaffs_tagscompat.h"
26 #ifndef CONFIG_YAFFS_USE_OWN_SORT
27 #include "yaffs_qsort.h"
29 #include "yaffs_nand.h"
31 #include "yaffs_checkptrw.h"
33 #include "yaffs_nand.h"
34 #include "yaffs_packedtags2.h"
37 #ifdef CONFIG_YAFFS_WINCE
38 void yfsd_LockYAFFS(BOOL fsLockOnly);
39 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
42 #define YAFFS_PASSIVE_GC_CHUNKS 2
44 #include "yaffs_ecc.h"
47 /* Robustification (if it ever comes about...) */
48 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
49 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk);
50 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
52 const yaffs_ExtendedTags * tags);
53 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
54 const yaffs_ExtendedTags * tags);
56 /* Other local prototypes */
57 static int yaffs_UnlinkObject( yaffs_Object *obj);
58 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
60 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
62 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
64 yaffs_ExtendedTags * tags,
66 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
67 int chunkInNAND, int inScan);
69 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
70 yaffs_ObjectType type);
71 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
73 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
74 int force, int isShrink, int shadows);
75 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
76 static int yaffs_CheckStructures(void);
77 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
78 int chunkOffset, int *limit);
79 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
81 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
84 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
87 static int yaffs_UnlinkWorker(yaffs_Object * obj);
88 static void yaffs_DestroyObject(yaffs_Object * obj);
90 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
93 loff_t yaffs_GetFileSize(yaffs_Object * obj);
95 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr);
97 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
99 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
101 static void yaffs_VerifyDirectory(yaffs_Object *directory);
102 #ifdef YAFFS_PARANOID
103 static int yaffs_CheckFileSanity(yaffs_Object * in);
105 #define yaffs_CheckFileSanity(in)
108 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
109 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
111 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
113 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
114 yaffs_ExtendedTags * tags);
116 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos);
117 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
118 yaffs_FileStructure * fStruct,
122 /* Function to calculate chunk and offset */
124 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut, __u32 *offsetOut)
129 chunk = (__u32)(addr >> dev->chunkShift);
131 if(dev->chunkDiv == 1)
133 /* easy power of 2 case */
134 offset = (__u32)(addr & dev->chunkMask);
138 /* Non power-of-2 case */
142 chunk /= dev->chunkDiv;
144 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
145 offset = (__u32)(addr - chunkBase);
152 /* Function to return the number of shifts for a power of 2 greater than or equal
153 * to the given number
154 * Note we don't try to cater for all possible numbers and this does not have to
155 * be hellishly efficient.
158 static __u32 ShiftsGE(__u32 x)
163 nShifts = extraBits = 0;
166 if(x & 1) extraBits++;
177 /* Function to return the number of shifts to get a 1 in bit 0
180 static __u32 Shifts(__u32 x)
199 * Temporary buffer manipulations.
202 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
205 __u8 *buf = (__u8 *)1;
207 memset(dev->tempBuffer,0,sizeof(dev->tempBuffer));
209 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
210 dev->tempBuffer[i].line = 0; /* not in use */
211 dev->tempBuffer[i].buffer = buf =
212 YMALLOC_DMA(dev->totalBytesPerChunk);
215 return buf ? YAFFS_OK : YAFFS_FAIL;
219 __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
224 if(dev->tempInUse > dev->maxTemp)
225 dev->maxTemp = dev->tempInUse;
227 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
228 if (dev->tempBuffer[i].line == 0) {
229 dev->tempBuffer[i].line = lineNo;
230 if ((i + 1) > dev->maxTemp) {
231 dev->maxTemp = i + 1;
232 for (j = 0; j <= i; j++)
233 dev->tempBuffer[j].maxLine =
234 dev->tempBuffer[j].line;
237 return dev->tempBuffer[i].buffer;
241 T(YAFFS_TRACE_BUFFERS,
242 (TSTR("Out of temp buffers at line %d, other held by lines:"),
244 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
245 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
247 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
250 * If we got here then we have to allocate an unmanaged one
254 dev->unmanagedTempAllocations++;
255 return YMALLOC(dev->nDataBytesPerChunk);
259 void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
266 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
267 if (dev->tempBuffer[i].buffer == buffer) {
268 dev->tempBuffer[i].line = 0;
274 /* assume it is an unmanaged one. */
275 T(YAFFS_TRACE_BUFFERS,
276 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
279 dev->unmanagedTempDeallocations++;
285 * Determine if we have a managed buffer.
287 int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
290 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
291 if (dev->tempBuffer[i].buffer == buffer)
296 for (i = 0; i < dev->nShortOpCaches; i++) {
297 if( dev->srCache[i].data == buffer )
302 if (buffer == dev->checkpointBuffer)
305 T(YAFFS_TRACE_ALWAYS,
306 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
313 * Chunk bitmap manipulations
316 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
318 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
320 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
324 return dev->chunkBits +
325 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
328 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
330 if(blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
331 chunk < 0 || chunk >= dev->nChunksPerBlock) {
333 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),blk,chunk));
338 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
340 __u8 *blkBits = yaffs_BlockBits(dev, blk);
342 memset(blkBits, 0, dev->chunkBitmapStride);
345 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
347 __u8 *blkBits = yaffs_BlockBits(dev, blk);
349 yaffs_VerifyChunkBitId(dev,blk,chunk);
351 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
354 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
356 __u8 *blkBits = yaffs_BlockBits(dev, blk);
358 yaffs_VerifyChunkBitId(dev,blk,chunk);
360 blkBits[chunk / 8] |= (1 << (chunk & 7));
363 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
365 __u8 *blkBits = yaffs_BlockBits(dev, blk);
366 yaffs_VerifyChunkBitId(dev,blk,chunk);
368 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
371 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
373 __u8 *blkBits = yaffs_BlockBits(dev, blk);
375 for (i = 0; i < dev->chunkBitmapStride; i++) {
383 static int yaffs_CountChunkBits(yaffs_Device * dev, int blk)
385 __u8 *blkBits = yaffs_BlockBits(dev, blk);
388 for (i = 0; i < dev->chunkBitmapStride; i++) {
405 static int yaffs_SkipVerification(yaffs_Device *dev)
407 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
410 static int yaffs_SkipFullVerification(yaffs_Device *dev)
412 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
415 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
417 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
420 static const char * blockStateName[] = {
433 static void yaffs_VerifyBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
438 if(yaffs_SkipVerification(dev))
441 /* Report illegal runtime states */
442 if(bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
443 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has undefined state %d"TENDSTR),n,bi->blockState));
445 switch(bi->blockState){
446 case YAFFS_BLOCK_STATE_UNKNOWN:
447 case YAFFS_BLOCK_STATE_SCANNING:
448 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
449 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has bad run-state %s"TENDSTR),
450 n,blockStateName[bi->blockState]));
453 /* Check pages in use and soft deletions are legal */
455 actuallyUsed = bi->pagesInUse - bi->softDeletions;
457 if(bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
458 bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
459 actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock)
460 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
461 n,bi->pagesInUse,bi->softDeletions));
464 /* Check chunk bitmap legal */
465 inUse = yaffs_CountChunkBits(dev,n);
466 if(inUse != bi->pagesInUse)
467 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
468 n,bi->pagesInUse,inUse));
470 /* Check that the sequence number is valid.
471 * Ten million is legal, but is very unlikely
474 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
475 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000 ))
476 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has suspect sequence number of %d"TENDSTR),
477 n,bi->sequenceNumber));
481 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
483 yaffs_VerifyBlock(dev,bi,n);
485 /* After collection the block should be in the erased state */
486 /* This will need to change if we do partial gc */
488 if(bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
489 bi->blockState != YAFFS_BLOCK_STATE_EMPTY){
490 T(YAFFS_TRACE_ERROR,(TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
495 static void yaffs_VerifyBlocks(yaffs_Device *dev)
498 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
499 int nIllegalBlockStates = 0;
502 if(yaffs_SkipVerification(dev))
505 memset(nBlocksPerState,0,sizeof(nBlocksPerState));
508 for(i = dev->internalStartBlock; i <= dev->internalEndBlock; i++){
509 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
510 yaffs_VerifyBlock(dev,bi,i);
512 if(bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
513 nBlocksPerState[bi->blockState]++;
515 nIllegalBlockStates++;
519 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
520 T(YAFFS_TRACE_VERIFY,(TSTR("Block summary"TENDSTR)));
522 T(YAFFS_TRACE_VERIFY,(TSTR("%d blocks have illegal states"TENDSTR),nIllegalBlockStates));
523 if(nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
524 T(YAFFS_TRACE_VERIFY,(TSTR("Too many allocating blocks"TENDSTR)));
526 for(i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
527 T(YAFFS_TRACE_VERIFY,
528 (TSTR("%s %d blocks"TENDSTR),
529 blockStateName[i],nBlocksPerState[i]));
531 if(dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
532 T(YAFFS_TRACE_VERIFY,
533 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
534 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
536 if(dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
537 T(YAFFS_TRACE_VERIFY,
538 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
539 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
541 if(nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
542 T(YAFFS_TRACE_VERIFY,
543 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
544 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
546 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
551 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
552 * case those tests will not be performed.
554 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
556 if(obj && yaffs_SkipVerification(obj->myDev))
559 if(!(tags && obj && oh)){
560 T(YAFFS_TRACE_VERIFY,
561 (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR),
562 (__u32)tags,(__u32)obj,(__u32)oh));
566 if(oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
567 oh->type > YAFFS_OBJECT_TYPE_MAX)
568 T(YAFFS_TRACE_VERIFY,
569 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
570 tags->objectId, oh->type));
572 if(tags->objectId != obj->objectId)
573 T(YAFFS_TRACE_VERIFY,
574 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
575 tags->objectId, obj->objectId));
579 * Check that the object's parent ids match if parentCheck requested.
581 * Tests do not apply to the root object.
584 if(parentCheck && tags->objectId > 1 && !obj->parent)
585 T(YAFFS_TRACE_VERIFY,
586 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
587 tags->objectId, oh->parentObjectId));
590 if(parentCheck && obj->parent &&
591 oh->parentObjectId != obj->parent->objectId &&
592 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
593 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
594 T(YAFFS_TRACE_VERIFY,
595 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
596 tags->objectId, oh->parentObjectId, obj->parent->objectId));
599 if(tags->objectId > 1 && oh->name[0] == 0) /* Null name */
600 T(YAFFS_TRACE_VERIFY,
601 (TSTR("Obj %d header name is NULL"TENDSTR),
604 if(tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
605 T(YAFFS_TRACE_VERIFY,
606 (TSTR("Obj %d header name is 0xFF"TENDSTR),
612 static int yaffs_VerifyTnodeWorker(yaffs_Object * obj, yaffs_Tnode * tn,
613 __u32 level, int chunkOffset)
616 yaffs_Device *dev = obj->myDev;
622 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
623 if (tn->internal[i]) {
624 ok = yaffs_VerifyTnodeWorker(obj,
627 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
630 } else if (level == 0) {
631 yaffs_ExtendedTags tags;
632 __u32 objectId = obj->objectId;
634 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
636 for(i = 0; i < YAFFS_NTNODES_LEVEL0; i++){
637 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
640 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
641 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
642 if(tags.objectId != objectId || tags.chunkId != chunkOffset){
643 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
644 objectId, chunkOffset, theChunk,
645 tags.objectId, tags.chunkId));
658 static void yaffs_VerifyFile(yaffs_Object *obj)
660 int requiredTallness;
666 yaffs_ExtendedTags tags;
673 if(yaffs_SkipVerification(obj->myDev))
677 objectId = obj->objectId;
679 /* Check file size is consistent with tnode depth */
680 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
681 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
682 requiredTallness = 0;
684 x >>= YAFFS_TNODES_INTERNAL_BITS;
688 actualTallness = obj->variant.fileVariant.topLevel;
690 if(requiredTallness > actualTallness )
691 T(YAFFS_TRACE_VERIFY,
692 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
693 obj->objectId,actualTallness, requiredTallness));
696 /* Check that the chunks in the tnode tree are all correct.
697 * We do this by scanning through the tnode tree and
698 * checking the tags for every chunk match.
701 if(yaffs_SkipNANDVerification(dev))
704 for(i = 1; i <= lastChunk; i++){
705 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant,i);
708 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
710 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
711 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
712 if(tags.objectId != objectId || tags.chunkId != i){
713 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
714 objectId, i, theChunk,
715 tags.objectId, tags.chunkId));
725 static void yaffs_VerifyHardLink(yaffs_Object *obj)
727 if(obj && yaffs_SkipVerification(obj->myDev))
730 /* Verify sane equivalent object */
733 static void yaffs_VerifySymlink(yaffs_Object *obj)
735 if(obj && yaffs_SkipVerification(obj->myDev))
738 /* Verify symlink string */
741 static void yaffs_VerifySpecial(yaffs_Object *obj)
743 if(obj && yaffs_SkipVerification(obj->myDev))
747 static void yaffs_VerifyObject(yaffs_Object *obj)
756 __u32 chunkShouldNotBeDeleted;
762 if(obj->beingCreated)
767 if(yaffs_SkipVerification(dev))
770 /* Check sane object header chunk */
772 chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
773 chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
775 chunkInRange = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
776 chunkIdOk = chunkInRange || obj->hdrChunk == 0;
777 chunkValid = chunkInRange &&
778 yaffs_CheckChunkBit(dev,
779 obj->hdrChunk / dev->nChunksPerBlock,
780 obj->hdrChunk % dev->nChunksPerBlock);
781 chunkShouldNotBeDeleted = chunkInRange && !chunkValid;
784 (!chunkIdOk || chunkShouldNotBeDeleted)) {
785 T(YAFFS_TRACE_VERIFY,
786 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
787 obj->objectId,obj->hdrChunk,
788 chunkIdOk ? "" : ",out of range",
789 chunkShouldNotBeDeleted ? ",marked as deleted" : ""));
792 if(chunkValid &&!yaffs_SkipNANDVerification(dev)) {
793 yaffs_ExtendedTags tags;
794 yaffs_ObjectHeader *oh;
795 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
797 oh = (yaffs_ObjectHeader *)buffer;
799 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk,buffer, &tags);
801 yaffs_VerifyObjectHeader(obj,oh,&tags,1);
803 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
806 /* Verify it has a parent */
807 if(obj && !obj->fake &&
808 (!obj->parent || obj->parent->myDev != dev)){
809 T(YAFFS_TRACE_VERIFY,
810 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
811 obj->objectId,obj->parent));
814 /* Verify parent is a directory */
815 if(obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
816 T(YAFFS_TRACE_VERIFY,
817 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
818 obj->objectId,obj->parent->variantType));
821 switch(obj->variantType){
822 case YAFFS_OBJECT_TYPE_FILE:
823 yaffs_VerifyFile(obj);
825 case YAFFS_OBJECT_TYPE_SYMLINK:
826 yaffs_VerifySymlink(obj);
828 case YAFFS_OBJECT_TYPE_DIRECTORY:
829 yaffs_VerifyDirectory(obj);
831 case YAFFS_OBJECT_TYPE_HARDLINK:
832 yaffs_VerifyHardLink(obj);
834 case YAFFS_OBJECT_TYPE_SPECIAL:
835 yaffs_VerifySpecial(obj);
837 case YAFFS_OBJECT_TYPE_UNKNOWN:
839 T(YAFFS_TRACE_VERIFY,
840 (TSTR("Obj %d has illegaltype %d"TENDSTR),
841 obj->objectId,obj->variantType));
848 static void yaffs_VerifyObjects(yaffs_Device *dev)
852 struct ylist_head *lh;
854 if(yaffs_SkipVerification(dev))
857 /* Iterate through the objects in each hash entry */
859 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++){
860 ylist_for_each(lh, &dev->objectBucket[i].list) {
862 obj = ylist_entry(lh, yaffs_Object, hashLink);
863 yaffs_VerifyObject(obj);
872 * Simple hash function. Needs to have a reasonable spread
875 static Y_INLINE int yaffs_HashFunction(int n)
878 return (n % YAFFS_NOBJECT_BUCKETS);
882 * Access functions to useful fake objects.
883 * Note that root might have a presence in NAND if permissions are set.
886 yaffs_Object *yaffs_Root(yaffs_Device * dev)
891 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
893 return dev->lostNFoundDir;
898 * Erased NAND checking functions
901 int yaffs_CheckFF(__u8 * buffer, int nBytes)
903 /* Horrible, slow implementation */
912 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
916 int retval = YAFFS_OK;
917 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
918 yaffs_ExtendedTags tags;
921 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
923 if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
927 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
928 T(YAFFS_TRACE_NANDACCESS,
929 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
933 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
939 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
941 yaffs_ExtendedTags * tags,
948 yaffs_InvalidateCheckpoint(dev);
951 yaffs_BlockInfo *bi = 0;
954 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
960 /* First check this chunk is erased, if it needs
961 * checking. The checking policy (unless forced
962 * always on) is as follows:
964 * Check the first page we try to write in a block.
965 * If the check passes then we don't need to check any
966 * more. If the check fails, we check again...
967 * If the block has been erased, we don't need to check.
969 * However, if the block has been prioritised for gc,
970 * then we think there might be something odd about
971 * this block and stop using it.
973 * Rationale: We should only ever see chunks that have
974 * not been erased if there was a partially written
975 * chunk due to power loss. This checking policy should
976 * catch that case with very few checks and thus save a
977 * lot of checks that are most likely not needed.
979 if (bi->gcPrioritise) {
980 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
981 /* try another chunk */
985 /* let's give it a try */
988 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
989 bi->skipErasedCheck = 0;
991 if (!bi->skipErasedCheck) {
992 erasedOk = yaffs_CheckChunkErased(dev, chunk);
993 if (erasedOk != YAFFS_OK) {
995 (TSTR ("**>> yaffs chunk %d was not erased"
998 /* try another chunk */
1001 bi->skipErasedCheck = 1;
1004 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
1006 if (writeOk != YAFFS_OK) {
1007 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
1008 /* try another chunk */
1012 /* Copy the data into the robustification buffer */
1013 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1015 } while (writeOk != YAFFS_OK &&
1016 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1022 T(YAFFS_TRACE_ERROR,
1023 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1026 dev->nRetriedWrites += (attempts - 1);
1033 * Block retiring for handling a broken block.
1036 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
1038 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1040 yaffs_InvalidateCheckpoint(dev);
1042 yaffs_MarkBlockBad(dev, blockInNAND);
1044 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1045 bi->gcPrioritise = 0;
1046 bi->needsRetiring = 0;
1048 dev->nRetiredBlocks++;
1052 * Functions for robustisizing TODO
1056 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
1058 const yaffs_ExtendedTags * tags)
1062 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
1063 const yaffs_ExtendedTags * tags)
1067 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1069 if(!bi->gcPrioritise){
1070 bi->gcPrioritise = 1;
1071 dev->hasPendingPrioritisedGCs = 1;
1072 bi->chunkErrorStrikes ++;
1074 if(bi->chunkErrorStrikes > 3){
1075 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1076 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1083 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
1086 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1087 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1089 yaffs_HandleChunkError(dev,bi);
1093 /* Was an actual write failure, so mark the block for retirement */
1094 bi->needsRetiring = 1;
1095 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1096 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1101 /* Delete the chunk */
1102 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1106 /*---------------- Name handling functions ------------*/
1108 static __u16 yaffs_CalcNameSum(const YCHAR * name)
1113 const YUCHAR *bname = (const YUCHAR *) name;
1115 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1117 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1118 sum += yaffs_toupper(*bname) * i;
1120 sum += (*bname) * i;
1130 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
1132 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1133 memset(obj->shortName,0,sizeof (YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1134 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
1135 yaffs_strcpy(obj->shortName, name);
1137 obj->shortName[0] = _Y('\0');
1140 obj->sum = yaffs_CalcNameSum(name);
1143 /*-------------------- TNODES -------------------
1145 * List of spare tnodes
1146 * The list is hooked together using the first pointer
1150 /* yaffs_CreateTnodes creates a bunch more tnodes and
1151 * adds them to the tnode free list.
1152 * Don't use this function directly
1155 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
1159 yaffs_Tnode *newTnodes;
1163 yaffs_TnodeList *tnl;
1168 /* Calculate the tnode size in bytes for variable width tnode support.
1169 * Must be a multiple of 32-bits */
1170 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1172 if(tnodeSize < sizeof(yaffs_Tnode))
1173 tnodeSize = sizeof(yaffs_Tnode);
1176 /* make these things */
1178 newTnodes = YMALLOC(nTnodes * tnodeSize);
1179 mem = (__u8 *)newTnodes;
1182 T(YAFFS_TRACE_ERROR,
1183 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1187 /* Hook them into the free list */
1189 for (i = 0; i < nTnodes - 1; i++) {
1190 newTnodes[i].internal[0] = &newTnodes[i + 1];
1191 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1192 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1196 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1197 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1198 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1200 dev->freeTnodes = newTnodes;
1202 /* New hookup for wide tnodes */
1203 for(i = 0; i < nTnodes -1; i++) {
1204 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1205 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1206 curr->internal[0] = next;
1209 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1210 curr->internal[0] = dev->freeTnodes;
1211 dev->freeTnodes = (yaffs_Tnode *)mem;
1216 dev->nFreeTnodes += nTnodes;
1217 dev->nTnodesCreated += nTnodes;
1219 /* Now add this bunch of tnodes to a list for freeing up.
1220 * NB If we can't add this to the management list it isn't fatal
1221 * but it just means we can't free this bunch of tnodes later.
1224 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1226 T(YAFFS_TRACE_ERROR,
1228 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1232 tnl->tnodes = newTnodes;
1233 tnl->next = dev->allocatedTnodeList;
1234 dev->allocatedTnodeList = tnl;
1237 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1242 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1244 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
1246 yaffs_Tnode *tn = NULL;
1248 /* If there are none left make more */
1249 if (!dev->freeTnodes) {
1250 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1253 if (dev->freeTnodes) {
1254 tn = dev->freeTnodes;
1255 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1256 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1257 /* Hoosterman, this thing looks like it isn't in the list */
1258 T(YAFFS_TRACE_ALWAYS,
1259 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1262 dev->freeTnodes = dev->freeTnodes->internal[0];
1266 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1271 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
1273 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1274 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1276 if(tnodeSize < sizeof(yaffs_Tnode))
1277 tnodeSize = sizeof(yaffs_Tnode);
1280 memset(tn, 0, tnodeSize);
1285 /* FreeTnode frees up a tnode and puts it back on the free list */
1286 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
1289 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1290 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1291 /* Hoosterman, this thing looks like it is already in the list */
1292 T(YAFFS_TRACE_ALWAYS,
1293 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1295 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1297 tn->internal[0] = dev->freeTnodes;
1298 dev->freeTnodes = tn;
1301 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1305 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
1307 /* Free the list of allocated tnodes */
1308 yaffs_TnodeList *tmp;
1310 while (dev->allocatedTnodeList) {
1311 tmp = dev->allocatedTnodeList->next;
1313 YFREE(dev->allocatedTnodeList->tnodes);
1314 YFREE(dev->allocatedTnodeList);
1315 dev->allocatedTnodeList = tmp;
1319 dev->freeTnodes = NULL;
1320 dev->nFreeTnodes = 0;
1323 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
1325 dev->allocatedTnodeList = NULL;
1326 dev->freeTnodes = NULL;
1327 dev->nFreeTnodes = 0;
1328 dev->nTnodesCreated = 0;
1333 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
1335 __u32 *map = (__u32 *)tn;
1341 pos &= YAFFS_TNODES_LEVEL0_MASK;
1342 val >>= dev->chunkGroupBits;
1344 bitInMap = pos * dev->tnodeWidth;
1345 wordInMap = bitInMap /32;
1346 bitInWord = bitInMap & (32 -1);
1348 mask = dev->tnodeMask << bitInWord;
1350 map[wordInMap] &= ~mask;
1351 map[wordInMap] |= (mask & (val << bitInWord));
1353 if(dev->tnodeWidth > (32-bitInWord)) {
1354 bitInWord = (32 - bitInWord);
1356 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1357 map[wordInMap] &= ~mask;
1358 map[wordInMap] |= (mask & (val >> bitInWord));
1362 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
1364 __u32 *map = (__u32 *)tn;
1370 pos &= YAFFS_TNODES_LEVEL0_MASK;
1372 bitInMap = pos * dev->tnodeWidth;
1373 wordInMap = bitInMap /32;
1374 bitInWord = bitInMap & (32 -1);
1376 val = map[wordInMap] >> bitInWord;
1378 if(dev->tnodeWidth > (32-bitInWord)) {
1379 bitInWord = (32 - bitInWord);
1381 val |= (map[wordInMap] << bitInWord);
1384 val &= dev->tnodeMask;
1385 val <<= dev->chunkGroupBits;
1390 /* ------------------- End of individual tnode manipulation -----------------*/
1392 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1393 * The look up tree is represented by the top tnode and the number of topLevel
1394 * in the tree. 0 means only the level 0 tnode is in the tree.
1397 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1398 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
1399 yaffs_FileStructure * fStruct,
1403 yaffs_Tnode *tn = fStruct->top;
1405 int requiredTallness;
1406 int level = fStruct->topLevel;
1408 /* Check sane level and chunk Id */
1409 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
1413 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1417 /* First check we're tall enough (ie enough topLevel) */
1419 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1420 requiredTallness = 0;
1422 i >>= YAFFS_TNODES_INTERNAL_BITS;
1426 if (requiredTallness > fStruct->topLevel) {
1427 /* Not tall enough, so we can't find it, return NULL. */
1431 /* Traverse down to level 0 */
1432 while (level > 0 && tn) {
1434 internal[(chunkId >>
1435 ( YAFFS_TNODES_LEVEL0_BITS +
1437 YAFFS_TNODES_INTERNAL_BITS)
1439 YAFFS_TNODES_INTERNAL_MASK];
1447 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1448 * This happens in two steps:
1449 * 1. If the tree isn't tall enough, then make it taller.
1450 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1452 * Used when modifying the tree.
1454 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1455 * be plugged into the ttree.
1458 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
1459 yaffs_FileStructure * fStruct,
1461 yaffs_Tnode *passedTn)
1464 int requiredTallness;
1472 /* Check sane level and page Id */
1473 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
1477 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1481 /* First check we're tall enough (ie enough topLevel) */
1483 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1484 requiredTallness = 0;
1486 x >>= YAFFS_TNODES_INTERNAL_BITS;
1491 if (requiredTallness > fStruct->topLevel) {
1492 /* Not tall enough,gotta make the tree taller */
1493 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1495 tn = yaffs_GetTnode(dev);
1498 tn->internal[0] = fStruct->top;
1501 T(YAFFS_TRACE_ERROR,
1502 (TSTR("yaffs: no more tnodes" TENDSTR)));
1506 fStruct->topLevel = requiredTallness;
1509 /* Traverse down to level 0, adding anything we need */
1511 l = fStruct->topLevel;
1515 while (l > 0 && tn) {
1517 ( YAFFS_TNODES_LEVEL0_BITS +
1518 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1519 YAFFS_TNODES_INTERNAL_MASK;
1522 if((l>1) && !tn->internal[x]){
1523 /* Add missing non-level-zero tnode */
1524 tn->internal[x] = yaffs_GetTnode(dev);
1527 /* Looking from level 1 at level 0 */
1529 /* If we already have one, then release it.*/
1531 yaffs_FreeTnode(dev,tn->internal[x]);
1532 tn->internal[x] = passedTn;
1534 } else if(!tn->internal[x]) {
1535 /* Don't have one, none passed in */
1536 tn->internal[x] = yaffs_GetTnode(dev);
1540 tn = tn->internal[x];
1544 /* top is level 0 */
1546 memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1547 yaffs_FreeTnode(dev,passedTn);
1554 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1555 yaffs_ExtendedTags * tags, int objectId,
1560 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1561 if (yaffs_CheckChunkBit
1562 (dev, theChunk / dev->nChunksPerBlock,
1563 theChunk % dev->nChunksPerBlock)) {
1564 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1566 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1578 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1579 * chunks and tnodes in the file
1580 * Returns 1 if the tree was deleted.
1581 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1584 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1585 int chunkOffset, int *limit)
1590 yaffs_ExtendedTags tags;
1592 yaffs_Device *dev = in->myDev;
1599 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1601 if (tn->internal[i]) {
1602 if (limit && (*limit) < 0) {
1606 yaffs_DeleteWorker(in,
1614 YAFFS_TNODES_INTERNAL_BITS)
1619 yaffs_FreeTnode(dev,
1622 tn->internal[i] = NULL;
1627 return (allDone) ? 1 : 0;
1628 } else if (level == 0) {
1631 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1633 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1638 YAFFS_TNODES_LEVEL0_BITS) + i;
1641 yaffs_FindChunkInGroup(dev,
1647 if (foundChunk > 0) {
1648 yaffs_DeleteChunk(dev,
1653 *limit = *limit - 1;
1661 yaffs_PutLevel0Tnode(dev,tn,i,0);
1665 return (i < 0) ? 1 : 0;
1675 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1678 yaffs_BlockInfo *theBlock;
1680 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1682 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1684 theBlock->softDeletions++;
1689 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1690 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1692 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1695 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1696 __u32 level, int chunkOffset)
1701 yaffs_Device *dev = in->myDev;
1706 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1708 if (tn->internal[i]) {
1710 yaffs_SoftDeleteWorker(in,
1716 YAFFS_TNODES_INTERNAL_BITS)
1719 yaffs_FreeTnode(dev,
1722 tn->internal[i] = NULL;
1724 /* Hoosterman... how could this happen? */
1728 return (allDone) ? 1 : 0;
1729 } else if (level == 0) {
1731 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1732 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1734 /* Note this does not find the real chunk, only the chunk group.
1735 * We make an assumption that a chunk group is not larger than
1738 yaffs_SoftDeleteChunk(dev, theChunk);
1739 yaffs_PutLevel0Tnode(dev,tn,i,0);
1753 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1756 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1757 if (obj->nDataChunks <= 0) {
1758 /* Empty file with no duplicate object headers, just delete it immediately */
1759 yaffs_FreeTnode(obj->myDev,
1760 obj->variant.fileVariant.top);
1761 obj->variant.fileVariant.top = NULL;
1762 T(YAFFS_TRACE_TRACING,
1763 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1765 yaffs_DoGenericObjectDeletion(obj);
1767 yaffs_SoftDeleteWorker(obj,
1768 obj->variant.fileVariant.top,
1769 obj->variant.fileVariant.
1771 obj->softDeleted = 1;
1776 /* Pruning removes any part of the file structure tree that is beyond the
1777 * bounds of the file (ie that does not point to chunks).
1779 * A file should only get pruned when its size is reduced.
1781 * Before pruning, the chunks must be pulled from the tree and the
1782 * level 0 tnode entries must be zeroed out.
1783 * Could also use this for file deletion, but that's probably better handled
1784 * by a special case.
1787 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1788 __u32 level, int del0)
1796 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1797 if (tn->internal[i] && level > 0) {
1799 yaffs_PruneWorker(dev, tn->internal[i],
1801 (i == 0) ? del0 : 1);
1804 if (tn->internal[i]) {
1809 if (hasData == 0 && del0) {
1810 /* Free and return NULL */
1812 yaffs_FreeTnode(dev, tn);
1822 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1823 yaffs_FileStructure * fStruct)
1830 if (fStruct->topLevel > 0) {
1832 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1834 /* Now we have a tree with all the non-zero branches NULL but the height
1835 * is the same as it was.
1836 * Let's see if we can trim internal tnodes to shorten the tree.
1837 * We can do this if only the 0th element in the tnode is in use
1838 * (ie all the non-zero are NULL)
1841 while (fStruct->topLevel && !done) {
1845 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1846 if (tn->internal[i]) {
1852 fStruct->top = tn->internal[0];
1853 fStruct->topLevel--;
1854 yaffs_FreeTnode(dev, tn);
1864 /*-------------------- End of File Structure functions.-------------------*/
1866 /* yaffs_CreateFreeObjects creates a bunch more objects and
1867 * adds them to the object free list.
1869 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1872 yaffs_Object *newObjects;
1873 yaffs_ObjectList *list;
1878 /* make these things */
1879 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1880 list = YMALLOC(sizeof(yaffs_ObjectList));
1882 if (!newObjects || !list) {
1887 T(YAFFS_TRACE_ALLOCATE,
1888 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1892 /* Hook them into the free list */
1893 for (i = 0; i < nObjects - 1; i++) {
1894 newObjects[i].siblings.next =
1895 (struct ylist_head *)(&newObjects[i + 1]);
1898 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1899 dev->freeObjects = newObjects;
1900 dev->nFreeObjects += nObjects;
1901 dev->nObjectsCreated += nObjects;
1903 /* Now add this bunch of Objects to a list for freeing up. */
1905 list->objects = newObjects;
1906 list->next = dev->allocatedObjectList;
1907 dev->allocatedObjectList = list;
1913 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1914 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1916 yaffs_Object *tn = NULL;
1918 #ifdef VALGRIND_TEST
1919 tn = YMALLOC(sizeof(yaffs_Object));
1921 /* If there are none left make more */
1922 if (!dev->freeObjects) {
1923 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1926 if (dev->freeObjects) {
1927 tn = dev->freeObjects;
1929 (yaffs_Object *) (dev->freeObjects->siblings.next);
1930 dev->nFreeObjects--;
1934 /* Now sweeten it up... */
1936 memset(tn, 0, sizeof(yaffs_Object));
1937 tn->beingCreated = 1;
1941 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1942 YINIT_LIST_HEAD(&(tn->hardLinks));
1943 YINIT_LIST_HEAD(&(tn->hashLink));
1944 YINIT_LIST_HEAD(&tn->siblings);
1947 /* Now make the directory sane */
1949 tn->parent = dev->rootDir;
1950 ylist_add(&(tn->siblings),&dev->rootDir->variant.directoryVariant.children);
1953 /* Add it to the lost and found directory.
1954 * NB Can't put root or lostNFound in lostNFound so
1955 * check if lostNFound exists first
1957 if (dev->lostNFoundDir) {
1958 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1961 tn->beingCreated = 0;
1964 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1969 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1974 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1976 obj->fake = 1; /* it is fake so it might have no NAND presence... */
1977 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1978 obj->unlinkAllowed = 0; /* ... or unlink it */
1981 obj->yst_mode = mode;
1983 obj->hdrChunk = 0; /* Not a valid chunk. */
1990 static void yaffs_UnhashObject(yaffs_Object * tn)
1993 yaffs_Device *dev = tn->myDev;
1995 /* If it is still linked into the bucket list, free from the list */
1996 if (!ylist_empty(&tn->hashLink)) {
1997 ylist_del_init(&tn->hashLink);
1998 bucket = yaffs_HashFunction(tn->objectId);
1999 dev->objectBucket[bucket].count--;
2004 /* FreeObject frees up a Object and puts it back on the free list */
2005 static void yaffs_FreeObject(yaffs_Object * tn)
2008 yaffs_Device *dev = tn->myDev;
2013 if(!ylist_empty(&tn->siblings))
2019 /* We're still hooked up to a cached inode.
2020 * Don't delete now, but mark for later deletion
2022 tn->deferedFree = 1;
2027 yaffs_UnhashObject(tn);
2029 #ifdef VALGRIND_TEST
2032 /* Link into the free list. */
2033 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2034 dev->freeObjects = tn;
2035 dev->nFreeObjects++;
2037 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2043 void yaffs_HandleDeferedFree(yaffs_Object * obj)
2045 if (obj->deferedFree) {
2046 yaffs_FreeObject(obj);
2052 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
2054 /* Free the list of allocated Objects */
2056 yaffs_ObjectList *tmp;
2058 while (dev->allocatedObjectList) {
2059 tmp = dev->allocatedObjectList->next;
2060 YFREE(dev->allocatedObjectList->objects);
2061 YFREE(dev->allocatedObjectList);
2063 dev->allocatedObjectList = tmp;
2066 dev->freeObjects = NULL;
2067 dev->nFreeObjects = 0;
2070 static void yaffs_InitialiseObjects(yaffs_Device * dev)
2074 dev->allocatedObjectList = NULL;
2075 dev->freeObjects = NULL;
2076 dev->nFreeObjects = 0;
2078 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2079 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2080 dev->objectBucket[i].count = 0;
2085 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
2090 int lowest = 999999;
2092 /* First let's see if we can find one that's empty. */
2094 for (i = 0; i < 10 && lowest > 0; i++) {
2096 x %= YAFFS_NOBJECT_BUCKETS;
2097 if (dev->objectBucket[x].count < lowest) {
2098 lowest = dev->objectBucket[x].count;
2104 /* If we didn't find an empty list, then try
2105 * looking a bit further for a short one
2108 for (i = 0; i < 10 && lowest > 3; i++) {
2110 x %= YAFFS_NOBJECT_BUCKETS;
2111 if (dev->objectBucket[x].count < lowest) {
2112 lowest = dev->objectBucket[x].count;
2121 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
2123 int bucket = yaffs_FindNiceObjectBucket(dev);
2125 /* Now find an object value that has not already been taken
2126 * by scanning the list.
2130 struct ylist_head *i;
2132 __u32 n = (__u32) bucket;
2134 /* yaffs_CheckObjectHashSanity(); */
2138 n += YAFFS_NOBJECT_BUCKETS;
2139 if (1 || dev->objectBucket[bucket].count > 0) {
2140 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2141 /* If there is already one in the list */
2143 && ylist_entry(i, yaffs_Object,
2144 hashLink)->objectId == n) {
2155 static void yaffs_HashObject(yaffs_Object * in)
2157 int bucket = yaffs_HashFunction(in->objectId);
2158 yaffs_Device *dev = in->myDev;
2160 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2161 dev->objectBucket[bucket].count++;
2165 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
2167 int bucket = yaffs_HashFunction(number);
2168 struct ylist_head *i;
2171 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2172 /* Look if it is in the list */
2174 in = ylist_entry(i, yaffs_Object, hashLink);
2175 if (in->objectId == number) {
2177 /* Don't tell the VFS about this one if it is defered free */
2178 if (in->deferedFree)
2190 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
2191 yaffs_ObjectType type)
2194 yaffs_Object *theObject;
2195 yaffs_Tnode *tn = NULL;
2198 number = yaffs_CreateNewObjectNumber(dev);
2201 theObject = yaffs_AllocateEmptyObject(dev);
2205 if(type == YAFFS_OBJECT_TYPE_FILE){
2206 tn = yaffs_GetTnode(dev);
2208 yaffs_FreeObject(theObject);
2216 theObject->fake = 0;
2217 theObject->renameAllowed = 1;
2218 theObject->unlinkAllowed = 1;
2219 theObject->objectId = number;
2220 yaffs_HashObject(theObject);
2221 theObject->variantType = type;
2222 #ifdef CONFIG_YAFFS_WINCE
2223 yfsd_WinFileTimeNow(theObject->win_atime);
2224 theObject->win_ctime[0] = theObject->win_mtime[0] =
2225 theObject->win_atime[0];
2226 theObject->win_ctime[1] = theObject->win_mtime[1] =
2227 theObject->win_atime[1];
2231 theObject->yst_atime = theObject->yst_mtime =
2232 theObject->yst_ctime = Y_CURRENT_TIME;
2236 theObject->sum_prev = 12345;
2237 theObject->sum_trailer = 6789;
2241 case YAFFS_OBJECT_TYPE_FILE:
2242 theObject->variant.fileVariant.fileSize = 0;
2243 theObject->variant.fileVariant.scannedFileSize = 0;
2244 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2245 theObject->variant.fileVariant.topLevel = 0;
2246 theObject->variant.fileVariant.top = tn;
2248 case YAFFS_OBJECT_TYPE_DIRECTORY:
2249 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2252 case YAFFS_OBJECT_TYPE_SYMLINK:
2253 case YAFFS_OBJECT_TYPE_HARDLINK:
2254 case YAFFS_OBJECT_TYPE_SPECIAL:
2255 /* No action required */
2257 case YAFFS_OBJECT_TYPE_UNKNOWN:
2258 /* todo this should not happen */
2266 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
2268 yaffs_ObjectType type)
2270 yaffs_Object *theObject = NULL;
2273 theObject = yaffs_FindObjectByNumber(dev, number);
2277 theObject = yaffs_CreateNewObject(dev, number, type);
2285 static YCHAR *yaffs_CloneString(const YCHAR * str)
2287 YCHAR *newStr = NULL;
2290 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2292 yaffs_strcpy(newStr, str);
2300 * Mknod (create) a new object.
2301 * equivalentObject only has meaning for a hard link;
2302 * aliasString only has meaning for a sumlink.
2303 * rdev only has meaning for devices (a subset of special objects)
2306 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2307 yaffs_Object * parent,
2312 yaffs_Object * equivalentObject,
2313 const YCHAR * aliasString, __u32 rdev)
2318 yaffs_Device *dev = parent->myDev;
2320 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2321 if (yaffs_FindObjectByName(parent, name)) {
2325 in = yaffs_CreateNewObject(dev, -1, type);
2330 if(type == YAFFS_OBJECT_TYPE_SYMLINK){
2331 str = yaffs_CloneString(aliasString);
2333 yaffs_FreeObject(in);
2343 in->variantType = type;
2345 in->yst_mode = mode;
2347 #ifdef CONFIG_YAFFS_WINCE
2348 yfsd_WinFileTimeNow(in->win_atime);
2349 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2350 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2353 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2355 in->yst_rdev = rdev;
2359 in->nDataChunks = 0;
2361 yaffs_SetObjectName(in, name);
2364 yaffs_AddObjectToDirectory(parent, in);
2366 in->myDev = parent->myDev;
2369 case YAFFS_OBJECT_TYPE_SYMLINK:
2370 in->variant.symLinkVariant.alias = str;
2372 case YAFFS_OBJECT_TYPE_HARDLINK:
2373 in->variant.hardLinkVariant.equivalentObject =
2375 in->variant.hardLinkVariant.equivalentObjectId =
2376 equivalentObject->objectId;
2377 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2379 case YAFFS_OBJECT_TYPE_FILE:
2380 case YAFFS_OBJECT_TYPE_DIRECTORY:
2381 case YAFFS_OBJECT_TYPE_SPECIAL:
2382 case YAFFS_OBJECT_TYPE_UNKNOWN:
2387 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2388 /* Could not create the object header, fail the creation */
2389 yaffs_DestroyObject(in);
2398 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
2399 __u32 mode, __u32 uid, __u32 gid)
2401 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2402 uid, gid, NULL, NULL, 0);
2405 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
2406 __u32 mode, __u32 uid, __u32 gid)
2408 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2409 mode, uid, gid, NULL, NULL, 0);
2412 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
2413 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2415 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2416 uid, gid, NULL, NULL, rdev);
2419 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
2420 __u32 mode, __u32 uid, __u32 gid,
2421 const YCHAR * alias)
2423 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2424 uid, gid, NULL, alias, 0);
2427 /* yaffs_Link returns the object id of the equivalent object.*/
2428 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
2429 yaffs_Object * equivalentObject)
2431 /* Get the real object in case we were fed a hard link as an equivalent object */
2432 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2434 if (yaffs_MknodObject
2435 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2436 equivalentObject, NULL, 0)) {
2437 return equivalentObject;
2444 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
2445 const YCHAR * newName, int force, int shadows)
2450 yaffs_Object *existingTarget;
2452 if (newDir == NULL) {
2453 newDir = obj->parent; /* use the old directory */
2456 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2457 T(YAFFS_TRACE_ALWAYS,
2459 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2464 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2465 if (obj->myDev->isYaffs2) {
2466 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2468 unlinkOp = (newDir == obj->myDev->unlinkedDir
2469 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2472 deleteOp = (newDir == obj->myDev->deletedDir);
2474 existingTarget = yaffs_FindObjectByName(newDir, newName);
2476 /* If the object is a file going into the unlinked directory,
2477 * then it is OK to just stuff it in since duplicate names are allowed.
2478 * else only proceed if the new name does not exist and if we're putting
2479 * it into a directory.
2486 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2487 yaffs_SetObjectName(obj, newName);
2490 yaffs_AddObjectToDirectory(newDir, obj);
2495 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2496 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
2503 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
2504 yaffs_Object * newDir, const YCHAR * newName)
2506 yaffs_Object *obj=NULL;
2507 yaffs_Object *existingTarget=NULL;
2511 if(!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2513 if(!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2516 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2517 /* Special case for case insemsitive systems (eg. WinCE).
2518 * While look-up is case insensitive, the name isn't.
2519 * Therefore we might want to change x.txt to X.txt
2521 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
2526 else if (yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2530 obj = yaffs_FindObjectByName(oldDir, oldName);
2532 if (obj && obj->renameAllowed) {
2534 /* Now do the handling for an existing target, if there is one */
2536 existingTarget = yaffs_FindObjectByName(newDir, newName);
2537 if (existingTarget &&
2538 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2539 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2540 /* There is a target that is a non-empty directory, so we fail */
2541 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2542 } else if (existingTarget && existingTarget != obj) {
2543 /* Nuke the target first, using shadowing,
2544 * but only if it isn't the same object
2546 yaffs_ChangeObjectName(obj, newDir, newName, force,
2547 existingTarget->objectId);
2548 yaffs_UnlinkObject(existingTarget);
2551 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2556 /*------------------------- Block Management and Page Allocation ----------------*/
2558 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
2560 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2562 dev->blockInfo = NULL;
2563 dev->chunkBits = NULL;
2565 dev->allocationBlock = -1; /* force it to get a new one */
2567 /* If the first allocation strategy fails, thry the alternate one */
2568 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2569 if(!dev->blockInfo){
2570 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2571 dev->blockInfoAlt = 1;
2574 dev->blockInfoAlt = 0;
2578 /* Set up dynamic blockinfo stuff. */
2579 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2580 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2581 if(!dev->chunkBits){
2582 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2583 dev->chunkBitsAlt = 1;
2586 dev->chunkBitsAlt = 0;
2589 if (dev->blockInfo && dev->chunkBits) {
2590 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2591 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2599 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
2601 if(dev->blockInfoAlt && dev->blockInfo)
2602 YFREE_ALT(dev->blockInfo);
2603 else if(dev->blockInfo)
2604 YFREE(dev->blockInfo);
2606 dev->blockInfoAlt = 0;
2608 dev->blockInfo = NULL;
2610 if(dev->chunkBitsAlt && dev->chunkBits)
2611 YFREE_ALT(dev->chunkBits);
2612 else if(dev->chunkBits)
2613 YFREE(dev->chunkBits);
2614 dev->chunkBitsAlt = 0;
2615 dev->chunkBits = NULL;
2618 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
2619 yaffs_BlockInfo * bi)
2626 return 1; /* disqualification only applies to yaffs2. */
2628 if (!bi->hasShrinkHeader)
2629 return 1; /* can gc */
2631 /* Find the oldest dirty sequence number if we don't know it and save it
2632 * so we don't have to keep recomputing it.
2634 if (!dev->oldestDirtySequence) {
2635 seq = dev->sequenceNumber;
2637 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2639 b = yaffs_GetBlockInfo(dev, i);
2640 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2641 (b->pagesInUse - b->softDeletions) <
2642 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2643 seq = b->sequenceNumber;
2646 dev->oldestDirtySequence = seq;
2649 /* Can't do gc of this block if there are any blocks older than this one that have
2652 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2656 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2657 * for garbage collection.
2660 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2664 int b = dev->currentDirtyChecker;
2671 yaffs_BlockInfo *bi;
2672 int pendingPrioritisedExist = 0;
2674 /* First let's see if we need to grab a prioritised block */
2675 if(dev->hasPendingPrioritisedGCs){
2676 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2678 bi = yaffs_GetBlockInfo(dev, i);
2679 //yaffs_VerifyBlock(dev,bi,i);
2681 if(bi->gcPrioritise) {
2682 pendingPrioritisedExist = 1;
2683 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2684 yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2685 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2688 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2693 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2694 dev->hasPendingPrioritisedGCs = 0;
2697 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2699 * else (we're doing a leasurely gc), then we only bother to do this if the
2700 * block has only a few pages in use.
2703 dev->nonAggressiveSkip--;
2705 if (!aggressive && (dev->nonAggressiveSkip > 0)) {
2711 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2715 dev->internalEndBlock - dev->internalStartBlock + 1;
2718 dev->internalEndBlock - dev->internalStartBlock + 1;
2719 iterations = iterations / 16;
2720 if (iterations > 200) {
2725 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2727 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2728 b = dev->internalStartBlock;
2731 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2732 T(YAFFS_TRACE_ERROR,
2733 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2737 bi = yaffs_GetBlockInfo(dev, b);
2740 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2747 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2748 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2749 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2751 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2755 dev->currentDirtyChecker = b;
2759 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2760 dev->nChunksPerBlock - pagesInUse,prioritised));
2763 dev->oldestDirtySequence = 0;
2766 dev->nonAggressiveSkip = 4;
2772 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2774 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2778 /* If the block is still healthy erase it and mark as clean.
2779 * If the block has had a data failure, then retire it.
2782 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2783 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2784 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2786 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2788 if (!bi->needsRetiring) {
2789 yaffs_InvalidateCheckpoint(dev);
2790 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2792 dev->nErasureFailures++;
2793 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2794 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2799 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2801 for (i = 0; i < dev->nChunksPerBlock; i++) {
2802 if (!yaffs_CheckChunkErased
2803 (dev, blockNo * dev->nChunksPerBlock + i)) {
2804 T(YAFFS_TRACE_ERROR,
2806 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2807 TENDSTR), blockNo, i));
2813 /* Clean it up... */
2814 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2815 dev->nErasedBlocks++;
2817 bi->softDeletions = 0;
2818 bi->hasShrinkHeader = 0;
2819 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2820 bi->gcPrioritise = 0;
2821 yaffs_ClearChunkBits(dev, blockNo);
2823 T(YAFFS_TRACE_ERASE,
2824 (TSTR("Erased block %d" TENDSTR), blockNo));
2826 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2828 yaffs_RetireBlock(dev, blockNo);
2829 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2830 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2834 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2838 yaffs_BlockInfo *bi;
2840 if (dev->nErasedBlocks < 1) {
2841 /* Hoosterman we've got a problem.
2842 * Can't get space to gc
2844 T(YAFFS_TRACE_ERROR,
2845 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2850 /* Find an empty block. */
2852 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2853 dev->allocationBlockFinder++;
2854 if (dev->allocationBlockFinder < dev->internalStartBlock
2855 || dev->allocationBlockFinder > dev->internalEndBlock) {
2856 dev->allocationBlockFinder = dev->internalStartBlock;
2859 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2861 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2862 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2863 dev->sequenceNumber++;
2864 bi->sequenceNumber = dev->sequenceNumber;
2865 dev->nErasedBlocks--;
2866 T(YAFFS_TRACE_ALLOCATE,
2867 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2868 dev->allocationBlockFinder, dev->sequenceNumber,
2869 dev->nErasedBlocks));
2870 return dev->allocationBlockFinder;
2874 T(YAFFS_TRACE_ALWAYS,
2876 ("yaffs tragedy: no more erased blocks, but there should have been %d"
2877 TENDSTR), dev->nErasedBlocks));
2884 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2886 if(!dev->nCheckpointBlocksRequired &&
2888 /* Not a valid value so recalculate */
2891 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2894 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2896 if(tnodeSize < sizeof(yaffs_Tnode))
2897 tnodeSize = sizeof(yaffs_Tnode);
2899 nBytes += sizeof(yaffs_CheckpointValidity);
2900 nBytes += sizeof(yaffs_CheckpointDevice);
2901 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2902 nBytes += devBlocks * dev->chunkBitmapStride;
2903 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2904 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2905 nBytes += sizeof(yaffs_CheckpointValidity);
2906 nBytes += sizeof(__u32); /* checksum*/
2908 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2910 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2912 dev->nCheckpointBlocksRequired = nBlocks;
2915 return dev->nCheckpointBlocksRequired;
2918 // Check if there's space to allocate...
2919 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2920 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2923 int reservedBlocks = dev->nReservedBlocks;
2924 int checkpointBlocks;
2927 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
2928 dev->blocksInCheckpoint;
2929 if(checkpointBlocks < 0)
2930 checkpointBlocks = 0;
2932 checkpointBlocks =0;
2935 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2937 return (dev->nFreeChunks > reservedChunks);
2940 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2943 yaffs_BlockInfo *bi;
2945 if (dev->allocationBlock < 0) {
2946 /* Get next block to allocate off */
2947 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2948 dev->allocationPage = 0;
2951 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2952 /* Not enough space to allocate unless we're allowed to use the reserve. */
2956 if (dev->nErasedBlocks < dev->nReservedBlocks
2957 && dev->allocationPage == 0) {
2958 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2961 /* Next page please.... */
2962 if (dev->allocationBlock >= 0) {
2963 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2965 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2966 dev->allocationPage;
2968 yaffs_SetChunkBit(dev, dev->allocationBlock,
2969 dev->allocationPage);
2971 dev->allocationPage++;
2975 /* If the block is full set the state to full */
2976 if (dev->allocationPage >= dev->nChunksPerBlock) {
2977 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2978 dev->allocationBlock = -1;
2987 T(YAFFS_TRACE_ERROR,
2988 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2993 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2997 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2999 if (dev->allocationBlock > 0) {
3000 n += (dev->nChunksPerBlock - dev->allocationPage);
3007 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block, int wholeBlock)
3012 int retVal = YAFFS_OK;
3015 int isCheckpointBlock;
3019 int chunksBefore = yaffs_GetErasedChunks(dev);
3022 yaffs_ExtendedTags tags;
3024 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3026 yaffs_Object *object;
3028 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3030 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3032 T(YAFFS_TRACE_TRACING,
3033 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3036 bi->hasShrinkHeader,
3039 /*yaffs_VerifyFreeChunks(dev); */
3041 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
3043 /* Take off the number of soft deleted entries because
3044 * they're going to get really deleted during GC.
3046 dev->nFreeChunks -= bi->softDeletions;
3050 if (isCheckpointBlock ||
3051 !yaffs_StillSomeChunkBits(dev, block)) {
3052 T(YAFFS_TRACE_TRACING,
3054 ("Collecting block %d that has no chunks in use" TENDSTR),
3056 yaffs_BlockBecameDirty(dev, block);
3059 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3061 yaffs_VerifyBlock(dev,bi,block);
3063 maxCopies = (wholeBlock) ? dev->nChunksPerBlock : 10;
3064 oldChunk = block * dev->nChunksPerBlock + dev->gcChunk;
3066 for ( /* init already done */;
3067 retVal == YAFFS_OK &&
3068 dev->gcChunk < dev->nChunksPerBlock &&
3069 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING)&&
3071 dev->gcChunk++, oldChunk++) {
3072 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3074 /* This page is in use and might need to be copied off */
3080 yaffs_InitialiseTags(&tags);
3082 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3086 yaffs_FindObjectByNumber(dev,
3089 T(YAFFS_TRACE_GC_DETAIL,
3091 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3092 dev->gcChunk, tags.objectId, tags.chunkId,
3095 if(object && !yaffs_SkipVerification(dev)){
3096 if(tags.chunkId == 0)
3097 matchingChunk = object->hdrChunk;
3098 else if(object->softDeleted)
3099 matchingChunk = oldChunk; /* Defeat the test */
3101 matchingChunk = yaffs_FindChunkInFile(object,tags.chunkId,NULL);
3103 if(oldChunk != matchingChunk)
3104 T(YAFFS_TRACE_ERROR,
3105 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3106 oldChunk,matchingChunk,tags.objectId, tags.chunkId));
3111 T(YAFFS_TRACE_ERROR,
3113 ("page %d in gc has no object: %d %d %d "
3115 tags.objectId, tags.chunkId, tags.byteCount));
3120 object->softDeleted &&
3121 tags.chunkId != 0) {
3122 /* Data chunk in a soft deleted file, throw it away
3123 * It's a soft deleted data chunk,
3124 * No need to copy this, just forget about it and
3125 * fix up the object.
3128 object->nDataChunks--;
3130 if (object->nDataChunks <= 0) {
3131 /* remeber to clean up the object */
3132 dev->gcCleanupList[cleanups] =
3138 /* Todo object && object->deleted && object->nDataChunks == 0 */
3140 /* Deleted object header with no data chunks.
3141 * Can be discarded and the file deleted.
3143 object->hdrChunk = 0;
3144 yaffs_FreeTnode(object->myDev,
3147 object->variant.fileVariant.top = NULL;
3148 yaffs_DoGenericObjectDeletion(object);
3150 } else if (object) {
3151 /* It's either a data chunk in a live file or
3152 * an ObjectHeader, so we're interested in it.
3153 * NB Need to keep the ObjectHeaders of deleted files
3154 * until the whole file has been deleted off
3156 tags.serialNumber++;
3160 if (tags.chunkId == 0) {
3161 /* It is an object Id,
3162 * We need to nuke the shrinkheader flags first
3163 * We no longer want the shrinkHeader flag since its work is done
3164 * and if it is left in place it will mess up scanning.
3165 * Also, clear out any shadowing stuff
3168 yaffs_ObjectHeader *oh;
3169 oh = (yaffs_ObjectHeader *)buffer;
3171 tags.extraShadows = 0;
3172 tags.extraIsShrinkHeader = 0;
3174 yaffs_VerifyObjectHeader(object,oh,&tags,1);
3178 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3181 retVal = YAFFS_FAIL;
3184 /* Ok, now fix up the Tnodes etc. */
3186 if (tags.chunkId == 0) {
3188 object->hdrChunk = newChunk;
3189 object->serial = tags.serialNumber;
3191 /* It's a data chunk */
3192 yaffs_PutChunkIntoFile
3200 if(retVal == YAFFS_OK)
3201 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3206 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3210 /* Do any required cleanups */
3211 for (i = 0; i < cleanups; i++) {
3212 /* Time to delete the file too */
3214 yaffs_FindObjectByNumber(dev,
3215 dev->gcCleanupList[i]);
3217 yaffs_FreeTnode(dev,
3218 object->variant.fileVariant.
3220 object->variant.fileVariant.top = NULL;
3223 ("yaffs: About to finally delete object %d"
3224 TENDSTR), object->objectId));
3225 yaffs_DoGenericObjectDeletion(object);
3226 object->myDev->nDeletedFiles--;
3233 yaffs_VerifyCollectedBlock(dev,bi,block);
3235 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
3238 ("gc did not increase free chunks before %d after %d"
3239 TENDSTR), chunksBefore, chunksAfter));
3242 /* If the gc completed then clear the current gcBlock so that we find another. */
3243 if(bi->blockState != YAFFS_BLOCK_STATE_COLLECTING){
3253 /* New garbage collector
3254 * If we're very low on erased blocks then we do aggressive garbage collection
3255 * otherwise we do "leasurely" garbage collection.
3256 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3257 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3259 * The idea is to help clear out space in a more spread-out manner.
3260 * Dunno if it really does anything useful.
3262 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
3266 int gcOk = YAFFS_OK;
3269 int checkpointBlockAdjust;
3271 if (dev->isDoingGC) {
3272 /* Bail out so we don't get recursive gc */
3276 /* This loop should pass the first time.
3277 * We'll only see looping here if the erase of the collected block fails.
3283 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3284 if(checkpointBlockAdjust < 0)
3285 checkpointBlockAdjust = 0;
3287 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3288 /* We need a block soon...*/
3291 /* We're in no hurry */
3295 if(dev->gcBlock <= 0){
3296 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3300 block = dev->gcBlock;
3303 dev->garbageCollections++;
3305 dev->passiveGarbageCollections++;
3310 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3311 dev->nErasedBlocks, aggressive));
3313 gcOk = yaffs_GarbageCollectBlock(dev,block,aggressive);
3316 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3319 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3320 TENDSTR), dev->nErasedBlocks, maxTries, block));
3322 } while ((dev->nErasedBlocks < dev->nReservedBlocks) &&
3326 return aggressive ? gcOk : YAFFS_OK;
3329 /*------------------------- TAGS --------------------------------*/
3331 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
3334 return (tags->chunkId == chunkInObject &&
3335 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3340 /*-------------------- Data file manipulation -----------------*/
3342 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
3343 yaffs_ExtendedTags * tags)
3345 /*Get the Tnode, then get the level 0 offset chunk offset */
3348 yaffs_ExtendedTags localTags;
3351 yaffs_Device *dev = in->myDev;
3354 /* Passed a NULL, so use our own tags space */
3358 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3361 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3364 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3370 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
3371 yaffs_ExtendedTags * tags)
3373 /* Get the Tnode, then get the level 0 offset chunk offset */
3376 yaffs_ExtendedTags localTags;
3378 yaffs_Device *dev = in->myDev;
3382 /* Passed a NULL, so use our own tags space */
3386 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3390 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3393 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3396 /* Delete the entry in the filestructure (if found) */
3398 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
3401 /*T(("No level 0 found for %d\n", chunkInInode)); */
3405 /* T(("Could not find %d to delete\n",chunkInInode)); */
3410 #ifdef YAFFS_PARANOID
3412 static int yaffs_CheckFileSanity(yaffs_Object * in)
3420 yaffs_Tags localTags;
3421 yaffs_Tags *tags = &localTags;
3425 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3426 /* T(("Object not a file\n")); */
3430 objId = in->objectId;
3431 fSize = in->variant.fileVariant.fileSize;
3433 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3435 for (chunk = 1; chunk <= nChunks; chunk++) {
3436 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3441 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
3443 if (yaffs_CheckChunkBits
3444 (dev, theChunk / dev->nChunksPerBlock,
3445 theChunk % dev->nChunksPerBlock)) {
3447 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3451 (tags, in->objectId, chunk, chunkDeleted)) {
3461 /* T(("No level 0 found for %d\n", chunk)); */
3465 return failed ? YAFFS_FAIL : YAFFS_OK;
3470 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
3471 int chunkInNAND, int inScan)
3473 /* NB inScan is zero unless scanning.
3474 * For forward scanning, inScan is > 0;
3475 * for backward scanning inScan is < 0
3479 yaffs_Device *dev = in->myDev;
3481 yaffs_ExtendedTags existingTags;
3482 yaffs_ExtendedTags newTags;
3483 unsigned existingSerial, newSerial;
3485 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3486 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3487 * If it is not during Scanning then something went wrong!
3490 T(YAFFS_TRACE_ERROR,
3492 ("yaffs tragedy:attempt to put data chunk into a non-file"
3497 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3501 tn = yaffs_AddOrFindLevel0Tnode(dev,
3502 &in->variant.fileVariant,
3509 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3512 /* If we're scanning then we need to test for duplicates
3513 * NB This does not need to be efficient since it should only ever
3514 * happen when the power fails during a write, then only one
3515 * chunk should ever be affected.
3517 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3518 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3521 if (existingChunk > 0) {
3522 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3523 * thus we have to do a FindChunkInFile to get the real chunk id.
3525 * We have a duplicate now we need to decide which one to use:
3527 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3528 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3529 * YAFFS1: Get both sets of tags and compare serial numbers.
3533 /* Only do this for forward scanning */
3534 yaffs_ReadChunkWithTagsFromNAND(dev,
3538 /* Do a proper find */
3540 yaffs_FindChunkInFile(in, chunkInInode,
3544 if (existingChunk <= 0) {
3545 /*Hoosterman - how did this happen? */
3547 T(YAFFS_TRACE_ERROR,
3549 ("yaffs tragedy: existing chunk < 0 in scan"
3554 /* NB The deleted flags should be false, otherwise the chunks will
3555 * not be loaded during a scan
3559 newSerial = newTags.serialNumber;
3560 existingSerial = existingTags.serialNumber;
3564 (in->myDev->isYaffs2 ||
3565 existingChunk <= 0 ||
3566 ((existingSerial + 1) & 3) == newSerial)) {
3567 /* Forward scanning.
3569 * Delete the old one and drop through to update the tnode
3571 yaffs_DeleteChunk(dev, existingChunk, 1,
3574 /* Backward scanning or we want to use the existing one
3576 * Delete the new one and return early so that the tnode isn't changed
3578 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3586 if (existingChunk == 0) {
3590 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
3595 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
3598 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3600 if (chunkInNAND >= 0) {
3601 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3604 T(YAFFS_TRACE_NANDACCESS,
3605 (TSTR("Chunk %d not found zero instead" TENDSTR),
3607 /* get sane (zero) data if you read a hole */
3608 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3614 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
3618 yaffs_ExtendedTags tags;
3619 yaffs_BlockInfo *bi;
3626 block = chunkId / dev->nChunksPerBlock;
3627 page = chunkId % dev->nChunksPerBlock;
3630 if(!yaffs_CheckChunkBit(dev,block,page))
3631 T(YAFFS_TRACE_VERIFY,
3632 (TSTR("Deleting invalid chunk %d"TENDSTR),
3635 bi = yaffs_GetBlockInfo(dev, block);
3637 T(YAFFS_TRACE_DELETION,
3638 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3641 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3643 yaffs_InitialiseTags(&tags);
3645 tags.chunkDeleted = 1;
3647 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3648 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3650 dev->nUnmarkedDeletions++;
3653 /* Pull out of the management area.
3654 * If the whole block became dirty, this will kick off an erasure.
3656 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3657 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3658 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3659 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3662 yaffs_ClearChunkBit(dev, block, page);
3666 if (bi->pagesInUse == 0 &&
3667 !bi->hasShrinkHeader &&
3668 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3669 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3670 yaffs_BlockBecameDirty(dev, block);
3674 /* T(("Bad news deleting chunk %d\n",chunkId)); */
3679 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
3680 const __u8 * buffer, int nBytes,
3683 /* Find old chunk Need to do this to get serial number
3684 * Write new one and patch into tree.
3685 * Invalidate old tags.
3689 yaffs_ExtendedTags prevTags;
3692 yaffs_ExtendedTags newTags;
3694 yaffs_Device *dev = in->myDev;
3696 yaffs_CheckGarbageCollection(dev);
3698 /* Get the previous chunk at this location in the file if it exists */
3699 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3701 /* Set up new tags */
3702 yaffs_InitialiseTags(&newTags);
3704 newTags.chunkId = chunkInInode;
3705 newTags.objectId = in->objectId;
3706 newTags.serialNumber =
3707 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
3708 newTags.byteCount = nBytes;
3710 if(nBytes < 1 || nBytes > dev->totalBytesPerChunk){
3711 T(YAFFS_TRACE_ERROR,
3712 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3719 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3722 if (newChunkId >= 0) {
3723 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3725 if (prevChunkId >= 0) {
3726 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3730 yaffs_CheckFileSanity(in);
3736 /* UpdateObjectHeader updates the header on NAND for an object.
3737 * If name is not NULL, then that new name is used.
3739 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
3740 int isShrink, int shadows)
3743 yaffs_BlockInfo *bi;
3745 yaffs_Device *dev = in->myDev;
3752 yaffs_ExtendedTags newTags;
3753 yaffs_ExtendedTags oldTags;
3755 __u8 *buffer = NULL;
3756 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3758 yaffs_ObjectHeader *oh = NULL;
3760 yaffs_strcpy(oldName,_Y("silly old name"));
3764 in == dev->rootDir || /* The rootDir should also be saved */
3767 yaffs_CheckGarbageCollection(dev);
3768 yaffs_CheckObjectDetailsLoaded(in);
3770 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3771 oh = (yaffs_ObjectHeader *) buffer;
3773 prevChunkId = in->hdrChunk;
3775 if (prevChunkId > 0) {
3776 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3779 yaffs_VerifyObjectHeader(in,oh,&oldTags,0);
3781 memcpy(oldName, oh->name, sizeof(oh->name));
3784 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3786 oh->type = in->variantType;
3787 oh->yst_mode = in->yst_mode;
3788 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3790 #ifdef CONFIG_YAFFS_WINCE
3791 oh->win_atime[0] = in->win_atime[0];
3792 oh->win_ctime[0] = in->win_ctime[0];
3793 oh->win_mtime[0] = in->win_mtime[0];
3794 oh->win_atime[1] = in->win_atime[1];
3795 oh->win_ctime[1] = in->win_ctime[1];
3796 oh->win_mtime[1] = in->win_mtime[1];
3798 oh->yst_uid = in->yst_uid;
3799 oh->yst_gid = in->yst_gid;
3800 oh->yst_atime = in->yst_atime;
3801 oh->yst_mtime = in->yst_mtime;
3802 oh->yst_ctime = in->yst_ctime;
3803 oh->yst_rdev = in->yst_rdev;
3806 oh->parentObjectId = in->parent->objectId;
3808 oh->parentObjectId = 0;
3811 if (name && *name) {
3812 memset(oh->name, 0, sizeof(oh->name));
3813 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3814 } else if (prevChunkId>=0) {
3815 memcpy(oh->name, oldName, sizeof(oh->name));
3817 memset(oh->name, 0, sizeof(oh->name));
3820 oh->isShrink = isShrink;
3822 switch (in->variantType) {
3823 case YAFFS_OBJECT_TYPE_UNKNOWN:
3824 /* Should not happen */
3826 case YAFFS_OBJECT_TYPE_FILE:
3828 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3829 || oh->parentObjectId ==
3830 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3831 fileVariant.fileSize;
3833 case YAFFS_OBJECT_TYPE_HARDLINK:
3834 oh->equivalentObjectId =
3835 in->variant.hardLinkVariant.equivalentObjectId;
3837 case YAFFS_OBJECT_TYPE_SPECIAL:
3840 case YAFFS_OBJECT_TYPE_DIRECTORY:
3843 case YAFFS_OBJECT_TYPE_SYMLINK:
3844 yaffs_strncpy(oh->alias,
3845 in->variant.symLinkVariant.alias,
3846 YAFFS_MAX_ALIAS_LENGTH);
3847 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3852 yaffs_InitialiseTags(&newTags);
3854 newTags.chunkId = 0;
3855 newTags.objectId = in->objectId;
3856 newTags.serialNumber = in->serial;
3858 /* Add extra info for file header */
3860 newTags.extraHeaderInfoAvailable = 1;
3861 newTags.extraParentObjectId = oh->parentObjectId;
3862 newTags.extraFileLength = oh->fileSize;
3863 newTags.extraIsShrinkHeader = oh->isShrink;
3864 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3865 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3866 newTags.extraObjectType = in->variantType;
3868 yaffs_VerifyObjectHeader(in,oh,&newTags,1);
3870 /* Create new chunk in NAND */
3872 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3873 (prevChunkId >= 0) ? 1 : 0);
3875 if (newChunkId >= 0) {
3877 in->hdrChunk = newChunkId;
3879 if (prevChunkId >= 0) {
3880 yaffs_DeleteChunk(dev, prevChunkId, 1,
3884 if(!yaffs_ObjectHasCachedWriteData(in))
3887 /* If this was a shrink, then mark the block that the chunk lives on */
3889 bi = yaffs_GetBlockInfo(in->myDev,
3890 newChunkId /in->myDev-> nChunksPerBlock);
3891 bi->hasShrinkHeader = 1;
3896 retVal = newChunkId;
3901 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3906 /*------------------------ Short Operations Cache ----------------------------------------
3907 * In many situations where there is no high level buffering (eg WinCE) a lot of
3908 * reads might be short sequential reads, and a lot of writes may be short
3909 * sequential writes. eg. scanning/writing a jpeg file.
3910 * In these cases, a short read/write cache can provide a huge perfomance benefit
3911 * with dumb-as-a-rock code.
3912 * In Linux, the page cache provides read buffering aand the short op cache provides write
3915 * There are a limited number (~10) of cache chunks per device so that we don't
3916 * need a very intelligent search.
3919 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3921 yaffs_Device *dev = obj->myDev;
3923 yaffs_ChunkCache *cache;
3924 int nCaches = obj->myDev->nShortOpCaches;
3926 for(i = 0; i < nCaches; i++){
3927 cache = &dev->srCache[i];
3928 if (cache->object == obj &&
3937 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3939 yaffs_Device *dev = obj->myDev;
3940 int lowest = -99; /* Stop compiler whining. */
3942 yaffs_ChunkCache *cache;
3943 int chunkWritten = 0;
3944 int nCaches = obj->myDev->nShortOpCaches;
3950 /* Find the dirty cache for this object with the lowest chunk id. */
3951 for (i = 0; i < nCaches; i++) {
3952 if (dev->srCache[i].object == obj &&
3953 dev->srCache[i].dirty) {
3955 || dev->srCache[i].chunkId <
3957 cache = &dev->srCache[i];
3958 lowest = cache->chunkId;
3963 if (cache && !cache->locked) {
3964 /* Write it out and free it up */
3967 yaffs_WriteChunkDataToObject(cache->object,
3973 cache->object = NULL;
3976 } while (cache && chunkWritten > 0);
3979 /* Hoosterman, disk full while writing cache out. */
3980 T(YAFFS_TRACE_ERROR,
3981 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3988 /*yaffs_FlushEntireDeviceCache(dev)
3993 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3996 int nCaches = dev->nShortOpCaches;
3999 /* Find a dirty object in the cache and flush it...
4000 * until there are no further dirty objects.
4004 for( i = 0; i < nCaches && !obj; i++) {
4005 if (dev->srCache[i].object &&
4006 dev->srCache[i].dirty)
4007 obj = dev->srCache[i].object;
4011 yaffs_FlushFilesChunkCache(obj);
4018 /* Grab us a cache chunk for use.
4019 * First look for an empty one.
4020 * Then look for the least recently used non-dirty one.
4021 * Then look for the least recently used dirty one...., flush and look again.
4023 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
4027 if (dev->nShortOpCaches > 0) {
4028 for (i = 0; i < dev->nShortOpCaches; i++) {
4029 if (!dev->srCache[i].object)
4030 return &dev->srCache[i];
4037 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
4039 yaffs_ChunkCache *cache;
4040 yaffs_Object *theObj;
4045 if (dev->nShortOpCaches > 0) {
4046 /* Try find a non-dirty one... */
4048 cache = yaffs_GrabChunkCacheWorker(dev);
4051 /* They were all dirty, find the last recently used object and flush
4052 * its cache, then find again.
4053 * NB what's here is not very accurate, we actually flush the object
4054 * the last recently used page.
4057 /* With locking we can't assume we can use entry zero */
4064 for (i = 0; i < dev->nShortOpCaches; i++) {
4065 if (dev->srCache[i].object &&
4066 !dev->srCache[i].locked &&
4067 (dev->srCache[i].lastUse < usage || !cache))
4069 usage = dev->srCache[i].lastUse;
4070 theObj = dev->srCache[i].object;
4071 cache = &dev->srCache[i];
4076 if (!cache || cache->dirty) {
4077 /* Flush and try again */
4078 yaffs_FlushFilesChunkCache(theObj);
4079 cache = yaffs_GrabChunkCacheWorker(dev);
4089 /* Find a cached chunk */
4090 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
4093 yaffs_Device *dev = obj->myDev;
4095 if (dev->nShortOpCaches > 0) {
4096 for (i = 0; i < dev->nShortOpCaches; i++) {
4097 if (dev->srCache[i].object == obj &&
4098 dev->srCache[i].chunkId == chunkId) {
4101 return &dev->srCache[i];
4108 /* Mark the chunk for the least recently used algorithym */
4109 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
4113 if (dev->nShortOpCaches > 0) {
4114 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4115 /* Reset the cache usages */
4117 for (i = 1; i < dev->nShortOpCaches; i++) {
4118 dev->srCache[i].lastUse = 0;
4125 cache->lastUse = dev->srLastUse;
4133 /* Invalidate a single cache page.
4134 * Do this when a whole page gets written,
4135 * ie the short cache for this page is no longer valid.
4137 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
4139 if (object->myDev->nShortOpCaches > 0) {
4140 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4143 cache->object = NULL;
4148 /* Invalidate all the cache pages associated with this object
4149 * Do this whenever ther file is deleted or resized.
4151 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
4154 yaffs_Device *dev = in->myDev;
4156 if (dev->nShortOpCaches > 0) {
4157 /* Invalidate it. */
4158 for (i = 0; i < dev->nShortOpCaches; i++) {
4159 if (dev->srCache[i].object == in) {
4160 dev->srCache[i].object = NULL;
4166 /*--------------------- Checkpointing --------------------*/
4169 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
4171 yaffs_CheckpointValidity cp;
4173 memset(&cp,0,sizeof(cp));
4175 cp.structType = sizeof(cp);
4176 cp.magic = YAFFS_MAGIC;
4177 cp.version = YAFFS_CHECKPOINT_VERSION;
4178 cp.head = (head) ? 1 : 0;
4180 return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
4184 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4186 yaffs_CheckpointValidity cp;
4189 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4192 ok = (cp.structType == sizeof(cp)) &&
4193 (cp.magic == YAFFS_MAGIC) &&
4194 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4195 (cp.head == ((head) ? 1 : 0));
4199 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4202 cp->nErasedBlocks = dev->nErasedBlocks;
4203 cp->allocationBlock = dev->allocationBlock;
4204 cp->allocationPage = dev->allocationPage;
4205 cp->nFreeChunks = dev->nFreeChunks;
4207 cp->nDeletedFiles = dev->nDeletedFiles;
4208 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4209 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4210 cp->sequenceNumber = dev->sequenceNumber;
4211 cp->oldestDirtySequence = dev->oldestDirtySequence;
4215 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4216 yaffs_CheckpointDevice *cp)
4218 dev->nErasedBlocks = cp->nErasedBlocks;
4219 dev->allocationBlock = cp->allocationBlock;
4220 dev->allocationPage = cp->allocationPage;
4221 dev->nFreeChunks = cp->nFreeChunks;
4223 dev->nDeletedFiles = cp->nDeletedFiles;
4224 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4225 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4226 dev->sequenceNumber = cp->sequenceNumber;
4227 dev->oldestDirtySequence = cp->oldestDirtySequence;
4231 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4233 yaffs_CheckpointDevice cp;
4235 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4239 /* Write device runtime values*/
4240 yaffs_DeviceToCheckpointDevice(&cp,dev);
4241 cp.structType = sizeof(cp);
4243 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4245 /* Write block info */
4247 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4248 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
4251 /* Write chunk bits */
4253 nBytes = nBlocks * dev->chunkBitmapStride;
4254 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
4260 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4262 yaffs_CheckpointDevice cp;
4264 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4268 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4272 if(cp.structType != sizeof(cp))
4276 yaffs_CheckpointDeviceToDevice(dev,&cp);
4278 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4280 ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
4284 nBytes = nBlocks * dev->chunkBitmapStride;
4286 ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
4291 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4295 cp->objectId = obj->objectId;
4296 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4297 cp->hdrChunk = obj->hdrChunk;
4298 cp->variantType = obj->variantType;
4299 cp->deleted = obj->deleted;
4300 cp->softDeleted = obj->softDeleted;
4301 cp->unlinked = obj->unlinked;
4302 cp->fake = obj->fake;
4303 cp->renameAllowed = obj->renameAllowed;
4304 cp->unlinkAllowed = obj->unlinkAllowed;
4305 cp->serial = obj->serial;
4306 cp->nDataChunks = obj->nDataChunks;
4308 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4309 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4310 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4311 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4314 static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
4317 yaffs_Object *parent;
4319 obj->objectId = cp->objectId;
4322 parent = yaffs_FindOrCreateObjectByNumber(
4325 YAFFS_OBJECT_TYPE_DIRECTORY);
4330 yaffs_AddObjectToDirectory(parent, obj);
4332 obj->hdrChunk = cp->hdrChunk;
4333 obj->variantType = cp->variantType;
4334 obj->deleted = cp->deleted;
4335 obj->softDeleted = cp->softDeleted;
4336 obj->unlinked = cp->unlinked;
4337 obj->fake = cp->fake;
4338 obj->renameAllowed = cp->renameAllowed;
4339 obj->unlinkAllowed = cp->unlinkAllowed;
4340 obj->serial = cp->serial;
4341 obj->nDataChunks = cp->nDataChunks;
4343 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4344 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4345 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4346 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4348 if(obj->hdrChunk > 0)
4349 obj->lazyLoaded = 1;
4354 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
4355 __u32 level, int chunkOffset)
4358 yaffs_Device *dev = in->myDev;
4360 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4362 if(tnodeSize < sizeof(yaffs_Tnode))
4363 tnodeSize = sizeof(yaffs_Tnode);
4369 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
4370 if (tn->internal[i]) {
4371 ok = yaffs_CheckpointTnodeWorker(in,
4374 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4377 } else if (level == 0) {
4378 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4379 ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
4381 ok = (yaffs_CheckpointWrite(dev,tn,tnodeSize) == tnodeSize);
4389 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4391 __u32 endMarker = ~0;
4394 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4395 ok = yaffs_CheckpointTnodeWorker(obj,
4396 obj->variant.fileVariant.top,
4397 obj->variant.fileVariant.topLevel,
4400 ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) ==
4407 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4411 yaffs_Device *dev = obj->myDev;
4412 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4415 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4417 if(tnodeSize < sizeof(yaffs_Tnode))
4418 tnodeSize = sizeof(yaffs_Tnode);
4420 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4422 while(ok && (~baseChunk)){
4424 /* Read level 0 tnode */
4427 tn = yaffs_GetTnodeRaw(dev);
4429 ok = (yaffs_CheckpointRead(dev,tn,tnodeSize) == tnodeSize);
4434 ok = yaffs_AddOrFindLevel0Tnode(dev,
4442 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4446 T(YAFFS_TRACE_CHECKPOINT,(
4447 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4448 nread,baseChunk,ok));
4454 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4457 yaffs_CheckpointObject cp;
4460 struct ylist_head *lh;
4463 /* Iterate through the objects in each hash entry,
4464 * dumping them to the checkpointing stream.
4467 for(i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++){
4468 ylist_for_each(lh, &dev->objectBucket[i].list) {
4470 obj = ylist_entry(lh, yaffs_Object, hashLink);
4471 if (!obj->deferedFree) {
4472 yaffs_ObjectToCheckpointObject(&cp,obj);
4473 cp.structType = sizeof(cp);
4475 T(YAFFS_TRACE_CHECKPOINT,(
4476 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
4477 cp.objectId,cp.parentId,cp.variantType,cp.hdrChunk,(unsigned) obj));
4479 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4481 if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4482 ok = yaffs_WriteCheckpointTnodes(obj);
4489 /* Dump end of list */
4490 memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
4491 cp.structType = sizeof(cp);
4494 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4499 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4502 yaffs_CheckpointObject cp;
4505 yaffs_Object *hardList = NULL;
4507 while(ok && !done) {
4508 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4509 if(cp.structType != sizeof(cp)) {
4510 T(YAFFS_TRACE_CHECKPOINT,(TSTR("struct size %d instead of %d ok %d"TENDSTR),
4511 cp.structType,sizeof(cp),ok));
4515 T(YAFFS_TRACE_CHECKPOINT,(TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4516 cp.objectId,cp.parentId,cp.variantType,cp.hdrChunk));
4518 if(ok && cp.objectId == ~0)
4521 obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
4523 yaffs_CheckpointObjectToObject(obj,&cp);
4524 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4525 ok = yaffs_ReadCheckpointTnodes(obj);
4526 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4527 obj->hardLinks.next =
4528 (struct ylist_head *)
4538 yaffs_HardlinkFixup(dev,hardList);
4543 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4545 __u32 checkpointSum;
4548 yaffs_GetCheckpointSum(dev,&checkpointSum);
4550 ok = (yaffs_CheckpointWrite(dev,&checkpointSum,sizeof(checkpointSum)) == sizeof(checkpointSum));
4558 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4560 __u32 checkpointSum0;
4561 __u32 checkpointSum1;
4564 yaffs_GetCheckpointSum(dev,&checkpointSum0);
4566 ok = (yaffs_CheckpointRead(dev,&checkpointSum1,sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4571 if(checkpointSum0 != checkpointSum1)
4578 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4583 if(dev->skipCheckpointWrite || !dev->isYaffs2){
4584 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint write" TENDSTR)));
4589 ok = yaffs_CheckpointOpen(dev,1);
4592 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4593 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
4596 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint device" TENDSTR)));
4597 ok = yaffs_WriteCheckpointDevice(dev);
4600 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint objects" TENDSTR)));
4601 ok = yaffs_WriteCheckpointObjects(dev);
4604 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4605 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
4609 ok = yaffs_WriteCheckpointSum(dev);
4613 if(!yaffs_CheckpointClose(dev))
4617 dev->isCheckpointed = 1;
4619 dev->isCheckpointed = 0;
4621 return dev->isCheckpointed;
4624 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4628 if(dev->skipCheckpointRead || !dev->isYaffs2){
4629 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint read" TENDSTR)));
4634 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
4637 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4638 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
4641 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint device" TENDSTR)));
4642 ok = yaffs_ReadCheckpointDevice(dev);
4645 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint objects" TENDSTR)));
4646 ok = yaffs_ReadCheckpointObjects(dev);
4649 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4650 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
4654 ok = yaffs_ReadCheckpointSum(dev);
4655 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint checksum %d" TENDSTR),ok));
4658 if(!yaffs_CheckpointClose(dev))
4662 dev->isCheckpointed = 1;
4664 dev->isCheckpointed = 0;
4670 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4672 if(dev->isCheckpointed ||
4673 dev->blocksInCheckpoint > 0){
4674 dev->isCheckpointed = 0;
4675 yaffs_CheckpointInvalidateStream(dev);
4676 if(dev->superBlock && dev->markSuperBlockDirty)
4677 dev->markSuperBlockDirty(dev->superBlock);
4682 int yaffs_CheckpointSave(yaffs_Device *dev)
4685 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4687 yaffs_VerifyObjects(dev);
4688 yaffs_VerifyBlocks(dev);
4689 yaffs_VerifyFreeChunks(dev);
4691 if(!dev->isCheckpointed) {
4692 yaffs_InvalidateCheckpoint(dev);
4693 yaffs_WriteCheckpointData(dev);
4696 T(YAFFS_TRACE_ALWAYS,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4698 return dev->isCheckpointed;
4701 int yaffs_CheckpointRestore(yaffs_Device *dev)
4704 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4706 retval = yaffs_ReadCheckpointData(dev);
4708 if(dev->isCheckpointed){
4709 yaffs_VerifyObjects(dev);
4710 yaffs_VerifyBlocks(dev);
4711 yaffs_VerifyFreeChunks(dev);
4714 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4719 /*--------------------- File read/write ------------------------
4720 * Read and write have very similar structures.
4721 * In general the read/write has three parts to it
4722 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4723 * Some complete chunks
4724 * An incomplete chunk to end off with
4726 * Curve-balls: the first chunk might also be the last chunk.
4729 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, loff_t offset,
4738 yaffs_ChunkCache *cache;
4745 //chunk = offset / dev->nDataBytesPerChunk + 1;
4746 //start = offset % dev->nDataBytesPerChunk;
4747 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4750 /* OK now check for the curveball where the start and end are in
4753 if ((start + n) < dev->nDataBytesPerChunk) {
4756 nToCopy = dev->nDataBytesPerChunk - start;
4759 cache = yaffs_FindChunkCache(in, chunk);
4761 /* If the chunk is already in the cache or it is less than a whole chunk
4762 * or we're using inband tags then use the cache (if there is caching)
4763 * else bypass the cache.
4765 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4766 if (dev->nShortOpCaches > 0) {
4768 /* If we can't find the data in the cache, then load it up. */
4771 cache = yaffs_GrabChunkCache(in->myDev);
4773 cache->chunkId = chunk;
4776 yaffs_ReadChunkDataFromObject(in, chunk,
4782 yaffs_UseChunkCache(dev, cache, 0);
4786 #ifdef CONFIG_YAFFS_WINCE
4787 yfsd_UnlockYAFFS(TRUE);
4789 memcpy(buffer, &cache->data[start], nToCopy);
4791 #ifdef CONFIG_YAFFS_WINCE
4792 yfsd_LockYAFFS(TRUE);
4796 /* Read into the local buffer then copy..*/
4799 yaffs_GetTempBuffer(dev, __LINE__);
4800 yaffs_ReadChunkDataFromObject(in, chunk,
4802 #ifdef CONFIG_YAFFS_WINCE
4803 yfsd_UnlockYAFFS(TRUE);
4805 memcpy(buffer, &localBuffer[start], nToCopy);
4807 #ifdef CONFIG_YAFFS_WINCE
4808 yfsd_LockYAFFS(TRUE);
4810 yaffs_ReleaseTempBuffer(dev, localBuffer,
4815 #ifdef CONFIG_YAFFS_WINCE
4816 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4818 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4819 * This is because we otherwise screw up WinCE's memory mapper
4821 yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
4823 #ifdef CONFIG_YAFFS_WINCE
4824 yfsd_UnlockYAFFS(TRUE);
4826 memcpy(buffer, localBuffer, dev->nDataBytesPerChunk);
4828 #ifdef CONFIG_YAFFS_WINCE
4829 yfsd_LockYAFFS(TRUE);
4830 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4834 /* A full chunk. Read directly into the supplied buffer. */
4835 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4849 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, loff_t offset,
4850 int nBytes, int writeThrough)
4859 int startOfWrite = offset;
4860 int chunkWritten = 0;
4868 while (n > 0 && chunkWritten >= 0) {
4869 //chunk = offset / dev->nDataBytesPerChunk + 1;
4870 //start = offset % dev->nDataBytesPerChunk;
4871 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4873 if(chunk * dev->nDataBytesPerChunk + start != offset ||
4874 start >= dev->nDataBytesPerChunk){
4875 T(YAFFS_TRACE_ERROR,(TSTR("AddrToChunk of offset %d gives chunk %d start %d"TENDSTR),
4876 (int)offset, chunk,start));
4880 /* OK now check for the curveball where the start and end are in
4884 if ((start + n) < dev->nDataBytesPerChunk) {
4887 /* Now folks, to calculate how many bytes to write back....
4888 * If we're overwriting and not writing to then end of file then
4889 * we need to write back as much as was there before.
4892 chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
4894 if(chunkStart > in->variant.fileVariant.fileSize)
4895 nBytesRead = 0; /* Past end of file */
4897 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
4899 if (nBytesRead > dev->nDataBytesPerChunk) {
4900 nBytesRead = dev->nDataBytesPerChunk;
4905 (start + n)) ? nBytesRead : (start + n);
4907 if(nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
4911 nToCopy = dev->nDataBytesPerChunk - start;
4912 nToWriteBack = dev->nDataBytesPerChunk;
4915 if (nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4916 /* An incomplete start or end chunk (or maybe both start and end chunk),
4917 * or we're using inband tags, so we want to use the cache buffers.
4919 if (dev->nShortOpCaches > 0) {
4920 yaffs_ChunkCache *cache;
4921 /* If we can't find the data in the cache, then load the cache */
4922 cache = yaffs_FindChunkCache(in, chunk);
4925 && yaffs_CheckSpaceForAllocation(in->
4927 cache = yaffs_GrabChunkCache(in->myDev);
4929 cache->chunkId = chunk;
4932 yaffs_ReadChunkDataFromObject(in, chunk,
4938 !yaffs_CheckSpaceForAllocation(in->myDev)){
4939 /* Drop the cache if it was a read cache item and
4940 * no space check has been made for it.
4946 yaffs_UseChunkCache(dev, cache, 1);
4948 #ifdef CONFIG_YAFFS_WINCE
4949 yfsd_UnlockYAFFS(TRUE);
4952 memcpy(&cache->data[start], buffer,
4955 #ifdef CONFIG_YAFFS_WINCE
4956 yfsd_LockYAFFS(TRUE);
4959 cache->nBytes = nToWriteBack;
4963 yaffs_WriteChunkDataToObject
4966 cache->data, cache->nBytes,
4972 chunkWritten = -1; /* fail the write */
4975 /* An incomplete start or end chunk (or maybe both start and end chunk)
4976 * Read into the local buffer then copy, then copy over and write back.
4980 yaffs_GetTempBuffer(dev, __LINE__);
4982 yaffs_ReadChunkDataFromObject(in, chunk,
4985 #ifdef CONFIG_YAFFS_WINCE
4986 yfsd_UnlockYAFFS(TRUE);
4989 memcpy(&localBuffer[start], buffer, nToCopy);
4991 #ifdef CONFIG_YAFFS_WINCE
4992 yfsd_LockYAFFS(TRUE);
4995 yaffs_WriteChunkDataToObject(in, chunk,
5000 yaffs_ReleaseTempBuffer(dev, localBuffer,
5006 /* A full chunk. Write directly from the supplied buffer. */
5008 #ifdef CONFIG_YAFFS_WINCE
5009 /* Under WinCE can't do direct transfer. Need to use a local buffer.
5010 * This is because we otherwise screw up WinCE's memory mapper
5012 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5013 #ifdef CONFIG_YAFFS_WINCE
5014 yfsd_UnlockYAFFS(TRUE);
5016 memcpy(localBuffer, buffer, dev->nDataBytesPerChunk);
5017 #ifdef CONFIG_YAFFS_WINCE
5018 yfsd_LockYAFFS(TRUE);
5021 yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
5022 dev->nDataBytesPerChunk,
5024 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5028 yaffs_WriteChunkDataToObject(in, chunk, buffer,
5029 dev->nDataBytesPerChunk,
5032 /* Since we've overwritten the cached data, we better invalidate it. */
5033 yaffs_InvalidateChunkCache(in, chunk);
5036 if (chunkWritten >= 0) {
5045 /* Update file object */
5047 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
5048 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
5057 /* ---------------------- File resizing stuff ------------------ */
5059 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
5062 yaffs_Device *dev = in->myDev;
5063 int oldFileSize = in->variant.fileVariant.fileSize;
5065 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
5067 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
5068 dev->nDataBytesPerChunk;
5072 /* Delete backwards so that we don't end up with holes if
5073 * power is lost part-way through the operation.
5075 for (i = lastDel; i >= startDel; i--) {
5076 /* NB this could be optimised somewhat,
5077 * eg. could retrieve the tags and write them without
5078 * using yaffs_DeleteChunk
5081 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5084 (dev->internalStartBlock * dev->nChunksPerBlock)
5086 ((dev->internalEndBlock +
5087 1) * dev->nChunksPerBlock)) {
5088 T(YAFFS_TRACE_ALWAYS,
5089 (TSTR("Found daft chunkId %d for %d" TENDSTR),
5093 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5100 int yaffs_ResizeFile(yaffs_Object * in, loff_t newSize)
5103 int oldFileSize = in->variant.fileVariant.fileSize;
5104 __u32 newSizeOfPartialChunk;
5107 yaffs_Device *dev = in->myDev;
5109 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5111 yaffs_FlushFilesChunkCache(in);
5112 yaffs_InvalidateWholeChunkCache(in);
5114 yaffs_CheckGarbageCollection(dev);
5116 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
5120 if (newSize == oldFileSize) {
5124 if (newSize < oldFileSize) {
5126 yaffs_PruneResizedChunks(in, newSize);
5128 if (newSizeOfPartialChunk != 0) {
5129 int lastChunk = 1 + newFullChunks;
5131 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5133 /* Got to read and rewrite the last chunk with its new size and zero pad */
5134 yaffs_ReadChunkDataFromObject(in, lastChunk,
5137 memset(localBuffer + newSizeOfPartialChunk, 0,
5138 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5140 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5141 newSizeOfPartialChunk, 1);
5143 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5146 in->variant.fileVariant.fileSize = newSize;
5148 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5150 /* newsSize > oldFileSize */
5151 in->variant.fileVariant.fileSize = newSize;
5156 /* Write a new object header.
5157 * show we've shrunk the file, if need be
5158 * Do this only if the file is not in the deleted directories.
5161 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5162 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
5163 yaffs_UpdateObjectHeader(in, NULL, 0,
5164 (newSize < oldFileSize) ? 1 : 0, 0);
5170 loff_t yaffs_GetFileSize(yaffs_Object * obj)
5172 obj = yaffs_GetEquivalentObject(obj);
5174 switch (obj->variantType) {
5175 case YAFFS_OBJECT_TYPE_FILE:
5176 return obj->variant.fileVariant.fileSize;
5177 case YAFFS_OBJECT_TYPE_SYMLINK:
5178 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5186 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
5190 yaffs_FlushFilesChunkCache(in);
5192 #ifdef CONFIG_YAFFS_WINCE
5193 yfsd_WinFileTimeNow(in->win_mtime);
5196 in->yst_mtime = Y_CURRENT_TIME;
5202 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5203 0) ? YAFFS_OK : YAFFS_FAIL;
5212 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
5215 /* First off, invalidate the file's data in the cache, without flushing. */
5216 yaffs_InvalidateWholeChunkCache(in);
5218 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5219 /* Move to the unlinked directory so we have a record that it was deleted. */
5220 yaffs_ChangeObjectName(in, in->myDev->deletedDir,_Y("deleted"), 0, 0);
5224 yaffs_RemoveObjectFromDirectory(in);
5225 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5228 yaffs_FreeObject(in);
5233 /* yaffs_DeleteFile deletes the whole file data
5234 * and the inode associated with the file.
5235 * It does not delete the links associated with the file.
5238 static int yaffs_UnlinkFile(yaffs_Object * in)
5242 int immediateDeletion = 0;
5246 immediateDeletion = 1;
5249 if (in->inUse <= 0) {
5250 immediateDeletion = 1;
5254 if (immediateDeletion) {
5256 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5257 _Y("deleted"), 0, 0);
5258 T(YAFFS_TRACE_TRACING,
5259 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5262 in->myDev->nDeletedFiles++;
5263 if (1 || in->myDev->isYaffs2) {
5264 yaffs_ResizeFile(in, 0);
5266 yaffs_SoftDeleteFile(in);
5269 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5270 _Y("unlinked"), 0, 0);
5277 int yaffs_DeleteFile(yaffs_Object * in)
5279 int retVal = YAFFS_OK;
5280 int deleted = in->deleted;
5282 yaffs_ResizeFile(in,0);
5284 if (in->nDataChunks > 0) {
5285 /* Use soft deletion if there is data in the file.
5286 * That won't be the case if it has been resized to zero.
5288 if (!in->unlinked) {
5289 retVal = yaffs_UnlinkFile(in);
5291 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5292 in->deleted = deleted = 1;
5293 in->myDev->nDeletedFiles++;
5294 yaffs_SoftDeleteFile(in);
5296 return deleted ? YAFFS_OK : YAFFS_FAIL;
5298 /* The file has no data chunks so we toss it immediately */
5299 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5300 in->variant.fileVariant.top = NULL;
5301 yaffs_DoGenericObjectDeletion(in);
5307 static int yaffs_DeleteDirectory(yaffs_Object * in)
5309 /* First check that the directory is empty. */
5310 if (ylist_empty(&in->variant.directoryVariant.children)) {
5311 return yaffs_DoGenericObjectDeletion(in);
5318 static int yaffs_DeleteSymLink(yaffs_Object * in)
5320 YFREE(in->variant.symLinkVariant.alias);
5322 return yaffs_DoGenericObjectDeletion(in);
5325 static int yaffs_DeleteHardLink(yaffs_Object * in)
5327 /* remove this hardlink from the list assocaited with the equivalent
5330 ylist_del_init(&in->hardLinks);
5331 return yaffs_DoGenericObjectDeletion(in);
5334 static void yaffs_DestroyObject(yaffs_Object * obj)
5336 switch (obj->variantType) {
5337 case YAFFS_OBJECT_TYPE_FILE:
5338 yaffs_DeleteFile(obj);
5340 case YAFFS_OBJECT_TYPE_DIRECTORY:
5341 yaffs_DeleteDirectory(obj);
5343 case YAFFS_OBJECT_TYPE_SYMLINK:
5344 yaffs_DeleteSymLink(obj);
5346 case YAFFS_OBJECT_TYPE_HARDLINK:
5347 yaffs_DeleteHardLink(obj);
5349 case YAFFS_OBJECT_TYPE_SPECIAL:
5350 yaffs_DoGenericObjectDeletion(obj);
5352 case YAFFS_OBJECT_TYPE_UNKNOWN:
5353 break; /* should not happen. */
5357 static int yaffs_UnlinkWorker(yaffs_Object * obj)
5360 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5361 return yaffs_DeleteHardLink(obj);
5362 } else if (!ylist_empty(&obj->hardLinks)) {
5363 /* Curve ball: We're unlinking an object that has a hardlink.
5365 * This problem arises because we are not strictly following
5366 * The Linux link/inode model.
5368 * We can't really delete the object.
5369 * Instead, we do the following:
5370 * - Select a hardlink.
5371 * - Unhook it from the hard links
5372 * - Unhook it from its parent directory (so that the rename can work)
5373 * - Rename the object to the hardlink's name.
5374 * - Delete the hardlink
5379 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5381 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5383 ylist_del_init(&hl->hardLinks);
5384 ylist_del_init(&hl->siblings);
5386 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5388 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
5390 if (retVal == YAFFS_OK) {
5391 retVal = yaffs_DoGenericObjectDeletion(hl);
5396 switch (obj->variantType) {
5397 case YAFFS_OBJECT_TYPE_FILE:
5398 return yaffs_UnlinkFile(obj);
5400 case YAFFS_OBJECT_TYPE_DIRECTORY:
5401 return yaffs_DeleteDirectory(obj);
5403 case YAFFS_OBJECT_TYPE_SYMLINK:
5404 return yaffs_DeleteSymLink(obj);
5406 case YAFFS_OBJECT_TYPE_SPECIAL:
5407 return yaffs_DoGenericObjectDeletion(obj);
5409 case YAFFS_OBJECT_TYPE_HARDLINK:
5410 case YAFFS_OBJECT_TYPE_UNKNOWN:
5418 static int yaffs_UnlinkObject( yaffs_Object *obj)
5421 if (obj && obj->unlinkAllowed) {
5422 return yaffs_UnlinkWorker(obj);
5428 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
5432 obj = yaffs_FindObjectByName(dir, name);
5433 return yaffs_UnlinkObject(obj);
5436 /*----------------------- Initialisation Scanning ---------------------- */
5438 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
5439 int backwardScanning)
5443 if (!backwardScanning) {
5444 /* Handle YAFFS1 forward scanning case
5445 * For YAFFS1 we always do the deletion
5449 /* Handle YAFFS2 case (backward scanning)
5450 * If the shadowed object exists then ignore.
5452 if (yaffs_FindObjectByNumber(dev, objId)) {
5457 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5458 * We put it in unlinked dir to be cleaned up after the scanning
5461 yaffs_FindOrCreateObjectByNumber(dev, objId,
5462 YAFFS_OBJECT_TYPE_FILE);
5463 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5464 obj->variant.fileVariant.shrinkSize = 0;
5465 obj->valid = 1; /* So that we don't read any other info for this file */
5475 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5482 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5484 in = yaffs_FindObjectByNumber(dev,
5485 hl->variant.hardLinkVariant.
5486 equivalentObjectId);
5489 /* Add the hardlink pointers */
5490 hl->variant.hardLinkVariant.equivalentObject = in;
5491 ylist_add(&hl->hardLinks, &in->hardLinks);
5493 /* Todo Need to report/handle this better.
5494 * Got a problem... hardlink to a non-existant object
5496 hl->variant.hardLinkVariant.equivalentObject = NULL;
5497 YINIT_LIST_HEAD(&hl->hardLinks);
5509 static int ybicmp(const void *a, const void *b){
5510 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5511 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5512 register int ablock = ((yaffs_BlockIndex *)a)->block;
5513 register int bblock = ((yaffs_BlockIndex *)b)->block;
5515 return ablock - bblock;
5522 struct yaffs_ShadowFixerStruct {
5525 struct yaffs_ShadowFixerStruct *next;
5529 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5532 * Sort out state of unlinked and deleted objects after scanning.
5534 struct ylist_head *i;
5535 struct ylist_head *n;
5538 /* Soft delete all the unlinked files */
5539 ylist_for_each_safe(i, n,
5540 &dev->unlinkedDir->variant.directoryVariant.children) {
5542 l = ylist_entry(i, yaffs_Object, siblings);
5543 yaffs_DestroyObject(l);
5547 ylist_for_each_safe(i, n,
5548 &dev->deletedDir->variant.directoryVariant.children) {
5550 l = ylist_entry(i, yaffs_Object, siblings);
5551 yaffs_DestroyObject(l);
5557 static int yaffs_Scan(yaffs_Device * dev)
5559 yaffs_ExtendedTags tags;
5569 yaffs_BlockState state;
5570 yaffs_Object *hardList = NULL;
5571 yaffs_BlockInfo *bi;
5572 __u32 sequenceNumber;
5573 yaffs_ObjectHeader *oh;
5575 yaffs_Object *parent;
5577 int alloc_failed = 0;
5579 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5587 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5588 dev->internalStartBlock, dev->internalEndBlock));
5590 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5592 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5594 /* Scan all the blocks to determine their state */
5595 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5596 bi = yaffs_GetBlockInfo(dev, blk);
5597 yaffs_ClearChunkBits(dev, blk);
5599 bi->softDeletions = 0;
5601 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5603 bi->blockState = state;
5604 bi->sequenceNumber = sequenceNumber;
5606 T(YAFFS_TRACE_SCAN_DEBUG,
5607 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5608 state, sequenceNumber));
5610 if (state == YAFFS_BLOCK_STATE_DEAD) {
5611 T(YAFFS_TRACE_BAD_BLOCKS,
5612 (TSTR("block %d is bad" TENDSTR), blk));
5613 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5614 T(YAFFS_TRACE_SCAN_DEBUG,
5615 (TSTR("Block empty " TENDSTR)));
5616 dev->nErasedBlocks++;
5617 dev->nFreeChunks += dev->nChunksPerBlock;
5621 startIterator = dev->internalStartBlock;
5622 endIterator = dev->internalEndBlock;
5624 /* For each block.... */
5625 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5632 blk = blockIterator;
5634 bi = yaffs_GetBlockInfo(dev, blk);
5635 state = bi->blockState;
5639 /* For each chunk in each block that needs scanning....*/
5640 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5641 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5642 /* Read the tags and decide what to do */
5643 chunk = blk * dev->nChunksPerBlock + c;
5645 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5648 /* Let's have a good look at this chunk... */
5650 if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
5656 /*T((" %d %d deleted\n",blk,c)); */
5657 } else if (!tags.chunkUsed) {
5658 /* An unassigned chunk in the block
5659 * This means that either the block is empty or
5660 * this is the one being allocated from
5664 /* We're looking at the first chunk in the block so the block is unused */
5665 state = YAFFS_BLOCK_STATE_EMPTY;
5666 dev->nErasedBlocks++;
5668 /* this is the block being allocated from */
5671 (" Allocating from %d %d" TENDSTR),
5673 state = YAFFS_BLOCK_STATE_ALLOCATING;
5674 dev->allocationBlock = blk;
5675 dev->allocationPage = c;
5676 dev->allocationBlockFinder = blk;
5677 /* Set it to here to encourage the allocator to go forth from here. */
5681 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5682 } else if (tags.chunkId > 0) {
5683 /* chunkId > 0 so it is a data chunk... */
5684 unsigned int endpos;
5686 yaffs_SetChunkBit(dev, blk, c);
5689 in = yaffs_FindOrCreateObjectByNumber(dev,
5692 YAFFS_OBJECT_TYPE_FILE);
5693 /* PutChunkIntoFile checks for a clash (two data chunks with
5694 * the same chunkId).
5701 if(!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,1))
5706 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5709 in->variantType == YAFFS_OBJECT_TYPE_FILE
5710 && in->variant.fileVariant.scannedFileSize <
5712 in->variant.fileVariant.
5713 scannedFileSize = endpos;
5714 if (!dev->useHeaderFileSize) {
5715 in->variant.fileVariant.
5717 in->variant.fileVariant.
5722 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
5724 /* chunkId == 0, so it is an ObjectHeader.
5725 * Thus, we read in the object header and make the object
5727 yaffs_SetChunkBit(dev, blk, c);
5730 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5734 oh = (yaffs_ObjectHeader *) chunkData;
5736 in = yaffs_FindObjectByNumber(dev,
5738 if (in && in->variantType != oh->type) {
5739 /* This should not happen, but somehow
5740 * Wev'e ended up with an objectId that has been reused but not yet
5741 * deleted, and worse still it has changed type. Delete the old object.
5744 yaffs_DestroyObject(in);
5749 in = yaffs_FindOrCreateObjectByNumber(dev,
5757 if (in && oh->shadowsObject > 0) {
5759 struct yaffs_ShadowFixerStruct *fixer;
5760 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
5762 fixer-> next = shadowFixerList;
5763 shadowFixerList = fixer;
5764 fixer->objectId = tags.objectId;
5765 fixer->shadowedId = oh->shadowsObject;
5770 if (in && in->valid) {
5771 /* We have already filled this one. We have a duplicate and need to resolve it. */
5773 unsigned existingSerial = in->serial;
5774 unsigned newSerial = tags.serialNumber;
5776 if (((existingSerial + 1) & 3) == newSerial) {
5777 /* Use new one - destroy the exisiting one */
5778 yaffs_DeleteChunk(dev,
5783 /* Use existing - destroy this one. */
5784 yaffs_DeleteChunk(dev, chunk, 1,
5789 if (in && !in->valid &&
5790 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5791 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5792 /* We only load some info, don't fiddle with directory structure */
5794 in->variantType = oh->type;
5796 in->yst_mode = oh->yst_mode;
5797 #ifdef CONFIG_YAFFS_WINCE
5798 in->win_atime[0] = oh->win_atime[0];
5799 in->win_ctime[0] = oh->win_ctime[0];
5800 in->win_mtime[0] = oh->win_mtime[0];
5801 in->win_atime[1] = oh->win_atime[1];
5802 in->win_ctime[1] = oh->win_ctime[1];
5803 in->win_mtime[1] = oh->win_mtime[1];
5805 in->yst_uid = oh->yst_uid;
5806 in->yst_gid = oh->yst_gid;
5807 in->yst_atime = oh->yst_atime;
5808 in->yst_mtime = oh->yst_mtime;
5809 in->yst_ctime = oh->yst_ctime;
5810 in->yst_rdev = oh->yst_rdev;
5812 in->hdrChunk = chunk;
5813 in->serial = tags.serialNumber;
5815 } else if (in && !in->valid) {
5816 /* we need to load this info */
5819 in->variantType = oh->type;
5821 in->yst_mode = oh->yst_mode;
5822 #ifdef CONFIG_YAFFS_WINCE
5823 in->win_atime[0] = oh->win_atime[0];
5824 in->win_ctime[0] = oh->win_ctime[0];
5825 in->win_mtime[0] = oh->win_mtime[0];
5826 in->win_atime[1] = oh->win_atime[1];
5827 in->win_ctime[1] = oh->win_ctime[1];
5828 in->win_mtime[1] = oh->win_mtime[1];
5830 in->yst_uid = oh->yst_uid;
5831 in->yst_gid = oh->yst_gid;
5832 in->yst_atime = oh->yst_atime;
5833 in->yst_mtime = oh->yst_mtime;
5834 in->yst_ctime = oh->yst_ctime;
5835 in->yst_rdev = oh->yst_rdev;
5837 in->hdrChunk = chunk;
5838 in->serial = tags.serialNumber;
5840 yaffs_SetObjectName(in, oh->name);
5843 /* directory stuff...
5848 yaffs_FindOrCreateObjectByNumber
5849 (dev, oh->parentObjectId,
5850 YAFFS_OBJECT_TYPE_DIRECTORY);
5851 if (parent->variantType ==
5852 YAFFS_OBJECT_TYPE_UNKNOWN) {
5853 /* Set up as a directory */
5854 parent->variantType =
5855 YAFFS_OBJECT_TYPE_DIRECTORY;
5856 YINIT_LIST_HEAD(&parent->variant.
5859 } else if (parent->variantType !=
5860 YAFFS_OBJECT_TYPE_DIRECTORY)
5862 /* Hoosterman, another problem....
5863 * We're trying to use a non-directory as a directory
5866 T(YAFFS_TRACE_ERROR,
5868 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
5870 parent = dev->lostNFoundDir;
5873 yaffs_AddObjectToDirectory(parent, in);
5875 if (0 && (parent == dev->deletedDir ||
5876 parent == dev->unlinkedDir)) {
5877 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
5878 dev->nDeletedFiles++;
5880 /* Note re hardlinks.
5881 * Since we might scan a hardlink before its equivalent object is scanned
5882 * we put them all in a list.
5883 * After scanning is complete, we should have all the objects, so we run through this
5884 * list and fix up all the chains.
5887 switch (in->variantType) {
5888 case YAFFS_OBJECT_TYPE_UNKNOWN:
5889 /* Todo got a problem */
5891 case YAFFS_OBJECT_TYPE_FILE:
5892 if (dev->useHeaderFileSize)
5894 in->variant.fileVariant.
5899 case YAFFS_OBJECT_TYPE_HARDLINK:
5900 in->variant.hardLinkVariant.
5901 equivalentObjectId =
5902 oh->equivalentObjectId;
5903 in->hardLinks.next =
5904 (struct ylist_head *)
5908 case YAFFS_OBJECT_TYPE_DIRECTORY:
5911 case YAFFS_OBJECT_TYPE_SPECIAL:
5914 case YAFFS_OBJECT_TYPE_SYMLINK:
5915 in->variant.symLinkVariant.alias =
5916 yaffs_CloneString(oh->alias);
5917 if(!in->variant.symLinkVariant.alias)
5923 if (parent == dev->deletedDir) {
5924 yaffs_DestroyObject(in);
5925 bi->hasShrinkHeader = 1;
5932 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5933 /* If we got this far while scanning, then the block is fully allocated.*/
5934 state = YAFFS_BLOCK_STATE_FULL;
5937 bi->blockState = state;
5939 /* Now let's see if it was dirty */
5940 if (bi->pagesInUse == 0 &&
5941 !bi->hasShrinkHeader &&
5942 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5943 yaffs_BlockBecameDirty(dev, blk);
5949 /* Ok, we've done all the scanning.
5950 * Fix up the hard link chains.
5951 * We should now have scanned all the objects, now it's time to add these
5955 yaffs_HardlinkFixup(dev,hardList);
5957 /* Fix up any shadowed objects */
5959 struct yaffs_ShadowFixerStruct *fixer;
5962 while(shadowFixerList){
5963 fixer = shadowFixerList;
5964 shadowFixerList = fixer->next;
5965 /* Complete the rename transaction by deleting the shadowed object
5966 * then setting the object header to unshadowed.
5968 obj = yaffs_FindObjectByNumber(dev,fixer->shadowedId);
5970 yaffs_DestroyObject(obj);
5972 obj = yaffs_FindObjectByNumber(dev,fixer->objectId);
5974 yaffs_UpdateObjectHeader(obj,NULL,1,0,0);
5981 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5987 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5993 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5996 yaffs_ObjectHeader *oh;
5998 yaffs_ExtendedTags tags;
6000 int alloc_failed = 0;
6008 T(YAFFS_TRACE_SCAN,(TSTR("details for object %d %s loaded" TENDSTR),
6010 in->lazyLoaded ? "not yet" : "already"));
6013 if(in->lazyLoaded && in->hdrChunk > 0){
6015 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6017 result = yaffs_ReadChunkWithTagsFromNAND(dev,in->hdrChunk,chunkData,&tags);
6018 oh = (yaffs_ObjectHeader *) chunkData;
6020 in->yst_mode = oh->yst_mode;
6021 #ifdef CONFIG_YAFFS_WINCE
6022 in->win_atime[0] = oh->win_atime[0];
6023 in->win_ctime[0] = oh->win_ctime[0];
6024 in->win_mtime[0] = oh->win_mtime[0];
6025 in->win_atime[1] = oh->win_atime[1];
6026 in->win_ctime[1] = oh->win_ctime[1];
6027 in->win_mtime[1] = oh->win_mtime[1];
6029 in->yst_uid = oh->yst_uid;
6030 in->yst_gid = oh->yst_gid;
6031 in->yst_atime = oh->yst_atime;
6032 in->yst_mtime = oh->yst_mtime;
6033 in->yst_ctime = oh->yst_ctime;
6034 in->yst_rdev = oh->yst_rdev;
6037 yaffs_SetObjectName(in, oh->name);
6039 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
6040 in->variant.symLinkVariant.alias =
6041 yaffs_CloneString(oh->alias);
6042 if(!in->variant.symLinkVariant.alias)
6043 alloc_failed = 1; /* Not returned to caller */
6046 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
6050 static int yaffs_ScanBackwards(yaffs_Device * dev)
6052 yaffs_ExtendedTags tags;
6057 int nBlocksToScan = 0;
6063 yaffs_BlockState state;
6064 yaffs_Object *hardList = NULL;
6065 yaffs_BlockInfo *bi;
6066 __u32 sequenceNumber;
6067 yaffs_ObjectHeader *oh;
6069 yaffs_Object *parent;
6070 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6076 int foundChunksInBlock;
6077 int equivalentObjectId;
6078 int alloc_failed = 0;
6081 yaffs_BlockIndex *blockIndex = NULL;
6082 int altBlockIndex = 0;
6084 if (!dev->isYaffs2) {
6086 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6092 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
6093 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6096 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6098 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6101 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6107 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6111 dev->blocksInCheckpoint = 0;
6113 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6115 /* Scan all the blocks to determine their state */
6116 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6117 bi = yaffs_GetBlockInfo(dev, blk);
6118 yaffs_ClearChunkBits(dev, blk);
6120 bi->softDeletions = 0;
6122 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6124 bi->blockState = state;
6125 bi->sequenceNumber = sequenceNumber;
6127 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6128 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6130 T(YAFFS_TRACE_SCAN_DEBUG,
6131 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6132 state, sequenceNumber));
6135 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
6136 dev->blocksInCheckpoint++;
6138 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6139 T(YAFFS_TRACE_BAD_BLOCKS,
6140 (TSTR("block %d is bad" TENDSTR), blk));
6141 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6142 T(YAFFS_TRACE_SCAN_DEBUG,
6143 (TSTR("Block empty " TENDSTR)));
6144 dev->nErasedBlocks++;
6145 dev->nFreeChunks += dev->nChunksPerBlock;
6146 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6148 /* Determine the highest sequence number */
6149 if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6150 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6152 blockIndex[nBlocksToScan].seq = sequenceNumber;
6153 blockIndex[nBlocksToScan].block = blk;
6157 if (sequenceNumber >= dev->sequenceNumber) {
6158 dev->sequenceNumber = sequenceNumber;
6161 /* TODO: Nasty sequence number! */
6164 ("Block scanning block %d has bad sequence number %d"
6165 TENDSTR), blk, sequenceNumber));
6172 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6178 /* Sort the blocks */
6179 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6181 /* Use qsort now. */
6182 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6186 /* Dungy old bubble sort... */
6188 yaffs_BlockIndex temp;
6192 for (i = 0; i < nBlocksToScan; i++)
6193 for (j = i + 1; j < nBlocksToScan; j++)
6194 if (blockIndex[i].seq > blockIndex[j].seq) {
6195 temp = blockIndex[j];
6196 blockIndex[j] = blockIndex[i];
6197 blockIndex[i] = temp;
6204 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6206 /* Now scan the blocks looking at the data. */
6208 endIterator = nBlocksToScan - 1;
6209 T(YAFFS_TRACE_SCAN_DEBUG,
6210 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6212 /* For each block.... backwards */
6213 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6215 /* Cooperative multitasking! This loop can run for so
6216 long that watchdog timers expire. */
6219 /* get the block to scan in the correct order */
6220 blk = blockIndex[blockIterator].block;
6222 bi = yaffs_GetBlockInfo(dev, blk);
6225 state = bi->blockState;
6229 /* For each chunk in each block that needs scanning.... */
6230 foundChunksInBlock = 0;
6231 for (c = dev->nChunksPerBlock - 1;
6232 !alloc_failed && c >= 0 &&
6233 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6234 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6235 /* Scan backwards...
6236 * Read the tags and decide what to do
6239 chunk = blk * dev->nChunksPerBlock + c;
6241 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6244 /* Let's have a good look at this chunk... */
6246 if (!tags.chunkUsed) {
6247 /* An unassigned chunk in the block.
6248 * If there are used chunks after this one, then
6249 * it is a chunk that was skipped due to failing the erased
6250 * check. Just skip it so that it can be deleted.
6251 * But, more typically, We get here when this is an unallocated
6252 * chunk and his means that either the block is empty or
6253 * this is the one being allocated from
6256 if(foundChunksInBlock)
6258 /* This is a chunk that was skipped due to failing the erased check */
6260 } else if (c == 0) {
6261 /* We're looking at the first chunk in the block so the block is unused */
6262 state = YAFFS_BLOCK_STATE_EMPTY;
6263 dev->nErasedBlocks++;
6265 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6266 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6267 if(dev->sequenceNumber == bi->sequenceNumber) {
6268 /* this is the block being allocated from */
6272 (" Allocating from %d %d"
6275 state = YAFFS_BLOCK_STATE_ALLOCATING;
6276 dev->allocationBlock = blk;
6277 dev->allocationPage = c;
6278 dev->allocationBlockFinder = blk;
6281 /* This is a partially written block that is not
6282 * the current allocation block. This block must have
6283 * had a write failure, so set up for retirement.
6286 /* bi->needsRetiring = 1; ??? TODO */
6287 bi->gcPrioritise = 1;
6289 T(YAFFS_TRACE_ALWAYS,
6290 (TSTR("Partially written block %d detected" TENDSTR),
6300 } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED){
6302 (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
6307 }else if (tags.chunkId > 0) {
6308 /* chunkId > 0 so it is a data chunk... */
6309 unsigned int endpos;
6311 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6313 foundChunksInBlock = 1;
6316 yaffs_SetChunkBit(dev, blk, c);
6319 in = yaffs_FindOrCreateObjectByNumber(dev,
6322 YAFFS_OBJECT_TYPE_FILE);
6329 in->variantType == YAFFS_OBJECT_TYPE_FILE
6331 in->variant.fileVariant.shrinkSize) {
6332 /* This has not been invalidated by a resize */
6333 if(!yaffs_PutChunkIntoFile(in, tags.chunkId,
6338 /* File size is calculated by looking at the data chunks if we have not
6339 * seen an object header yet. Stop this practice once we find an object header.
6343 1) * dev->nDataBytesPerChunk +
6346 if (!in->valid && /* have not got an object header yet */
6347 in->variant.fileVariant.
6348 scannedFileSize < endpos) {
6349 in->variant.fileVariant.
6350 scannedFileSize = endpos;
6351 in->variant.fileVariant.
6353 in->variant.fileVariant.
6358 /* This chunk has been invalidated by a resize, so delete */
6359 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6363 /* chunkId == 0, so it is an ObjectHeader.
6364 * Thus, we read in the object header and make the object
6366 foundChunksInBlock = 1;
6368 yaffs_SetChunkBit(dev, blk, c);
6374 if (tags.extraHeaderInfoAvailable) {
6375 in = yaffs_FindOrCreateObjectByNumber
6376 (dev, tags.objectId,
6377 tags.extraObjectType);
6381 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
6384 tags.extraShadows ||
6386 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6387 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
6390 /* If we don't have valid info then we need to read the chunk
6391 * TODO In future we can probably defer reading the chunk and
6392 * living with invalid data until needed.
6395 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6400 oh = (yaffs_ObjectHeader *) chunkData;
6402 if(dev->inbandTags){
6403 /* Fix up the header if they got corrupted by inband tags */
6404 oh->shadowsObject = oh->inbandShadowsObject;
6405 oh->isShrink = oh->inbandIsShrink;
6409 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6414 /* TODO Hoosterman we have a problem! */
6415 T(YAFFS_TRACE_ERROR,
6417 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6418 TENDSTR), tags.objectId, chunk));
6423 /* We have already filled this one.
6424 * We have a duplicate that will be discarded, but
6425 * we first have to suck out resize info if it is a file.
6428 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6430 oh-> type == YAFFS_OBJECT_TYPE_FILE)||
6431 (tags.extraHeaderInfoAvailable &&
6432 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
6435 (oh) ? oh->fileSize : tags.
6437 __u32 parentObjectId =
6439 parentObjectId : tags.
6440 extraParentObjectId;
6444 (oh) ? oh->isShrink : tags.
6445 extraIsShrinkHeader;
6447 /* If it is deleted (unlinked at start also means deleted)
6448 * we treat the file size as being zeroed at this point.
6450 if (parentObjectId ==
6451 YAFFS_OBJECTID_DELETED
6452 || parentObjectId ==
6453 YAFFS_OBJECTID_UNLINKED) {
6459 in->variant.fileVariant.
6460 shrinkSize > thisSize) {
6461 in->variant.fileVariant.
6467 bi->hasShrinkHeader = 1;
6471 /* Use existing - destroy this one. */
6472 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6477 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6479 YAFFS_OBJECTID_LOSTNFOUND)) {
6480 /* We only load some info, don't fiddle with directory structure */
6484 in->variantType = oh->type;
6486 in->yst_mode = oh->yst_mode;
6487 #ifdef CONFIG_YAFFS_WINCE
6488 in->win_atime[0] = oh->win_atime[0];
6489 in->win_ctime[0] = oh->win_ctime[0];
6490 in->win_mtime[0] = oh->win_mtime[0];
6491 in->win_atime[1] = oh->win_atime[1];
6492 in->win_ctime[1] = oh->win_ctime[1];
6493 in->win_mtime[1] = oh->win_mtime[1];
6495 in->yst_uid = oh->yst_uid;
6496 in->yst_gid = oh->yst_gid;
6497 in->yst_atime = oh->yst_atime;
6498 in->yst_mtime = oh->yst_mtime;
6499 in->yst_ctime = oh->yst_ctime;
6500 in->yst_rdev = oh->yst_rdev;
6504 in->variantType = tags.extraObjectType;
6508 in->hdrChunk = chunk;
6510 } else if (!in->valid) {
6511 /* we need to load this info */
6514 in->hdrChunk = chunk;
6517 in->variantType = oh->type;
6519 in->yst_mode = oh->yst_mode;
6520 #ifdef CONFIG_YAFFS_WINCE
6521 in->win_atime[0] = oh->win_atime[0];
6522 in->win_ctime[0] = oh->win_ctime[0];
6523 in->win_mtime[0] = oh->win_mtime[0];
6524 in->win_atime[1] = oh->win_atime[1];
6525 in->win_ctime[1] = oh->win_ctime[1];
6526 in->win_mtime[1] = oh->win_mtime[1];
6528 in->yst_uid = oh->yst_uid;
6529 in->yst_gid = oh->yst_gid;
6530 in->yst_atime = oh->yst_atime;
6531 in->yst_mtime = oh->yst_mtime;
6532 in->yst_ctime = oh->yst_ctime;
6533 in->yst_rdev = oh->yst_rdev;
6536 if (oh->shadowsObject > 0)
6537 yaffs_HandleShadowedObject(dev,
6543 yaffs_SetObjectName(in, oh->name);
6545 yaffs_FindOrCreateObjectByNumber
6546 (dev, oh->parentObjectId,
6547 YAFFS_OBJECT_TYPE_DIRECTORY);
6549 fileSize = oh->fileSize;
6550 isShrink = oh->isShrink;
6551 equivalentObjectId = oh->equivalentObjectId;
6555 in->variantType = tags.extraObjectType;
6557 yaffs_FindOrCreateObjectByNumber
6558 (dev, tags.extraParentObjectId,
6559 YAFFS_OBJECT_TYPE_DIRECTORY);
6560 fileSize = tags.extraFileLength;
6561 isShrink = tags.extraIsShrinkHeader;
6562 equivalentObjectId = tags.extraEquivalentObjectId;
6568 /* directory stuff...
6572 if (parent->variantType ==
6573 YAFFS_OBJECT_TYPE_UNKNOWN) {
6574 /* Set up as a directory */
6575 parent->variantType =
6576 YAFFS_OBJECT_TYPE_DIRECTORY;
6577 YINIT_LIST_HEAD(&parent->variant.
6580 } else if (parent->variantType !=
6581 YAFFS_OBJECT_TYPE_DIRECTORY)
6583 /* Hoosterman, another problem....
6584 * We're trying to use a non-directory as a directory
6587 T(YAFFS_TRACE_ERROR,
6589 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6591 parent = dev->lostNFoundDir;
6594 yaffs_AddObjectToDirectory(parent, in);
6596 itsUnlinked = (parent == dev->deletedDir) ||
6597 (parent == dev->unlinkedDir);
6600 /* Mark the block as having a shrinkHeader */
6601 bi->hasShrinkHeader = 1;
6604 /* Note re hardlinks.
6605 * Since we might scan a hardlink before its equivalent object is scanned
6606 * we put them all in a list.
6607 * After scanning is complete, we should have all the objects, so we run
6608 * through this list and fix up all the chains.
6611 switch (in->variantType) {
6612 case YAFFS_OBJECT_TYPE_UNKNOWN:
6613 /* Todo got a problem */
6615 case YAFFS_OBJECT_TYPE_FILE:
6617 if (in->variant.fileVariant.
6618 scannedFileSize < fileSize) {
6619 /* This covers the case where the file size is greater
6620 * than where the data is
6621 * This will happen if the file is resized to be larger
6622 * than its current data extents.
6624 in->variant.fileVariant.fileSize = fileSize;
6625 in->variant.fileVariant.scannedFileSize =
6626 in->variant.fileVariant.fileSize;
6630 in->variant.fileVariant.shrinkSize > fileSize) {
6631 in->variant.fileVariant.shrinkSize = fileSize;
6635 case YAFFS_OBJECT_TYPE_HARDLINK:
6637 in->variant.hardLinkVariant.equivalentObjectId =
6639 in->hardLinks.next =
6640 (struct ylist_head *) hardList;
6644 case YAFFS_OBJECT_TYPE_DIRECTORY:
6647 case YAFFS_OBJECT_TYPE_SPECIAL:
6650 case YAFFS_OBJECT_TYPE_SYMLINK:
6652 in->variant.symLinkVariant.alias =
6653 yaffs_CloneString(oh->
6655 if(!in->variant.symLinkVariant.alias)
6665 } /* End of scanning for each chunk */
6667 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6668 /* If we got this far while scanning, then the block is fully allocated. */
6669 state = YAFFS_BLOCK_STATE_FULL;
6672 bi->blockState = state;
6674 /* Now let's see if it was dirty */
6675 if (bi->pagesInUse == 0 &&
6676 !bi->hasShrinkHeader &&
6677 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6678 yaffs_BlockBecameDirty(dev, blk);
6684 YFREE_ALT(blockIndex);
6688 /* Ok, we've done all the scanning.
6689 * Fix up the hard link chains.
6690 * We should now have scanned all the objects, now it's time to add these
6693 yaffs_HardlinkFixup(dev,hardList);
6696 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6702 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6707 /*------------------------------ Directory Functions ----------------------------- */
6709 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
6711 struct ylist_head *lh;
6712 yaffs_Object *listObj;
6717 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
6721 if(yaffs_SkipVerification(obj->myDev))
6725 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
6729 if(obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
6730 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
6734 /* Iterate through the objects in each hash entry */
6736 ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
6738 listObj = ylist_entry(lh, yaffs_Object, siblings);
6739 yaffs_VerifyObject(listObj);
6746 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR),count));
6752 static void yaffs_VerifyDirectory(yaffs_Object *directory)
6755 struct ylist_head *lh;
6756 yaffs_Object *listObj;
6761 if(yaffs_SkipFullVerification(directory->myDev))
6765 if(directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
6766 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR),directory->variantType));
6770 /* Iterate through the objects in each hash entry */
6772 ylist_for_each(lh, &directory->variant.directoryVariant.children) {
6774 listObj = ylist_entry(lh, yaffs_Object, siblings);
6775 if(listObj->parent != directory){
6776 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR),listObj->parent));
6779 yaffs_VerifyObjectInDirectory(listObj);
6786 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
6788 yaffs_Device *dev = obj->myDev;
6789 yaffs_Object *parent;
6791 yaffs_VerifyObjectInDirectory(obj);
6792 parent = obj->parent;
6794 yaffs_VerifyDirectory(parent);
6796 if(dev && dev->removeObjectCallback)
6797 dev->removeObjectCallback(obj);
6800 ylist_del_init(&obj->siblings);
6803 yaffs_VerifyDirectory(parent);
6808 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
6813 T(YAFFS_TRACE_ALWAYS,
6815 ("tragedy: Trying to add an object to a null pointer directory"
6819 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6820 T(YAFFS_TRACE_ALWAYS,
6822 ("tragedy: Trying to add an object to a non-directory"
6827 if (obj->siblings.prev == NULL) {
6828 /* Not initialised */
6831 } else if (ylist_empty(&obj->siblings)) {
6836 yaffs_VerifyDirectory(directory);
6838 yaffs_RemoveObjectFromDirectory(obj);
6842 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
6843 obj->parent = directory;
6845 if (directory == obj->myDev->unlinkedDir
6846 || directory == obj->myDev->deletedDir) {
6848 obj->myDev->nUnlinkedFiles++;
6849 obj->renameAllowed = 0;
6852 yaffs_VerifyDirectory(directory);
6853 yaffs_VerifyObjectInDirectory(obj);
6858 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
6863 struct ylist_head *i;
6864 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
6873 T(YAFFS_TRACE_ALWAYS,
6875 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6879 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6880 T(YAFFS_TRACE_ALWAYS,
6882 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6886 sum = yaffs_CalcNameSum(name);
6888 ylist_for_each(i, &directory->variant.directoryVariant.children) {
6890 l = ylist_entry(i, yaffs_Object, siblings);
6892 if(l->parent != directory)
6895 yaffs_CheckObjectDetailsLoaded(l);
6897 /* Special case for lost-n-found */
6898 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6899 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
6902 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0){
6903 /* LostnFound chunk called Objxxx
6906 yaffs_GetObjectName(l, buffer,
6907 YAFFS_MAX_NAME_LENGTH);
6908 if (yaffs_strncmp(name, buffer,YAFFS_MAX_NAME_LENGTH) == 0) {
6921 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
6922 int (*fn) (yaffs_Object *))
6924 struct ylist_head *i;
6928 T(YAFFS_TRACE_ALWAYS,
6930 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6934 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6935 T(YAFFS_TRACE_ALWAYS,
6937 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6941 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
6943 l = ylist_entry(i, yaffs_Object, siblings);
6955 /* GetEquivalentObject dereferences any hard links to get to the
6959 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
6961 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
6962 /* We want the object id of the equivalent object, not this one */
6963 obj = obj->variant.hardLinkVariant.equivalentObject;
6964 yaffs_CheckObjectDetailsLoaded(obj);
6970 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
6972 memset(name, 0, buffSize * sizeof(YCHAR));
6974 yaffs_CheckObjectDetailsLoaded(obj);
6976 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6977 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
6978 } else if (obj->hdrChunk <= 0) {
6980 YCHAR numString[20];
6981 YCHAR *x = &numString[19];
6982 unsigned v = obj->objectId;
6986 *x = '0' + (v % 10);
6989 /* make up a name */
6990 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
6991 yaffs_strcat(locName,x);
6992 yaffs_strncpy(name, locName, buffSize - 1);
6995 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
6996 else if (obj->shortName[0]) {
6997 yaffs_strcpy(name, obj->shortName);
7002 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
7004 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
7006 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
7008 if (obj->hdrChunk > 0) {
7009 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
7010 obj->hdrChunk, buffer,
7013 yaffs_strncpy(name, oh->name, buffSize - 1);
7015 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
7018 return yaffs_strlen(name);
7021 int yaffs_GetObjectFileLength(yaffs_Object * obj)
7024 /* Dereference any hard linking */
7025 obj = yaffs_GetEquivalentObject(obj);
7027 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
7028 return obj->variant.fileVariant.fileSize;
7030 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
7031 return yaffs_strlen(obj->variant.symLinkVariant.alias);
7033 /* Only a directory should drop through to here */
7034 return obj->myDev->nDataBytesPerChunk;
7038 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
7041 struct ylist_head *i;
7043 if (!obj->unlinked) {
7044 count++; /* the object itself */
7046 ylist_for_each(i, &obj->hardLinks) {
7047 count++; /* add the hard links; */
7053 int yaffs_GetObjectInode(yaffs_Object * obj)
7055 obj = yaffs_GetEquivalentObject(obj);
7057 return obj->objectId;
7060 unsigned yaffs_GetObjectType(yaffs_Object * obj)
7062 obj = yaffs_GetEquivalentObject(obj);
7064 switch (obj->variantType) {
7065 case YAFFS_OBJECT_TYPE_FILE:
7068 case YAFFS_OBJECT_TYPE_DIRECTORY:
7071 case YAFFS_OBJECT_TYPE_SYMLINK:
7074 case YAFFS_OBJECT_TYPE_HARDLINK:
7077 case YAFFS_OBJECT_TYPE_SPECIAL:
7078 if (S_ISFIFO(obj->yst_mode))
7080 if (S_ISCHR(obj->yst_mode))
7082 if (S_ISBLK(obj->yst_mode))
7084 if (S_ISSOCK(obj->yst_mode))
7092 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
7094 obj = yaffs_GetEquivalentObject(obj);
7095 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
7096 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7098 return yaffs_CloneString(_Y(""));
7102 #ifndef CONFIG_YAFFS_WINCE
7104 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
7106 unsigned int valid = attr->ia_valid;
7108 if (valid & ATTR_MODE)
7109 obj->yst_mode = attr->ia_mode;
7110 if (valid & ATTR_UID)
7111 obj->yst_uid = attr->ia_uid;
7112 if (valid & ATTR_GID)
7113 obj->yst_gid = attr->ia_gid;
7115 if (valid & ATTR_ATIME)
7116 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7117 if (valid & ATTR_CTIME)
7118 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7119 if (valid & ATTR_MTIME)
7120 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7122 if (valid & ATTR_SIZE)
7123 yaffs_ResizeFile(obj, attr->ia_size);
7125 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7130 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
7132 unsigned int valid = 0;
7134 attr->ia_mode = obj->yst_mode;
7136 attr->ia_uid = obj->yst_uid;
7138 attr->ia_gid = obj->yst_gid;
7141 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7142 valid |= ATTR_ATIME;
7143 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7144 valid |= ATTR_CTIME;
7145 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7146 valid |= ATTR_MTIME;
7148 attr->ia_size = yaffs_GetFileSize(obj);
7151 attr->ia_valid = valid;
7160 int yaffs_DumpObject(yaffs_Object * obj)
7164 yaffs_GetObjectName(obj, name, 256);
7166 T(YAFFS_TRACE_ALWAYS,
7168 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7169 " chunk %d type %d size %d\n"
7170 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7171 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7172 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7178 /*---------------------------- Initialisation code -------------------------------------- */
7180 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
7183 /* Common functions, gotta have */
7184 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
7187 #ifdef CONFIG_YAFFS_YAFFS2
7189 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7190 if (dev->writeChunkWithTagsToNAND &&
7191 dev->readChunkWithTagsFromNAND &&
7192 !dev->writeChunkToNAND &&
7193 !dev->readChunkFromNAND &&
7194 dev->markNANDBlockBad && dev->queryNANDBlock)
7198 /* Can use the "spare" style interface for yaffs1 */
7199 if (!dev->isYaffs2 &&
7200 !dev->writeChunkWithTagsToNAND &&
7201 !dev->readChunkWithTagsFromNAND &&
7202 dev->writeChunkToNAND &&
7203 dev->readChunkFromNAND &&
7204 !dev->markNANDBlockBad && !dev->queryNANDBlock)
7211 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7213 /* Initialise the unlinked, deleted, root and lost and found directories */
7215 dev->lostNFoundDir = dev->rootDir = NULL;
7216 dev->unlinkedDir = dev->deletedDir = NULL;
7219 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7222 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7225 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7226 YAFFS_ROOT_MODE | S_IFDIR);
7227 dev->lostNFoundDir =
7228 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7229 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7231 if(dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir){
7232 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7239 int yaffs_GutsInitialise(yaffs_Device * dev)
7241 int init_failed = 0;
7245 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7247 /* Check stuff that must be set */
7250 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7254 dev->internalStartBlock = dev->startBlock;
7255 dev->internalEndBlock = dev->endBlock;
7256 dev->blockOffset = 0;
7257 dev->chunkOffset = 0;
7258 dev->nFreeChunks = 0;
7262 if (dev->startBlock == 0) {
7263 dev->internalStartBlock = dev->startBlock + 1;
7264 dev->internalEndBlock = dev->endBlock + 1;
7265 dev->blockOffset = 1;
7266 dev->chunkOffset = dev->nChunksPerBlock;
7269 /* Check geometry parameters. */
7271 if ((!dev->inbandTags && dev->isYaffs2 && dev->totalBytesPerChunk < 1024) ||
7272 (!dev->isYaffs2 && dev->totalBytesPerChunk < 512) ||
7273 (dev->inbandTags && !dev->isYaffs2 ) ||
7274 dev->nChunksPerBlock < 2 ||
7275 dev->nReservedBlocks < 2 ||
7276 dev->internalStartBlock <= 0 ||
7277 dev->internalEndBlock <= 0 ||
7278 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
7280 T(YAFFS_TRACE_ALWAYS,
7282 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7283 TENDSTR), dev->totalBytesPerChunk, dev->isYaffs2 ? "2" : "", dev->inbandTags));
7287 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7288 T(YAFFS_TRACE_ALWAYS,
7289 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7293 /* Sort out space for inband tags, if required */
7295 dev->nDataBytesPerChunk = dev->totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7297 dev->nDataBytesPerChunk = dev->totalBytesPerChunk;
7299 /* Got the right mix of functions? */
7300 if (!yaffs_CheckDevFunctions(dev)) {
7301 /* Function missing */
7302 T(YAFFS_TRACE_ALWAYS,
7304 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7309 /* This is really a compilation check. */
7310 if (!yaffs_CheckStructures()) {
7311 T(YAFFS_TRACE_ALWAYS,
7312 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7316 if (dev->isMounted) {
7317 T(YAFFS_TRACE_ALWAYS,
7318 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7322 /* Finished with most checks. One or two more checks happen later on too. */
7326 /* OK now calculate a few things for the device */
7329 * Calculate all the chunk size manipulation numbers:
7331 x = dev->nDataBytesPerChunk;
7332 /* We always use dev->chunkShift and dev->chunkDiv */
7333 dev->chunkShift = Shifts(x);
7334 x >>= dev->chunkShift;
7336 /* We only use chunk mask if chunkDiv is 1 */
7337 dev->chunkMask = (1<<dev->chunkShift) - 1;
7340 * Calculate chunkGroupBits.
7341 * We need to find the next power of 2 > than internalEndBlock
7344 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7348 /* Set up tnode width if wide tnodes are enabled. */
7349 if(!dev->wideTnodesDisabled){
7350 /* bits must be even so that we end up with 32-bit words */
7354 dev->tnodeWidth = 16;
7356 dev->tnodeWidth = bits;
7359 dev->tnodeWidth = 16;
7361 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7363 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7364 * so if the bitwidth of the
7365 * chunk range we're using is greater than 16 we need
7366 * to figure out chunk shift and chunkGroupSize
7369 if (bits <= dev->tnodeWidth)
7370 dev->chunkGroupBits = 0;
7372 dev->chunkGroupBits = bits - dev->tnodeWidth;
7375 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7377 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7378 /* We have a problem because the soft delete won't work if
7379 * the chunk group size > chunks per block.
7380 * This can be remedied by using larger "virtual blocks".
7382 T(YAFFS_TRACE_ALWAYS,
7383 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7388 /* OK, we've finished verifying the device, lets continue with initialisation */
7390 /* More device initialisation */
7391 dev->garbageCollections = 0;
7392 dev->passiveGarbageCollections = 0;
7393 dev->currentDirtyChecker = 0;
7394 dev->bufferedBlock = -1;
7395 dev->doingBufferedBlockRewrite = 0;
7396 dev->nDeletedFiles = 0;
7397 dev->nBackgroundDeletions = 0;
7398 dev->nUnlinkedFiles = 0;
7400 dev->eccUnfixed = 0;
7401 dev->tagsEccFixed = 0;
7402 dev->tagsEccUnfixed = 0;
7403 dev->nErasureFailures = 0;
7404 dev->nErasedBlocks = 0;
7406 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7408 /* Initialise temporary buffers and caches. */
7409 if(!yaffs_InitialiseTempBuffers(dev))
7412 dev->srCache = NULL;
7413 dev->gcCleanupList = NULL;
7417 dev->nShortOpCaches > 0) {
7420 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7422 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
7423 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7426 dev->srCache = YMALLOC(srCacheBytes);
7428 buf = (__u8 *) dev->srCache;
7431 memset(dev->srCache,0,srCacheBytes);
7433 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7434 dev->srCache[i].object = NULL;
7435 dev->srCache[i].lastUse = 0;
7436 dev->srCache[i].dirty = 0;
7437 dev->srCache[i].data = buf = YMALLOC_DMA(dev->totalBytesPerChunk);
7448 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7449 if(!dev->gcCleanupList)
7453 if (dev->isYaffs2) {
7454 dev->useHeaderFileSize = 1;
7456 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7459 yaffs_InitialiseTnodes(dev);
7460 yaffs_InitialiseObjects(dev);
7462 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7467 /* Now scan the flash. */
7468 if (dev->isYaffs2) {
7469 if(yaffs_CheckpointRestore(dev)) {
7470 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7471 T(YAFFS_TRACE_ALWAYS,
7472 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7475 /* Clean up the mess caused by an aborted checkpoint load
7476 * and scan backwards.
7478 yaffs_DeinitialiseBlocks(dev);
7479 yaffs_DeinitialiseTnodes(dev);
7480 yaffs_DeinitialiseObjects(dev);
7483 dev->nErasedBlocks = 0;
7484 dev->nFreeChunks = 0;
7485 dev->allocationBlock = -1;
7486 dev->allocationPage = -1;
7487 dev->nDeletedFiles = 0;
7488 dev->nUnlinkedFiles = 0;
7489 dev->nBackgroundDeletions = 0;
7490 dev->oldestDirtySequence = 0;
7492 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7495 yaffs_InitialiseTnodes(dev);
7496 yaffs_InitialiseObjects(dev);
7498 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7501 if(!init_failed && !yaffs_ScanBackwards(dev))
7505 if(!yaffs_Scan(dev))
7508 yaffs_StripDeletedObjects(dev);
7512 /* Clean up the mess */
7513 T(YAFFS_TRACE_TRACING,
7514 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7516 yaffs_Deinitialise(dev);
7520 /* Zero out stats */
7521 dev->nPageReads = 0;
7522 dev->nPageWrites = 0;
7523 dev->nBlockErasures = 0;
7525 dev->nRetriedWrites = 0;
7527 dev->nRetiredBlocks = 0;
7529 yaffs_VerifyFreeChunks(dev);
7530 yaffs_VerifyBlocks(dev);
7533 T(YAFFS_TRACE_TRACING,
7534 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7539 void yaffs_Deinitialise(yaffs_Device * dev)
7541 if (dev->isMounted) {
7544 yaffs_DeinitialiseBlocks(dev);
7545 yaffs_DeinitialiseTnodes(dev);
7546 yaffs_DeinitialiseObjects(dev);
7547 if (dev->nShortOpCaches > 0 &&
7550 for (i = 0; i < dev->nShortOpCaches; i++) {
7551 if(dev->srCache[i].data)
7552 YFREE(dev->srCache[i].data);
7553 dev->srCache[i].data = NULL;
7556 YFREE(dev->srCache);
7557 dev->srCache = NULL;
7560 YFREE(dev->gcCleanupList);
7562 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
7563 YFREE(dev->tempBuffer[i].buffer);
7569 if(dev->deinitialiseNAND)
7570 dev->deinitialiseNAND(dev);
7575 static int yaffs_CountFreeChunks(yaffs_Device * dev)
7580 yaffs_BlockInfo *blk;
7582 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7584 blk = yaffs_GetBlockInfo(dev, b);
7586 switch (blk->blockState) {
7587 case YAFFS_BLOCK_STATE_EMPTY:
7588 case YAFFS_BLOCK_STATE_ALLOCATING:
7589 case YAFFS_BLOCK_STATE_COLLECTING:
7590 case YAFFS_BLOCK_STATE_FULL:
7592 (dev->nChunksPerBlock - blk->pagesInUse +
7593 blk->softDeletions);
7604 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
7606 /* This is what we report to the outside world */
7609 int nDirtyCacheChunks;
7610 int blocksForCheckpoint;
7613 nFree = dev->nFreeChunks;
7615 nFree = yaffs_CountFreeChunks(dev);
7618 nFree += dev->nDeletedFiles;
7620 /* Now count the number of dirty chunks in the cache and subtract those */
7624 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7625 if (dev->srCache[i].dirty)
7626 nDirtyCacheChunks++;
7630 nFree -= nDirtyCacheChunks;
7632 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7634 /* Now we figure out how much to reserve for the checkpoint and report that... */
7635 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7636 if(blocksForCheckpoint < 0)
7637 blocksForCheckpoint = 0;
7639 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7648 static int yaffs_freeVerificationFailures;
7650 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
7655 if(yaffs_SkipVerification(dev))
7658 counted = yaffs_CountFreeChunks(dev);
7660 difference = dev->nFreeChunks - counted;
7663 T(YAFFS_TRACE_ALWAYS,
7664 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7665 dev->nFreeChunks, counted, difference));
7666 yaffs_freeVerificationFailures++;
7670 /*---------------------------------------- YAFFS test code ----------------------*/
7672 #define yaffs_CheckStruct(structure,syze, name) \
7674 if(sizeof(structure) != syze) \
7676 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
7677 name,syze,sizeof(structure))); \
7678 return YAFFS_FAIL; \
7682 static int yaffs_CheckStructures(void)
7684 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
7685 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
7686 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
7687 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7688 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode");
7690 #ifndef CONFIG_YAFFS_WINCE
7691 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");