2 * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
4 * Copyright (C) 2002-2007 Aleph One Ltd.
5 * for Toby Churchill Ltd and Brightstar Engineering
7 * Created by Charles Manning <charles@aleph1.co.uk>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2 as
11 * published by the Free Software Foundation.
14 const char *yaffs_guts_c_version =
15 "$Id: yaffs_guts.c,v 1.79 2009-03-05 01:45:28 charles Exp $";
19 #include "yaffsinterface.h"
20 #include "yaffs_guts.h"
21 #include "yaffs_tagsvalidity.h"
22 #include "yaffs_getblockinfo.h"
24 #include "yaffs_tagscompat.h"
25 #ifndef CONFIG_YAFFS_USE_OWN_SORT
26 #include "yaffs_qsort.h"
28 #include "yaffs_nand.h"
30 #include "yaffs_checkptrw.h"
32 #include "yaffs_nand.h"
33 #include "yaffs_packedtags2.h"
36 #define YAFFS_PASSIVE_GC_CHUNKS 2
38 #include "yaffs_ecc.h"
41 /* Robustification (if it ever comes about...) */
42 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
43 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk);
44 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
46 const yaffs_ExtendedTags * tags);
47 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
48 const yaffs_ExtendedTags * tags);
50 /* Other local prototypes */
51 static int yaffs_UnlinkObject( yaffs_Object *obj);
52 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
54 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
56 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
58 yaffs_ExtendedTags * tags,
60 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
61 int chunkInNAND, int inScan);
63 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
64 yaffs_ObjectType type);
65 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
67 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
68 int force, int isShrink, int shadows);
69 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
70 static int yaffs_CheckStructures(void);
71 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
72 int chunkOffset, int *limit);
73 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
75 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
78 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
81 static int yaffs_UnlinkWorker(yaffs_Object * obj);
83 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
86 loff_t yaffs_GetFileSize(yaffs_Object * obj);
88 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr);
90 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
92 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
94 static void yaffs_VerifyDirectory(yaffs_Object *directory);
96 static int yaffs_CheckFileSanity(yaffs_Object * in);
98 #define yaffs_CheckFileSanity(in)
101 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
102 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
104 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
106 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
107 yaffs_ExtendedTags * tags);
109 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos);
110 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
111 yaffs_FileStructure * fStruct,
115 /* Function to calculate chunk and offset */
117 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut, __u32 *offsetOut)
122 chunk = (__u32)(addr >> dev->chunkShift);
124 if(dev->chunkDiv == 1)
126 /* easy power of 2 case */
127 offset = (__u32)(addr & dev->chunkMask);
131 /* Non power-of-2 case */
135 chunk /= dev->chunkDiv;
137 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
138 offset = (__u32)(addr - chunkBase);
145 /* Function to return the number of shifts for a power of 2 greater than or equal
146 * to the given number
147 * Note we don't try to cater for all possible numbers and this does not have to
148 * be hellishly efficient.
151 static __u32 ShiftsGE(__u32 x)
156 nShifts = extraBits = 0;
159 if(x & 1) extraBits++;
170 /* Function to return the number of shifts to get a 1 in bit 0
173 static __u32 Shifts(__u32 x)
192 * Temporary buffer manipulations.
195 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
198 __u8 *buf = (__u8 *)1;
200 memset(dev->tempBuffer,0,sizeof(dev->tempBuffer));
202 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
203 dev->tempBuffer[i].line = 0; /* not in use */
204 dev->tempBuffer[i].buffer = buf =
205 YMALLOC_DMA(dev->totalBytesPerChunk);
208 return buf ? YAFFS_OK : YAFFS_FAIL;
212 __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
217 if(dev->tempInUse > dev->maxTemp)
218 dev->maxTemp = dev->tempInUse;
220 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
221 if (dev->tempBuffer[i].line == 0) {
222 dev->tempBuffer[i].line = lineNo;
223 if ((i + 1) > dev->maxTemp) {
224 dev->maxTemp = i + 1;
225 for (j = 0; j <= i; j++)
226 dev->tempBuffer[j].maxLine =
227 dev->tempBuffer[j].line;
230 return dev->tempBuffer[i].buffer;
234 T(YAFFS_TRACE_BUFFERS,
235 (TSTR("Out of temp buffers at line %d, other held by lines:"),
237 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
238 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
240 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
243 * If we got here then we have to allocate an unmanaged one
247 dev->unmanagedTempAllocations++;
248 return YMALLOC(dev->nDataBytesPerChunk);
252 void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
259 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
260 if (dev->tempBuffer[i].buffer == buffer) {
261 dev->tempBuffer[i].line = 0;
267 /* assume it is an unmanaged one. */
268 T(YAFFS_TRACE_BUFFERS,
269 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
272 dev->unmanagedTempDeallocations++;
278 * Determine if we have a managed buffer.
280 int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
283 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
284 if (dev->tempBuffer[i].buffer == buffer)
289 for (i = 0; i < dev->nShortOpCaches; i++) {
290 if( dev->srCache[i].data == buffer )
295 if (buffer == dev->checkpointBuffer)
298 T(YAFFS_TRACE_ALWAYS,
299 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
306 * Chunk bitmap manipulations
309 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
311 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
313 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
317 return dev->chunkBits +
318 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
321 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
323 if(blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
324 chunk < 0 || chunk >= dev->nChunksPerBlock) {
326 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),blk,chunk));
331 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
333 __u8 *blkBits = yaffs_BlockBits(dev, blk);
335 memset(blkBits, 0, dev->chunkBitmapStride);
338 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
340 __u8 *blkBits = yaffs_BlockBits(dev, blk);
342 yaffs_VerifyChunkBitId(dev,blk,chunk);
344 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
347 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
349 __u8 *blkBits = yaffs_BlockBits(dev, blk);
351 yaffs_VerifyChunkBitId(dev,blk,chunk);
353 blkBits[chunk / 8] |= (1 << (chunk & 7));
356 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
358 __u8 *blkBits = yaffs_BlockBits(dev, blk);
359 yaffs_VerifyChunkBitId(dev,blk,chunk);
361 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
364 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
366 __u8 *blkBits = yaffs_BlockBits(dev, blk);
368 for (i = 0; i < dev->chunkBitmapStride; i++) {
376 static int yaffs_CountChunkBits(yaffs_Device * dev, int blk)
378 __u8 *blkBits = yaffs_BlockBits(dev, blk);
381 for (i = 0; i < dev->chunkBitmapStride; i++) {
398 static int yaffs_SkipVerification(yaffs_Device *dev)
400 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
403 static int yaffs_SkipFullVerification(yaffs_Device *dev)
405 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
408 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
410 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
413 static const char * blockStateName[] = {
426 static void yaffs_VerifyBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
431 if(yaffs_SkipVerification(dev))
434 /* Report illegal runtime states */
435 if(bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
436 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has undefined state %d"TENDSTR),n,bi->blockState));
438 switch(bi->blockState){
439 case YAFFS_BLOCK_STATE_UNKNOWN:
440 case YAFFS_BLOCK_STATE_SCANNING:
441 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
442 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has bad run-state %s"TENDSTR),
443 n,blockStateName[bi->blockState]));
446 /* Check pages in use and soft deletions are legal */
448 actuallyUsed = bi->pagesInUse - bi->softDeletions;
450 if(bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
451 bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
452 actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock)
453 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
454 n,bi->pagesInUse,bi->softDeletions));
457 /* Check chunk bitmap legal */
458 inUse = yaffs_CountChunkBits(dev,n);
459 if(inUse != bi->pagesInUse)
460 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
461 n,bi->pagesInUse,inUse));
463 /* Check that the sequence number is valid.
464 * Ten million is legal, but is very unlikely
467 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
468 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000 ))
469 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has suspect sequence number of %d"TENDSTR),
470 n,bi->sequenceNumber));
474 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
476 yaffs_VerifyBlock(dev,bi,n);
478 /* After collection the block should be in the erased state */
479 /* This will need to change if we do partial gc */
481 if(bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
482 bi->blockState != YAFFS_BLOCK_STATE_EMPTY){
483 T(YAFFS_TRACE_ERROR,(TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
488 static void yaffs_VerifyBlocks(yaffs_Device *dev)
491 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
492 int nIllegalBlockStates = 0;
495 if(yaffs_SkipVerification(dev))
498 memset(nBlocksPerState,0,sizeof(nBlocksPerState));
501 for(i = dev->internalStartBlock; i <= dev->internalEndBlock; i++){
502 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
503 yaffs_VerifyBlock(dev,bi,i);
505 if(bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
506 nBlocksPerState[bi->blockState]++;
508 nIllegalBlockStates++;
512 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
513 T(YAFFS_TRACE_VERIFY,(TSTR("Block summary"TENDSTR)));
515 T(YAFFS_TRACE_VERIFY,(TSTR("%d blocks have illegal states"TENDSTR),nIllegalBlockStates));
516 if(nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
517 T(YAFFS_TRACE_VERIFY,(TSTR("Too many allocating blocks"TENDSTR)));
519 for(i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
520 T(YAFFS_TRACE_VERIFY,
521 (TSTR("%s %d blocks"TENDSTR),
522 blockStateName[i],nBlocksPerState[i]));
524 if(dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
525 T(YAFFS_TRACE_VERIFY,
526 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
527 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
529 if(dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
530 T(YAFFS_TRACE_VERIFY,
531 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
532 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
534 if(nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
535 T(YAFFS_TRACE_VERIFY,
536 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
537 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
539 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
544 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
545 * case those tests will not be performed.
547 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
549 if(obj && yaffs_SkipVerification(obj->myDev))
552 if(!(tags && obj && oh)){
553 T(YAFFS_TRACE_VERIFY,
554 (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR),
555 (__u32)tags,(__u32)obj,(__u32)oh));
559 if(oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
560 oh->type > YAFFS_OBJECT_TYPE_MAX)
561 T(YAFFS_TRACE_VERIFY,
562 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
563 tags->objectId, oh->type));
565 if(tags->objectId != obj->objectId)
566 T(YAFFS_TRACE_VERIFY,
567 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
568 tags->objectId, obj->objectId));
572 * Check that the object's parent ids match if parentCheck requested.
574 * Tests do not apply to the root object.
577 if(parentCheck && tags->objectId > 1 && !obj->parent)
578 T(YAFFS_TRACE_VERIFY,
579 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
580 tags->objectId, oh->parentObjectId));
583 if(parentCheck && obj->parent &&
584 oh->parentObjectId != obj->parent->objectId &&
585 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
586 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
587 T(YAFFS_TRACE_VERIFY,
588 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
589 tags->objectId, oh->parentObjectId, obj->parent->objectId));
592 if(tags->objectId > 1 && oh->name[0] == 0) /* Null name */
593 T(YAFFS_TRACE_VERIFY,
594 (TSTR("Obj %d header name is NULL"TENDSTR),
597 if(tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
598 T(YAFFS_TRACE_VERIFY,
599 (TSTR("Obj %d header name is 0xFF"TENDSTR),
605 static int yaffs_VerifyTnodeWorker(yaffs_Object * obj, yaffs_Tnode * tn,
606 __u32 level, int chunkOffset)
609 yaffs_Device *dev = obj->myDev;
615 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
616 if (tn->internal[i]) {
617 ok = yaffs_VerifyTnodeWorker(obj,
620 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
623 } else if (level == 0) {
624 yaffs_ExtendedTags tags;
625 __u32 objectId = obj->objectId;
627 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
629 for(i = 0; i < YAFFS_NTNODES_LEVEL0; i++){
630 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
633 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
634 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
635 if(tags.objectId != objectId || tags.chunkId != chunkOffset){
636 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
637 objectId, chunkOffset, theChunk,
638 tags.objectId, tags.chunkId));
651 static void yaffs_VerifyFile(yaffs_Object *obj)
653 int requiredTallness;
659 yaffs_ExtendedTags tags;
666 if(yaffs_SkipVerification(obj->myDev))
670 objectId = obj->objectId;
672 /* Check file size is consistent with tnode depth */
673 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
674 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
675 requiredTallness = 0;
677 x >>= YAFFS_TNODES_INTERNAL_BITS;
681 actualTallness = obj->variant.fileVariant.topLevel;
683 if(requiredTallness > actualTallness )
684 T(YAFFS_TRACE_VERIFY,
685 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
686 obj->objectId,actualTallness, requiredTallness));
689 /* Check that the chunks in the tnode tree are all correct.
690 * We do this by scanning through the tnode tree and
691 * checking the tags for every chunk match.
694 if(yaffs_SkipNANDVerification(dev))
697 for(i = 1; i <= lastChunk; i++){
698 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant,i);
701 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
703 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
704 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
705 if(tags.objectId != objectId || tags.chunkId != i){
706 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
707 objectId, i, theChunk,
708 tags.objectId, tags.chunkId));
718 static void yaffs_VerifyHardLink(yaffs_Object *obj)
720 if(obj && yaffs_SkipVerification(obj->myDev))
723 /* Verify sane equivalent object */
726 static void yaffs_VerifySymlink(yaffs_Object *obj)
728 if(obj && yaffs_SkipVerification(obj->myDev))
731 /* Verify symlink string */
734 static void yaffs_VerifySpecial(yaffs_Object *obj)
736 if(obj && yaffs_SkipVerification(obj->myDev))
740 static void yaffs_VerifyObject(yaffs_Object *obj)
749 __u32 chunkShouldNotBeDeleted;
755 if(obj->beingCreated)
760 if(yaffs_SkipVerification(dev))
763 /* Check sane object header chunk */
765 chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
766 chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
768 chunkInRange = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
769 chunkIdOk = chunkInRange || obj->hdrChunk == 0;
770 chunkValid = chunkInRange &&
771 yaffs_CheckChunkBit(dev,
772 obj->hdrChunk / dev->nChunksPerBlock,
773 obj->hdrChunk % dev->nChunksPerBlock);
774 chunkShouldNotBeDeleted = chunkInRange && !chunkValid;
777 (!chunkIdOk || chunkShouldNotBeDeleted)) {
778 T(YAFFS_TRACE_VERIFY,
779 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
780 obj->objectId,obj->hdrChunk,
781 chunkIdOk ? "" : ",out of range",
782 chunkShouldNotBeDeleted ? ",marked as deleted" : ""));
785 if(chunkValid &&!yaffs_SkipNANDVerification(dev)) {
786 yaffs_ExtendedTags tags;
787 yaffs_ObjectHeader *oh;
788 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
790 oh = (yaffs_ObjectHeader *)buffer;
792 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk,buffer, &tags);
794 yaffs_VerifyObjectHeader(obj,oh,&tags,1);
796 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
799 /* Verify it has a parent */
800 if(obj && !obj->fake &&
801 (!obj->parent || obj->parent->myDev != dev)){
802 T(YAFFS_TRACE_VERIFY,
803 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
804 obj->objectId,obj->parent));
807 /* Verify parent is a directory */
808 if(obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
809 T(YAFFS_TRACE_VERIFY,
810 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
811 obj->objectId,obj->parent->variantType));
814 switch(obj->variantType){
815 case YAFFS_OBJECT_TYPE_FILE:
816 yaffs_VerifyFile(obj);
818 case YAFFS_OBJECT_TYPE_SYMLINK:
819 yaffs_VerifySymlink(obj);
821 case YAFFS_OBJECT_TYPE_DIRECTORY:
822 yaffs_VerifyDirectory(obj);
824 case YAFFS_OBJECT_TYPE_HARDLINK:
825 yaffs_VerifyHardLink(obj);
827 case YAFFS_OBJECT_TYPE_SPECIAL:
828 yaffs_VerifySpecial(obj);
830 case YAFFS_OBJECT_TYPE_UNKNOWN:
832 T(YAFFS_TRACE_VERIFY,
833 (TSTR("Obj %d has illegaltype %d"TENDSTR),
834 obj->objectId,obj->variantType));
841 static void yaffs_VerifyObjects(yaffs_Device *dev)
845 struct ylist_head *lh;
847 if(yaffs_SkipVerification(dev))
850 /* Iterate through the objects in each hash entry */
852 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++){
853 ylist_for_each(lh, &dev->objectBucket[i].list) {
855 obj = ylist_entry(lh, yaffs_Object, hashLink);
856 yaffs_VerifyObject(obj);
865 * Simple hash function. Needs to have a reasonable spread
868 static Y_INLINE int yaffs_HashFunction(int n)
871 return (n % YAFFS_NOBJECT_BUCKETS);
875 * Access functions to useful fake objects.
876 * Note that root might have a presence in NAND if permissions are set.
879 yaffs_Object *yaffs_Root(yaffs_Device * dev)
884 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
886 return dev->lostNFoundDir;
891 * Erased NAND checking functions
894 int yaffs_CheckFF(__u8 * buffer, int nBytes)
896 /* Horrible, slow implementation */
905 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
909 int retval = YAFFS_OK;
910 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
911 yaffs_ExtendedTags tags;
914 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
916 if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
920 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
921 T(YAFFS_TRACE_NANDACCESS,
922 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
926 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
932 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
934 yaffs_ExtendedTags * tags,
941 yaffs_InvalidateCheckpoint(dev);
944 yaffs_BlockInfo *bi = 0;
947 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
953 /* First check this chunk is erased, if it needs
954 * checking. The checking policy (unless forced
955 * always on) is as follows:
957 * Check the first page we try to write in a block.
958 * If the check passes then we don't need to check any
959 * more. If the check fails, we check again...
960 * If the block has been erased, we don't need to check.
962 * However, if the block has been prioritised for gc,
963 * then we think there might be something odd about
964 * this block and stop using it.
966 * Rationale: We should only ever see chunks that have
967 * not been erased if there was a partially written
968 * chunk due to power loss. This checking policy should
969 * catch that case with very few checks and thus save a
970 * lot of checks that are most likely not needed.
972 if (bi->gcPrioritise) {
973 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
974 /* try another chunk */
978 /* let's give it a try */
981 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
982 bi->skipErasedCheck = 0;
984 if (!bi->skipErasedCheck) {
985 erasedOk = yaffs_CheckChunkErased(dev, chunk);
986 if (erasedOk != YAFFS_OK) {
988 (TSTR ("**>> yaffs chunk %d was not erased"
991 /* try another chunk */
994 bi->skipErasedCheck = 1;
997 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
999 if (writeOk != YAFFS_OK) {
1000 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
1001 /* try another chunk */
1005 /* Copy the data into the robustification buffer */
1006 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1008 } while (writeOk != YAFFS_OK &&
1009 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1015 T(YAFFS_TRACE_ERROR,
1016 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1019 dev->nRetriedWrites += (attempts - 1);
1026 * Block retiring for handling a broken block.
1029 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
1031 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1033 yaffs_InvalidateCheckpoint(dev);
1035 if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
1036 if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
1037 T(YAFFS_TRACE_ALWAYS, (TSTR(
1038 "yaffs: Failed to mark bad and erase block %d"
1039 TENDSTR), blockInNAND));
1042 yaffs_ExtendedTags tags;
1043 int chunkId = blockInNAND * dev->nChunksPerBlock;
1045 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
1047 memset(buffer, 0xff, dev->nDataBytesPerChunk);
1048 yaffs_InitialiseTags(&tags);
1049 tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
1050 if (dev->writeChunkWithTagsToNAND(dev, chunkId -
1051 dev->chunkOffset, buffer, &tags) != YAFFS_OK)
1052 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
1053 TCONT("write bad block marker to block %d")
1054 TENDSTR), blockInNAND));
1056 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
1060 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1061 bi->gcPrioritise = 0;
1062 bi->needsRetiring = 0;
1064 dev->nRetiredBlocks++;
1068 * Functions for robustisizing TODO
1072 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
1074 const yaffs_ExtendedTags * tags)
1078 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
1079 const yaffs_ExtendedTags * tags)
1083 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1085 if(!bi->gcPrioritise){
1086 bi->gcPrioritise = 1;
1087 dev->hasPendingPrioritisedGCs = 1;
1088 bi->chunkErrorStrikes ++;
1090 if(bi->chunkErrorStrikes > 3){
1091 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1092 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1099 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
1102 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1103 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1105 yaffs_HandleChunkError(dev,bi);
1109 /* Was an actual write failure, so mark the block for retirement */
1110 bi->needsRetiring = 1;
1111 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1112 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1117 /* Delete the chunk */
1118 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1122 /*---------------- Name handling functions ------------*/
1124 static __u16 yaffs_CalcNameSum(const YCHAR * name)
1129 const YUCHAR *bname = (const YUCHAR *) name;
1131 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1133 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1134 sum += yaffs_toupper(*bname) * i;
1136 sum += (*bname) * i;
1145 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
1147 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1148 memset(obj->shortName,0,sizeof (YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1149 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
1150 yaffs_strcpy(obj->shortName, name);
1152 obj->shortName[0] = _Y('\0');
1155 obj->sum = yaffs_CalcNameSum(name);
1158 /*-------------------- TNODES -------------------
1160 * List of spare tnodes
1161 * The list is hooked together using the first pointer
1165 /* yaffs_CreateTnodes creates a bunch more tnodes and
1166 * adds them to the tnode free list.
1167 * Don't use this function directly
1170 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
1174 yaffs_Tnode *newTnodes;
1178 yaffs_TnodeList *tnl;
1183 /* Calculate the tnode size in bytes for variable width tnode support.
1184 * Must be a multiple of 32-bits */
1185 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1187 if(tnodeSize < sizeof(yaffs_Tnode))
1188 tnodeSize = sizeof(yaffs_Tnode);
1191 /* make these things */
1193 newTnodes = YMALLOC(nTnodes * tnodeSize);
1194 mem = (__u8 *)newTnodes;
1197 T(YAFFS_TRACE_ERROR,
1198 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1202 /* Hook them into the free list */
1204 for (i = 0; i < nTnodes - 1; i++) {
1205 newTnodes[i].internal[0] = &newTnodes[i + 1];
1206 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1207 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1211 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1212 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1213 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1215 dev->freeTnodes = newTnodes;
1217 /* New hookup for wide tnodes */
1218 for(i = 0; i < nTnodes -1; i++) {
1219 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1220 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1221 curr->internal[0] = next;
1224 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1225 curr->internal[0] = dev->freeTnodes;
1226 dev->freeTnodes = (yaffs_Tnode *)mem;
1231 dev->nFreeTnodes += nTnodes;
1232 dev->nTnodesCreated += nTnodes;
1234 /* Now add this bunch of tnodes to a list for freeing up.
1235 * NB If we can't add this to the management list it isn't fatal
1236 * but it just means we can't free this bunch of tnodes later.
1239 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1241 T(YAFFS_TRACE_ERROR,
1243 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1247 tnl->tnodes = newTnodes;
1248 tnl->next = dev->allocatedTnodeList;
1249 dev->allocatedTnodeList = tnl;
1252 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1257 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1259 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
1261 yaffs_Tnode *tn = NULL;
1263 /* If there are none left make more */
1264 if (!dev->freeTnodes) {
1265 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1268 if (dev->freeTnodes) {
1269 tn = dev->freeTnodes;
1270 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1271 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1272 /* Hoosterman, this thing looks like it isn't in the list */
1273 T(YAFFS_TRACE_ALWAYS,
1274 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1277 dev->freeTnodes = dev->freeTnodes->internal[0];
1281 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1286 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
1288 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1289 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1291 if(tnodeSize < sizeof(yaffs_Tnode))
1292 tnodeSize = sizeof(yaffs_Tnode);
1295 memset(tn, 0, tnodeSize);
1300 /* FreeTnode frees up a tnode and puts it back on the free list */
1301 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
1304 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1305 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1306 /* Hoosterman, this thing looks like it is already in the list */
1307 T(YAFFS_TRACE_ALWAYS,
1308 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1310 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1312 tn->internal[0] = dev->freeTnodes;
1313 dev->freeTnodes = tn;
1316 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1320 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
1322 /* Free the list of allocated tnodes */
1323 yaffs_TnodeList *tmp;
1325 while (dev->allocatedTnodeList) {
1326 tmp = dev->allocatedTnodeList->next;
1328 YFREE(dev->allocatedTnodeList->tnodes);
1329 YFREE(dev->allocatedTnodeList);
1330 dev->allocatedTnodeList = tmp;
1334 dev->freeTnodes = NULL;
1335 dev->nFreeTnodes = 0;
1338 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
1340 dev->allocatedTnodeList = NULL;
1341 dev->freeTnodes = NULL;
1342 dev->nFreeTnodes = 0;
1343 dev->nTnodesCreated = 0;
1348 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
1350 __u32 *map = (__u32 *)tn;
1356 pos &= YAFFS_TNODES_LEVEL0_MASK;
1357 val >>= dev->chunkGroupBits;
1359 bitInMap = pos * dev->tnodeWidth;
1360 wordInMap = bitInMap /32;
1361 bitInWord = bitInMap & (32 -1);
1363 mask = dev->tnodeMask << bitInWord;
1365 map[wordInMap] &= ~mask;
1366 map[wordInMap] |= (mask & (val << bitInWord));
1368 if(dev->tnodeWidth > (32-bitInWord)) {
1369 bitInWord = (32 - bitInWord);
1371 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1372 map[wordInMap] &= ~mask;
1373 map[wordInMap] |= (mask & (val >> bitInWord));
1377 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
1379 __u32 *map = (__u32 *)tn;
1385 pos &= YAFFS_TNODES_LEVEL0_MASK;
1387 bitInMap = pos * dev->tnodeWidth;
1388 wordInMap = bitInMap /32;
1389 bitInWord = bitInMap & (32 -1);
1391 val = map[wordInMap] >> bitInWord;
1393 if(dev->tnodeWidth > (32-bitInWord)) {
1394 bitInWord = (32 - bitInWord);
1396 val |= (map[wordInMap] << bitInWord);
1399 val &= dev->tnodeMask;
1400 val <<= dev->chunkGroupBits;
1405 /* ------------------- End of individual tnode manipulation -----------------*/
1407 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1408 * The look up tree is represented by the top tnode and the number of topLevel
1409 * in the tree. 0 means only the level 0 tnode is in the tree.
1412 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1413 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
1414 yaffs_FileStructure * fStruct,
1418 yaffs_Tnode *tn = fStruct->top;
1420 int requiredTallness;
1421 int level = fStruct->topLevel;
1423 /* Check sane level and chunk Id */
1424 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
1428 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1432 /* First check we're tall enough (ie enough topLevel) */
1434 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1435 requiredTallness = 0;
1437 i >>= YAFFS_TNODES_INTERNAL_BITS;
1441 if (requiredTallness > fStruct->topLevel) {
1442 /* Not tall enough, so we can't find it, return NULL. */
1446 /* Traverse down to level 0 */
1447 while (level > 0 && tn) {
1449 internal[(chunkId >>
1450 ( YAFFS_TNODES_LEVEL0_BITS +
1452 YAFFS_TNODES_INTERNAL_BITS)
1454 YAFFS_TNODES_INTERNAL_MASK];
1462 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1463 * This happens in two steps:
1464 * 1. If the tree isn't tall enough, then make it taller.
1465 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1467 * Used when modifying the tree.
1469 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1470 * be plugged into the ttree.
1473 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
1474 yaffs_FileStructure * fStruct,
1476 yaffs_Tnode *passedTn)
1479 int requiredTallness;
1487 /* Check sane level and page Id */
1488 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
1492 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1496 /* First check we're tall enough (ie enough topLevel) */
1498 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1499 requiredTallness = 0;
1501 x >>= YAFFS_TNODES_INTERNAL_BITS;
1506 if (requiredTallness > fStruct->topLevel) {
1507 /* Not tall enough,gotta make the tree taller */
1508 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1510 tn = yaffs_GetTnode(dev);
1513 tn->internal[0] = fStruct->top;
1516 T(YAFFS_TRACE_ERROR,
1517 (TSTR("yaffs: no more tnodes" TENDSTR)));
1521 fStruct->topLevel = requiredTallness;
1524 /* Traverse down to level 0, adding anything we need */
1526 l = fStruct->topLevel;
1530 while (l > 0 && tn) {
1532 ( YAFFS_TNODES_LEVEL0_BITS +
1533 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1534 YAFFS_TNODES_INTERNAL_MASK;
1537 if((l>1) && !tn->internal[x]){
1538 /* Add missing non-level-zero tnode */
1539 tn->internal[x] = yaffs_GetTnode(dev);
1542 /* Looking from level 1 at level 0 */
1544 /* If we already have one, then release it.*/
1546 yaffs_FreeTnode(dev,tn->internal[x]);
1547 tn->internal[x] = passedTn;
1549 } else if(!tn->internal[x]) {
1550 /* Don't have one, none passed in */
1551 tn->internal[x] = yaffs_GetTnode(dev);
1555 tn = tn->internal[x];
1559 /* top is level 0 */
1561 memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1562 yaffs_FreeTnode(dev,passedTn);
1569 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1570 yaffs_ExtendedTags * tags, int objectId,
1575 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1576 if (yaffs_CheckChunkBit
1577 (dev, theChunk / dev->nChunksPerBlock,
1578 theChunk % dev->nChunksPerBlock)) {
1579 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1581 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1593 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1594 * chunks and tnodes in the file
1595 * Returns 1 if the tree was deleted.
1596 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1599 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1600 int chunkOffset, int *limit)
1605 yaffs_ExtendedTags tags;
1607 yaffs_Device *dev = in->myDev;
1614 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1616 if (tn->internal[i]) {
1617 if (limit && (*limit) < 0) {
1621 yaffs_DeleteWorker(in,
1629 YAFFS_TNODES_INTERNAL_BITS)
1634 yaffs_FreeTnode(dev,
1637 tn->internal[i] = NULL;
1642 return (allDone) ? 1 : 0;
1643 } else if (level == 0) {
1646 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1648 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1653 YAFFS_TNODES_LEVEL0_BITS) + i;
1656 yaffs_FindChunkInGroup(dev,
1662 if (foundChunk > 0) {
1663 yaffs_DeleteChunk(dev,
1668 *limit = *limit - 1;
1676 yaffs_PutLevel0Tnode(dev,tn,i,0);
1680 return (i < 0) ? 1 : 0;
1690 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1693 yaffs_BlockInfo *theBlock;
1695 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1697 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1699 theBlock->softDeletions++;
1704 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1705 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1707 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1710 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1711 __u32 level, int chunkOffset)
1716 yaffs_Device *dev = in->myDev;
1721 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1723 if (tn->internal[i]) {
1725 yaffs_SoftDeleteWorker(in,
1731 YAFFS_TNODES_INTERNAL_BITS)
1734 yaffs_FreeTnode(dev,
1737 tn->internal[i] = NULL;
1739 /* Hoosterman... how could this happen? */
1743 return (allDone) ? 1 : 0;
1744 } else if (level == 0) {
1746 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1747 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1749 /* Note this does not find the real chunk, only the chunk group.
1750 * We make an assumption that a chunk group is not larger than
1753 yaffs_SoftDeleteChunk(dev, theChunk);
1754 yaffs_PutLevel0Tnode(dev,tn,i,0);
1768 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1771 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1772 if (obj->nDataChunks <= 0) {
1773 /* Empty file with no duplicate object headers, just delete it immediately */
1774 yaffs_FreeTnode(obj->myDev,
1775 obj->variant.fileVariant.top);
1776 obj->variant.fileVariant.top = NULL;
1777 T(YAFFS_TRACE_TRACING,
1778 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1780 yaffs_DoGenericObjectDeletion(obj);
1782 yaffs_SoftDeleteWorker(obj,
1783 obj->variant.fileVariant.top,
1784 obj->variant.fileVariant.
1786 obj->softDeleted = 1;
1791 /* Pruning removes any part of the file structure tree that is beyond the
1792 * bounds of the file (ie that does not point to chunks).
1794 * A file should only get pruned when its size is reduced.
1796 * Before pruning, the chunks must be pulled from the tree and the
1797 * level 0 tnode entries must be zeroed out.
1798 * Could also use this for file deletion, but that's probably better handled
1799 * by a special case.
1802 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1803 __u32 level, int del0)
1811 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1812 if (tn->internal[i] && level > 0) {
1814 yaffs_PruneWorker(dev, tn->internal[i],
1816 (i == 0) ? del0 : 1);
1819 if (tn->internal[i]) {
1824 if (hasData == 0 && del0) {
1825 /* Free and return NULL */
1827 yaffs_FreeTnode(dev, tn);
1837 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1838 yaffs_FileStructure * fStruct)
1845 if (fStruct->topLevel > 0) {
1847 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1849 /* Now we have a tree with all the non-zero branches NULL but the height
1850 * is the same as it was.
1851 * Let's see if we can trim internal tnodes to shorten the tree.
1852 * We can do this if only the 0th element in the tnode is in use
1853 * (ie all the non-zero are NULL)
1856 while (fStruct->topLevel && !done) {
1860 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1861 if (tn->internal[i]) {
1867 fStruct->top = tn->internal[0];
1868 fStruct->topLevel--;
1869 yaffs_FreeTnode(dev, tn);
1879 /*-------------------- End of File Structure functions.-------------------*/
1881 /* yaffs_CreateFreeObjects creates a bunch more objects and
1882 * adds them to the object free list.
1884 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1887 yaffs_Object *newObjects;
1888 yaffs_ObjectList *list;
1893 /* make these things */
1894 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1895 list = YMALLOC(sizeof(yaffs_ObjectList));
1897 if (!newObjects || !list) {
1902 T(YAFFS_TRACE_ALLOCATE,
1903 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1907 /* Hook them into the free list */
1908 for (i = 0; i < nObjects - 1; i++) {
1909 newObjects[i].siblings.next =
1910 (struct ylist_head *)(&newObjects[i + 1]);
1913 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1914 dev->freeObjects = newObjects;
1915 dev->nFreeObjects += nObjects;
1916 dev->nObjectsCreated += nObjects;
1918 /* Now add this bunch of Objects to a list for freeing up. */
1920 list->objects = newObjects;
1921 list->next = dev->allocatedObjectList;
1922 dev->allocatedObjectList = list;
1928 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1929 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1931 yaffs_Object *tn = NULL;
1933 #ifdef VALGRIND_TEST
1934 tn = YMALLOC(sizeof(yaffs_Object));
1936 /* If there are none left make more */
1937 if (!dev->freeObjects) {
1938 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1941 if (dev->freeObjects) {
1942 tn = dev->freeObjects;
1944 (yaffs_Object *) (dev->freeObjects->siblings.next);
1945 dev->nFreeObjects--;
1949 /* Now sweeten it up... */
1951 memset(tn, 0, sizeof(yaffs_Object));
1952 tn->beingCreated = 1;
1956 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1957 YINIT_LIST_HEAD(&(tn->hardLinks));
1958 YINIT_LIST_HEAD(&(tn->hashLink));
1959 YINIT_LIST_HEAD(&tn->siblings);
1962 /* Now make the directory sane */
1964 tn->parent = dev->rootDir;
1965 ylist_add(&(tn->siblings),&dev->rootDir->variant.directoryVariant.children);
1968 /* Add it to the lost and found directory.
1969 * NB Can't put root or lostNFound in lostNFound so
1970 * check if lostNFound exists first
1972 if (dev->lostNFoundDir) {
1973 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1976 tn->beingCreated = 0;
1979 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1984 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1989 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1991 obj->fake = 1; /* it is fake so it might have no NAND presence... */
1992 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1993 obj->unlinkAllowed = 0; /* ... or unlink it */
1996 obj->yst_mode = mode;
1998 obj->hdrChunk = 0; /* Not a valid chunk. */
2005 static void yaffs_UnhashObject(yaffs_Object * tn)
2008 yaffs_Device *dev = tn->myDev;
2010 /* If it is still linked into the bucket list, free from the list */
2011 if (!ylist_empty(&tn->hashLink)) {
2012 ylist_del_init(&tn->hashLink);
2013 bucket = yaffs_HashFunction(tn->objectId);
2014 dev->objectBucket[bucket].count--;
2019 /* FreeObject frees up a Object and puts it back on the free list */
2020 static void yaffs_FreeObject(yaffs_Object * tn)
2023 yaffs_Device *dev = tn->myDev;
2026 T(YAFFS_TRACE_OS,(TSTR("FreeObject %p inode %p"TENDSTR),tn,tn->myInode));
2031 if(!ylist_empty(&tn->siblings))
2037 /* We're still hooked up to a cached inode.
2038 * Don't delete now, but mark for later deletion
2040 tn->deferedFree = 1;
2045 yaffs_UnhashObject(tn);
2047 #ifdef VALGRIND_TEST
2050 /* Link into the free list. */
2051 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2052 dev->freeObjects = tn;
2053 dev->nFreeObjects++;
2055 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2061 void yaffs_HandleDeferedFree(yaffs_Object * obj)
2063 if (obj->deferedFree) {
2064 yaffs_FreeObject(obj);
2070 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
2072 /* Free the list of allocated Objects */
2074 yaffs_ObjectList *tmp;
2076 while (dev->allocatedObjectList) {
2077 tmp = dev->allocatedObjectList->next;
2078 YFREE(dev->allocatedObjectList->objects);
2079 YFREE(dev->allocatedObjectList);
2081 dev->allocatedObjectList = tmp;
2084 dev->freeObjects = NULL;
2085 dev->nFreeObjects = 0;
2088 static void yaffs_InitialiseObjects(yaffs_Device * dev)
2092 dev->allocatedObjectList = NULL;
2093 dev->freeObjects = NULL;
2094 dev->nFreeObjects = 0;
2096 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2097 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2098 dev->objectBucket[i].count = 0;
2103 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
2108 int lowest = 999999;
2110 /* First let's see if we can find one that's empty. */
2112 for (i = 0; i < 10 && lowest > 0; i++) {
2114 x %= YAFFS_NOBJECT_BUCKETS;
2115 if (dev->objectBucket[x].count < lowest) {
2116 lowest = dev->objectBucket[x].count;
2122 /* If we didn't find an empty list, then try
2123 * looking a bit further for a short one
2126 for (i = 0; i < 10 && lowest > 3; i++) {
2128 x %= YAFFS_NOBJECT_BUCKETS;
2129 if (dev->objectBucket[x].count < lowest) {
2130 lowest = dev->objectBucket[x].count;
2139 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
2141 int bucket = yaffs_FindNiceObjectBucket(dev);
2143 /* Now find an object value that has not already been taken
2144 * by scanning the list.
2148 struct ylist_head *i;
2150 __u32 n = (__u32) bucket;
2152 /* yaffs_CheckObjectHashSanity(); */
2156 n += YAFFS_NOBJECT_BUCKETS;
2157 if (1 || dev->objectBucket[bucket].count > 0) {
2158 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2159 /* If there is already one in the list */
2161 && ylist_entry(i, yaffs_Object,
2162 hashLink)->objectId == n) {
2173 static void yaffs_HashObject(yaffs_Object * in)
2175 int bucket = yaffs_HashFunction(in->objectId);
2176 yaffs_Device *dev = in->myDev;
2178 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2179 dev->objectBucket[bucket].count++;
2183 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
2185 int bucket = yaffs_HashFunction(number);
2186 struct ylist_head *i;
2189 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2190 /* Look if it is in the list */
2192 in = ylist_entry(i, yaffs_Object, hashLink);
2193 if (in->objectId == number) {
2195 /* Don't tell the VFS about this one if it is defered free */
2196 if (in->deferedFree)
2208 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
2209 yaffs_ObjectType type)
2212 yaffs_Object *theObject;
2213 yaffs_Tnode *tn = NULL;
2216 number = yaffs_CreateNewObjectNumber(dev);
2219 theObject = yaffs_AllocateEmptyObject(dev);
2223 if(type == YAFFS_OBJECT_TYPE_FILE){
2224 tn = yaffs_GetTnode(dev);
2226 yaffs_FreeObject(theObject);
2234 theObject->fake = 0;
2235 theObject->renameAllowed = 1;
2236 theObject->unlinkAllowed = 1;
2237 theObject->objectId = number;
2238 yaffs_HashObject(theObject);
2239 theObject->variantType = type;
2240 #ifdef CONFIG_YAFFS_WINCE
2241 yfsd_WinFileTimeNow(theObject->win_atime);
2242 theObject->win_ctime[0] = theObject->win_mtime[0] =
2243 theObject->win_atime[0];
2244 theObject->win_ctime[1] = theObject->win_mtime[1] =
2245 theObject->win_atime[1];
2249 theObject->yst_atime = theObject->yst_mtime =
2250 theObject->yst_ctime = Y_CURRENT_TIME;
2253 case YAFFS_OBJECT_TYPE_FILE:
2254 theObject->variant.fileVariant.fileSize = 0;
2255 theObject->variant.fileVariant.scannedFileSize = 0;
2256 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2257 theObject->variant.fileVariant.topLevel = 0;
2258 theObject->variant.fileVariant.top = tn;
2260 case YAFFS_OBJECT_TYPE_DIRECTORY:
2261 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2264 case YAFFS_OBJECT_TYPE_SYMLINK:
2265 case YAFFS_OBJECT_TYPE_HARDLINK:
2266 case YAFFS_OBJECT_TYPE_SPECIAL:
2267 /* No action required */
2269 case YAFFS_OBJECT_TYPE_UNKNOWN:
2270 /* todo this should not happen */
2278 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
2280 yaffs_ObjectType type)
2282 yaffs_Object *theObject = NULL;
2285 theObject = yaffs_FindObjectByNumber(dev, number);
2289 theObject = yaffs_CreateNewObject(dev, number, type);
2297 static YCHAR *yaffs_CloneString(const YCHAR * str)
2299 YCHAR *newStr = NULL;
2302 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2304 yaffs_strcpy(newStr, str);
2312 * Mknod (create) a new object.
2313 * equivalentObject only has meaning for a hard link;
2314 * aliasString only has meaning for a sumlink.
2315 * rdev only has meaning for devices (a subset of special objects)
2318 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2319 yaffs_Object * parent,
2324 yaffs_Object * equivalentObject,
2325 const YCHAR * aliasString, __u32 rdev)
2330 yaffs_Device *dev = parent->myDev;
2332 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2333 if (yaffs_FindObjectByName(parent, name)) {
2337 in = yaffs_CreateNewObject(dev, -1, type);
2342 if(type == YAFFS_OBJECT_TYPE_SYMLINK){
2343 str = yaffs_CloneString(aliasString);
2345 yaffs_FreeObject(in);
2355 in->variantType = type;
2357 in->yst_mode = mode;
2359 #ifdef CONFIG_YAFFS_WINCE
2360 yfsd_WinFileTimeNow(in->win_atime);
2361 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2362 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2365 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2367 in->yst_rdev = rdev;
2371 in->nDataChunks = 0;
2373 yaffs_SetObjectName(in, name);
2376 yaffs_AddObjectToDirectory(parent, in);
2378 in->myDev = parent->myDev;
2381 case YAFFS_OBJECT_TYPE_SYMLINK:
2382 in->variant.symLinkVariant.alias = str;
2384 case YAFFS_OBJECT_TYPE_HARDLINK:
2385 in->variant.hardLinkVariant.equivalentObject =
2387 in->variant.hardLinkVariant.equivalentObjectId =
2388 equivalentObject->objectId;
2389 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2391 case YAFFS_OBJECT_TYPE_FILE:
2392 case YAFFS_OBJECT_TYPE_DIRECTORY:
2393 case YAFFS_OBJECT_TYPE_SPECIAL:
2394 case YAFFS_OBJECT_TYPE_UNKNOWN:
2399 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2400 /* Could not create the object header, fail the creation */
2401 yaffs_DeleteObject(in);
2410 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
2411 __u32 mode, __u32 uid, __u32 gid)
2413 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2414 uid, gid, NULL, NULL, 0);
2417 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
2418 __u32 mode, __u32 uid, __u32 gid)
2420 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2421 mode, uid, gid, NULL, NULL, 0);
2424 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
2425 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2427 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2428 uid, gid, NULL, NULL, rdev);
2431 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
2432 __u32 mode, __u32 uid, __u32 gid,
2433 const YCHAR * alias)
2435 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2436 uid, gid, NULL, alias, 0);
2439 /* yaffs_Link returns the object id of the equivalent object.*/
2440 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
2441 yaffs_Object * equivalentObject)
2443 /* Get the real object in case we were fed a hard link as an equivalent object */
2444 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2446 if (yaffs_MknodObject
2447 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2448 equivalentObject, NULL, 0)) {
2449 return equivalentObject;
2456 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
2457 const YCHAR * newName, int force, int shadows)
2462 yaffs_Object *existingTarget;
2464 if (newDir == NULL) {
2465 newDir = obj->parent; /* use the old directory */
2468 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2469 T(YAFFS_TRACE_ALWAYS,
2471 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2476 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2477 if (obj->myDev->isYaffs2) {
2478 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2480 unlinkOp = (newDir == obj->myDev->unlinkedDir
2481 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2484 deleteOp = (newDir == obj->myDev->deletedDir);
2486 existingTarget = yaffs_FindObjectByName(newDir, newName);
2488 /* If the object is a file going into the unlinked directory,
2489 * then it is OK to just stuff it in since duplicate names are allowed.
2490 * else only proceed if the new name does not exist and if we're putting
2491 * it into a directory.
2498 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2499 yaffs_SetObjectName(obj, newName);
2502 yaffs_AddObjectToDirectory(newDir, obj);
2507 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2508 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
2515 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
2516 yaffs_Object * newDir, const YCHAR * newName)
2518 yaffs_Object *obj=NULL;
2519 yaffs_Object *existingTarget=NULL;
2523 if(!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2525 if(!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2528 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2529 /* Special case for case insemsitive systems (eg. WinCE).
2530 * While look-up is case insensitive, the name isn't.
2531 * Therefore we might want to change x.txt to X.txt
2533 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
2538 else if (yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2542 obj = yaffs_FindObjectByName(oldDir, oldName);
2544 if (obj && obj->renameAllowed) {
2546 /* Now do the handling for an existing target, if there is one */
2548 existingTarget = yaffs_FindObjectByName(newDir, newName);
2549 if (existingTarget &&
2550 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2551 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2552 /* There is a target that is a non-empty directory, so we fail */
2553 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2554 } else if (existingTarget && existingTarget != obj) {
2555 /* Nuke the target first, using shadowing,
2556 * but only if it isn't the same object
2558 yaffs_ChangeObjectName(obj, newDir, newName, force,
2559 existingTarget->objectId);
2560 yaffs_UnlinkObject(existingTarget);
2563 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2568 /*------------------------- Block Management and Page Allocation ----------------*/
2570 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
2572 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2574 dev->blockInfo = NULL;
2575 dev->chunkBits = NULL;
2577 dev->allocationBlock = -1; /* force it to get a new one */
2579 /* If the first allocation strategy fails, thry the alternate one */
2580 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2581 if(!dev->blockInfo){
2582 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2583 dev->blockInfoAlt = 1;
2586 dev->blockInfoAlt = 0;
2590 /* Set up dynamic blockinfo stuff. */
2591 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2592 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2593 if(!dev->chunkBits){
2594 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2595 dev->chunkBitsAlt = 1;
2598 dev->chunkBitsAlt = 0;
2601 if (dev->blockInfo && dev->chunkBits) {
2602 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2603 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2611 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
2613 if(dev->blockInfoAlt && dev->blockInfo)
2614 YFREE_ALT(dev->blockInfo);
2615 else if(dev->blockInfo)
2616 YFREE(dev->blockInfo);
2618 dev->blockInfoAlt = 0;
2620 dev->blockInfo = NULL;
2622 if(dev->chunkBitsAlt && dev->chunkBits)
2623 YFREE_ALT(dev->chunkBits);
2624 else if(dev->chunkBits)
2625 YFREE(dev->chunkBits);
2626 dev->chunkBitsAlt = 0;
2627 dev->chunkBits = NULL;
2630 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
2631 yaffs_BlockInfo * bi)
2638 return 1; /* disqualification only applies to yaffs2. */
2640 if (!bi->hasShrinkHeader)
2641 return 1; /* can gc */
2643 /* Find the oldest dirty sequence number if we don't know it and save it
2644 * so we don't have to keep recomputing it.
2646 if (!dev->oldestDirtySequence) {
2647 seq = dev->sequenceNumber;
2649 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2651 b = yaffs_GetBlockInfo(dev, i);
2652 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2653 (b->pagesInUse - b->softDeletions) <
2654 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2655 seq = b->sequenceNumber;
2658 dev->oldestDirtySequence = seq;
2661 /* Can't do gc of this block if there are any blocks older than this one that have
2664 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2668 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2669 * for garbage collection.
2672 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2676 int b = dev->currentDirtyChecker;
2683 yaffs_BlockInfo *bi;
2684 int pendingPrioritisedExist = 0;
2686 /* First let's see if we need to grab a prioritised block */
2687 if(dev->hasPendingPrioritisedGCs){
2688 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2690 bi = yaffs_GetBlockInfo(dev, i);
2691 //yaffs_VerifyBlock(dev,bi,i);
2693 if(bi->gcPrioritise) {
2694 pendingPrioritisedExist = 1;
2695 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2696 yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2697 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2700 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2705 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2706 dev->hasPendingPrioritisedGCs = 0;
2709 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2711 * else (we're doing a leasurely gc), then we only bother to do this if the
2712 * block has only a few pages in use.
2715 dev->nonAggressiveSkip--;
2717 if (!aggressive && (dev->nonAggressiveSkip > 0)) {
2723 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2727 dev->internalEndBlock - dev->internalStartBlock + 1;
2730 dev->internalEndBlock - dev->internalStartBlock + 1;
2731 iterations = iterations / 16;
2732 if (iterations > 200) {
2737 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2739 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2740 b = dev->internalStartBlock;
2743 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2744 T(YAFFS_TRACE_ERROR,
2745 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2749 bi = yaffs_GetBlockInfo(dev, b);
2752 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2759 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2760 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2761 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2763 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2767 dev->currentDirtyChecker = b;
2771 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2772 dev->nChunksPerBlock - pagesInUse,prioritised));
2775 dev->oldestDirtySequence = 0;
2778 dev->nonAggressiveSkip = 4;
2784 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2786 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2790 /* If the block is still healthy erase it and mark as clean.
2791 * If the block has had a data failure, then retire it.
2794 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2795 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2796 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2798 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2800 if (!bi->needsRetiring) {
2801 yaffs_InvalidateCheckpoint(dev);
2802 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2804 dev->nErasureFailures++;
2805 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2806 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2811 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2813 for (i = 0; i < dev->nChunksPerBlock; i++) {
2814 if (!yaffs_CheckChunkErased
2815 (dev, blockNo * dev->nChunksPerBlock + i)) {
2816 T(YAFFS_TRACE_ERROR,
2818 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2819 TENDSTR), blockNo, i));
2825 /* Clean it up... */
2826 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2827 dev->nErasedBlocks++;
2829 bi->softDeletions = 0;
2830 bi->hasShrinkHeader = 0;
2831 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2832 bi->gcPrioritise = 0;
2833 yaffs_ClearChunkBits(dev, blockNo);
2835 T(YAFFS_TRACE_ERASE,
2836 (TSTR("Erased block %d" TENDSTR), blockNo));
2838 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2840 yaffs_RetireBlock(dev, blockNo);
2841 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2842 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2846 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2850 yaffs_BlockInfo *bi;
2852 if (dev->nErasedBlocks < 1) {
2853 /* Hoosterman we've got a problem.
2854 * Can't get space to gc
2856 T(YAFFS_TRACE_ERROR,
2857 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2862 /* Find an empty block. */
2864 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2865 dev->allocationBlockFinder++;
2866 if (dev->allocationBlockFinder < dev->internalStartBlock
2867 || dev->allocationBlockFinder > dev->internalEndBlock) {
2868 dev->allocationBlockFinder = dev->internalStartBlock;
2871 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2873 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2874 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2875 dev->sequenceNumber++;
2876 bi->sequenceNumber = dev->sequenceNumber;
2877 dev->nErasedBlocks--;
2878 T(YAFFS_TRACE_ALLOCATE,
2879 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2880 dev->allocationBlockFinder, dev->sequenceNumber,
2881 dev->nErasedBlocks));
2882 return dev->allocationBlockFinder;
2886 T(YAFFS_TRACE_ALWAYS,
2888 ("yaffs tragedy: no more erased blocks, but there should have been %d"
2889 TENDSTR), dev->nErasedBlocks));
2896 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2898 if(!dev->nCheckpointBlocksRequired &&
2900 /* Not a valid value so recalculate */
2903 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2906 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2908 if(tnodeSize < sizeof(yaffs_Tnode))
2909 tnodeSize = sizeof(yaffs_Tnode);
2911 nBytes += sizeof(yaffs_CheckpointValidity);
2912 nBytes += sizeof(yaffs_CheckpointDevice);
2913 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2914 nBytes += devBlocks * dev->chunkBitmapStride;
2915 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2916 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2917 nBytes += sizeof(yaffs_CheckpointValidity);
2918 nBytes += sizeof(__u32); /* checksum*/
2920 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2922 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2924 dev->nCheckpointBlocksRequired = nBlocks;
2927 return dev->nCheckpointBlocksRequired;
2930 // Check if there's space to allocate...
2931 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2932 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2935 int reservedBlocks = dev->nReservedBlocks;
2936 int checkpointBlocks;
2939 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
2940 dev->blocksInCheckpoint;
2941 if(checkpointBlocks < 0)
2942 checkpointBlocks = 0;
2944 checkpointBlocks =0;
2947 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2949 return (dev->nFreeChunks > reservedChunks);
2952 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2955 yaffs_BlockInfo *bi;
2957 if (dev->allocationBlock < 0) {
2958 /* Get next block to allocate off */
2959 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2960 dev->allocationPage = 0;
2963 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2964 /* Not enough space to allocate unless we're allowed to use the reserve. */
2968 if (dev->nErasedBlocks < dev->nReservedBlocks
2969 && dev->allocationPage == 0) {
2970 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2973 /* Next page please.... */
2974 if (dev->allocationBlock >= 0) {
2975 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2977 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2978 dev->allocationPage;
2980 yaffs_SetChunkBit(dev, dev->allocationBlock,
2981 dev->allocationPage);
2983 dev->allocationPage++;
2987 /* If the block is full set the state to full */
2988 if (dev->allocationPage >= dev->nChunksPerBlock) {
2989 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2990 dev->allocationBlock = -1;
2999 T(YAFFS_TRACE_ERROR,
3000 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
3005 static int yaffs_GetErasedChunks(yaffs_Device * dev)
3009 n = dev->nErasedBlocks * dev->nChunksPerBlock;
3011 if (dev->allocationBlock > 0) {
3012 n += (dev->nChunksPerBlock - dev->allocationPage);
3019 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block, int wholeBlock)
3024 int retVal = YAFFS_OK;
3027 int isCheckpointBlock;
3031 int chunksBefore = yaffs_GetErasedChunks(dev);
3034 yaffs_ExtendedTags tags;
3036 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3038 yaffs_Object *object;
3040 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3042 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3044 T(YAFFS_TRACE_TRACING,
3045 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3048 bi->hasShrinkHeader,
3051 /*yaffs_VerifyFreeChunks(dev); */
3053 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
3055 /* Take off the number of soft deleted entries because
3056 * they're going to get really deleted during GC.
3058 dev->nFreeChunks -= bi->softDeletions;
3062 if (isCheckpointBlock ||
3063 !yaffs_StillSomeChunkBits(dev, block)) {
3064 T(YAFFS_TRACE_TRACING,
3066 ("Collecting block %d that has no chunks in use" TENDSTR),
3068 yaffs_BlockBecameDirty(dev, block);
3071 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3073 yaffs_VerifyBlock(dev,bi,block);
3075 maxCopies = (wholeBlock) ? dev->nChunksPerBlock : 10;
3076 oldChunk = block * dev->nChunksPerBlock + dev->gcChunk;
3078 for ( /* init already done */;
3079 retVal == YAFFS_OK &&
3080 dev->gcChunk < dev->nChunksPerBlock &&
3081 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING)&&
3083 dev->gcChunk++, oldChunk++) {
3084 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3086 /* This page is in use and might need to be copied off */
3092 yaffs_InitialiseTags(&tags);
3094 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3098 yaffs_FindObjectByNumber(dev,
3101 T(YAFFS_TRACE_GC_DETAIL,
3103 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3104 dev->gcChunk, tags.objectId, tags.chunkId,
3107 if(object && !yaffs_SkipVerification(dev)){
3108 if(tags.chunkId == 0)
3109 matchingChunk = object->hdrChunk;
3110 else if(object->softDeleted)
3111 matchingChunk = oldChunk; /* Defeat the test */
3113 matchingChunk = yaffs_FindChunkInFile(object,tags.chunkId,NULL);
3115 if(oldChunk != matchingChunk)
3116 T(YAFFS_TRACE_ERROR,
3117 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3118 oldChunk,matchingChunk,tags.objectId, tags.chunkId));
3123 T(YAFFS_TRACE_ERROR,
3125 ("page %d in gc has no object: %d %d %d "
3127 tags.objectId, tags.chunkId, tags.byteCount));
3132 object->softDeleted &&
3133 tags.chunkId != 0) {
3134 /* Data chunk in a soft deleted file, throw it away
3135 * It's a soft deleted data chunk,
3136 * No need to copy this, just forget about it and
3137 * fix up the object.
3140 object->nDataChunks--;
3142 if (object->nDataChunks <= 0) {
3143 /* remeber to clean up the object */
3144 dev->gcCleanupList[cleanups] =
3150 /* Todo object && object->deleted && object->nDataChunks == 0 */
3152 /* Deleted object header with no data chunks.
3153 * Can be discarded and the file deleted.
3155 object->hdrChunk = 0;
3156 yaffs_FreeTnode(object->myDev,
3159 object->variant.fileVariant.top = NULL;
3160 yaffs_DoGenericObjectDeletion(object);
3162 } else if (object) {
3163 /* It's either a data chunk in a live file or
3164 * an ObjectHeader, so we're interested in it.
3165 * NB Need to keep the ObjectHeaders of deleted files
3166 * until the whole file has been deleted off
3168 tags.serialNumber++;
3172 if (tags.chunkId == 0) {
3173 /* It is an object Id,
3174 * We need to nuke the shrinkheader flags first
3175 * We no longer want the shrinkHeader flag since its work is done
3176 * and if it is left in place it will mess up scanning.
3179 yaffs_ObjectHeader *oh;
3180 oh = (yaffs_ObjectHeader *)buffer;
3182 tags.extraIsShrinkHeader = 0;
3184 yaffs_VerifyObjectHeader(object,oh,&tags,1);
3188 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3191 retVal = YAFFS_FAIL;
3194 /* Ok, now fix up the Tnodes etc. */
3196 if (tags.chunkId == 0) {
3198 object->hdrChunk = newChunk;
3199 object->serial = tags.serialNumber;
3201 /* It's a data chunk */
3202 yaffs_PutChunkIntoFile
3210 if(retVal == YAFFS_OK)
3211 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3216 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3219 /* Do any required cleanups */
3220 for (i = 0; i < cleanups; i++) {
3221 /* Time to delete the file too */
3223 yaffs_FindObjectByNumber(dev,
3224 dev->gcCleanupList[i]);
3226 yaffs_FreeTnode(dev,
3227 object->variant.fileVariant.
3229 object->variant.fileVariant.top = NULL;
3232 ("yaffs: About to finally delete object %d"
3233 TENDSTR), object->objectId));
3234 yaffs_DoGenericObjectDeletion(object);
3235 object->myDev->nDeletedFiles--;
3242 yaffs_VerifyCollectedBlock(dev,bi,block);
3244 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
3247 ("gc did not increase free chunks before %d after %d"
3248 TENDSTR), chunksBefore, chunksAfter));
3251 /* If the gc completed then clear the current gcBlock so that we find another. */
3252 if(bi->blockState != YAFFS_BLOCK_STATE_COLLECTING){
3262 /* New garbage collector
3263 * If we're very low on erased blocks then we do aggressive garbage collection
3264 * otherwise we do "leasurely" garbage collection.
3265 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3266 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3268 * The idea is to help clear out space in a more spread-out manner.
3269 * Dunno if it really does anything useful.
3271 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
3275 int gcOk = YAFFS_OK;
3278 int checkpointBlockAdjust;
3280 if (dev->isDoingGC) {
3281 /* Bail out so we don't get recursive gc */
3285 /* This loop should pass the first time.
3286 * We'll only see looping here if the erase of the collected block fails.
3292 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3293 if(checkpointBlockAdjust < 0)
3294 checkpointBlockAdjust = 0;
3296 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3297 /* We need a block soon...*/
3300 /* We're in no hurry */
3304 if(dev->gcBlock <= 0){
3305 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3309 block = dev->gcBlock;
3312 dev->garbageCollections++;
3314 dev->passiveGarbageCollections++;
3319 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3320 dev->nErasedBlocks, aggressive));
3322 gcOk = yaffs_GarbageCollectBlock(dev,block,aggressive);
3325 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3328 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3329 TENDSTR), dev->nErasedBlocks, maxTries, block));
3331 } while ((dev->nErasedBlocks < dev->nReservedBlocks) &&
3335 return aggressive ? gcOk : YAFFS_OK;
3338 /*------------------------- TAGS --------------------------------*/
3340 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
3343 return (tags->chunkId == chunkInObject &&
3344 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3349 /*-------------------- Data file manipulation -----------------*/
3351 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
3352 yaffs_ExtendedTags * tags)
3354 /*Get the Tnode, then get the level 0 offset chunk offset */
3357 yaffs_ExtendedTags localTags;
3360 yaffs_Device *dev = in->myDev;
3363 /* Passed a NULL, so use our own tags space */
3367 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3370 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3373 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3379 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
3380 yaffs_ExtendedTags * tags)
3382 /* Get the Tnode, then get the level 0 offset chunk offset */
3385 yaffs_ExtendedTags localTags;
3387 yaffs_Device *dev = in->myDev;
3391 /* Passed a NULL, so use our own tags space */
3395 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3399 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3402 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3405 /* Delete the entry in the filestructure (if found) */
3407 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
3410 /*T(("No level 0 found for %d\n", chunkInInode)); */
3414 /* T(("Could not find %d to delete\n",chunkInInode)); */
3419 #ifdef YAFFS_PARANOID
3421 static int yaffs_CheckFileSanity(yaffs_Object * in)
3429 yaffs_Tags localTags;
3430 yaffs_Tags *tags = &localTags;
3434 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3435 /* T(("Object not a file\n")); */
3439 objId = in->objectId;
3440 fSize = in->variant.fileVariant.fileSize;
3442 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3444 for (chunk = 1; chunk <= nChunks; chunk++) {
3445 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3450 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
3452 if (yaffs_CheckChunkBits
3453 (dev, theChunk / dev->nChunksPerBlock,
3454 theChunk % dev->nChunksPerBlock)) {
3456 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3460 (tags, in->objectId, chunk, chunkDeleted)) {
3470 /* T(("No level 0 found for %d\n", chunk)); */
3474 return failed ? YAFFS_FAIL : YAFFS_OK;
3479 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
3480 int chunkInNAND, int inScan)
3482 /* NB inScan is zero unless scanning.
3483 * For forward scanning, inScan is > 0;
3484 * for backward scanning inScan is < 0
3488 yaffs_Device *dev = in->myDev;
3490 yaffs_ExtendedTags existingTags;
3491 yaffs_ExtendedTags newTags;
3492 unsigned existingSerial, newSerial;
3494 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3495 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3496 * If it is not during Scanning then something went wrong!
3499 T(YAFFS_TRACE_ERROR,
3501 ("yaffs tragedy:attempt to put data chunk into a non-file"
3506 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3510 tn = yaffs_AddOrFindLevel0Tnode(dev,
3511 &in->variant.fileVariant,
3518 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3521 /* If we're scanning then we need to test for duplicates
3522 * NB This does not need to be efficient since it should only ever
3523 * happen when the power fails during a write, then only one
3524 * chunk should ever be affected.
3526 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3527 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3530 if (existingChunk > 0) {
3531 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3532 * thus we have to do a FindChunkInFile to get the real chunk id.
3534 * We have a duplicate now we need to decide which one to use:
3536 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3537 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3538 * YAFFS1: Get both sets of tags and compare serial numbers.
3542 /* Only do this for forward scanning */
3543 yaffs_ReadChunkWithTagsFromNAND(dev,
3547 /* Do a proper find */
3549 yaffs_FindChunkInFile(in, chunkInInode,
3553 if (existingChunk <= 0) {
3554 /*Hoosterman - how did this happen? */
3556 T(YAFFS_TRACE_ERROR,
3558 ("yaffs tragedy: existing chunk < 0 in scan"
3563 /* NB The deleted flags should be false, otherwise the chunks will
3564 * not be loaded during a scan
3568 newSerial = newTags.serialNumber;
3569 existingSerial = existingTags.serialNumber;
3573 (in->myDev->isYaffs2 ||
3574 existingChunk <= 0 ||
3575 ((existingSerial + 1) & 3) == newSerial)) {
3576 /* Forward scanning.
3578 * Delete the old one and drop through to update the tnode
3580 yaffs_DeleteChunk(dev, existingChunk, 1,
3583 /* Backward scanning or we want to use the existing one
3585 * Delete the new one and return early so that the tnode isn't changed
3587 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3595 if (existingChunk == 0) {
3599 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
3604 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
3607 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3609 if (chunkInNAND >= 0) {
3610 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3613 T(YAFFS_TRACE_NANDACCESS,
3614 (TSTR("Chunk %d not found zero instead" TENDSTR),
3616 /* get sane (zero) data if you read a hole */
3617 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3623 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
3627 yaffs_ExtendedTags tags;
3628 yaffs_BlockInfo *bi;
3635 block = chunkId / dev->nChunksPerBlock;
3636 page = chunkId % dev->nChunksPerBlock;
3639 if(!yaffs_CheckChunkBit(dev,block,page))
3640 T(YAFFS_TRACE_VERIFY,
3641 (TSTR("Deleting invalid chunk %d"TENDSTR),
3644 bi = yaffs_GetBlockInfo(dev, block);
3646 T(YAFFS_TRACE_DELETION,
3647 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3650 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3652 yaffs_InitialiseTags(&tags);
3654 tags.chunkDeleted = 1;
3656 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3657 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3659 dev->nUnmarkedDeletions++;
3662 /* Pull out of the management area.
3663 * If the whole block became dirty, this will kick off an erasure.
3665 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3666 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3667 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3668 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3671 yaffs_ClearChunkBit(dev, block, page);
3675 if (bi->pagesInUse == 0 &&
3676 !bi->hasShrinkHeader &&
3677 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3678 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3679 yaffs_BlockBecameDirty(dev, block);
3683 /* T(("Bad news deleting chunk %d\n",chunkId)); */
3688 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
3689 const __u8 * buffer, int nBytes,
3692 /* Find old chunk Need to do this to get serial number
3693 * Write new one and patch into tree.
3694 * Invalidate old tags.
3698 yaffs_ExtendedTags prevTags;
3701 yaffs_ExtendedTags newTags;
3703 yaffs_Device *dev = in->myDev;
3705 yaffs_CheckGarbageCollection(dev);
3707 /* Get the previous chunk at this location in the file if it exists */
3708 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3710 /* Set up new tags */
3711 yaffs_InitialiseTags(&newTags);
3713 newTags.chunkId = chunkInInode;
3714 newTags.objectId = in->objectId;
3715 newTags.serialNumber =
3716 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
3717 newTags.byteCount = nBytes;
3719 if(nBytes < 1 || nBytes > dev->totalBytesPerChunk){
3720 T(YAFFS_TRACE_ERROR,
3721 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3728 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3731 if (newChunkId >= 0) {
3732 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3734 if (prevChunkId >= 0) {
3735 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3739 yaffs_CheckFileSanity(in);
3745 /* UpdateObjectHeader updates the header on NAND for an object.
3746 * If name is not NULL, then that new name is used.
3748 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
3749 int isShrink, int shadows)
3752 yaffs_BlockInfo *bi;
3754 yaffs_Device *dev = in->myDev;
3761 yaffs_ExtendedTags newTags;
3762 yaffs_ExtendedTags oldTags;
3764 __u8 *buffer = NULL;
3765 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3767 yaffs_ObjectHeader *oh = NULL;
3769 yaffs_strcpy(oldName,_Y("silly old name"));
3773 in == dev->rootDir || /* The rootDir should also be saved */
3776 yaffs_CheckGarbageCollection(dev);
3777 yaffs_CheckObjectDetailsLoaded(in);
3779 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3780 oh = (yaffs_ObjectHeader *) buffer;
3782 prevChunkId = in->hdrChunk;
3784 if (prevChunkId > 0) {
3785 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3788 yaffs_VerifyObjectHeader(in,oh,&oldTags,0);
3790 memcpy(oldName, oh->name, sizeof(oh->name));
3793 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3795 oh->type = in->variantType;
3796 oh->yst_mode = in->yst_mode;
3797 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3799 #ifdef CONFIG_YAFFS_WINCE
3800 oh->win_atime[0] = in->win_atime[0];
3801 oh->win_ctime[0] = in->win_ctime[0];
3802 oh->win_mtime[0] = in->win_mtime[0];
3803 oh->win_atime[1] = in->win_atime[1];
3804 oh->win_ctime[1] = in->win_ctime[1];
3805 oh->win_mtime[1] = in->win_mtime[1];
3807 oh->yst_uid = in->yst_uid;
3808 oh->yst_gid = in->yst_gid;
3809 oh->yst_atime = in->yst_atime;
3810 oh->yst_mtime = in->yst_mtime;
3811 oh->yst_ctime = in->yst_ctime;
3812 oh->yst_rdev = in->yst_rdev;
3815 oh->parentObjectId = in->parent->objectId;
3817 oh->parentObjectId = 0;
3820 if (name && *name) {
3821 memset(oh->name, 0, sizeof(oh->name));
3822 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3823 } else if (prevChunkId>=0) {
3824 memcpy(oh->name, oldName, sizeof(oh->name));
3826 memset(oh->name, 0, sizeof(oh->name));
3829 oh->isShrink = isShrink;
3831 switch (in->variantType) {
3832 case YAFFS_OBJECT_TYPE_UNKNOWN:
3833 /* Should not happen */
3835 case YAFFS_OBJECT_TYPE_FILE:
3837 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3838 || oh->parentObjectId ==
3839 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3840 fileVariant.fileSize;
3842 case YAFFS_OBJECT_TYPE_HARDLINK:
3843 oh->equivalentObjectId =
3844 in->variant.hardLinkVariant.equivalentObjectId;
3846 case YAFFS_OBJECT_TYPE_SPECIAL:
3849 case YAFFS_OBJECT_TYPE_DIRECTORY:
3852 case YAFFS_OBJECT_TYPE_SYMLINK:
3853 yaffs_strncpy(oh->alias,
3854 in->variant.symLinkVariant.alias,
3855 YAFFS_MAX_ALIAS_LENGTH);
3856 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3861 yaffs_InitialiseTags(&newTags);
3863 newTags.chunkId = 0;
3864 newTags.objectId = in->objectId;
3865 newTags.serialNumber = in->serial;
3867 /* Add extra info for file header */
3869 newTags.extraHeaderInfoAvailable = 1;
3870 newTags.extraParentObjectId = oh->parentObjectId;
3871 newTags.extraFileLength = oh->fileSize;
3872 newTags.extraIsShrinkHeader = oh->isShrink;
3873 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3874 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3875 newTags.extraObjectType = in->variantType;
3877 yaffs_VerifyObjectHeader(in,oh,&newTags,1);
3879 /* Create new chunk in NAND */
3881 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3882 (prevChunkId >= 0) ? 1 : 0);
3884 if (newChunkId >= 0) {
3886 in->hdrChunk = newChunkId;
3888 if (prevChunkId >= 0) {
3889 yaffs_DeleteChunk(dev, prevChunkId, 1,
3893 if(!yaffs_ObjectHasCachedWriteData(in))
3896 /* If this was a shrink, then mark the block that the chunk lives on */
3898 bi = yaffs_GetBlockInfo(in->myDev,
3899 newChunkId /in->myDev-> nChunksPerBlock);
3900 bi->hasShrinkHeader = 1;
3905 retVal = newChunkId;
3910 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3915 /*------------------------ Short Operations Cache ----------------------------------------
3916 * In many situations where there is no high level buffering (eg WinCE) a lot of
3917 * reads might be short sequential reads, and a lot of writes may be short
3918 * sequential writes. eg. scanning/writing a jpeg file.
3919 * In these cases, a short read/write cache can provide a huge perfomance benefit
3920 * with dumb-as-a-rock code.
3921 * In Linux, the page cache provides read buffering aand the short op cache provides write
3924 * There are a limited number (~10) of cache chunks per device so that we don't
3925 * need a very intelligent search.
3928 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3930 yaffs_Device *dev = obj->myDev;
3932 yaffs_ChunkCache *cache;
3933 int nCaches = obj->myDev->nShortOpCaches;
3935 for(i = 0; i < nCaches; i++){
3936 cache = &dev->srCache[i];
3937 if (cache->object == obj &&
3946 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3948 yaffs_Device *dev = obj->myDev;
3949 int lowest = -99; /* Stop compiler whining. */
3951 yaffs_ChunkCache *cache;
3952 int chunkWritten = 0;
3953 int nCaches = obj->myDev->nShortOpCaches;
3959 /* Find the dirty cache for this object with the lowest chunk id. */
3960 for (i = 0; i < nCaches; i++) {
3961 if (dev->srCache[i].object == obj &&
3962 dev->srCache[i].dirty) {
3964 || dev->srCache[i].chunkId <
3966 cache = &dev->srCache[i];
3967 lowest = cache->chunkId;
3972 if (cache && !cache->locked) {
3973 /* Write it out and free it up */
3976 yaffs_WriteChunkDataToObject(cache->object,
3982 cache->object = NULL;
3985 } while (cache && chunkWritten > 0);
3988 /* Hoosterman, disk full while writing cache out. */
3989 T(YAFFS_TRACE_ERROR,
3990 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3997 /*yaffs_FlushEntireDeviceCache(dev)
4002 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
4005 int nCaches = dev->nShortOpCaches;
4008 /* Find a dirty object in the cache and flush it...
4009 * until there are no further dirty objects.
4013 for( i = 0; i < nCaches && !obj; i++) {
4014 if (dev->srCache[i].object &&
4015 dev->srCache[i].dirty)
4016 obj = dev->srCache[i].object;
4020 yaffs_FlushFilesChunkCache(obj);
4027 /* Grab us a cache chunk for use.
4028 * First look for an empty one.
4029 * Then look for the least recently used non-dirty one.
4030 * Then look for the least recently used dirty one...., flush and look again.
4032 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
4036 if (dev->nShortOpCaches > 0) {
4037 for (i = 0; i < dev->nShortOpCaches; i++) {
4038 if (!dev->srCache[i].object)
4039 return &dev->srCache[i];
4046 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
4048 yaffs_ChunkCache *cache;
4049 yaffs_Object *theObj;
4054 if (dev->nShortOpCaches > 0) {
4055 /* Try find a non-dirty one... */
4057 cache = yaffs_GrabChunkCacheWorker(dev);
4060 /* They were all dirty, find the last recently used object and flush
4061 * its cache, then find again.
4062 * NB what's here is not very accurate, we actually flush the object
4063 * the last recently used page.
4066 /* With locking we can't assume we can use entry zero */
4073 for (i = 0; i < dev->nShortOpCaches; i++) {
4074 if (dev->srCache[i].object &&
4075 !dev->srCache[i].locked &&
4076 (dev->srCache[i].lastUse < usage || !cache))
4078 usage = dev->srCache[i].lastUse;
4079 theObj = dev->srCache[i].object;
4080 cache = &dev->srCache[i];
4085 if (!cache || cache->dirty) {
4086 /* Flush and try again */
4087 yaffs_FlushFilesChunkCache(theObj);
4088 cache = yaffs_GrabChunkCacheWorker(dev);
4098 /* Find a cached chunk */
4099 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
4102 yaffs_Device *dev = obj->myDev;
4104 if (dev->nShortOpCaches > 0) {
4105 for (i = 0; i < dev->nShortOpCaches; i++) {
4106 if (dev->srCache[i].object == obj &&
4107 dev->srCache[i].chunkId == chunkId) {
4110 return &dev->srCache[i];
4117 /* Mark the chunk for the least recently used algorithym */
4118 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
4122 if (dev->nShortOpCaches > 0) {
4123 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4124 /* Reset the cache usages */
4126 for (i = 1; i < dev->nShortOpCaches; i++) {
4127 dev->srCache[i].lastUse = 0;
4134 cache->lastUse = dev->srLastUse;
4142 /* Invalidate a single cache page.
4143 * Do this when a whole page gets written,
4144 * ie the short cache for this page is no longer valid.
4146 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
4148 if (object->myDev->nShortOpCaches > 0) {
4149 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4152 cache->object = NULL;
4157 /* Invalidate all the cache pages associated with this object
4158 * Do this whenever ther file is deleted or resized.
4160 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
4163 yaffs_Device *dev = in->myDev;
4165 if (dev->nShortOpCaches > 0) {
4166 /* Invalidate it. */
4167 for (i = 0; i < dev->nShortOpCaches; i++) {
4168 if (dev->srCache[i].object == in) {
4169 dev->srCache[i].object = NULL;
4175 /*--------------------- Checkpointing --------------------*/
4178 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
4180 yaffs_CheckpointValidity cp;
4182 memset(&cp,0,sizeof(cp));
4184 cp.structType = sizeof(cp);
4185 cp.magic = YAFFS_MAGIC;
4186 cp.version = YAFFS_CHECKPOINT_VERSION;
4187 cp.head = (head) ? 1 : 0;
4189 return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
4193 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4195 yaffs_CheckpointValidity cp;
4198 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4201 ok = (cp.structType == sizeof(cp)) &&
4202 (cp.magic == YAFFS_MAGIC) &&
4203 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4204 (cp.head == ((head) ? 1 : 0));
4208 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4211 cp->nErasedBlocks = dev->nErasedBlocks;
4212 cp->allocationBlock = dev->allocationBlock;
4213 cp->allocationPage = dev->allocationPage;
4214 cp->nFreeChunks = dev->nFreeChunks;
4216 cp->nDeletedFiles = dev->nDeletedFiles;
4217 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4218 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4219 cp->sequenceNumber = dev->sequenceNumber;
4220 cp->oldestDirtySequence = dev->oldestDirtySequence;
4224 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4225 yaffs_CheckpointDevice *cp)
4227 dev->nErasedBlocks = cp->nErasedBlocks;
4228 dev->allocationBlock = cp->allocationBlock;
4229 dev->allocationPage = cp->allocationPage;
4230 dev->nFreeChunks = cp->nFreeChunks;
4232 dev->nDeletedFiles = cp->nDeletedFiles;
4233 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4234 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4235 dev->sequenceNumber = cp->sequenceNumber;
4236 dev->oldestDirtySequence = cp->oldestDirtySequence;
4240 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4242 yaffs_CheckpointDevice cp;
4244 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4248 /* Write device runtime values*/
4249 yaffs_DeviceToCheckpointDevice(&cp,dev);
4250 cp.structType = sizeof(cp);
4252 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4254 /* Write block info */
4256 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4257 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
4260 /* Write chunk bits */
4262 nBytes = nBlocks * dev->chunkBitmapStride;
4263 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
4269 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4271 yaffs_CheckpointDevice cp;
4273 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4277 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4281 if(cp.structType != sizeof(cp))
4285 yaffs_CheckpointDeviceToDevice(dev,&cp);
4287 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4289 ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
4293 nBytes = nBlocks * dev->chunkBitmapStride;
4295 ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
4300 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4304 cp->objectId = obj->objectId;
4305 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4306 cp->hdrChunk = obj->hdrChunk;
4307 cp->variantType = obj->variantType;
4308 cp->deleted = obj->deleted;
4309 cp->softDeleted = obj->softDeleted;
4310 cp->unlinked = obj->unlinked;
4311 cp->fake = obj->fake;
4312 cp->renameAllowed = obj->renameAllowed;
4313 cp->unlinkAllowed = obj->unlinkAllowed;
4314 cp->serial = obj->serial;
4315 cp->nDataChunks = obj->nDataChunks;
4317 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4318 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4319 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4320 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4323 static int yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
4326 yaffs_Object *parent;
4328 if (obj->variantType != cp->variantType) {
4329 T(YAFFS_TRACE_ERROR,(TSTR("Checkpoint read object %d type %d "
4330 TCONT("chunk %d does not match existing object type %d")
4331 TENDSTR), cp->objectId, cp->variantType, cp->hdrChunk,
4336 obj->objectId = cp->objectId;
4339 parent = yaffs_FindOrCreateObjectByNumber(
4342 YAFFS_OBJECT_TYPE_DIRECTORY);
4347 if (parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4348 T(YAFFS_TRACE_ALWAYS,(TSTR("Checkpoint read object %d parent %d type %d"
4349 TCONT(" chunk %d Parent type, %d, not directory")
4351 cp->objectId,cp->parentId,cp->variantType,cp->hdrChunk,parent->variantType));
4354 yaffs_AddObjectToDirectory(parent, obj);
4357 obj->hdrChunk = cp->hdrChunk;
4358 obj->variantType = cp->variantType;
4359 obj->deleted = cp->deleted;
4360 obj->softDeleted = cp->softDeleted;
4361 obj->unlinked = cp->unlinked;
4362 obj->fake = cp->fake;
4363 obj->renameAllowed = cp->renameAllowed;
4364 obj->unlinkAllowed = cp->unlinkAllowed;
4365 obj->serial = cp->serial;
4366 obj->nDataChunks = cp->nDataChunks;
4368 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4369 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4370 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4371 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4373 if(obj->hdrChunk > 0)
4374 obj->lazyLoaded = 1;
4380 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
4381 __u32 level, int chunkOffset)
4384 yaffs_Device *dev = in->myDev;
4386 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4388 if(tnodeSize < sizeof(yaffs_Tnode))
4389 tnodeSize = sizeof(yaffs_Tnode);
4395 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
4396 if (tn->internal[i]) {
4397 ok = yaffs_CheckpointTnodeWorker(in,
4400 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4403 } else if (level == 0) {
4404 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4405 ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
4407 ok = (yaffs_CheckpointWrite(dev,tn,tnodeSize) == tnodeSize);
4415 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4417 __u32 endMarker = ~0;
4420 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4421 ok = yaffs_CheckpointTnodeWorker(obj,
4422 obj->variant.fileVariant.top,
4423 obj->variant.fileVariant.topLevel,
4426 ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) ==
4433 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4437 yaffs_Device *dev = obj->myDev;
4438 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4441 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4443 if(tnodeSize < sizeof(yaffs_Tnode))
4444 tnodeSize = sizeof(yaffs_Tnode);
4446 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4448 while(ok && (~baseChunk)){
4450 /* Read level 0 tnode */
4453 tn = yaffs_GetTnodeRaw(dev);
4455 ok = (yaffs_CheckpointRead(dev,tn,tnodeSize) == tnodeSize);
4460 ok = yaffs_AddOrFindLevel0Tnode(dev,
4468 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4472 T(YAFFS_TRACE_CHECKPOINT,(
4473 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4474 nread,baseChunk,ok));
4480 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4483 yaffs_CheckpointObject cp;
4486 struct ylist_head *lh;
4489 /* Iterate through the objects in each hash entry,
4490 * dumping them to the checkpointing stream.
4493 for(i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++){
4494 ylist_for_each(lh, &dev->objectBucket[i].list) {
4496 obj = ylist_entry(lh, yaffs_Object, hashLink);
4497 if (!obj->deferedFree) {
4498 yaffs_ObjectToCheckpointObject(&cp,obj);
4499 cp.structType = sizeof(cp);
4501 T(YAFFS_TRACE_CHECKPOINT,(
4502 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
4503 cp.objectId,cp.parentId,cp.variantType,cp.hdrChunk,(unsigned) obj));
4505 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4507 if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4508 ok = yaffs_WriteCheckpointTnodes(obj);
4515 /* Dump end of list */
4516 memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
4517 cp.structType = sizeof(cp);
4520 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4525 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4528 yaffs_CheckpointObject cp;
4531 yaffs_Object *hardList = NULL;
4533 while(ok && !done) {
4534 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4535 if(cp.structType != sizeof(cp)) {
4536 T(YAFFS_TRACE_CHECKPOINT,(TSTR("struct size %d instead of %d ok %d"TENDSTR),
4537 cp.structType,sizeof(cp),ok));
4541 T(YAFFS_TRACE_CHECKPOINT,(TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4542 cp.objectId,cp.parentId,cp.variantType,cp.hdrChunk));
4544 if(ok && cp.objectId == ~0)
4547 obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
4549 ok = yaffs_CheckpointObjectToObject(obj,&cp);
4552 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4553 ok = yaffs_ReadCheckpointTnodes(obj);
4554 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4555 obj->hardLinks.next =
4556 (struct ylist_head *)
4568 yaffs_HardlinkFixup(dev,hardList);
4573 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4575 __u32 checkpointSum;
4578 yaffs_GetCheckpointSum(dev,&checkpointSum);
4580 ok = (yaffs_CheckpointWrite(dev,&checkpointSum,sizeof(checkpointSum)) == sizeof(checkpointSum));
4588 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4590 __u32 checkpointSum0;
4591 __u32 checkpointSum1;
4594 yaffs_GetCheckpointSum(dev,&checkpointSum0);
4596 ok = (yaffs_CheckpointRead(dev,&checkpointSum1,sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4601 if(checkpointSum0 != checkpointSum1)
4608 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4613 if(dev->skipCheckpointWrite || !dev->isYaffs2){
4614 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint write" TENDSTR)));
4619 ok = yaffs_CheckpointOpen(dev,1);
4622 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4623 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
4626 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint device" TENDSTR)));
4627 ok = yaffs_WriteCheckpointDevice(dev);
4630 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint objects" TENDSTR)));
4631 ok = yaffs_WriteCheckpointObjects(dev);
4634 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4635 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
4639 ok = yaffs_WriteCheckpointSum(dev);
4643 if(!yaffs_CheckpointClose(dev))
4647 dev->isCheckpointed = 1;
4649 dev->isCheckpointed = 0;
4651 return dev->isCheckpointed;
4654 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4658 if(dev->skipCheckpointRead || !dev->isYaffs2){
4659 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint read" TENDSTR)));
4664 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
4667 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4668 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
4671 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint device" TENDSTR)));
4672 ok = yaffs_ReadCheckpointDevice(dev);
4675 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint objects" TENDSTR)));
4676 ok = yaffs_ReadCheckpointObjects(dev);
4679 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4680 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
4684 ok = yaffs_ReadCheckpointSum(dev);
4685 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint checksum %d" TENDSTR),ok));
4688 if(!yaffs_CheckpointClose(dev))
4692 dev->isCheckpointed = 1;
4694 dev->isCheckpointed = 0;
4700 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4702 if(dev->isCheckpointed ||
4703 dev->blocksInCheckpoint > 0){
4704 dev->isCheckpointed = 0;
4705 yaffs_CheckpointInvalidateStream(dev);
4706 if(dev->superBlock && dev->markSuperBlockDirty)
4707 dev->markSuperBlockDirty(dev->superBlock);
4712 int yaffs_CheckpointSave(yaffs_Device *dev)
4715 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4717 yaffs_VerifyObjects(dev);
4718 yaffs_VerifyBlocks(dev);
4719 yaffs_VerifyFreeChunks(dev);
4721 if(!dev->isCheckpointed) {
4722 yaffs_InvalidateCheckpoint(dev);
4723 yaffs_WriteCheckpointData(dev);
4726 T(YAFFS_TRACE_ALWAYS,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4728 return dev->isCheckpointed;
4731 int yaffs_CheckpointRestore(yaffs_Device *dev)
4734 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4736 retval = yaffs_ReadCheckpointData(dev);
4738 if(dev->isCheckpointed){
4739 yaffs_VerifyObjects(dev);
4740 yaffs_VerifyBlocks(dev);
4741 yaffs_VerifyFreeChunks(dev);
4744 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4749 /*--------------------- File read/write ------------------------
4750 * Read and write have very similar structures.
4751 * In general the read/write has three parts to it
4752 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4753 * Some complete chunks
4754 * An incomplete chunk to end off with
4756 * Curve-balls: the first chunk might also be the last chunk.
4759 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, loff_t offset,
4768 yaffs_ChunkCache *cache;
4775 //chunk = offset / dev->nDataBytesPerChunk + 1;
4776 //start = offset % dev->nDataBytesPerChunk;
4777 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4780 /* OK now check for the curveball where the start and end are in
4783 if ((start + n) < dev->nDataBytesPerChunk) {
4786 nToCopy = dev->nDataBytesPerChunk - start;
4789 cache = yaffs_FindChunkCache(in, chunk);
4791 /* If the chunk is already in the cache or it is less than a whole chunk
4792 * or we're using inband tags then use the cache (if there is caching)
4793 * else bypass the cache.
4795 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4796 if (dev->nShortOpCaches > 0) {
4798 /* If we can't find the data in the cache, then load it up. */
4801 cache = yaffs_GrabChunkCache(in->myDev);
4803 cache->chunkId = chunk;
4806 yaffs_ReadChunkDataFromObject(in, chunk,
4812 yaffs_UseChunkCache(dev, cache, 0);
4817 memcpy(buffer, &cache->data[start], nToCopy);
4821 /* Read into the local buffer then copy..*/
4824 yaffs_GetTempBuffer(dev, __LINE__);
4825 yaffs_ReadChunkDataFromObject(in, chunk,
4828 memcpy(buffer, &localBuffer[start], nToCopy);
4831 yaffs_ReleaseTempBuffer(dev, localBuffer,
4837 /* A full chunk. Read directly into the supplied buffer. */
4838 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4852 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, loff_t offset,
4853 int nBytes, int writeThrough)
4862 int startOfWrite = offset;
4863 int chunkWritten = 0;
4871 while (n > 0 && chunkWritten >= 0) {
4872 //chunk = offset / dev->nDataBytesPerChunk + 1;
4873 //start = offset % dev->nDataBytesPerChunk;
4874 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4876 if(chunk * dev->nDataBytesPerChunk + start != offset ||
4877 start >= dev->nDataBytesPerChunk){
4878 T(YAFFS_TRACE_ERROR,(
4879 TSTR("AddrToChunk of offset %d gives chunk %d start %d"
4881 (int)offset, chunk,start));
4885 /* OK now check for the curveball where the start and end are in
4889 if ((start + n) < dev->nDataBytesPerChunk) {
4892 /* Now folks, to calculate how many bytes to write back....
4893 * If we're overwriting and not writing to then end of file then
4894 * we need to write back as much as was there before.
4897 chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
4899 if(chunkStart > in->variant.fileVariant.fileSize)
4900 nBytesRead = 0; /* Past end of file */
4902 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
4904 if (nBytesRead > dev->nDataBytesPerChunk) {
4905 nBytesRead = dev->nDataBytesPerChunk;
4910 (start + n)) ? nBytesRead : (start + n);
4912 if(nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
4916 nToCopy = dev->nDataBytesPerChunk - start;
4917 nToWriteBack = dev->nDataBytesPerChunk;
4920 if (nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4921 /* An incomplete start or end chunk (or maybe both start and end chunk),
4922 * or we're using inband tags, so we want to use the cache buffers.
4924 if (dev->nShortOpCaches > 0) {
4925 yaffs_ChunkCache *cache;
4926 /* If we can't find the data in the cache, then load the cache */
4927 cache = yaffs_FindChunkCache(in, chunk);
4930 && yaffs_CheckSpaceForAllocation(in->
4932 cache = yaffs_GrabChunkCache(in->myDev);
4934 cache->chunkId = chunk;
4937 yaffs_ReadChunkDataFromObject(in, chunk,
4943 !yaffs_CheckSpaceForAllocation(in->myDev)){
4944 /* Drop the cache if it was a read cache item and
4945 * no space check has been made for it.
4951 yaffs_UseChunkCache(dev, cache, 1);
4955 memcpy(&cache->data[start], buffer,
4960 cache->nBytes = nToWriteBack;
4964 yaffs_WriteChunkDataToObject
4967 cache->data, cache->nBytes,
4973 chunkWritten = -1; /* fail the write */
4976 /* An incomplete start or end chunk (or maybe both start and end chunk)
4977 * Read into the local buffer then copy, then copy over and write back.
4981 yaffs_GetTempBuffer(dev, __LINE__);
4983 yaffs_ReadChunkDataFromObject(in, chunk,
4988 memcpy(&localBuffer[start], buffer, nToCopy);
4991 yaffs_WriteChunkDataToObject(in, chunk,
4996 yaffs_ReleaseTempBuffer(dev, localBuffer,
5002 /* A full chunk. Write directly from the supplied buffer. */
5007 yaffs_WriteChunkDataToObject(in, chunk, buffer,
5008 dev->nDataBytesPerChunk,
5011 /* Since we've overwritten the cached data, we better invalidate it. */
5012 yaffs_InvalidateChunkCache(in, chunk);
5015 if (chunkWritten >= 0) {
5024 /* Update file object */
5026 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
5027 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
5036 /* ---------------------- File resizing stuff ------------------ */
5038 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
5041 yaffs_Device *dev = in->myDev;
5042 int oldFileSize = in->variant.fileVariant.fileSize;
5044 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
5046 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
5047 dev->nDataBytesPerChunk;
5051 /* Delete backwards so that we don't end up with holes if
5052 * power is lost part-way through the operation.
5054 for (i = lastDel; i >= startDel; i--) {
5055 /* NB this could be optimised somewhat,
5056 * eg. could retrieve the tags and write them without
5057 * using yaffs_DeleteChunk
5060 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5063 (dev->internalStartBlock * dev->nChunksPerBlock)
5065 ((dev->internalEndBlock +
5066 1) * dev->nChunksPerBlock)) {
5067 T(YAFFS_TRACE_ALWAYS,
5068 (TSTR("Found daft chunkId %d for %d" TENDSTR),
5072 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5079 int yaffs_ResizeFile(yaffs_Object * in, loff_t newSize)
5082 int oldFileSize = in->variant.fileVariant.fileSize;
5083 __u32 newSizeOfPartialChunk;
5086 yaffs_Device *dev = in->myDev;
5088 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5090 yaffs_FlushFilesChunkCache(in);
5091 yaffs_InvalidateWholeChunkCache(in);
5093 yaffs_CheckGarbageCollection(dev);
5095 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
5099 if (newSize == oldFileSize) {
5103 if (newSize < oldFileSize) {
5105 yaffs_PruneResizedChunks(in, newSize);
5107 if (newSizeOfPartialChunk != 0) {
5108 int lastChunk = 1 + newFullChunks;
5110 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5112 /* Got to read and rewrite the last chunk with its new size and zero pad */
5113 yaffs_ReadChunkDataFromObject(in, lastChunk,
5116 memset(localBuffer + newSizeOfPartialChunk, 0,
5117 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5119 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5120 newSizeOfPartialChunk, 1);
5122 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5125 in->variant.fileVariant.fileSize = newSize;
5127 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5129 /* newsSize > oldFileSize */
5130 in->variant.fileVariant.fileSize = newSize;
5135 /* Write a new object header.
5136 * show we've shrunk the file, if need be
5137 * Do this only if the file is not in the deleted directories.
5140 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5141 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
5142 yaffs_UpdateObjectHeader(in, NULL, 0,
5143 (newSize < oldFileSize) ? 1 : 0, 0);
5149 loff_t yaffs_GetFileSize(yaffs_Object * obj)
5151 obj = yaffs_GetEquivalentObject(obj);
5153 switch (obj->variantType) {
5154 case YAFFS_OBJECT_TYPE_FILE:
5155 return obj->variant.fileVariant.fileSize;
5156 case YAFFS_OBJECT_TYPE_SYMLINK:
5157 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5165 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
5169 yaffs_FlushFilesChunkCache(in);
5171 #ifdef CONFIG_YAFFS_WINCE
5172 yfsd_WinFileTimeNow(in->win_mtime);
5175 in->yst_mtime = Y_CURRENT_TIME;
5181 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5182 0) ? YAFFS_OK : YAFFS_FAIL;
5191 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
5194 /* First off, invalidate the file's data in the cache, without flushing. */
5195 yaffs_InvalidateWholeChunkCache(in);
5197 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5198 /* Move to the unlinked directory so we have a record that it was deleted. */
5199 yaffs_ChangeObjectName(in, in->myDev->deletedDir,_Y("deleted"), 0, 0);
5203 yaffs_RemoveObjectFromDirectory(in);
5204 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5207 yaffs_FreeObject(in);
5212 /* yaffs_DeleteFile deletes the whole file data
5213 * and the inode associated with the file.
5214 * It does not delete the links associated with the file.
5216 static int yaffs_UnlinkFileIfNeeded(yaffs_Object * in)
5220 int immediateDeletion = 0;
5224 immediateDeletion = 1;
5227 if (in->inUse <= 0) {
5228 immediateDeletion = 1;
5232 if (immediateDeletion) {
5234 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5235 _Y("deleted"), 0, 0);
5236 T(YAFFS_TRACE_TRACING,
5237 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5240 in->myDev->nDeletedFiles++;
5241 if (1 || in->myDev->isYaffs2) {
5242 yaffs_ResizeFile(in, 0);
5244 yaffs_SoftDeleteFile(in);
5247 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5248 _Y("unlinked"), 0, 0);
5255 int yaffs_DeleteFile(yaffs_Object * in)
5257 int retVal = YAFFS_OK;
5258 int deleted = in->deleted;
5260 yaffs_ResizeFile(in,0);
5262 if (in->nDataChunks > 0) {
5263 /* Use soft deletion if there is data in the file.
5264 * That won't be the case if it has been resized to zero.
5266 if (!in->unlinked) {
5267 retVal = yaffs_UnlinkFileIfNeeded(in);
5269 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5270 in->deleted = deleted = 1;
5271 in->myDev->nDeletedFiles++;
5272 yaffs_SoftDeleteFile(in);
5274 return deleted ? YAFFS_OK : YAFFS_FAIL;
5276 /* The file has no data chunks so we toss it immediately */
5277 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5278 in->variant.fileVariant.top = NULL;
5279 yaffs_DoGenericObjectDeletion(in);
5285 static int yaffs_DeleteDirectory(yaffs_Object * in)
5287 /* First check that the directory is empty. */
5288 if (ylist_empty(&in->variant.directoryVariant.children)) {
5289 return yaffs_DoGenericObjectDeletion(in);
5296 static int yaffs_DeleteSymLink(yaffs_Object * in)
5298 YFREE(in->variant.symLinkVariant.alias);
5300 return yaffs_DoGenericObjectDeletion(in);
5303 static int yaffs_DeleteHardLink(yaffs_Object * in)
5305 /* remove this hardlink from the list assocaited with the equivalent
5308 ylist_del_init(&in->hardLinks);
5309 return yaffs_DoGenericObjectDeletion(in);
5312 int yaffs_DeleteObject(yaffs_Object * obj)
5315 switch (obj->variantType) {
5316 case YAFFS_OBJECT_TYPE_FILE:
5317 retVal = yaffs_DeleteFile(obj);
5319 case YAFFS_OBJECT_TYPE_DIRECTORY:
5320 return yaffs_DeleteDirectory(obj);
5322 case YAFFS_OBJECT_TYPE_SYMLINK:
5323 retVal = yaffs_DeleteSymLink(obj);
5325 case YAFFS_OBJECT_TYPE_HARDLINK:
5326 retVal = yaffs_DeleteHardLink(obj);
5328 case YAFFS_OBJECT_TYPE_SPECIAL:
5329 retVal = yaffs_DoGenericObjectDeletion(obj);
5331 case YAFFS_OBJECT_TYPE_UNKNOWN:
5333 break; /* should not happen. */
5339 static int yaffs_UnlinkWorker(yaffs_Object * obj)
5342 int immediateDeletion = 0;
5345 if (!obj->myInode) {
5346 immediateDeletion = 1;
5349 if (obj->inUse <= 0) {
5350 immediateDeletion = 1;
5354 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5355 return yaffs_DeleteHardLink(obj);
5356 } else if (!ylist_empty(&obj->hardLinks)) {
5357 /* Curve ball: We're unlinking an object that has a hardlink.
5359 * This problem arises because we are not strictly following
5360 * The Linux link/inode model.
5362 * We can't really delete the object.
5363 * Instead, we do the following:
5364 * - Select a hardlink.
5365 * - Unhook it from the hard links
5366 * - Unhook it from its parent directory (so that the rename can work)
5367 * - Rename the object to the hardlink's name.
5368 * - Delete the hardlink
5373 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5375 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5377 ylist_del_init(&hl->hardLinks);
5378 ylist_del_init(&hl->siblings);
5380 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5382 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
5384 if (retVal == YAFFS_OK) {
5385 retVal = yaffs_DoGenericObjectDeletion(hl);
5389 } else if(immediateDeletion){
5390 switch (obj->variantType) {
5391 case YAFFS_OBJECT_TYPE_FILE:
5392 return yaffs_DeleteFile(obj);
5394 case YAFFS_OBJECT_TYPE_DIRECTORY:
5395 return yaffs_DeleteDirectory(obj);
5397 case YAFFS_OBJECT_TYPE_SYMLINK:
5398 return yaffs_DeleteSymLink(obj);
5400 case YAFFS_OBJECT_TYPE_SPECIAL:
5401 return yaffs_DoGenericObjectDeletion(obj);
5403 case YAFFS_OBJECT_TYPE_HARDLINK:
5404 case YAFFS_OBJECT_TYPE_UNKNOWN:
5409 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
5410 _Y("unlinked"), 0, 0);
5415 static int yaffs_UnlinkObject( yaffs_Object *obj)
5418 if (obj && obj->unlinkAllowed) {
5419 return yaffs_UnlinkWorker(obj);
5425 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
5429 obj = yaffs_FindObjectByName(dir, name);
5430 return yaffs_UnlinkObject(obj);
5433 /*----------------------- Initialisation Scanning ---------------------- */
5435 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
5436 int backwardScanning)
5440 if (!backwardScanning) {
5441 /* Handle YAFFS1 forward scanning case
5442 * For YAFFS1 we always do the deletion
5446 /* Handle YAFFS2 case (backward scanning)
5447 * If the shadowed object exists then ignore.
5449 if (yaffs_FindObjectByNumber(dev, objId)) {
5454 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5455 * We put it in unlinked dir to be cleaned up after the scanning
5458 yaffs_FindOrCreateObjectByNumber(dev, objId,
5459 YAFFS_OBJECT_TYPE_FILE);
5462 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5463 obj->variant.fileVariant.shrinkSize = 0;
5464 obj->valid = 1; /* So that we don't read any other info for this file */
5474 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5481 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5483 in = yaffs_FindObjectByNumber(dev,
5484 hl->variant.hardLinkVariant.
5485 equivalentObjectId);
5488 /* Add the hardlink pointers */
5489 hl->variant.hardLinkVariant.equivalentObject = in;
5490 ylist_add(&hl->hardLinks, &in->hardLinks);
5492 /* Todo Need to report/handle this better.
5493 * Got a problem... hardlink to a non-existant object
5495 hl->variant.hardLinkVariant.equivalentObject = NULL;
5496 YINIT_LIST_HEAD(&hl->hardLinks);
5508 static int ybicmp(const void *a, const void *b){
5509 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5510 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5511 register int ablock = ((yaffs_BlockIndex *)a)->block;
5512 register int bblock = ((yaffs_BlockIndex *)b)->block;
5514 return ablock - bblock;
5521 struct yaffs_ShadowFixerStruct {
5524 struct yaffs_ShadowFixerStruct *next;
5528 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5531 * Sort out state of unlinked and deleted objects after scanning.
5533 struct ylist_head *i;
5534 struct ylist_head *n;
5537 /* Soft delete all the unlinked files */
5538 ylist_for_each_safe(i, n,
5539 &dev->unlinkedDir->variant.directoryVariant.children) {
5541 l = ylist_entry(i, yaffs_Object, siblings);
5542 yaffs_DeleteObject(l);
5546 ylist_for_each_safe(i, n,
5547 &dev->deletedDir->variant.directoryVariant.children) {
5549 l = ylist_entry(i, yaffs_Object, siblings);
5550 yaffs_DeleteObject(l);
5556 static int yaffs_Scan(yaffs_Device * dev)
5558 yaffs_ExtendedTags tags;
5568 yaffs_BlockState state;
5569 yaffs_Object *hardList = NULL;
5570 yaffs_BlockInfo *bi;
5571 __u32 sequenceNumber;
5572 yaffs_ObjectHeader *oh;
5574 yaffs_Object *parent;
5576 int alloc_failed = 0;
5578 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5586 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5587 dev->internalStartBlock, dev->internalEndBlock));
5589 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5591 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5593 /* Scan all the blocks to determine their state */
5594 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5595 bi = yaffs_GetBlockInfo(dev, blk);
5596 yaffs_ClearChunkBits(dev, blk);
5598 bi->softDeletions = 0;
5600 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5602 bi->blockState = state;
5603 bi->sequenceNumber = sequenceNumber;
5605 if(bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
5606 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
5608 T(YAFFS_TRACE_SCAN_DEBUG,
5609 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5610 state, sequenceNumber));
5612 if (state == YAFFS_BLOCK_STATE_DEAD) {
5613 T(YAFFS_TRACE_BAD_BLOCKS,
5614 (TSTR("block %d is bad" TENDSTR), blk));
5615 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5616 T(YAFFS_TRACE_SCAN_DEBUG,
5617 (TSTR("Block empty " TENDSTR)));
5618 dev->nErasedBlocks++;
5619 dev->nFreeChunks += dev->nChunksPerBlock;
5623 startIterator = dev->internalStartBlock;
5624 endIterator = dev->internalEndBlock;
5626 /* For each block.... */
5627 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5634 blk = blockIterator;
5636 bi = yaffs_GetBlockInfo(dev, blk);
5637 state = bi->blockState;
5641 /* For each chunk in each block that needs scanning....*/
5642 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5643 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5644 /* Read the tags and decide what to do */
5645 chunk = blk * dev->nChunksPerBlock + c;
5647 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5650 /* Let's have a good look at this chunk... */
5652 if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
5658 /*T((" %d %d deleted\n",blk,c)); */
5659 } else if (!tags.chunkUsed) {
5660 /* An unassigned chunk in the block
5661 * This means that either the block is empty or
5662 * this is the one being allocated from
5666 /* We're looking at the first chunk in the block so the block is unused */
5667 state = YAFFS_BLOCK_STATE_EMPTY;
5668 dev->nErasedBlocks++;
5670 /* this is the block being allocated from */
5673 (" Allocating from %d %d" TENDSTR),
5675 state = YAFFS_BLOCK_STATE_ALLOCATING;
5676 dev->allocationBlock = blk;
5677 dev->allocationPage = c;
5678 dev->allocationBlockFinder = blk;
5679 /* Set it to here to encourage the allocator to go forth from here. */
5683 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5684 } else if (tags.chunkId > 0) {
5685 /* chunkId > 0 so it is a data chunk... */
5686 unsigned int endpos;
5688 yaffs_SetChunkBit(dev, blk, c);
5691 in = yaffs_FindOrCreateObjectByNumber(dev,
5694 YAFFS_OBJECT_TYPE_FILE);
5695 /* PutChunkIntoFile checks for a clash (two data chunks with
5696 * the same chunkId).
5703 if(!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,1))
5708 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5711 in->variantType == YAFFS_OBJECT_TYPE_FILE
5712 && in->variant.fileVariant.scannedFileSize <
5714 in->variant.fileVariant.
5715 scannedFileSize = endpos;
5716 if (!dev->useHeaderFileSize) {
5717 in->variant.fileVariant.
5719 in->variant.fileVariant.
5724 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
5726 /* chunkId == 0, so it is an ObjectHeader.
5727 * Thus, we read in the object header and make the object
5729 yaffs_SetChunkBit(dev, blk, c);
5732 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5736 oh = (yaffs_ObjectHeader *) chunkData;
5738 in = yaffs_FindObjectByNumber(dev,
5740 if (in && in->variantType != oh->type) {
5741 /* This should not happen, but somehow
5742 * Wev'e ended up with an objectId that has been reused but not yet
5743 * deleted, and worse still it has changed type. Delete the old object.
5746 yaffs_DeleteObject(in);
5751 in = yaffs_FindOrCreateObjectByNumber(dev,
5759 if (in && oh->shadowsObject > 0) {
5761 struct yaffs_ShadowFixerStruct *fixer;
5762 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
5764 fixer-> next = shadowFixerList;
5765 shadowFixerList = fixer;
5766 fixer->objectId = tags.objectId;
5767 fixer->shadowedId = oh->shadowsObject;
5772 if (in && in->valid) {
5773 /* We have already filled this one. We have a duplicate and need to resolve it. */
5775 unsigned existingSerial = in->serial;
5776 unsigned newSerial = tags.serialNumber;
5778 if (((existingSerial + 1) & 3) == newSerial) {
5779 /* Use new one - destroy the exisiting one */
5780 yaffs_DeleteChunk(dev,
5785 /* Use existing - destroy this one. */
5786 yaffs_DeleteChunk(dev, chunk, 1,
5791 if (in && !in->valid &&
5792 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5793 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5794 /* We only load some info, don't fiddle with directory structure */
5796 in->variantType = oh->type;
5798 in->yst_mode = oh->yst_mode;
5799 #ifdef CONFIG_YAFFS_WINCE
5800 in->win_atime[0] = oh->win_atime[0];
5801 in->win_ctime[0] = oh->win_ctime[0];
5802 in->win_mtime[0] = oh->win_mtime[0];
5803 in->win_atime[1] = oh->win_atime[1];
5804 in->win_ctime[1] = oh->win_ctime[1];
5805 in->win_mtime[1] = oh->win_mtime[1];
5807 in->yst_uid = oh->yst_uid;
5808 in->yst_gid = oh->yst_gid;
5809 in->yst_atime = oh->yst_atime;
5810 in->yst_mtime = oh->yst_mtime;
5811 in->yst_ctime = oh->yst_ctime;
5812 in->yst_rdev = oh->yst_rdev;
5814 in->hdrChunk = chunk;
5815 in->serial = tags.serialNumber;
5817 } else if (in && !in->valid) {
5818 /* we need to load this info */
5821 in->variantType = oh->type;
5823 in->yst_mode = oh->yst_mode;
5824 #ifdef CONFIG_YAFFS_WINCE
5825 in->win_atime[0] = oh->win_atime[0];
5826 in->win_ctime[0] = oh->win_ctime[0];
5827 in->win_mtime[0] = oh->win_mtime[0];
5828 in->win_atime[1] = oh->win_atime[1];
5829 in->win_ctime[1] = oh->win_ctime[1];
5830 in->win_mtime[1] = oh->win_mtime[1];
5832 in->yst_uid = oh->yst_uid;
5833 in->yst_gid = oh->yst_gid;
5834 in->yst_atime = oh->yst_atime;
5835 in->yst_mtime = oh->yst_mtime;
5836 in->yst_ctime = oh->yst_ctime;
5837 in->yst_rdev = oh->yst_rdev;
5839 in->hdrChunk = chunk;
5840 in->serial = tags.serialNumber;
5842 yaffs_SetObjectName(in, oh->name);
5845 /* directory stuff...
5850 yaffs_FindOrCreateObjectByNumber
5851 (dev, oh->parentObjectId,
5852 YAFFS_OBJECT_TYPE_DIRECTORY);
5855 if (parent && parent->variantType ==
5856 YAFFS_OBJECT_TYPE_UNKNOWN) {
5857 /* Set up as a directory */
5858 parent->variantType =
5859 YAFFS_OBJECT_TYPE_DIRECTORY;
5860 YINIT_LIST_HEAD(&parent->variant.
5863 } else if (!parent || parent->variantType !=
5864 YAFFS_OBJECT_TYPE_DIRECTORY)
5866 /* Hoosterman, another problem....
5867 * We're trying to use a non-directory as a directory
5870 T(YAFFS_TRACE_ERROR,
5872 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
5874 parent = dev->lostNFoundDir;
5877 yaffs_AddObjectToDirectory(parent, in);
5879 if (0 && (parent == dev->deletedDir ||
5880 parent == dev->unlinkedDir)) {
5881 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
5882 dev->nDeletedFiles++;
5884 /* Note re hardlinks.
5885 * Since we might scan a hardlink before its equivalent object is scanned
5886 * we put them all in a list.
5887 * After scanning is complete, we should have all the objects, so we run through this
5888 * list and fix up all the chains.
5891 switch (in->variantType) {
5892 case YAFFS_OBJECT_TYPE_UNKNOWN:
5893 /* Todo got a problem */
5895 case YAFFS_OBJECT_TYPE_FILE:
5896 if (dev->useHeaderFileSize)
5898 in->variant.fileVariant.
5903 case YAFFS_OBJECT_TYPE_HARDLINK:
5904 in->variant.hardLinkVariant.
5905 equivalentObjectId =
5906 oh->equivalentObjectId;
5907 in->hardLinks.next =
5908 (struct ylist_head *)
5912 case YAFFS_OBJECT_TYPE_DIRECTORY:
5915 case YAFFS_OBJECT_TYPE_SPECIAL:
5918 case YAFFS_OBJECT_TYPE_SYMLINK:
5919 in->variant.symLinkVariant.alias =
5920 yaffs_CloneString(oh->alias);
5921 if(!in->variant.symLinkVariant.alias)
5927 if (parent == dev->deletedDir) {
5928 yaffs_DestroyObject(in);
5929 bi->hasShrinkHeader = 1;
5936 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5937 /* If we got this far while scanning, then the block is fully allocated.*/
5938 state = YAFFS_BLOCK_STATE_FULL;
5941 bi->blockState = state;
5943 /* Now let's see if it was dirty */
5944 if (bi->pagesInUse == 0 &&
5945 !bi->hasShrinkHeader &&
5946 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5947 yaffs_BlockBecameDirty(dev, blk);
5953 /* Ok, we've done all the scanning.
5954 * Fix up the hard link chains.
5955 * We should now have scanned all the objects, now it's time to add these
5959 yaffs_HardlinkFixup(dev,hardList);
5961 /* Fix up any shadowed objects */
5963 struct yaffs_ShadowFixerStruct *fixer;
5966 while(shadowFixerList){
5967 fixer = shadowFixerList;
5968 shadowFixerList = fixer->next;
5969 /* Complete the rename transaction by deleting the shadowed object
5970 * then setting the object header to unshadowed.
5972 obj = yaffs_FindObjectByNumber(dev,fixer->shadowedId);
5974 yaffs_DeleteObject(obj);
5976 obj = yaffs_FindObjectByNumber(dev,fixer->objectId);
5978 yaffs_UpdateObjectHeader(obj,NULL,1,0,0);
5985 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5991 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5997 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
6000 yaffs_ObjectHeader *oh;
6002 yaffs_ExtendedTags tags;
6004 int alloc_failed = 0;
6012 T(YAFFS_TRACE_SCAN,(TSTR("details for object %d %s loaded" TENDSTR),
6014 in->lazyLoaded ? "not yet" : "already"));
6017 if(in->lazyLoaded && in->hdrChunk > 0){
6019 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6021 result = yaffs_ReadChunkWithTagsFromNAND(dev,in->hdrChunk,chunkData,&tags);
6022 oh = (yaffs_ObjectHeader *) chunkData;
6024 in->yst_mode = oh->yst_mode;
6025 #ifdef CONFIG_YAFFS_WINCE
6026 in->win_atime[0] = oh->win_atime[0];
6027 in->win_ctime[0] = oh->win_ctime[0];
6028 in->win_mtime[0] = oh->win_mtime[0];
6029 in->win_atime[1] = oh->win_atime[1];
6030 in->win_ctime[1] = oh->win_ctime[1];
6031 in->win_mtime[1] = oh->win_mtime[1];
6033 in->yst_uid = oh->yst_uid;
6034 in->yst_gid = oh->yst_gid;
6035 in->yst_atime = oh->yst_atime;
6036 in->yst_mtime = oh->yst_mtime;
6037 in->yst_ctime = oh->yst_ctime;
6038 in->yst_rdev = oh->yst_rdev;
6041 yaffs_SetObjectName(in, oh->name);
6043 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
6044 in->variant.symLinkVariant.alias =
6045 yaffs_CloneString(oh->alias);
6046 if(!in->variant.symLinkVariant.alias)
6047 alloc_failed = 1; /* Not returned to caller */
6050 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
6054 static int yaffs_ScanBackwards(yaffs_Device * dev)
6056 yaffs_ExtendedTags tags;
6061 int nBlocksToScan = 0;
6067 yaffs_BlockState state;
6068 yaffs_Object *hardList = NULL;
6069 yaffs_BlockInfo *bi;
6070 __u32 sequenceNumber;
6071 yaffs_ObjectHeader *oh;
6073 yaffs_Object *parent;
6074 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6080 int foundChunksInBlock;
6081 int equivalentObjectId;
6082 int alloc_failed = 0;
6085 yaffs_BlockIndex *blockIndex = NULL;
6086 int altBlockIndex = 0;
6088 if (!dev->isYaffs2) {
6090 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6096 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
6097 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6100 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6102 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6105 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6111 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6115 dev->blocksInCheckpoint = 0;
6117 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6119 /* Scan all the blocks to determine their state */
6120 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6121 bi = yaffs_GetBlockInfo(dev, blk);
6122 yaffs_ClearChunkBits(dev, blk);
6124 bi->softDeletions = 0;
6126 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6128 bi->blockState = state;
6129 bi->sequenceNumber = sequenceNumber;
6131 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6132 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6133 if(bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6134 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6136 T(YAFFS_TRACE_SCAN_DEBUG,
6137 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6138 state, sequenceNumber));
6141 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
6142 dev->blocksInCheckpoint++;
6144 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6145 T(YAFFS_TRACE_BAD_BLOCKS,
6146 (TSTR("block %d is bad" TENDSTR), blk));
6147 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6148 T(YAFFS_TRACE_SCAN_DEBUG,
6149 (TSTR("Block empty " TENDSTR)));
6150 dev->nErasedBlocks++;
6151 dev->nFreeChunks += dev->nChunksPerBlock;
6152 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6154 /* Determine the highest sequence number */
6155 if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6156 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6158 blockIndex[nBlocksToScan].seq = sequenceNumber;
6159 blockIndex[nBlocksToScan].block = blk;
6163 if (sequenceNumber >= dev->sequenceNumber) {
6164 dev->sequenceNumber = sequenceNumber;
6167 /* TODO: Nasty sequence number! */
6170 ("Block scanning block %d has bad sequence number %d"
6171 TENDSTR), blk, sequenceNumber));
6178 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6184 /* Sort the blocks */
6185 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6187 /* Use qsort now. */
6188 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6192 /* Dungy old bubble sort... */
6194 yaffs_BlockIndex temp;
6198 for (i = 0; i < nBlocksToScan; i++)
6199 for (j = i + 1; j < nBlocksToScan; j++)
6200 if (blockIndex[i].seq > blockIndex[j].seq) {
6201 temp = blockIndex[j];
6202 blockIndex[j] = blockIndex[i];
6203 blockIndex[i] = temp;
6210 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6212 /* Now scan the blocks looking at the data. */
6214 endIterator = nBlocksToScan - 1;
6215 T(YAFFS_TRACE_SCAN_DEBUG,
6216 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6218 /* For each block.... backwards */
6219 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6221 /* Cooperative multitasking! This loop can run for so
6222 long that watchdog timers expire. */
6225 /* get the block to scan in the correct order */
6226 blk = blockIndex[blockIterator].block;
6228 bi = yaffs_GetBlockInfo(dev, blk);
6231 state = bi->blockState;
6235 /* For each chunk in each block that needs scanning.... */
6236 foundChunksInBlock = 0;
6237 for (c = dev->nChunksPerBlock - 1;
6238 !alloc_failed && c >= 0 &&
6239 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6240 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6241 /* Scan backwards...
6242 * Read the tags and decide what to do
6245 chunk = blk * dev->nChunksPerBlock + c;
6247 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6250 /* Let's have a good look at this chunk... */
6252 if (!tags.chunkUsed) {
6253 /* An unassigned chunk in the block.
6254 * If there are used chunks after this one, then
6255 * it is a chunk that was skipped due to failing the erased
6256 * check. Just skip it so that it can be deleted.
6257 * But, more typically, We get here when this is an unallocated
6258 * chunk and his means that either the block is empty or
6259 * this is the one being allocated from
6262 if(foundChunksInBlock)
6264 /* This is a chunk that was skipped due to failing the erased check */
6266 } else if (c == 0) {
6267 /* We're looking at the first chunk in the block so the block is unused */
6268 state = YAFFS_BLOCK_STATE_EMPTY;
6269 dev->nErasedBlocks++;
6271 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6272 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6273 if(dev->sequenceNumber == bi->sequenceNumber) {
6274 /* this is the block being allocated from */
6278 (" Allocating from %d %d"
6281 state = YAFFS_BLOCK_STATE_ALLOCATING;
6282 dev->allocationBlock = blk;
6283 dev->allocationPage = c;
6284 dev->allocationBlockFinder = blk;
6287 /* This is a partially written block that is not
6288 * the current allocation block. This block must have
6289 * had a write failure, so set up for retirement.
6292 /* bi->needsRetiring = 1; ??? TODO */
6293 bi->gcPrioritise = 1;
6295 T(YAFFS_TRACE_ALWAYS,
6296 (TSTR("Partially written block %d detected" TENDSTR),
6306 } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED){
6308 (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
6313 }else if (tags.chunkId > 0) {
6314 /* chunkId > 0 so it is a data chunk... */
6315 unsigned int endpos;
6317 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6319 foundChunksInBlock = 1;
6322 yaffs_SetChunkBit(dev, blk, c);
6325 in = yaffs_FindOrCreateObjectByNumber(dev,
6328 YAFFS_OBJECT_TYPE_FILE);
6335 in->variantType == YAFFS_OBJECT_TYPE_FILE
6337 in->variant.fileVariant.shrinkSize) {
6338 /* This has not been invalidated by a resize */
6339 if(!yaffs_PutChunkIntoFile(in, tags.chunkId,
6344 /* File size is calculated by looking at the data chunks if we have not
6345 * seen an object header yet. Stop this practice once we find an object header.
6349 1) * dev->nDataBytesPerChunk +
6352 if (!in->valid && /* have not got an object header yet */
6353 in->variant.fileVariant.
6354 scannedFileSize < endpos) {
6355 in->variant.fileVariant.
6356 scannedFileSize = endpos;
6357 in->variant.fileVariant.
6359 in->variant.fileVariant.
6364 /* This chunk has been invalidated by a resize, so delete */
6365 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6369 /* chunkId == 0, so it is an ObjectHeader.
6370 * Thus, we read in the object header and make the object
6372 foundChunksInBlock = 1;
6374 yaffs_SetChunkBit(dev, blk, c);
6380 if (tags.extraHeaderInfoAvailable) {
6381 in = yaffs_FindOrCreateObjectByNumber
6382 (dev, tags.objectId,
6383 tags.extraObjectType);
6389 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
6392 tags.extraShadows ||
6394 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6395 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
6398 /* If we don't have valid info then we need to read the chunk
6399 * TODO In future we can probably defer reading the chunk and
6400 * living with invalid data until needed.
6403 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6408 oh = (yaffs_ObjectHeader *) chunkData;
6410 if(dev->inbandTags){
6411 /* Fix up the header if they got corrupted by inband tags */
6412 oh->shadowsObject = oh->inbandShadowsObject;
6413 oh->isShrink = oh->inbandIsShrink;
6417 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6425 /* TODO Hoosterman we have a problem! */
6426 T(YAFFS_TRACE_ERROR,
6428 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6429 TENDSTR), tags.objectId, chunk));
6434 /* We have already filled this one.
6435 * We have a duplicate that will be discarded, but
6436 * we first have to suck out resize info if it is a file.
6439 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6441 oh-> type == YAFFS_OBJECT_TYPE_FILE)||
6442 (tags.extraHeaderInfoAvailable &&
6443 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
6446 (oh) ? oh->fileSize : tags.
6448 __u32 parentObjectId =
6450 parentObjectId : tags.
6451 extraParentObjectId;
6455 (oh) ? oh->isShrink : tags.
6456 extraIsShrinkHeader;
6458 /* If it is deleted (unlinked at start also means deleted)
6459 * we treat the file size as being zeroed at this point.
6461 if (parentObjectId ==
6462 YAFFS_OBJECTID_DELETED
6463 || parentObjectId ==
6464 YAFFS_OBJECTID_UNLINKED) {
6470 in->variant.fileVariant.
6471 shrinkSize > thisSize) {
6472 in->variant.fileVariant.
6478 bi->hasShrinkHeader = 1;
6482 /* Use existing - destroy this one. */
6483 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6487 if (!in->valid && in->variantType !=
6488 (oh ? oh->type : tags.extraObjectType))
6489 T(YAFFS_TRACE_ERROR, (
6490 TSTR("yaffs tragedy: Bad object type, "
6491 TCONT("%d != %d, for object %d at chunk ")
6492 TCONT("%d during scan")
6494 oh->type : tags.extraObjectType,
6495 in->variantType, tags.objectId,
6499 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6501 YAFFS_OBJECTID_LOSTNFOUND)) {
6502 /* We only load some info, don't fiddle with directory structure */
6506 in->variantType = oh->type;
6508 in->yst_mode = oh->yst_mode;
6509 #ifdef CONFIG_YAFFS_WINCE
6510 in->win_atime[0] = oh->win_atime[0];
6511 in->win_ctime[0] = oh->win_ctime[0];
6512 in->win_mtime[0] = oh->win_mtime[0];
6513 in->win_atime[1] = oh->win_atime[1];
6514 in->win_ctime[1] = oh->win_ctime[1];
6515 in->win_mtime[1] = oh->win_mtime[1];
6517 in->yst_uid = oh->yst_uid;
6518 in->yst_gid = oh->yst_gid;
6519 in->yst_atime = oh->yst_atime;
6520 in->yst_mtime = oh->yst_mtime;
6521 in->yst_ctime = oh->yst_ctime;
6522 in->yst_rdev = oh->yst_rdev;
6526 in->variantType = tags.extraObjectType;
6530 in->hdrChunk = chunk;
6532 } else if (!in->valid) {
6533 /* we need to load this info */
6536 in->hdrChunk = chunk;
6539 in->variantType = oh->type;
6541 in->yst_mode = oh->yst_mode;
6542 #ifdef CONFIG_YAFFS_WINCE
6543 in->win_atime[0] = oh->win_atime[0];
6544 in->win_ctime[0] = oh->win_ctime[0];
6545 in->win_mtime[0] = oh->win_mtime[0];
6546 in->win_atime[1] = oh->win_atime[1];
6547 in->win_ctime[1] = oh->win_ctime[1];
6548 in->win_mtime[1] = oh->win_mtime[1];
6550 in->yst_uid = oh->yst_uid;
6551 in->yst_gid = oh->yst_gid;
6552 in->yst_atime = oh->yst_atime;
6553 in->yst_mtime = oh->yst_mtime;
6554 in->yst_ctime = oh->yst_ctime;
6555 in->yst_rdev = oh->yst_rdev;
6558 if (oh->shadowsObject > 0)
6559 yaffs_HandleShadowedObject(dev,
6565 yaffs_SetObjectName(in, oh->name);
6567 yaffs_FindOrCreateObjectByNumber
6568 (dev, oh->parentObjectId,
6569 YAFFS_OBJECT_TYPE_DIRECTORY);
6571 fileSize = oh->fileSize;
6572 isShrink = oh->isShrink;
6573 equivalentObjectId = oh->equivalentObjectId;
6577 in->variantType = tags.extraObjectType;
6579 yaffs_FindOrCreateObjectByNumber
6580 (dev, tags.extraParentObjectId,
6581 YAFFS_OBJECT_TYPE_DIRECTORY);
6582 fileSize = tags.extraFileLength;
6583 isShrink = tags.extraIsShrinkHeader;
6584 equivalentObjectId = tags.extraEquivalentObjectId;
6593 /* directory stuff...
6597 if (parent && parent->variantType ==
6598 YAFFS_OBJECT_TYPE_UNKNOWN) {
6599 /* Set up as a directory */
6600 parent->variantType =
6601 YAFFS_OBJECT_TYPE_DIRECTORY;
6602 YINIT_LIST_HEAD(&parent->variant.
6605 } else if (!parent || parent->variantType !=
6606 YAFFS_OBJECT_TYPE_DIRECTORY)
6608 /* Hoosterman, another problem....
6609 * We're trying to use a non-directory as a directory
6612 T(YAFFS_TRACE_ERROR,
6614 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6616 parent = dev->lostNFoundDir;
6619 yaffs_AddObjectToDirectory(parent, in);
6621 itsUnlinked = (parent == dev->deletedDir) ||
6622 (parent == dev->unlinkedDir);
6625 /* Mark the block as having a shrinkHeader */
6626 bi->hasShrinkHeader = 1;
6629 /* Note re hardlinks.
6630 * Since we might scan a hardlink before its equivalent object is scanned
6631 * we put them all in a list.
6632 * After scanning is complete, we should have all the objects, so we run
6633 * through this list and fix up all the chains.
6636 switch (in->variantType) {
6637 case YAFFS_OBJECT_TYPE_UNKNOWN:
6638 /* Todo got a problem */
6640 case YAFFS_OBJECT_TYPE_FILE:
6642 if (in->variant.fileVariant.
6643 scannedFileSize < fileSize) {
6644 /* This covers the case where the file size is greater
6645 * than where the data is
6646 * This will happen if the file is resized to be larger
6647 * than its current data extents.
6649 in->variant.fileVariant.fileSize = fileSize;
6650 in->variant.fileVariant.scannedFileSize =
6651 in->variant.fileVariant.fileSize;
6655 in->variant.fileVariant.shrinkSize > fileSize) {
6656 in->variant.fileVariant.shrinkSize = fileSize;
6660 case YAFFS_OBJECT_TYPE_HARDLINK:
6662 in->variant.hardLinkVariant.equivalentObjectId =
6664 in->hardLinks.next =
6665 (struct ylist_head *) hardList;
6669 case YAFFS_OBJECT_TYPE_DIRECTORY:
6672 case YAFFS_OBJECT_TYPE_SPECIAL:
6675 case YAFFS_OBJECT_TYPE_SYMLINK:
6677 in->variant.symLinkVariant.alias =
6678 yaffs_CloneString(oh->
6680 if(!in->variant.symLinkVariant.alias)
6690 } /* End of scanning for each chunk */
6692 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6693 /* If we got this far while scanning, then the block is fully allocated. */
6694 state = YAFFS_BLOCK_STATE_FULL;
6697 bi->blockState = state;
6699 /* Now let's see if it was dirty */
6700 if (bi->pagesInUse == 0 &&
6701 !bi->hasShrinkHeader &&
6702 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6703 yaffs_BlockBecameDirty(dev, blk);
6709 YFREE_ALT(blockIndex);
6713 /* Ok, we've done all the scanning.
6714 * Fix up the hard link chains.
6715 * We should now have scanned all the objects, now it's time to add these
6718 yaffs_HardlinkFixup(dev,hardList);
6721 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6727 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6732 /*------------------------------ Directory Functions ----------------------------- */
6734 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
6736 struct ylist_head *lh;
6737 yaffs_Object *listObj;
6742 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
6747 if(yaffs_SkipVerification(obj->myDev))
6751 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
6756 if(obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
6757 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
6761 /* Iterate through the objects in each hash entry */
6763 ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
6765 listObj = ylist_entry(lh, yaffs_Object, siblings);
6766 yaffs_VerifyObject(listObj);
6773 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR),count));
6779 static void yaffs_VerifyDirectory(yaffs_Object *directory)
6782 struct ylist_head *lh;
6783 yaffs_Object *listObj;
6790 if(yaffs_SkipFullVerification(directory->myDev))
6794 if(directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
6795 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR),directory->variantType));
6799 /* Iterate through the objects in each hash entry */
6801 ylist_for_each(lh, &directory->variant.directoryVariant.children) {
6803 listObj = ylist_entry(lh, yaffs_Object, siblings);
6804 if(listObj->parent != directory){
6805 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR),listObj->parent));
6808 yaffs_VerifyObjectInDirectory(listObj);
6815 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
6817 yaffs_Device *dev = obj->myDev;
6818 yaffs_Object *parent;
6820 yaffs_VerifyObjectInDirectory(obj);
6821 parent = obj->parent;
6823 yaffs_VerifyDirectory(parent);
6825 if(dev && dev->removeObjectCallback)
6826 dev->removeObjectCallback(obj);
6829 ylist_del_init(&obj->siblings);
6832 yaffs_VerifyDirectory(parent);
6837 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
6842 T(YAFFS_TRACE_ALWAYS,
6844 ("tragedy: Trying to add an object to a null pointer directory"
6849 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6850 T(YAFFS_TRACE_ALWAYS,
6852 ("tragedy: Trying to add an object to a non-directory"
6857 if (obj->siblings.prev == NULL) {
6858 /* Not initialised */
6861 } else if (ylist_empty(&obj->siblings)) {
6866 yaffs_VerifyDirectory(directory);
6868 yaffs_RemoveObjectFromDirectory(obj);
6872 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
6873 obj->parent = directory;
6875 if (directory == obj->myDev->unlinkedDir
6876 || directory == obj->myDev->deletedDir) {
6878 obj->myDev->nUnlinkedFiles++;
6879 obj->renameAllowed = 0;
6882 yaffs_VerifyDirectory(directory);
6883 yaffs_VerifyObjectInDirectory(obj);
6888 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
6893 struct ylist_head *i;
6894 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
6903 T(YAFFS_TRACE_ALWAYS,
6905 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6910 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6911 T(YAFFS_TRACE_ALWAYS,
6913 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6917 sum = yaffs_CalcNameSum(name);
6919 ylist_for_each(i, &directory->variant.directoryVariant.children) {
6921 l = ylist_entry(i, yaffs_Object, siblings);
6923 if(l->parent != directory)
6926 yaffs_CheckObjectDetailsLoaded(l);
6928 /* Special case for lost-n-found */
6929 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6930 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
6933 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0){
6934 /* LostnFound chunk called Objxxx
6937 yaffs_GetObjectName(l, buffer,
6938 YAFFS_MAX_NAME_LENGTH);
6939 if (yaffs_strncmp(name, buffer,YAFFS_MAX_NAME_LENGTH) == 0) {
6952 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
6953 int (*fn) (yaffs_Object *))
6955 struct ylist_head *i;
6959 T(YAFFS_TRACE_ALWAYS,
6961 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6966 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6967 T(YAFFS_TRACE_ALWAYS,
6969 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6974 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
6976 l = ylist_entry(i, yaffs_Object, siblings);
6988 /* GetEquivalentObject dereferences any hard links to get to the
6992 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
6994 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
6995 /* We want the object id of the equivalent object, not this one */
6996 obj = obj->variant.hardLinkVariant.equivalentObject;
6997 yaffs_CheckObjectDetailsLoaded(obj);
7003 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
7005 memset(name, 0, buffSize * sizeof(YCHAR));
7007 yaffs_CheckObjectDetailsLoaded(obj);
7009 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7010 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
7011 } else if (obj->hdrChunk <= 0) {
7013 YCHAR numString[20];
7014 YCHAR *x = &numString[19];
7015 unsigned v = obj->objectId;
7019 *x = '0' + (v % 10);
7022 /* make up a name */
7023 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
7024 yaffs_strcat(locName,x);
7025 yaffs_strncpy(name, locName, buffSize - 1);
7028 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
7029 else if (obj->shortName[0]) {
7030 yaffs_strcpy(name, obj->shortName);
7035 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
7037 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
7039 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
7041 if (obj->hdrChunk > 0) {
7042 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
7043 obj->hdrChunk, buffer,
7046 yaffs_strncpy(name, oh->name, buffSize - 1);
7048 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
7051 return yaffs_strlen(name);
7054 int yaffs_GetObjectFileLength(yaffs_Object * obj)
7057 /* Dereference any hard linking */
7058 obj = yaffs_GetEquivalentObject(obj);
7060 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
7061 return obj->variant.fileVariant.fileSize;
7063 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
7064 return yaffs_strlen(obj->variant.symLinkVariant.alias);
7066 /* Only a directory should drop through to here */
7067 return obj->myDev->nDataBytesPerChunk;
7071 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
7074 struct ylist_head *i;
7076 if (!obj->unlinked) {
7077 count++; /* the object itself */
7079 ylist_for_each(i, &obj->hardLinks) {
7080 count++; /* add the hard links; */
7086 int yaffs_GetObjectInode(yaffs_Object * obj)
7088 obj = yaffs_GetEquivalentObject(obj);
7090 return obj->objectId;
7093 unsigned yaffs_GetObjectType(yaffs_Object * obj)
7095 obj = yaffs_GetEquivalentObject(obj);
7097 switch (obj->variantType) {
7098 case YAFFS_OBJECT_TYPE_FILE:
7101 case YAFFS_OBJECT_TYPE_DIRECTORY:
7104 case YAFFS_OBJECT_TYPE_SYMLINK:
7107 case YAFFS_OBJECT_TYPE_HARDLINK:
7110 case YAFFS_OBJECT_TYPE_SPECIAL:
7111 if (S_ISFIFO(obj->yst_mode))
7113 if (S_ISCHR(obj->yst_mode))
7115 if (S_ISBLK(obj->yst_mode))
7117 if (S_ISSOCK(obj->yst_mode))
7125 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
7127 obj = yaffs_GetEquivalentObject(obj);
7128 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
7129 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7131 return yaffs_CloneString(_Y(""));
7135 #ifndef CONFIG_YAFFS_WINCE
7137 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
7139 unsigned int valid = attr->ia_valid;
7141 if (valid & ATTR_MODE)
7142 obj->yst_mode = attr->ia_mode;
7143 if (valid & ATTR_UID)
7144 obj->yst_uid = attr->ia_uid;
7145 if (valid & ATTR_GID)
7146 obj->yst_gid = attr->ia_gid;
7148 if (valid & ATTR_ATIME)
7149 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7150 if (valid & ATTR_CTIME)
7151 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7152 if (valid & ATTR_MTIME)
7153 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7155 if (valid & ATTR_SIZE)
7156 yaffs_ResizeFile(obj, attr->ia_size);
7158 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7163 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
7165 unsigned int valid = 0;
7167 attr->ia_mode = obj->yst_mode;
7169 attr->ia_uid = obj->yst_uid;
7171 attr->ia_gid = obj->yst_gid;
7174 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7175 valid |= ATTR_ATIME;
7176 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7177 valid |= ATTR_CTIME;
7178 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7179 valid |= ATTR_MTIME;
7181 attr->ia_size = yaffs_GetFileSize(obj);
7184 attr->ia_valid = valid;
7193 int yaffs_DumpObject(yaffs_Object * obj)
7197 yaffs_GetObjectName(obj, name, 256);
7199 T(YAFFS_TRACE_ALWAYS,
7201 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7202 " chunk %d type %d size %d\n"
7203 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7204 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7205 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7211 /*---------------------------- Initialisation code -------------------------------------- */
7213 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
7216 /* Common functions, gotta have */
7217 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
7220 #ifdef CONFIG_YAFFS_YAFFS2
7222 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7223 if (dev->writeChunkWithTagsToNAND &&
7224 dev->readChunkWithTagsFromNAND &&
7225 !dev->writeChunkToNAND &&
7226 !dev->readChunkFromNAND &&
7227 dev->markNANDBlockBad && dev->queryNANDBlock)
7231 /* Can use the "spare" style interface for yaffs1 */
7232 if (!dev->isYaffs2 &&
7233 !dev->writeChunkWithTagsToNAND &&
7234 !dev->readChunkWithTagsFromNAND &&
7235 dev->writeChunkToNAND &&
7236 dev->readChunkFromNAND &&
7237 !dev->markNANDBlockBad && !dev->queryNANDBlock)
7244 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7246 /* Initialise the unlinked, deleted, root and lost and found directories */
7248 dev->lostNFoundDir = dev->rootDir = NULL;
7249 dev->unlinkedDir = dev->deletedDir = NULL;
7252 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7255 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7258 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7259 YAFFS_ROOT_MODE | S_IFDIR);
7260 dev->lostNFoundDir =
7261 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7262 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7264 if(dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir){
7265 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7272 int yaffs_GutsInitialise(yaffs_Device * dev)
7274 int init_failed = 0;
7278 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7280 /* Check stuff that must be set */
7283 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7287 dev->internalStartBlock = dev->startBlock;
7288 dev->internalEndBlock = dev->endBlock;
7289 dev->blockOffset = 0;
7290 dev->chunkOffset = 0;
7291 dev->nFreeChunks = 0;
7295 if (dev->startBlock == 0) {
7296 dev->internalStartBlock = dev->startBlock + 1;
7297 dev->internalEndBlock = dev->endBlock + 1;
7298 dev->blockOffset = 1;
7299 dev->chunkOffset = dev->nChunksPerBlock;
7302 /* Check geometry parameters. */
7304 if ((!dev->inbandTags && dev->isYaffs2 && dev->totalBytesPerChunk < 1024) ||
7305 (!dev->isYaffs2 && dev->totalBytesPerChunk < 512) ||
7306 (dev->inbandTags && !dev->isYaffs2 ) ||
7307 dev->nChunksPerBlock < 2 ||
7308 dev->nReservedBlocks < 2 ||
7309 dev->internalStartBlock <= 0 ||
7310 dev->internalEndBlock <= 0 ||
7311 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
7313 T(YAFFS_TRACE_ALWAYS,
7315 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7316 TENDSTR), dev->totalBytesPerChunk, dev->isYaffs2 ? "2" : "", dev->inbandTags));
7320 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7321 T(YAFFS_TRACE_ALWAYS,
7322 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7326 /* Sort out space for inband tags, if required */
7328 dev->nDataBytesPerChunk = dev->totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7330 dev->nDataBytesPerChunk = dev->totalBytesPerChunk;
7332 /* Got the right mix of functions? */
7333 if (!yaffs_CheckDevFunctions(dev)) {
7334 /* Function missing */
7335 T(YAFFS_TRACE_ALWAYS,
7337 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7342 /* This is really a compilation check. */
7343 if (!yaffs_CheckStructures()) {
7344 T(YAFFS_TRACE_ALWAYS,
7345 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7349 if (dev->isMounted) {
7350 T(YAFFS_TRACE_ALWAYS,
7351 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7355 /* Finished with most checks. One or two more checks happen later on too. */
7359 /* OK now calculate a few things for the device */
7362 * Calculate all the chunk size manipulation numbers:
7364 x = dev->nDataBytesPerChunk;
7365 /* We always use dev->chunkShift and dev->chunkDiv */
7366 dev->chunkShift = Shifts(x);
7367 x >>= dev->chunkShift;
7369 /* We only use chunk mask if chunkDiv is 1 */
7370 dev->chunkMask = (1<<dev->chunkShift) - 1;
7373 * Calculate chunkGroupBits.
7374 * We need to find the next power of 2 > than internalEndBlock
7377 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7381 /* Set up tnode width if wide tnodes are enabled. */
7382 if(!dev->wideTnodesDisabled){
7383 /* bits must be even so that we end up with 32-bit words */
7387 dev->tnodeWidth = 16;
7389 dev->tnodeWidth = bits;
7392 dev->tnodeWidth = 16;
7394 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7396 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7397 * so if the bitwidth of the
7398 * chunk range we're using is greater than 16 we need
7399 * to figure out chunk shift and chunkGroupSize
7402 if (bits <= dev->tnodeWidth)
7403 dev->chunkGroupBits = 0;
7405 dev->chunkGroupBits = bits - dev->tnodeWidth;
7408 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7410 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7411 /* We have a problem because the soft delete won't work if
7412 * the chunk group size > chunks per block.
7413 * This can be remedied by using larger "virtual blocks".
7415 T(YAFFS_TRACE_ALWAYS,
7416 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7421 /* OK, we've finished verifying the device, lets continue with initialisation */
7423 /* More device initialisation */
7424 dev->garbageCollections = 0;
7425 dev->passiveGarbageCollections = 0;
7426 dev->currentDirtyChecker = 0;
7427 dev->bufferedBlock = -1;
7428 dev->doingBufferedBlockRewrite = 0;
7429 dev->nDeletedFiles = 0;
7430 dev->nBackgroundDeletions = 0;
7431 dev->nUnlinkedFiles = 0;
7433 dev->eccUnfixed = 0;
7434 dev->tagsEccFixed = 0;
7435 dev->tagsEccUnfixed = 0;
7436 dev->nErasureFailures = 0;
7437 dev->nErasedBlocks = 0;
7439 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7441 /* Initialise temporary buffers and caches. */
7442 if(!yaffs_InitialiseTempBuffers(dev))
7445 dev->srCache = NULL;
7446 dev->gcCleanupList = NULL;
7450 dev->nShortOpCaches > 0) {
7453 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7455 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
7456 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7459 dev->srCache = YMALLOC(srCacheBytes);
7461 buf = (__u8 *) dev->srCache;
7464 memset(dev->srCache,0,srCacheBytes);
7466 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7467 dev->srCache[i].object = NULL;
7468 dev->srCache[i].lastUse = 0;
7469 dev->srCache[i].dirty = 0;
7470 dev->srCache[i].data = buf = YMALLOC_DMA(dev->totalBytesPerChunk);
7481 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7482 if(!dev->gcCleanupList)
7486 if (dev->isYaffs2) {
7487 dev->useHeaderFileSize = 1;
7489 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7492 yaffs_InitialiseTnodes(dev);
7493 yaffs_InitialiseObjects(dev);
7495 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7500 /* Now scan the flash. */
7501 if (dev->isYaffs2) {
7502 if(yaffs_CheckpointRestore(dev)) {
7503 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7504 T(YAFFS_TRACE_ALWAYS,
7505 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7508 /* Clean up the mess caused by an aborted checkpoint load
7509 * and scan backwards.
7511 yaffs_DeinitialiseBlocks(dev);
7512 yaffs_DeinitialiseTnodes(dev);
7513 yaffs_DeinitialiseObjects(dev);
7516 dev->nErasedBlocks = 0;
7517 dev->nFreeChunks = 0;
7518 dev->allocationBlock = -1;
7519 dev->allocationPage = -1;
7520 dev->nDeletedFiles = 0;
7521 dev->nUnlinkedFiles = 0;
7522 dev->nBackgroundDeletions = 0;
7523 dev->oldestDirtySequence = 0;
7525 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7528 yaffs_InitialiseTnodes(dev);
7529 yaffs_InitialiseObjects(dev);
7531 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7534 if(!init_failed && !yaffs_ScanBackwards(dev))
7538 if(!yaffs_Scan(dev))
7541 yaffs_StripDeletedObjects(dev);
7545 /* Clean up the mess */
7546 T(YAFFS_TRACE_TRACING,
7547 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7549 yaffs_Deinitialise(dev);
7553 /* Zero out stats */
7554 dev->nPageReads = 0;
7555 dev->nPageWrites = 0;
7556 dev->nBlockErasures = 0;
7558 dev->nRetriedWrites = 0;
7560 dev->nRetiredBlocks = 0;
7562 yaffs_VerifyFreeChunks(dev);
7563 yaffs_VerifyBlocks(dev);
7566 T(YAFFS_TRACE_TRACING,
7567 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7572 void yaffs_Deinitialise(yaffs_Device * dev)
7574 if (dev->isMounted) {
7577 yaffs_DeinitialiseBlocks(dev);
7578 yaffs_DeinitialiseTnodes(dev);
7579 yaffs_DeinitialiseObjects(dev);
7580 if (dev->nShortOpCaches > 0 &&
7583 for (i = 0; i < dev->nShortOpCaches; i++) {
7584 if(dev->srCache[i].data)
7585 YFREE(dev->srCache[i].data);
7586 dev->srCache[i].data = NULL;
7589 YFREE(dev->srCache);
7590 dev->srCache = NULL;
7593 YFREE(dev->gcCleanupList);
7595 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
7596 YFREE(dev->tempBuffer[i].buffer);
7602 if(dev->deinitialiseNAND)
7603 dev->deinitialiseNAND(dev);
7608 static int yaffs_CountFreeChunks(yaffs_Device * dev)
7613 yaffs_BlockInfo *blk;
7615 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7617 blk = yaffs_GetBlockInfo(dev, b);
7619 switch (blk->blockState) {
7620 case YAFFS_BLOCK_STATE_EMPTY:
7621 case YAFFS_BLOCK_STATE_ALLOCATING:
7622 case YAFFS_BLOCK_STATE_COLLECTING:
7623 case YAFFS_BLOCK_STATE_FULL:
7625 (dev->nChunksPerBlock - blk->pagesInUse +
7626 blk->softDeletions);
7637 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
7639 /* This is what we report to the outside world */
7642 int nDirtyCacheChunks;
7643 int blocksForCheckpoint;
7646 nFree = dev->nFreeChunks;
7648 nFree = yaffs_CountFreeChunks(dev);
7651 nFree += dev->nDeletedFiles;
7653 /* Now count the number of dirty chunks in the cache and subtract those */
7657 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7658 if (dev->srCache[i].dirty)
7659 nDirtyCacheChunks++;
7663 nFree -= nDirtyCacheChunks;
7665 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7667 /* Now we figure out how much to reserve for the checkpoint and report that... */
7668 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7669 if(blocksForCheckpoint < 0)
7670 blocksForCheckpoint = 0;
7672 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7681 static int yaffs_freeVerificationFailures;
7683 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
7688 if(yaffs_SkipVerification(dev))
7691 counted = yaffs_CountFreeChunks(dev);
7693 difference = dev->nFreeChunks - counted;
7696 T(YAFFS_TRACE_ALWAYS,
7697 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7698 dev->nFreeChunks, counted, difference));
7699 yaffs_freeVerificationFailures++;
7703 /*---------------------------------------- YAFFS test code ----------------------*/
7705 #define yaffs_CheckStruct(structure,syze, name) \
7707 if(sizeof(structure) != syze) \
7709 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
7710 name,syze,sizeof(structure))); \
7711 return YAFFS_FAIL; \
7715 static int yaffs_CheckStructures(void)
7717 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
7718 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
7719 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
7720 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7721 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode");
7723 #ifndef CONFIG_YAFFS_WINCE
7724 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");