2 * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
4 * Copyright (C) 2002-2007 Aleph One Ltd.
5 * for Toby Churchill Ltd and Brightstar Engineering
7 * Created by Charles Manning <charles@aleph1.co.uk>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2 as
11 * published by the Free Software Foundation.
15 const char *yaffs_guts_c_version =
16 "$Id: yaffs_guts.c,v 1.76 2009-01-23 06:36:49 charles Exp $";
20 #include "yaffsinterface.h"
21 #include "yaffs_guts.h"
22 #include "yaffs_tagsvalidity.h"
23 #include "yaffs_getblockinfo.h"
25 #include "yaffs_tagscompat.h"
26 #ifndef CONFIG_YAFFS_USE_OWN_SORT
27 #include "yaffs_qsort.h"
29 #include "yaffs_nand.h"
31 #include "yaffs_checkptrw.h"
33 #include "yaffs_nand.h"
34 #include "yaffs_packedtags2.h"
37 #define YAFFS_PASSIVE_GC_CHUNKS 2
39 #include "yaffs_ecc.h"
42 /* Robustification (if it ever comes about...) */
43 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
44 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk);
45 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
47 const yaffs_ExtendedTags * tags);
48 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
49 const yaffs_ExtendedTags * tags);
51 /* Other local prototypes */
52 static int yaffs_UnlinkObject( yaffs_Object *obj);
53 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
55 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
57 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
59 yaffs_ExtendedTags * tags,
61 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
62 int chunkInNAND, int inScan);
64 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
65 yaffs_ObjectType type);
66 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
68 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
69 int force, int isShrink, int shadows);
70 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
71 static int yaffs_CheckStructures(void);
72 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
73 int chunkOffset, int *limit);
74 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
76 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
79 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
82 static int yaffs_UnlinkWorker(yaffs_Object * obj);
83 static void yaffs_DestroyObject(yaffs_Object * obj);
85 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
88 loff_t yaffs_GetFileSize(yaffs_Object * obj);
90 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr);
92 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
94 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
96 static void yaffs_VerifyDirectory(yaffs_Object *directory);
98 static int yaffs_CheckFileSanity(yaffs_Object * in);
100 #define yaffs_CheckFileSanity(in)
103 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
104 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
106 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
108 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
109 yaffs_ExtendedTags * tags);
111 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos);
112 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
113 yaffs_FileStructure * fStruct,
117 /* Function to calculate chunk and offset */
119 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut, __u32 *offsetOut)
124 chunk = (__u32)(addr >> dev->chunkShift);
126 if(dev->chunkDiv == 1)
128 /* easy power of 2 case */
129 offset = (__u32)(addr & dev->chunkMask);
133 /* Non power-of-2 case */
137 chunk /= dev->chunkDiv;
139 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
140 offset = (__u32)(addr - chunkBase);
147 /* Function to return the number of shifts for a power of 2 greater than or equal
148 * to the given number
149 * Note we don't try to cater for all possible numbers and this does not have to
150 * be hellishly efficient.
153 static __u32 ShiftsGE(__u32 x)
158 nShifts = extraBits = 0;
161 if(x & 1) extraBits++;
172 /* Function to return the number of shifts to get a 1 in bit 0
175 static __u32 Shifts(__u32 x)
194 * Temporary buffer manipulations.
197 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
200 __u8 *buf = (__u8 *)1;
202 memset(dev->tempBuffer,0,sizeof(dev->tempBuffer));
204 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
205 dev->tempBuffer[i].line = 0; /* not in use */
206 dev->tempBuffer[i].buffer = buf =
207 YMALLOC_DMA(dev->totalBytesPerChunk);
210 return buf ? YAFFS_OK : YAFFS_FAIL;
214 __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
219 if(dev->tempInUse > dev->maxTemp)
220 dev->maxTemp = dev->tempInUse;
222 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
223 if (dev->tempBuffer[i].line == 0) {
224 dev->tempBuffer[i].line = lineNo;
225 if ((i + 1) > dev->maxTemp) {
226 dev->maxTemp = i + 1;
227 for (j = 0; j <= i; j++)
228 dev->tempBuffer[j].maxLine =
229 dev->tempBuffer[j].line;
232 return dev->tempBuffer[i].buffer;
236 T(YAFFS_TRACE_BUFFERS,
237 (TSTR("Out of temp buffers at line %d, other held by lines:"),
239 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
240 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
242 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
245 * If we got here then we have to allocate an unmanaged one
249 dev->unmanagedTempAllocations++;
250 return YMALLOC(dev->nDataBytesPerChunk);
254 void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
261 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
262 if (dev->tempBuffer[i].buffer == buffer) {
263 dev->tempBuffer[i].line = 0;
269 /* assume it is an unmanaged one. */
270 T(YAFFS_TRACE_BUFFERS,
271 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
274 dev->unmanagedTempDeallocations++;
280 * Determine if we have a managed buffer.
282 int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
285 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
286 if (dev->tempBuffer[i].buffer == buffer)
291 for (i = 0; i < dev->nShortOpCaches; i++) {
292 if( dev->srCache[i].data == buffer )
297 if (buffer == dev->checkpointBuffer)
300 T(YAFFS_TRACE_ALWAYS,
301 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
308 * Chunk bitmap manipulations
311 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
313 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
315 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
319 return dev->chunkBits +
320 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
323 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
325 if(blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
326 chunk < 0 || chunk >= dev->nChunksPerBlock) {
328 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),blk,chunk));
333 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
335 __u8 *blkBits = yaffs_BlockBits(dev, blk);
337 memset(blkBits, 0, dev->chunkBitmapStride);
340 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
342 __u8 *blkBits = yaffs_BlockBits(dev, blk);
344 yaffs_VerifyChunkBitId(dev,blk,chunk);
346 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
349 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
351 __u8 *blkBits = yaffs_BlockBits(dev, blk);
353 yaffs_VerifyChunkBitId(dev,blk,chunk);
355 blkBits[chunk / 8] |= (1 << (chunk & 7));
358 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
360 __u8 *blkBits = yaffs_BlockBits(dev, blk);
361 yaffs_VerifyChunkBitId(dev,blk,chunk);
363 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
366 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
368 __u8 *blkBits = yaffs_BlockBits(dev, blk);
370 for (i = 0; i < dev->chunkBitmapStride; i++) {
378 static int yaffs_CountChunkBits(yaffs_Device * dev, int blk)
380 __u8 *blkBits = yaffs_BlockBits(dev, blk);
383 for (i = 0; i < dev->chunkBitmapStride; i++) {
400 static int yaffs_SkipVerification(yaffs_Device *dev)
402 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
405 static int yaffs_SkipFullVerification(yaffs_Device *dev)
407 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
410 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
412 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
415 static const char * blockStateName[] = {
428 static void yaffs_VerifyBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
433 if(yaffs_SkipVerification(dev))
436 /* Report illegal runtime states */
437 if(bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
438 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has undefined state %d"TENDSTR),n,bi->blockState));
440 switch(bi->blockState){
441 case YAFFS_BLOCK_STATE_UNKNOWN:
442 case YAFFS_BLOCK_STATE_SCANNING:
443 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
444 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has bad run-state %s"TENDSTR),
445 n,blockStateName[bi->blockState]));
448 /* Check pages in use and soft deletions are legal */
450 actuallyUsed = bi->pagesInUse - bi->softDeletions;
452 if(bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
453 bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
454 actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock)
455 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
456 n,bi->pagesInUse,bi->softDeletions));
459 /* Check chunk bitmap legal */
460 inUse = yaffs_CountChunkBits(dev,n);
461 if(inUse != bi->pagesInUse)
462 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
463 n,bi->pagesInUse,inUse));
465 /* Check that the sequence number is valid.
466 * Ten million is legal, but is very unlikely
469 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
470 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000 ))
471 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has suspect sequence number of %d"TENDSTR),
472 n,bi->sequenceNumber));
476 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
478 yaffs_VerifyBlock(dev,bi,n);
480 /* After collection the block should be in the erased state */
481 /* This will need to change if we do partial gc */
483 if(bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
484 bi->blockState != YAFFS_BLOCK_STATE_EMPTY){
485 T(YAFFS_TRACE_ERROR,(TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
490 static void yaffs_VerifyBlocks(yaffs_Device *dev)
493 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
494 int nIllegalBlockStates = 0;
497 if(yaffs_SkipVerification(dev))
500 memset(nBlocksPerState,0,sizeof(nBlocksPerState));
503 for(i = dev->internalStartBlock; i <= dev->internalEndBlock; i++){
504 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
505 yaffs_VerifyBlock(dev,bi,i);
507 if(bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
508 nBlocksPerState[bi->blockState]++;
510 nIllegalBlockStates++;
514 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
515 T(YAFFS_TRACE_VERIFY,(TSTR("Block summary"TENDSTR)));
517 T(YAFFS_TRACE_VERIFY,(TSTR("%d blocks have illegal states"TENDSTR),nIllegalBlockStates));
518 if(nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
519 T(YAFFS_TRACE_VERIFY,(TSTR("Too many allocating blocks"TENDSTR)));
521 for(i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
522 T(YAFFS_TRACE_VERIFY,
523 (TSTR("%s %d blocks"TENDSTR),
524 blockStateName[i],nBlocksPerState[i]));
526 if(dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
527 T(YAFFS_TRACE_VERIFY,
528 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
529 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
531 if(dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
532 T(YAFFS_TRACE_VERIFY,
533 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
534 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
536 if(nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
537 T(YAFFS_TRACE_VERIFY,
538 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
539 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
541 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
546 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
547 * case those tests will not be performed.
549 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
551 if(obj && yaffs_SkipVerification(obj->myDev))
554 if(!(tags && obj && oh)){
555 T(YAFFS_TRACE_VERIFY,
556 (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR),
557 (__u32)tags,(__u32)obj,(__u32)oh));
561 if(oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
562 oh->type > YAFFS_OBJECT_TYPE_MAX)
563 T(YAFFS_TRACE_VERIFY,
564 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
565 tags->objectId, oh->type));
567 if(tags->objectId != obj->objectId)
568 T(YAFFS_TRACE_VERIFY,
569 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
570 tags->objectId, obj->objectId));
574 * Check that the object's parent ids match if parentCheck requested.
576 * Tests do not apply to the root object.
579 if(parentCheck && tags->objectId > 1 && !obj->parent)
580 T(YAFFS_TRACE_VERIFY,
581 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
582 tags->objectId, oh->parentObjectId));
585 if(parentCheck && obj->parent &&
586 oh->parentObjectId != obj->parent->objectId &&
587 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
588 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
589 T(YAFFS_TRACE_VERIFY,
590 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
591 tags->objectId, oh->parentObjectId, obj->parent->objectId));
594 if(tags->objectId > 1 && oh->name[0] == 0) /* Null name */
595 T(YAFFS_TRACE_VERIFY,
596 (TSTR("Obj %d header name is NULL"TENDSTR),
599 if(tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
600 T(YAFFS_TRACE_VERIFY,
601 (TSTR("Obj %d header name is 0xFF"TENDSTR),
607 static int yaffs_VerifyTnodeWorker(yaffs_Object * obj, yaffs_Tnode * tn,
608 __u32 level, int chunkOffset)
611 yaffs_Device *dev = obj->myDev;
617 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
618 if (tn->internal[i]) {
619 ok = yaffs_VerifyTnodeWorker(obj,
622 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
625 } else if (level == 0) {
626 yaffs_ExtendedTags tags;
627 __u32 objectId = obj->objectId;
629 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
631 for(i = 0; i < YAFFS_NTNODES_LEVEL0; i++){
632 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
635 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
636 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
637 if(tags.objectId != objectId || tags.chunkId != chunkOffset){
638 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
639 objectId, chunkOffset, theChunk,
640 tags.objectId, tags.chunkId));
653 static void yaffs_VerifyFile(yaffs_Object *obj)
655 int requiredTallness;
661 yaffs_ExtendedTags tags;
668 if(yaffs_SkipVerification(obj->myDev))
672 objectId = obj->objectId;
674 /* Check file size is consistent with tnode depth */
675 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
676 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
677 requiredTallness = 0;
679 x >>= YAFFS_TNODES_INTERNAL_BITS;
683 actualTallness = obj->variant.fileVariant.topLevel;
685 if(requiredTallness > actualTallness )
686 T(YAFFS_TRACE_VERIFY,
687 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
688 obj->objectId,actualTallness, requiredTallness));
691 /* Check that the chunks in the tnode tree are all correct.
692 * We do this by scanning through the tnode tree and
693 * checking the tags for every chunk match.
696 if(yaffs_SkipNANDVerification(dev))
699 for(i = 1; i <= lastChunk; i++){
700 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant,i);
703 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
705 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
706 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
707 if(tags.objectId != objectId || tags.chunkId != i){
708 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
709 objectId, i, theChunk,
710 tags.objectId, tags.chunkId));
720 static void yaffs_VerifyHardLink(yaffs_Object *obj)
722 if(obj && yaffs_SkipVerification(obj->myDev))
725 /* Verify sane equivalent object */
728 static void yaffs_VerifySymlink(yaffs_Object *obj)
730 if(obj && yaffs_SkipVerification(obj->myDev))
733 /* Verify symlink string */
736 static void yaffs_VerifySpecial(yaffs_Object *obj)
738 if(obj && yaffs_SkipVerification(obj->myDev))
742 static void yaffs_VerifyObject(yaffs_Object *obj)
751 __u32 chunkShouldNotBeDeleted;
757 if(obj->beingCreated)
762 if(yaffs_SkipVerification(dev))
765 /* Check sane object header chunk */
767 chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
768 chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
770 chunkInRange = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
771 chunkIdOk = chunkInRange || obj->hdrChunk == 0;
772 chunkValid = chunkInRange &&
773 yaffs_CheckChunkBit(dev,
774 obj->hdrChunk / dev->nChunksPerBlock,
775 obj->hdrChunk % dev->nChunksPerBlock);
776 chunkShouldNotBeDeleted = chunkInRange && !chunkValid;
779 (!chunkIdOk || chunkShouldNotBeDeleted)) {
780 T(YAFFS_TRACE_VERIFY,
781 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
782 obj->objectId,obj->hdrChunk,
783 chunkIdOk ? "" : ",out of range",
784 chunkShouldNotBeDeleted ? ",marked as deleted" : ""));
787 if(chunkValid &&!yaffs_SkipNANDVerification(dev)) {
788 yaffs_ExtendedTags tags;
789 yaffs_ObjectHeader *oh;
790 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
792 oh = (yaffs_ObjectHeader *)buffer;
794 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk,buffer, &tags);
796 yaffs_VerifyObjectHeader(obj,oh,&tags,1);
798 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
801 /* Verify it has a parent */
802 if(obj && !obj->fake &&
803 (!obj->parent || obj->parent->myDev != dev)){
804 T(YAFFS_TRACE_VERIFY,
805 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
806 obj->objectId,obj->parent));
809 /* Verify parent is a directory */
810 if(obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
811 T(YAFFS_TRACE_VERIFY,
812 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
813 obj->objectId,obj->parent->variantType));
816 switch(obj->variantType){
817 case YAFFS_OBJECT_TYPE_FILE:
818 yaffs_VerifyFile(obj);
820 case YAFFS_OBJECT_TYPE_SYMLINK:
821 yaffs_VerifySymlink(obj);
823 case YAFFS_OBJECT_TYPE_DIRECTORY:
824 yaffs_VerifyDirectory(obj);
826 case YAFFS_OBJECT_TYPE_HARDLINK:
827 yaffs_VerifyHardLink(obj);
829 case YAFFS_OBJECT_TYPE_SPECIAL:
830 yaffs_VerifySpecial(obj);
832 case YAFFS_OBJECT_TYPE_UNKNOWN:
834 T(YAFFS_TRACE_VERIFY,
835 (TSTR("Obj %d has illegaltype %d"TENDSTR),
836 obj->objectId,obj->variantType));
843 static void yaffs_VerifyObjects(yaffs_Device *dev)
847 struct ylist_head *lh;
849 if(yaffs_SkipVerification(dev))
852 /* Iterate through the objects in each hash entry */
854 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++){
855 ylist_for_each(lh, &dev->objectBucket[i].list) {
857 obj = ylist_entry(lh, yaffs_Object, hashLink);
858 yaffs_VerifyObject(obj);
867 * Simple hash function. Needs to have a reasonable spread
870 static Y_INLINE int yaffs_HashFunction(int n)
873 return (n % YAFFS_NOBJECT_BUCKETS);
877 * Access functions to useful fake objects.
878 * Note that root might have a presence in NAND if permissions are set.
881 yaffs_Object *yaffs_Root(yaffs_Device * dev)
886 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
888 return dev->lostNFoundDir;
893 * Erased NAND checking functions
896 int yaffs_CheckFF(__u8 * buffer, int nBytes)
898 /* Horrible, slow implementation */
907 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
911 int retval = YAFFS_OK;
912 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
913 yaffs_ExtendedTags tags;
916 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
918 if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
922 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
923 T(YAFFS_TRACE_NANDACCESS,
924 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
928 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
934 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
936 yaffs_ExtendedTags * tags,
943 yaffs_InvalidateCheckpoint(dev);
946 yaffs_BlockInfo *bi = 0;
949 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
955 /* First check this chunk is erased, if it needs
956 * checking. The checking policy (unless forced
957 * always on) is as follows:
959 * Check the first page we try to write in a block.
960 * If the check passes then we don't need to check any
961 * more. If the check fails, we check again...
962 * If the block has been erased, we don't need to check.
964 * However, if the block has been prioritised for gc,
965 * then we think there might be something odd about
966 * this block and stop using it.
968 * Rationale: We should only ever see chunks that have
969 * not been erased if there was a partially written
970 * chunk due to power loss. This checking policy should
971 * catch that case with very few checks and thus save a
972 * lot of checks that are most likely not needed.
974 if (bi->gcPrioritise) {
975 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
976 /* try another chunk */
980 /* let's give it a try */
983 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
984 bi->skipErasedCheck = 0;
986 if (!bi->skipErasedCheck) {
987 erasedOk = yaffs_CheckChunkErased(dev, chunk);
988 if (erasedOk != YAFFS_OK) {
990 (TSTR ("**>> yaffs chunk %d was not erased"
993 /* try another chunk */
996 bi->skipErasedCheck = 1;
999 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
1001 if (writeOk != YAFFS_OK) {
1002 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
1003 /* try another chunk */
1007 /* Copy the data into the robustification buffer */
1008 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1010 } while (writeOk != YAFFS_OK &&
1011 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1017 T(YAFFS_TRACE_ERROR,
1018 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1021 dev->nRetriedWrites += (attempts - 1);
1028 * Block retiring for handling a broken block.
1031 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
1033 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1035 yaffs_InvalidateCheckpoint(dev);
1037 yaffs_MarkBlockBad(dev, blockInNAND);
1039 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1040 bi->gcPrioritise = 0;
1041 bi->needsRetiring = 0;
1043 dev->nRetiredBlocks++;
1047 * Functions for robustisizing TODO
1051 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
1053 const yaffs_ExtendedTags * tags)
1057 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
1058 const yaffs_ExtendedTags * tags)
1062 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1064 if(!bi->gcPrioritise){
1065 bi->gcPrioritise = 1;
1066 dev->hasPendingPrioritisedGCs = 1;
1067 bi->chunkErrorStrikes ++;
1069 if(bi->chunkErrorStrikes > 3){
1070 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1071 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1078 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
1081 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1082 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1084 yaffs_HandleChunkError(dev,bi);
1088 /* Was an actual write failure, so mark the block for retirement */
1089 bi->needsRetiring = 1;
1090 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1091 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1096 /* Delete the chunk */
1097 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1101 /*---------------- Name handling functions ------------*/
1103 static __u16 yaffs_CalcNameSum(const YCHAR * name)
1108 const YUCHAR *bname = (const YUCHAR *) name;
1110 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1112 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1113 sum += yaffs_toupper(*bname) * i;
1115 sum += (*bname) * i;
1125 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
1127 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1128 memset(obj->shortName,0,sizeof (YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1129 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
1130 yaffs_strcpy(obj->shortName, name);
1132 obj->shortName[0] = _Y('\0');
1135 obj->sum = yaffs_CalcNameSum(name);
1138 /*-------------------- TNODES -------------------
1140 * List of spare tnodes
1141 * The list is hooked together using the first pointer
1145 /* yaffs_CreateTnodes creates a bunch more tnodes and
1146 * adds them to the tnode free list.
1147 * Don't use this function directly
1150 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
1154 yaffs_Tnode *newTnodes;
1158 yaffs_TnodeList *tnl;
1163 /* Calculate the tnode size in bytes for variable width tnode support.
1164 * Must be a multiple of 32-bits */
1165 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1167 if(tnodeSize < sizeof(yaffs_Tnode))
1168 tnodeSize = sizeof(yaffs_Tnode);
1171 /* make these things */
1173 newTnodes = YMALLOC(nTnodes * tnodeSize);
1174 mem = (__u8 *)newTnodes;
1177 T(YAFFS_TRACE_ERROR,
1178 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1182 /* Hook them into the free list */
1184 for (i = 0; i < nTnodes - 1; i++) {
1185 newTnodes[i].internal[0] = &newTnodes[i + 1];
1186 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1187 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1191 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1192 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1193 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1195 dev->freeTnodes = newTnodes;
1197 /* New hookup for wide tnodes */
1198 for(i = 0; i < nTnodes -1; i++) {
1199 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1200 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1201 curr->internal[0] = next;
1204 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1205 curr->internal[0] = dev->freeTnodes;
1206 dev->freeTnodes = (yaffs_Tnode *)mem;
1211 dev->nFreeTnodes += nTnodes;
1212 dev->nTnodesCreated += nTnodes;
1214 /* Now add this bunch of tnodes to a list for freeing up.
1215 * NB If we can't add this to the management list it isn't fatal
1216 * but it just means we can't free this bunch of tnodes later.
1219 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1221 T(YAFFS_TRACE_ERROR,
1223 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1227 tnl->tnodes = newTnodes;
1228 tnl->next = dev->allocatedTnodeList;
1229 dev->allocatedTnodeList = tnl;
1232 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1237 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1239 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
1241 yaffs_Tnode *tn = NULL;
1243 /* If there are none left make more */
1244 if (!dev->freeTnodes) {
1245 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1248 if (dev->freeTnodes) {
1249 tn = dev->freeTnodes;
1250 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1251 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1252 /* Hoosterman, this thing looks like it isn't in the list */
1253 T(YAFFS_TRACE_ALWAYS,
1254 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1257 dev->freeTnodes = dev->freeTnodes->internal[0];
1261 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1266 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
1268 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1269 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1271 if(tnodeSize < sizeof(yaffs_Tnode))
1272 tnodeSize = sizeof(yaffs_Tnode);
1275 memset(tn, 0, tnodeSize);
1280 /* FreeTnode frees up a tnode and puts it back on the free list */
1281 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
1284 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1285 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1286 /* Hoosterman, this thing looks like it is already in the list */
1287 T(YAFFS_TRACE_ALWAYS,
1288 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1290 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1292 tn->internal[0] = dev->freeTnodes;
1293 dev->freeTnodes = tn;
1296 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1300 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
1302 /* Free the list of allocated tnodes */
1303 yaffs_TnodeList *tmp;
1305 while (dev->allocatedTnodeList) {
1306 tmp = dev->allocatedTnodeList->next;
1308 YFREE(dev->allocatedTnodeList->tnodes);
1309 YFREE(dev->allocatedTnodeList);
1310 dev->allocatedTnodeList = tmp;
1314 dev->freeTnodes = NULL;
1315 dev->nFreeTnodes = 0;
1318 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
1320 dev->allocatedTnodeList = NULL;
1321 dev->freeTnodes = NULL;
1322 dev->nFreeTnodes = 0;
1323 dev->nTnodesCreated = 0;
1328 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
1330 __u32 *map = (__u32 *)tn;
1336 pos &= YAFFS_TNODES_LEVEL0_MASK;
1337 val >>= dev->chunkGroupBits;
1339 bitInMap = pos * dev->tnodeWidth;
1340 wordInMap = bitInMap /32;
1341 bitInWord = bitInMap & (32 -1);
1343 mask = dev->tnodeMask << bitInWord;
1345 map[wordInMap] &= ~mask;
1346 map[wordInMap] |= (mask & (val << bitInWord));
1348 if(dev->tnodeWidth > (32-bitInWord)) {
1349 bitInWord = (32 - bitInWord);
1351 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1352 map[wordInMap] &= ~mask;
1353 map[wordInMap] |= (mask & (val >> bitInWord));
1357 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
1359 __u32 *map = (__u32 *)tn;
1365 pos &= YAFFS_TNODES_LEVEL0_MASK;
1367 bitInMap = pos * dev->tnodeWidth;
1368 wordInMap = bitInMap /32;
1369 bitInWord = bitInMap & (32 -1);
1371 val = map[wordInMap] >> bitInWord;
1373 if(dev->tnodeWidth > (32-bitInWord)) {
1374 bitInWord = (32 - bitInWord);
1376 val |= (map[wordInMap] << bitInWord);
1379 val &= dev->tnodeMask;
1380 val <<= dev->chunkGroupBits;
1385 /* ------------------- End of individual tnode manipulation -----------------*/
1387 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1388 * The look up tree is represented by the top tnode and the number of topLevel
1389 * in the tree. 0 means only the level 0 tnode is in the tree.
1392 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1393 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
1394 yaffs_FileStructure * fStruct,
1398 yaffs_Tnode *tn = fStruct->top;
1400 int requiredTallness;
1401 int level = fStruct->topLevel;
1403 /* Check sane level and chunk Id */
1404 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
1408 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1412 /* First check we're tall enough (ie enough topLevel) */
1414 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1415 requiredTallness = 0;
1417 i >>= YAFFS_TNODES_INTERNAL_BITS;
1421 if (requiredTallness > fStruct->topLevel) {
1422 /* Not tall enough, so we can't find it, return NULL. */
1426 /* Traverse down to level 0 */
1427 while (level > 0 && tn) {
1429 internal[(chunkId >>
1430 ( YAFFS_TNODES_LEVEL0_BITS +
1432 YAFFS_TNODES_INTERNAL_BITS)
1434 YAFFS_TNODES_INTERNAL_MASK];
1442 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1443 * This happens in two steps:
1444 * 1. If the tree isn't tall enough, then make it taller.
1445 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1447 * Used when modifying the tree.
1449 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1450 * be plugged into the ttree.
1453 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
1454 yaffs_FileStructure * fStruct,
1456 yaffs_Tnode *passedTn)
1459 int requiredTallness;
1467 /* Check sane level and page Id */
1468 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
1472 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1476 /* First check we're tall enough (ie enough topLevel) */
1478 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1479 requiredTallness = 0;
1481 x >>= YAFFS_TNODES_INTERNAL_BITS;
1486 if (requiredTallness > fStruct->topLevel) {
1487 /* Not tall enough,gotta make the tree taller */
1488 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1490 tn = yaffs_GetTnode(dev);
1493 tn->internal[0] = fStruct->top;
1496 T(YAFFS_TRACE_ERROR,
1497 (TSTR("yaffs: no more tnodes" TENDSTR)));
1501 fStruct->topLevel = requiredTallness;
1504 /* Traverse down to level 0, adding anything we need */
1506 l = fStruct->topLevel;
1510 while (l > 0 && tn) {
1512 ( YAFFS_TNODES_LEVEL0_BITS +
1513 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1514 YAFFS_TNODES_INTERNAL_MASK;
1517 if((l>1) && !tn->internal[x]){
1518 /* Add missing non-level-zero tnode */
1519 tn->internal[x] = yaffs_GetTnode(dev);
1522 /* Looking from level 1 at level 0 */
1524 /* If we already have one, then release it.*/
1526 yaffs_FreeTnode(dev,tn->internal[x]);
1527 tn->internal[x] = passedTn;
1529 } else if(!tn->internal[x]) {
1530 /* Don't have one, none passed in */
1531 tn->internal[x] = yaffs_GetTnode(dev);
1535 tn = tn->internal[x];
1539 /* top is level 0 */
1541 memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1542 yaffs_FreeTnode(dev,passedTn);
1549 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1550 yaffs_ExtendedTags * tags, int objectId,
1555 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1556 if (yaffs_CheckChunkBit
1557 (dev, theChunk / dev->nChunksPerBlock,
1558 theChunk % dev->nChunksPerBlock)) {
1559 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1561 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1573 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1574 * chunks and tnodes in the file
1575 * Returns 1 if the tree was deleted.
1576 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1579 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1580 int chunkOffset, int *limit)
1585 yaffs_ExtendedTags tags;
1587 yaffs_Device *dev = in->myDev;
1594 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1596 if (tn->internal[i]) {
1597 if (limit && (*limit) < 0) {
1601 yaffs_DeleteWorker(in,
1609 YAFFS_TNODES_INTERNAL_BITS)
1614 yaffs_FreeTnode(dev,
1617 tn->internal[i] = NULL;
1622 return (allDone) ? 1 : 0;
1623 } else if (level == 0) {
1626 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1628 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1633 YAFFS_TNODES_LEVEL0_BITS) + i;
1636 yaffs_FindChunkInGroup(dev,
1642 if (foundChunk > 0) {
1643 yaffs_DeleteChunk(dev,
1648 *limit = *limit - 1;
1656 yaffs_PutLevel0Tnode(dev,tn,i,0);
1660 return (i < 0) ? 1 : 0;
1670 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1673 yaffs_BlockInfo *theBlock;
1675 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1677 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1679 theBlock->softDeletions++;
1684 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1685 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1687 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1690 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1691 __u32 level, int chunkOffset)
1696 yaffs_Device *dev = in->myDev;
1701 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1703 if (tn->internal[i]) {
1705 yaffs_SoftDeleteWorker(in,
1711 YAFFS_TNODES_INTERNAL_BITS)
1714 yaffs_FreeTnode(dev,
1717 tn->internal[i] = NULL;
1719 /* Hoosterman... how could this happen? */
1723 return (allDone) ? 1 : 0;
1724 } else if (level == 0) {
1726 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1727 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1729 /* Note this does not find the real chunk, only the chunk group.
1730 * We make an assumption that a chunk group is not larger than
1733 yaffs_SoftDeleteChunk(dev, theChunk);
1734 yaffs_PutLevel0Tnode(dev,tn,i,0);
1748 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1751 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1752 if (obj->nDataChunks <= 0) {
1753 /* Empty file with no duplicate object headers, just delete it immediately */
1754 yaffs_FreeTnode(obj->myDev,
1755 obj->variant.fileVariant.top);
1756 obj->variant.fileVariant.top = NULL;
1757 T(YAFFS_TRACE_TRACING,
1758 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1760 yaffs_DoGenericObjectDeletion(obj);
1762 yaffs_SoftDeleteWorker(obj,
1763 obj->variant.fileVariant.top,
1764 obj->variant.fileVariant.
1766 obj->softDeleted = 1;
1771 /* Pruning removes any part of the file structure tree that is beyond the
1772 * bounds of the file (ie that does not point to chunks).
1774 * A file should only get pruned when its size is reduced.
1776 * Before pruning, the chunks must be pulled from the tree and the
1777 * level 0 tnode entries must be zeroed out.
1778 * Could also use this for file deletion, but that's probably better handled
1779 * by a special case.
1782 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1783 __u32 level, int del0)
1791 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1792 if (tn->internal[i] && level > 0) {
1794 yaffs_PruneWorker(dev, tn->internal[i],
1796 (i == 0) ? del0 : 1);
1799 if (tn->internal[i]) {
1804 if (hasData == 0 && del0) {
1805 /* Free and return NULL */
1807 yaffs_FreeTnode(dev, tn);
1817 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1818 yaffs_FileStructure * fStruct)
1825 if (fStruct->topLevel > 0) {
1827 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1829 /* Now we have a tree with all the non-zero branches NULL but the height
1830 * is the same as it was.
1831 * Let's see if we can trim internal tnodes to shorten the tree.
1832 * We can do this if only the 0th element in the tnode is in use
1833 * (ie all the non-zero are NULL)
1836 while (fStruct->topLevel && !done) {
1840 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1841 if (tn->internal[i]) {
1847 fStruct->top = tn->internal[0];
1848 fStruct->topLevel--;
1849 yaffs_FreeTnode(dev, tn);
1859 /*-------------------- End of File Structure functions.-------------------*/
1861 /* yaffs_CreateFreeObjects creates a bunch more objects and
1862 * adds them to the object free list.
1864 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1867 yaffs_Object *newObjects;
1868 yaffs_ObjectList *list;
1873 /* make these things */
1874 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1875 list = YMALLOC(sizeof(yaffs_ObjectList));
1877 if (!newObjects || !list) {
1882 T(YAFFS_TRACE_ALLOCATE,
1883 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1887 /* Hook them into the free list */
1888 for (i = 0; i < nObjects - 1; i++) {
1889 newObjects[i].siblings.next =
1890 (struct ylist_head *)(&newObjects[i + 1]);
1893 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1894 dev->freeObjects = newObjects;
1895 dev->nFreeObjects += nObjects;
1896 dev->nObjectsCreated += nObjects;
1898 /* Now add this bunch of Objects to a list for freeing up. */
1900 list->objects = newObjects;
1901 list->next = dev->allocatedObjectList;
1902 dev->allocatedObjectList = list;
1908 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1909 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1911 yaffs_Object *tn = NULL;
1913 #ifdef VALGRIND_TEST
1914 tn = YMALLOC(sizeof(yaffs_Object));
1916 /* If there are none left make more */
1917 if (!dev->freeObjects) {
1918 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1921 if (dev->freeObjects) {
1922 tn = dev->freeObjects;
1924 (yaffs_Object *) (dev->freeObjects->siblings.next);
1925 dev->nFreeObjects--;
1929 /* Now sweeten it up... */
1931 memset(tn, 0, sizeof(yaffs_Object));
1932 tn->beingCreated = 1;
1936 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1937 YINIT_LIST_HEAD(&(tn->hardLinks));
1938 YINIT_LIST_HEAD(&(tn->hashLink));
1939 YINIT_LIST_HEAD(&tn->siblings);
1942 /* Now make the directory sane */
1944 tn->parent = dev->rootDir;
1945 ylist_add(&(tn->siblings),&dev->rootDir->variant.directoryVariant.children);
1948 /* Add it to the lost and found directory.
1949 * NB Can't put root or lostNFound in lostNFound so
1950 * check if lostNFound exists first
1952 if (dev->lostNFoundDir) {
1953 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1956 tn->beingCreated = 0;
1959 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1964 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1969 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1971 obj->fake = 1; /* it is fake so it might have no NAND presence... */
1972 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1973 obj->unlinkAllowed = 0; /* ... or unlink it */
1976 obj->yst_mode = mode;
1978 obj->hdrChunk = 0; /* Not a valid chunk. */
1985 static void yaffs_UnhashObject(yaffs_Object * tn)
1988 yaffs_Device *dev = tn->myDev;
1990 /* If it is still linked into the bucket list, free from the list */
1991 if (!ylist_empty(&tn->hashLink)) {
1992 ylist_del_init(&tn->hashLink);
1993 bucket = yaffs_HashFunction(tn->objectId);
1994 dev->objectBucket[bucket].count--;
1999 /* FreeObject frees up a Object and puts it back on the free list */
2000 static void yaffs_FreeObject(yaffs_Object * tn)
2003 yaffs_Device *dev = tn->myDev;
2008 if(!ylist_empty(&tn->siblings))
2014 /* We're still hooked up to a cached inode.
2015 * Don't delete now, but mark for later deletion
2017 tn->deferedFree = 1;
2022 yaffs_UnhashObject(tn);
2024 #ifdef VALGRIND_TEST
2027 /* Link into the free list. */
2028 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2029 dev->freeObjects = tn;
2030 dev->nFreeObjects++;
2032 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2038 void yaffs_HandleDeferedFree(yaffs_Object * obj)
2040 if (obj->deferedFree) {
2041 yaffs_FreeObject(obj);
2047 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
2049 /* Free the list of allocated Objects */
2051 yaffs_ObjectList *tmp;
2053 while (dev->allocatedObjectList) {
2054 tmp = dev->allocatedObjectList->next;
2055 YFREE(dev->allocatedObjectList->objects);
2056 YFREE(dev->allocatedObjectList);
2058 dev->allocatedObjectList = tmp;
2061 dev->freeObjects = NULL;
2062 dev->nFreeObjects = 0;
2065 static void yaffs_InitialiseObjects(yaffs_Device * dev)
2069 dev->allocatedObjectList = NULL;
2070 dev->freeObjects = NULL;
2071 dev->nFreeObjects = 0;
2073 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2074 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2075 dev->objectBucket[i].count = 0;
2080 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
2085 int lowest = 999999;
2087 /* First let's see if we can find one that's empty. */
2089 for (i = 0; i < 10 && lowest > 0; i++) {
2091 x %= YAFFS_NOBJECT_BUCKETS;
2092 if (dev->objectBucket[x].count < lowest) {
2093 lowest = dev->objectBucket[x].count;
2099 /* If we didn't find an empty list, then try
2100 * looking a bit further for a short one
2103 for (i = 0; i < 10 && lowest > 3; i++) {
2105 x %= YAFFS_NOBJECT_BUCKETS;
2106 if (dev->objectBucket[x].count < lowest) {
2107 lowest = dev->objectBucket[x].count;
2116 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
2118 int bucket = yaffs_FindNiceObjectBucket(dev);
2120 /* Now find an object value that has not already been taken
2121 * by scanning the list.
2125 struct ylist_head *i;
2127 __u32 n = (__u32) bucket;
2129 /* yaffs_CheckObjectHashSanity(); */
2133 n += YAFFS_NOBJECT_BUCKETS;
2134 if (1 || dev->objectBucket[bucket].count > 0) {
2135 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2136 /* If there is already one in the list */
2138 && ylist_entry(i, yaffs_Object,
2139 hashLink)->objectId == n) {
2150 static void yaffs_HashObject(yaffs_Object * in)
2152 int bucket = yaffs_HashFunction(in->objectId);
2153 yaffs_Device *dev = in->myDev;
2155 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2156 dev->objectBucket[bucket].count++;
2160 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
2162 int bucket = yaffs_HashFunction(number);
2163 struct ylist_head *i;
2166 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2167 /* Look if it is in the list */
2169 in = ylist_entry(i, yaffs_Object, hashLink);
2170 if (in->objectId == number) {
2172 /* Don't tell the VFS about this one if it is defered free */
2173 if (in->deferedFree)
2185 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
2186 yaffs_ObjectType type)
2189 yaffs_Object *theObject;
2190 yaffs_Tnode *tn = NULL;
2193 number = yaffs_CreateNewObjectNumber(dev);
2196 theObject = yaffs_AllocateEmptyObject(dev);
2200 if(type == YAFFS_OBJECT_TYPE_FILE){
2201 tn = yaffs_GetTnode(dev);
2203 yaffs_FreeObject(theObject);
2211 theObject->fake = 0;
2212 theObject->renameAllowed = 1;
2213 theObject->unlinkAllowed = 1;
2214 theObject->objectId = number;
2215 yaffs_HashObject(theObject);
2216 theObject->variantType = type;
2217 #ifdef CONFIG_YAFFS_WINCE
2218 yfsd_WinFileTimeNow(theObject->win_atime);
2219 theObject->win_ctime[0] = theObject->win_mtime[0] =
2220 theObject->win_atime[0];
2221 theObject->win_ctime[1] = theObject->win_mtime[1] =
2222 theObject->win_atime[1];
2226 theObject->yst_atime = theObject->yst_mtime =
2227 theObject->yst_ctime = Y_CURRENT_TIME;
2231 theObject->sum_prev = 12345;
2232 theObject->sum_trailer = 6789;
2236 case YAFFS_OBJECT_TYPE_FILE:
2237 theObject->variant.fileVariant.fileSize = 0;
2238 theObject->variant.fileVariant.scannedFileSize = 0;
2239 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2240 theObject->variant.fileVariant.topLevel = 0;
2241 theObject->variant.fileVariant.top = tn;
2243 case YAFFS_OBJECT_TYPE_DIRECTORY:
2244 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2247 case YAFFS_OBJECT_TYPE_SYMLINK:
2248 case YAFFS_OBJECT_TYPE_HARDLINK:
2249 case YAFFS_OBJECT_TYPE_SPECIAL:
2250 /* No action required */
2252 case YAFFS_OBJECT_TYPE_UNKNOWN:
2253 /* todo this should not happen */
2261 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
2263 yaffs_ObjectType type)
2265 yaffs_Object *theObject = NULL;
2268 theObject = yaffs_FindObjectByNumber(dev, number);
2272 theObject = yaffs_CreateNewObject(dev, number, type);
2280 static YCHAR *yaffs_CloneString(const YCHAR * str)
2282 YCHAR *newStr = NULL;
2285 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2287 yaffs_strcpy(newStr, str);
2295 * Mknod (create) a new object.
2296 * equivalentObject only has meaning for a hard link;
2297 * aliasString only has meaning for a sumlink.
2298 * rdev only has meaning for devices (a subset of special objects)
2301 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2302 yaffs_Object * parent,
2307 yaffs_Object * equivalentObject,
2308 const YCHAR * aliasString, __u32 rdev)
2313 yaffs_Device *dev = parent->myDev;
2315 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2316 if (yaffs_FindObjectByName(parent, name)) {
2320 in = yaffs_CreateNewObject(dev, -1, type);
2325 if(type == YAFFS_OBJECT_TYPE_SYMLINK){
2326 str = yaffs_CloneString(aliasString);
2328 yaffs_FreeObject(in);
2338 in->variantType = type;
2340 in->yst_mode = mode;
2342 #ifdef CONFIG_YAFFS_WINCE
2343 yfsd_WinFileTimeNow(in->win_atime);
2344 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2345 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2348 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2350 in->yst_rdev = rdev;
2354 in->nDataChunks = 0;
2356 yaffs_SetObjectName(in, name);
2359 yaffs_AddObjectToDirectory(parent, in);
2361 in->myDev = parent->myDev;
2364 case YAFFS_OBJECT_TYPE_SYMLINK:
2365 in->variant.symLinkVariant.alias = str;
2367 case YAFFS_OBJECT_TYPE_HARDLINK:
2368 in->variant.hardLinkVariant.equivalentObject =
2370 in->variant.hardLinkVariant.equivalentObjectId =
2371 equivalentObject->objectId;
2372 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2374 case YAFFS_OBJECT_TYPE_FILE:
2375 case YAFFS_OBJECT_TYPE_DIRECTORY:
2376 case YAFFS_OBJECT_TYPE_SPECIAL:
2377 case YAFFS_OBJECT_TYPE_UNKNOWN:
2382 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2383 /* Could not create the object header, fail the creation */
2384 yaffs_DestroyObject(in);
2393 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
2394 __u32 mode, __u32 uid, __u32 gid)
2396 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2397 uid, gid, NULL, NULL, 0);
2400 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
2401 __u32 mode, __u32 uid, __u32 gid)
2403 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2404 mode, uid, gid, NULL, NULL, 0);
2407 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
2408 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2410 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2411 uid, gid, NULL, NULL, rdev);
2414 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
2415 __u32 mode, __u32 uid, __u32 gid,
2416 const YCHAR * alias)
2418 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2419 uid, gid, NULL, alias, 0);
2422 /* yaffs_Link returns the object id of the equivalent object.*/
2423 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
2424 yaffs_Object * equivalentObject)
2426 /* Get the real object in case we were fed a hard link as an equivalent object */
2427 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2429 if (yaffs_MknodObject
2430 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2431 equivalentObject, NULL, 0)) {
2432 return equivalentObject;
2439 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
2440 const YCHAR * newName, int force, int shadows)
2445 yaffs_Object *existingTarget;
2447 if (newDir == NULL) {
2448 newDir = obj->parent; /* use the old directory */
2451 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2452 T(YAFFS_TRACE_ALWAYS,
2454 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2459 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2460 if (obj->myDev->isYaffs2) {
2461 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2463 unlinkOp = (newDir == obj->myDev->unlinkedDir
2464 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2467 deleteOp = (newDir == obj->myDev->deletedDir);
2469 existingTarget = yaffs_FindObjectByName(newDir, newName);
2471 /* If the object is a file going into the unlinked directory,
2472 * then it is OK to just stuff it in since duplicate names are allowed.
2473 * else only proceed if the new name does not exist and if we're putting
2474 * it into a directory.
2481 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2482 yaffs_SetObjectName(obj, newName);
2485 yaffs_AddObjectToDirectory(newDir, obj);
2490 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2491 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
2498 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
2499 yaffs_Object * newDir, const YCHAR * newName)
2501 yaffs_Object *obj=NULL;
2502 yaffs_Object *existingTarget=NULL;
2506 if(!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2508 if(!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2511 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2512 /* Special case for case insemsitive systems (eg. WinCE).
2513 * While look-up is case insensitive, the name isn't.
2514 * Therefore we might want to change x.txt to X.txt
2516 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
2521 else if (yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2525 obj = yaffs_FindObjectByName(oldDir, oldName);
2527 if (obj && obj->renameAllowed) {
2529 /* Now do the handling for an existing target, if there is one */
2531 existingTarget = yaffs_FindObjectByName(newDir, newName);
2532 if (existingTarget &&
2533 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2534 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2535 /* There is a target that is a non-empty directory, so we fail */
2536 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2537 } else if (existingTarget && existingTarget != obj) {
2538 /* Nuke the target first, using shadowing,
2539 * but only if it isn't the same object
2541 yaffs_ChangeObjectName(obj, newDir, newName, force,
2542 existingTarget->objectId);
2543 yaffs_UnlinkObject(existingTarget);
2546 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2551 /*------------------------- Block Management and Page Allocation ----------------*/
2553 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
2555 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2557 dev->blockInfo = NULL;
2558 dev->chunkBits = NULL;
2560 dev->allocationBlock = -1; /* force it to get a new one */
2562 /* If the first allocation strategy fails, thry the alternate one */
2563 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2564 if(!dev->blockInfo){
2565 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2566 dev->blockInfoAlt = 1;
2569 dev->blockInfoAlt = 0;
2573 /* Set up dynamic blockinfo stuff. */
2574 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2575 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2576 if(!dev->chunkBits){
2577 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2578 dev->chunkBitsAlt = 1;
2581 dev->chunkBitsAlt = 0;
2584 if (dev->blockInfo && dev->chunkBits) {
2585 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2586 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2594 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
2596 if(dev->blockInfoAlt && dev->blockInfo)
2597 YFREE_ALT(dev->blockInfo);
2598 else if(dev->blockInfo)
2599 YFREE(dev->blockInfo);
2601 dev->blockInfoAlt = 0;
2603 dev->blockInfo = NULL;
2605 if(dev->chunkBitsAlt && dev->chunkBits)
2606 YFREE_ALT(dev->chunkBits);
2607 else if(dev->chunkBits)
2608 YFREE(dev->chunkBits);
2609 dev->chunkBitsAlt = 0;
2610 dev->chunkBits = NULL;
2613 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
2614 yaffs_BlockInfo * bi)
2621 return 1; /* disqualification only applies to yaffs2. */
2623 if (!bi->hasShrinkHeader)
2624 return 1; /* can gc */
2626 /* Find the oldest dirty sequence number if we don't know it and save it
2627 * so we don't have to keep recomputing it.
2629 if (!dev->oldestDirtySequence) {
2630 seq = dev->sequenceNumber;
2632 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2634 b = yaffs_GetBlockInfo(dev, i);
2635 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2636 (b->pagesInUse - b->softDeletions) <
2637 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2638 seq = b->sequenceNumber;
2641 dev->oldestDirtySequence = seq;
2644 /* Can't do gc of this block if there are any blocks older than this one that have
2647 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2651 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2652 * for garbage collection.
2655 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2659 int b = dev->currentDirtyChecker;
2666 yaffs_BlockInfo *bi;
2667 int pendingPrioritisedExist = 0;
2669 /* First let's see if we need to grab a prioritised block */
2670 if(dev->hasPendingPrioritisedGCs){
2671 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2673 bi = yaffs_GetBlockInfo(dev, i);
2674 //yaffs_VerifyBlock(dev,bi,i);
2676 if(bi->gcPrioritise) {
2677 pendingPrioritisedExist = 1;
2678 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2679 yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2680 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2683 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2688 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2689 dev->hasPendingPrioritisedGCs = 0;
2692 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2694 * else (we're doing a leasurely gc), then we only bother to do this if the
2695 * block has only a few pages in use.
2698 dev->nonAggressiveSkip--;
2700 if (!aggressive && (dev->nonAggressiveSkip > 0)) {
2706 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2710 dev->internalEndBlock - dev->internalStartBlock + 1;
2713 dev->internalEndBlock - dev->internalStartBlock + 1;
2714 iterations = iterations / 16;
2715 if (iterations > 200) {
2720 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2722 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2723 b = dev->internalStartBlock;
2726 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2727 T(YAFFS_TRACE_ERROR,
2728 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2732 bi = yaffs_GetBlockInfo(dev, b);
2735 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2742 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2743 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2744 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2746 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2750 dev->currentDirtyChecker = b;
2754 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2755 dev->nChunksPerBlock - pagesInUse,prioritised));
2758 dev->oldestDirtySequence = 0;
2761 dev->nonAggressiveSkip = 4;
2767 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2769 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2773 /* If the block is still healthy erase it and mark as clean.
2774 * If the block has had a data failure, then retire it.
2777 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2778 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2779 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2781 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2783 if (!bi->needsRetiring) {
2784 yaffs_InvalidateCheckpoint(dev);
2785 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2787 dev->nErasureFailures++;
2788 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2789 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2794 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2796 for (i = 0; i < dev->nChunksPerBlock; i++) {
2797 if (!yaffs_CheckChunkErased
2798 (dev, blockNo * dev->nChunksPerBlock + i)) {
2799 T(YAFFS_TRACE_ERROR,
2801 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2802 TENDSTR), blockNo, i));
2808 /* Clean it up... */
2809 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2810 dev->nErasedBlocks++;
2812 bi->softDeletions = 0;
2813 bi->hasShrinkHeader = 0;
2814 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2815 bi->gcPrioritise = 0;
2816 yaffs_ClearChunkBits(dev, blockNo);
2818 T(YAFFS_TRACE_ERASE,
2819 (TSTR("Erased block %d" TENDSTR), blockNo));
2821 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2823 yaffs_RetireBlock(dev, blockNo);
2824 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2825 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2829 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2833 yaffs_BlockInfo *bi;
2835 if (dev->nErasedBlocks < 1) {
2836 /* Hoosterman we've got a problem.
2837 * Can't get space to gc
2839 T(YAFFS_TRACE_ERROR,
2840 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2845 /* Find an empty block. */
2847 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2848 dev->allocationBlockFinder++;
2849 if (dev->allocationBlockFinder < dev->internalStartBlock
2850 || dev->allocationBlockFinder > dev->internalEndBlock) {
2851 dev->allocationBlockFinder = dev->internalStartBlock;
2854 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2856 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2857 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2858 dev->sequenceNumber++;
2859 bi->sequenceNumber = dev->sequenceNumber;
2860 dev->nErasedBlocks--;
2861 T(YAFFS_TRACE_ALLOCATE,
2862 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2863 dev->allocationBlockFinder, dev->sequenceNumber,
2864 dev->nErasedBlocks));
2865 return dev->allocationBlockFinder;
2869 T(YAFFS_TRACE_ALWAYS,
2871 ("yaffs tragedy: no more erased blocks, but there should have been %d"
2872 TENDSTR), dev->nErasedBlocks));
2879 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2881 if(!dev->nCheckpointBlocksRequired &&
2883 /* Not a valid value so recalculate */
2886 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2889 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2891 if(tnodeSize < sizeof(yaffs_Tnode))
2892 tnodeSize = sizeof(yaffs_Tnode);
2894 nBytes += sizeof(yaffs_CheckpointValidity);
2895 nBytes += sizeof(yaffs_CheckpointDevice);
2896 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2897 nBytes += devBlocks * dev->chunkBitmapStride;
2898 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2899 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2900 nBytes += sizeof(yaffs_CheckpointValidity);
2901 nBytes += sizeof(__u32); /* checksum*/
2903 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2905 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2907 dev->nCheckpointBlocksRequired = nBlocks;
2910 return dev->nCheckpointBlocksRequired;
2913 // Check if there's space to allocate...
2914 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2915 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2918 int reservedBlocks = dev->nReservedBlocks;
2919 int checkpointBlocks;
2922 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
2923 dev->blocksInCheckpoint;
2924 if(checkpointBlocks < 0)
2925 checkpointBlocks = 0;
2927 checkpointBlocks =0;
2930 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2932 return (dev->nFreeChunks > reservedChunks);
2935 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2938 yaffs_BlockInfo *bi;
2940 if (dev->allocationBlock < 0) {
2941 /* Get next block to allocate off */
2942 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2943 dev->allocationPage = 0;
2946 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2947 /* Not enough space to allocate unless we're allowed to use the reserve. */
2951 if (dev->nErasedBlocks < dev->nReservedBlocks
2952 && dev->allocationPage == 0) {
2953 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2956 /* Next page please.... */
2957 if (dev->allocationBlock >= 0) {
2958 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2960 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2961 dev->allocationPage;
2963 yaffs_SetChunkBit(dev, dev->allocationBlock,
2964 dev->allocationPage);
2966 dev->allocationPage++;
2970 /* If the block is full set the state to full */
2971 if (dev->allocationPage >= dev->nChunksPerBlock) {
2972 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2973 dev->allocationBlock = -1;
2982 T(YAFFS_TRACE_ERROR,
2983 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2988 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2992 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2994 if (dev->allocationBlock > 0) {
2995 n += (dev->nChunksPerBlock - dev->allocationPage);
3002 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block, int wholeBlock)
3007 int retVal = YAFFS_OK;
3010 int isCheckpointBlock;
3014 int chunksBefore = yaffs_GetErasedChunks(dev);
3017 yaffs_ExtendedTags tags;
3019 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3021 yaffs_Object *object;
3023 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3025 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3027 T(YAFFS_TRACE_TRACING,
3028 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3031 bi->hasShrinkHeader,
3034 /*yaffs_VerifyFreeChunks(dev); */
3036 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
3038 /* Take off the number of soft deleted entries because
3039 * they're going to get really deleted during GC.
3041 dev->nFreeChunks -= bi->softDeletions;
3045 if (isCheckpointBlock ||
3046 !yaffs_StillSomeChunkBits(dev, block)) {
3047 T(YAFFS_TRACE_TRACING,
3049 ("Collecting block %d that has no chunks in use" TENDSTR),
3051 yaffs_BlockBecameDirty(dev, block);
3054 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3056 yaffs_VerifyBlock(dev,bi,block);
3058 maxCopies = (wholeBlock) ? dev->nChunksPerBlock : 10;
3059 oldChunk = block * dev->nChunksPerBlock + dev->gcChunk;
3061 for ( /* init already done */;
3062 retVal == YAFFS_OK &&
3063 dev->gcChunk < dev->nChunksPerBlock &&
3064 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING)&&
3066 dev->gcChunk++, oldChunk++) {
3067 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3069 /* This page is in use and might need to be copied off */
3075 yaffs_InitialiseTags(&tags);
3077 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3081 yaffs_FindObjectByNumber(dev,
3084 T(YAFFS_TRACE_GC_DETAIL,
3086 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3087 dev->gcChunk, tags.objectId, tags.chunkId,
3090 if(object && !yaffs_SkipVerification(dev)){
3091 if(tags.chunkId == 0)
3092 matchingChunk = object->hdrChunk;
3093 else if(object->softDeleted)
3094 matchingChunk = oldChunk; /* Defeat the test */
3096 matchingChunk = yaffs_FindChunkInFile(object,tags.chunkId,NULL);
3098 if(oldChunk != matchingChunk)
3099 T(YAFFS_TRACE_ERROR,
3100 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3101 oldChunk,matchingChunk,tags.objectId, tags.chunkId));
3106 T(YAFFS_TRACE_ERROR,
3108 ("page %d in gc has no object: %d %d %d "
3110 tags.objectId, tags.chunkId, tags.byteCount));
3115 object->softDeleted &&
3116 tags.chunkId != 0) {
3117 /* Data chunk in a soft deleted file, throw it away
3118 * It's a soft deleted data chunk,
3119 * No need to copy this, just forget about it and
3120 * fix up the object.
3123 object->nDataChunks--;
3125 if (object->nDataChunks <= 0) {
3126 /* remeber to clean up the object */
3127 dev->gcCleanupList[cleanups] =
3133 /* Todo object && object->deleted && object->nDataChunks == 0 */
3135 /* Deleted object header with no data chunks.
3136 * Can be discarded and the file deleted.
3138 object->hdrChunk = 0;
3139 yaffs_FreeTnode(object->myDev,
3142 object->variant.fileVariant.top = NULL;
3143 yaffs_DoGenericObjectDeletion(object);
3145 } else if (object) {
3146 /* It's either a data chunk in a live file or
3147 * an ObjectHeader, so we're interested in it.
3148 * NB Need to keep the ObjectHeaders of deleted files
3149 * until the whole file has been deleted off
3151 tags.serialNumber++;
3155 if (tags.chunkId == 0) {
3156 /* It is an object Id,
3157 * We need to nuke the shrinkheader flags first
3158 * We no longer want the shrinkHeader flag since its work is done
3159 * and if it is left in place it will mess up scanning.
3160 * Also, clear out any shadowing stuff
3163 yaffs_ObjectHeader *oh;
3164 oh = (yaffs_ObjectHeader *)buffer;
3166 tags.extraShadows = 0;
3167 tags.extraIsShrinkHeader = 0;
3169 yaffs_VerifyObjectHeader(object,oh,&tags,1);
3173 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3176 retVal = YAFFS_FAIL;
3179 /* Ok, now fix up the Tnodes etc. */
3181 if (tags.chunkId == 0) {
3183 object->hdrChunk = newChunk;
3184 object->serial = tags.serialNumber;
3186 /* It's a data chunk */
3187 yaffs_PutChunkIntoFile
3195 if(retVal == YAFFS_OK)
3196 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3201 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3205 /* Do any required cleanups */
3206 for (i = 0; i < cleanups; i++) {
3207 /* Time to delete the file too */
3209 yaffs_FindObjectByNumber(dev,
3210 dev->gcCleanupList[i]);
3212 yaffs_FreeTnode(dev,
3213 object->variant.fileVariant.
3215 object->variant.fileVariant.top = NULL;
3218 ("yaffs: About to finally delete object %d"
3219 TENDSTR), object->objectId));
3220 yaffs_DoGenericObjectDeletion(object);
3221 object->myDev->nDeletedFiles--;
3228 yaffs_VerifyCollectedBlock(dev,bi,block);
3230 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
3233 ("gc did not increase free chunks before %d after %d"
3234 TENDSTR), chunksBefore, chunksAfter));
3237 /* If the gc completed then clear the current gcBlock so that we find another. */
3238 if(bi->blockState != YAFFS_BLOCK_STATE_COLLECTING){
3248 /* New garbage collector
3249 * If we're very low on erased blocks then we do aggressive garbage collection
3250 * otherwise we do "leasurely" garbage collection.
3251 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3252 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3254 * The idea is to help clear out space in a more spread-out manner.
3255 * Dunno if it really does anything useful.
3257 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
3261 int gcOk = YAFFS_OK;
3264 int checkpointBlockAdjust;
3266 if (dev->isDoingGC) {
3267 /* Bail out so we don't get recursive gc */
3271 /* This loop should pass the first time.
3272 * We'll only see looping here if the erase of the collected block fails.
3278 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3279 if(checkpointBlockAdjust < 0)
3280 checkpointBlockAdjust = 0;
3282 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3283 /* We need a block soon...*/
3286 /* We're in no hurry */
3290 if(dev->gcBlock <= 0){
3291 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3295 block = dev->gcBlock;
3298 dev->garbageCollections++;
3300 dev->passiveGarbageCollections++;
3305 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3306 dev->nErasedBlocks, aggressive));
3308 gcOk = yaffs_GarbageCollectBlock(dev,block,aggressive);
3311 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3314 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3315 TENDSTR), dev->nErasedBlocks, maxTries, block));
3317 } while ((dev->nErasedBlocks < dev->nReservedBlocks) &&
3321 return aggressive ? gcOk : YAFFS_OK;
3324 /*------------------------- TAGS --------------------------------*/
3326 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
3329 return (tags->chunkId == chunkInObject &&
3330 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3335 /*-------------------- Data file manipulation -----------------*/
3337 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
3338 yaffs_ExtendedTags * tags)
3340 /*Get the Tnode, then get the level 0 offset chunk offset */
3343 yaffs_ExtendedTags localTags;
3346 yaffs_Device *dev = in->myDev;
3349 /* Passed a NULL, so use our own tags space */
3353 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3356 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3359 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3365 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
3366 yaffs_ExtendedTags * tags)
3368 /* Get the Tnode, then get the level 0 offset chunk offset */
3371 yaffs_ExtendedTags localTags;
3373 yaffs_Device *dev = in->myDev;
3377 /* Passed a NULL, so use our own tags space */
3381 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3385 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3388 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3391 /* Delete the entry in the filestructure (if found) */
3393 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
3396 /*T(("No level 0 found for %d\n", chunkInInode)); */
3400 /* T(("Could not find %d to delete\n",chunkInInode)); */
3405 #ifdef YAFFS_PARANOID
3407 static int yaffs_CheckFileSanity(yaffs_Object * in)
3415 yaffs_Tags localTags;
3416 yaffs_Tags *tags = &localTags;
3420 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3421 /* T(("Object not a file\n")); */
3425 objId = in->objectId;
3426 fSize = in->variant.fileVariant.fileSize;
3428 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3430 for (chunk = 1; chunk <= nChunks; chunk++) {
3431 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3436 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
3438 if (yaffs_CheckChunkBits
3439 (dev, theChunk / dev->nChunksPerBlock,
3440 theChunk % dev->nChunksPerBlock)) {
3442 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3446 (tags, in->objectId, chunk, chunkDeleted)) {
3456 /* T(("No level 0 found for %d\n", chunk)); */
3460 return failed ? YAFFS_FAIL : YAFFS_OK;
3465 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
3466 int chunkInNAND, int inScan)
3468 /* NB inScan is zero unless scanning.
3469 * For forward scanning, inScan is > 0;
3470 * for backward scanning inScan is < 0
3474 yaffs_Device *dev = in->myDev;
3476 yaffs_ExtendedTags existingTags;
3477 yaffs_ExtendedTags newTags;
3478 unsigned existingSerial, newSerial;
3480 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3481 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3482 * If it is not during Scanning then something went wrong!
3485 T(YAFFS_TRACE_ERROR,
3487 ("yaffs tragedy:attempt to put data chunk into a non-file"
3492 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3496 tn = yaffs_AddOrFindLevel0Tnode(dev,
3497 &in->variant.fileVariant,
3504 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3507 /* If we're scanning then we need to test for duplicates
3508 * NB This does not need to be efficient since it should only ever
3509 * happen when the power fails during a write, then only one
3510 * chunk should ever be affected.
3512 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3513 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3516 if (existingChunk > 0) {
3517 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3518 * thus we have to do a FindChunkInFile to get the real chunk id.
3520 * We have a duplicate now we need to decide which one to use:
3522 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3523 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3524 * YAFFS1: Get both sets of tags and compare serial numbers.
3528 /* Only do this for forward scanning */
3529 yaffs_ReadChunkWithTagsFromNAND(dev,
3533 /* Do a proper find */
3535 yaffs_FindChunkInFile(in, chunkInInode,
3539 if (existingChunk <= 0) {
3540 /*Hoosterman - how did this happen? */
3542 T(YAFFS_TRACE_ERROR,
3544 ("yaffs tragedy: existing chunk < 0 in scan"
3549 /* NB The deleted flags should be false, otherwise the chunks will
3550 * not be loaded during a scan
3554 newSerial = newTags.serialNumber;
3555 existingSerial = existingTags.serialNumber;
3559 (in->myDev->isYaffs2 ||
3560 existingChunk <= 0 ||
3561 ((existingSerial + 1) & 3) == newSerial)) {
3562 /* Forward scanning.
3564 * Delete the old one and drop through to update the tnode
3566 yaffs_DeleteChunk(dev, existingChunk, 1,
3569 /* Backward scanning or we want to use the existing one
3571 * Delete the new one and return early so that the tnode isn't changed
3573 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3581 if (existingChunk == 0) {
3585 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
3590 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
3593 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3595 if (chunkInNAND >= 0) {
3596 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3599 T(YAFFS_TRACE_NANDACCESS,
3600 (TSTR("Chunk %d not found zero instead" TENDSTR),
3602 /* get sane (zero) data if you read a hole */
3603 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3609 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
3613 yaffs_ExtendedTags tags;
3614 yaffs_BlockInfo *bi;
3621 block = chunkId / dev->nChunksPerBlock;
3622 page = chunkId % dev->nChunksPerBlock;
3625 if(!yaffs_CheckChunkBit(dev,block,page))
3626 T(YAFFS_TRACE_VERIFY,
3627 (TSTR("Deleting invalid chunk %d"TENDSTR),
3630 bi = yaffs_GetBlockInfo(dev, block);
3632 T(YAFFS_TRACE_DELETION,
3633 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3636 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3638 yaffs_InitialiseTags(&tags);
3640 tags.chunkDeleted = 1;
3642 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3643 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3645 dev->nUnmarkedDeletions++;
3648 /* Pull out of the management area.
3649 * If the whole block became dirty, this will kick off an erasure.
3651 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3652 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3653 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3654 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3657 yaffs_ClearChunkBit(dev, block, page);
3661 if (bi->pagesInUse == 0 &&
3662 !bi->hasShrinkHeader &&
3663 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3664 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3665 yaffs_BlockBecameDirty(dev, block);
3669 /* T(("Bad news deleting chunk %d\n",chunkId)); */
3674 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
3675 const __u8 * buffer, int nBytes,
3678 /* Find old chunk Need to do this to get serial number
3679 * Write new one and patch into tree.
3680 * Invalidate old tags.
3684 yaffs_ExtendedTags prevTags;
3687 yaffs_ExtendedTags newTags;
3689 yaffs_Device *dev = in->myDev;
3691 yaffs_CheckGarbageCollection(dev);
3693 /* Get the previous chunk at this location in the file if it exists */
3694 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3696 /* Set up new tags */
3697 yaffs_InitialiseTags(&newTags);
3699 newTags.chunkId = chunkInInode;
3700 newTags.objectId = in->objectId;
3701 newTags.serialNumber =
3702 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
3703 newTags.byteCount = nBytes;
3705 if(nBytes < 1 || nBytes > dev->totalBytesPerChunk){
3706 T(YAFFS_TRACE_ERROR,
3707 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3714 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3717 if (newChunkId >= 0) {
3718 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3720 if (prevChunkId >= 0) {
3721 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3725 yaffs_CheckFileSanity(in);
3731 /* UpdateObjectHeader updates the header on NAND for an object.
3732 * If name is not NULL, then that new name is used.
3734 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
3735 int isShrink, int shadows)
3738 yaffs_BlockInfo *bi;
3740 yaffs_Device *dev = in->myDev;
3747 yaffs_ExtendedTags newTags;
3748 yaffs_ExtendedTags oldTags;
3750 __u8 *buffer = NULL;
3751 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3753 yaffs_ObjectHeader *oh = NULL;
3755 yaffs_strcpy(oldName,_Y("silly old name"));
3759 in == dev->rootDir || /* The rootDir should also be saved */
3762 yaffs_CheckGarbageCollection(dev);
3763 yaffs_CheckObjectDetailsLoaded(in);
3765 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3766 oh = (yaffs_ObjectHeader *) buffer;
3768 prevChunkId = in->hdrChunk;
3770 if (prevChunkId > 0) {
3771 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3774 yaffs_VerifyObjectHeader(in,oh,&oldTags,0);
3776 memcpy(oldName, oh->name, sizeof(oh->name));
3779 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3781 oh->type = in->variantType;
3782 oh->yst_mode = in->yst_mode;
3783 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3785 #ifdef CONFIG_YAFFS_WINCE
3786 oh->win_atime[0] = in->win_atime[0];
3787 oh->win_ctime[0] = in->win_ctime[0];
3788 oh->win_mtime[0] = in->win_mtime[0];
3789 oh->win_atime[1] = in->win_atime[1];
3790 oh->win_ctime[1] = in->win_ctime[1];
3791 oh->win_mtime[1] = in->win_mtime[1];
3793 oh->yst_uid = in->yst_uid;
3794 oh->yst_gid = in->yst_gid;
3795 oh->yst_atime = in->yst_atime;
3796 oh->yst_mtime = in->yst_mtime;
3797 oh->yst_ctime = in->yst_ctime;
3798 oh->yst_rdev = in->yst_rdev;
3801 oh->parentObjectId = in->parent->objectId;
3803 oh->parentObjectId = 0;
3806 if (name && *name) {
3807 memset(oh->name, 0, sizeof(oh->name));
3808 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3809 } else if (prevChunkId>=0) {
3810 memcpy(oh->name, oldName, sizeof(oh->name));
3812 memset(oh->name, 0, sizeof(oh->name));
3815 oh->isShrink = isShrink;
3817 switch (in->variantType) {
3818 case YAFFS_OBJECT_TYPE_UNKNOWN:
3819 /* Should not happen */
3821 case YAFFS_OBJECT_TYPE_FILE:
3823 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3824 || oh->parentObjectId ==
3825 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3826 fileVariant.fileSize;
3828 case YAFFS_OBJECT_TYPE_HARDLINK:
3829 oh->equivalentObjectId =
3830 in->variant.hardLinkVariant.equivalentObjectId;
3832 case YAFFS_OBJECT_TYPE_SPECIAL:
3835 case YAFFS_OBJECT_TYPE_DIRECTORY:
3838 case YAFFS_OBJECT_TYPE_SYMLINK:
3839 yaffs_strncpy(oh->alias,
3840 in->variant.symLinkVariant.alias,
3841 YAFFS_MAX_ALIAS_LENGTH);
3842 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3847 yaffs_InitialiseTags(&newTags);
3849 newTags.chunkId = 0;
3850 newTags.objectId = in->objectId;
3851 newTags.serialNumber = in->serial;
3853 /* Add extra info for file header */
3855 newTags.extraHeaderInfoAvailable = 1;
3856 newTags.extraParentObjectId = oh->parentObjectId;
3857 newTags.extraFileLength = oh->fileSize;
3858 newTags.extraIsShrinkHeader = oh->isShrink;
3859 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3860 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3861 newTags.extraObjectType = in->variantType;
3863 yaffs_VerifyObjectHeader(in,oh,&newTags,1);
3865 /* Create new chunk in NAND */
3867 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3868 (prevChunkId >= 0) ? 1 : 0);
3870 if (newChunkId >= 0) {
3872 in->hdrChunk = newChunkId;
3874 if (prevChunkId >= 0) {
3875 yaffs_DeleteChunk(dev, prevChunkId, 1,
3879 if(!yaffs_ObjectHasCachedWriteData(in))
3882 /* If this was a shrink, then mark the block that the chunk lives on */
3884 bi = yaffs_GetBlockInfo(in->myDev,
3885 newChunkId /in->myDev-> nChunksPerBlock);
3886 bi->hasShrinkHeader = 1;
3891 retVal = newChunkId;
3896 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3901 /*------------------------ Short Operations Cache ----------------------------------------
3902 * In many situations where there is no high level buffering (eg WinCE) a lot of
3903 * reads might be short sequential reads, and a lot of writes may be short
3904 * sequential writes. eg. scanning/writing a jpeg file.
3905 * In these cases, a short read/write cache can provide a huge perfomance benefit
3906 * with dumb-as-a-rock code.
3907 * In Linux, the page cache provides read buffering aand the short op cache provides write
3910 * There are a limited number (~10) of cache chunks per device so that we don't
3911 * need a very intelligent search.
3914 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3916 yaffs_Device *dev = obj->myDev;
3918 yaffs_ChunkCache *cache;
3919 int nCaches = obj->myDev->nShortOpCaches;
3921 for(i = 0; i < nCaches; i++){
3922 cache = &dev->srCache[i];
3923 if (cache->object == obj &&
3932 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3934 yaffs_Device *dev = obj->myDev;
3935 int lowest = -99; /* Stop compiler whining. */
3937 yaffs_ChunkCache *cache;
3938 int chunkWritten = 0;
3939 int nCaches = obj->myDev->nShortOpCaches;
3945 /* Find the dirty cache for this object with the lowest chunk id. */
3946 for (i = 0; i < nCaches; i++) {
3947 if (dev->srCache[i].object == obj &&
3948 dev->srCache[i].dirty) {
3950 || dev->srCache[i].chunkId <
3952 cache = &dev->srCache[i];
3953 lowest = cache->chunkId;
3958 if (cache && !cache->locked) {
3959 /* Write it out and free it up */
3962 yaffs_WriteChunkDataToObject(cache->object,
3968 cache->object = NULL;
3971 } while (cache && chunkWritten > 0);
3974 /* Hoosterman, disk full while writing cache out. */
3975 T(YAFFS_TRACE_ERROR,
3976 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3983 /*yaffs_FlushEntireDeviceCache(dev)
3988 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3991 int nCaches = dev->nShortOpCaches;
3994 /* Find a dirty object in the cache and flush it...
3995 * until there are no further dirty objects.
3999 for( i = 0; i < nCaches && !obj; i++) {
4000 if (dev->srCache[i].object &&
4001 dev->srCache[i].dirty)
4002 obj = dev->srCache[i].object;
4006 yaffs_FlushFilesChunkCache(obj);
4013 /* Grab us a cache chunk for use.
4014 * First look for an empty one.
4015 * Then look for the least recently used non-dirty one.
4016 * Then look for the least recently used dirty one...., flush and look again.
4018 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
4022 if (dev->nShortOpCaches > 0) {
4023 for (i = 0; i < dev->nShortOpCaches; i++) {
4024 if (!dev->srCache[i].object)
4025 return &dev->srCache[i];
4032 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
4034 yaffs_ChunkCache *cache;
4035 yaffs_Object *theObj;
4040 if (dev->nShortOpCaches > 0) {
4041 /* Try find a non-dirty one... */
4043 cache = yaffs_GrabChunkCacheWorker(dev);
4046 /* They were all dirty, find the last recently used object and flush
4047 * its cache, then find again.
4048 * NB what's here is not very accurate, we actually flush the object
4049 * the last recently used page.
4052 /* With locking we can't assume we can use entry zero */
4059 for (i = 0; i < dev->nShortOpCaches; i++) {
4060 if (dev->srCache[i].object &&
4061 !dev->srCache[i].locked &&
4062 (dev->srCache[i].lastUse < usage || !cache))
4064 usage = dev->srCache[i].lastUse;
4065 theObj = dev->srCache[i].object;
4066 cache = &dev->srCache[i];
4071 if (!cache || cache->dirty) {
4072 /* Flush and try again */
4073 yaffs_FlushFilesChunkCache(theObj);
4074 cache = yaffs_GrabChunkCacheWorker(dev);
4084 /* Find a cached chunk */
4085 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
4088 yaffs_Device *dev = obj->myDev;
4090 if (dev->nShortOpCaches > 0) {
4091 for (i = 0; i < dev->nShortOpCaches; i++) {
4092 if (dev->srCache[i].object == obj &&
4093 dev->srCache[i].chunkId == chunkId) {
4096 return &dev->srCache[i];
4103 /* Mark the chunk for the least recently used algorithym */
4104 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
4108 if (dev->nShortOpCaches > 0) {
4109 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4110 /* Reset the cache usages */
4112 for (i = 1; i < dev->nShortOpCaches; i++) {
4113 dev->srCache[i].lastUse = 0;
4120 cache->lastUse = dev->srLastUse;
4128 /* Invalidate a single cache page.
4129 * Do this when a whole page gets written,
4130 * ie the short cache for this page is no longer valid.
4132 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
4134 if (object->myDev->nShortOpCaches > 0) {
4135 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4138 cache->object = NULL;
4143 /* Invalidate all the cache pages associated with this object
4144 * Do this whenever ther file is deleted or resized.
4146 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
4149 yaffs_Device *dev = in->myDev;
4151 if (dev->nShortOpCaches > 0) {
4152 /* Invalidate it. */
4153 for (i = 0; i < dev->nShortOpCaches; i++) {
4154 if (dev->srCache[i].object == in) {
4155 dev->srCache[i].object = NULL;
4161 /*--------------------- Checkpointing --------------------*/
4164 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
4166 yaffs_CheckpointValidity cp;
4168 memset(&cp,0,sizeof(cp));
4170 cp.structType = sizeof(cp);
4171 cp.magic = YAFFS_MAGIC;
4172 cp.version = YAFFS_CHECKPOINT_VERSION;
4173 cp.head = (head) ? 1 : 0;
4175 return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
4179 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4181 yaffs_CheckpointValidity cp;
4184 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4187 ok = (cp.structType == sizeof(cp)) &&
4188 (cp.magic == YAFFS_MAGIC) &&
4189 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4190 (cp.head == ((head) ? 1 : 0));
4194 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4197 cp->nErasedBlocks = dev->nErasedBlocks;
4198 cp->allocationBlock = dev->allocationBlock;
4199 cp->allocationPage = dev->allocationPage;
4200 cp->nFreeChunks = dev->nFreeChunks;
4202 cp->nDeletedFiles = dev->nDeletedFiles;
4203 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4204 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4205 cp->sequenceNumber = dev->sequenceNumber;
4206 cp->oldestDirtySequence = dev->oldestDirtySequence;
4210 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4211 yaffs_CheckpointDevice *cp)
4213 dev->nErasedBlocks = cp->nErasedBlocks;
4214 dev->allocationBlock = cp->allocationBlock;
4215 dev->allocationPage = cp->allocationPage;
4216 dev->nFreeChunks = cp->nFreeChunks;
4218 dev->nDeletedFiles = cp->nDeletedFiles;
4219 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4220 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4221 dev->sequenceNumber = cp->sequenceNumber;
4222 dev->oldestDirtySequence = cp->oldestDirtySequence;
4226 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4228 yaffs_CheckpointDevice cp;
4230 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4234 /* Write device runtime values*/
4235 yaffs_DeviceToCheckpointDevice(&cp,dev);
4236 cp.structType = sizeof(cp);
4238 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4240 /* Write block info */
4242 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4243 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
4246 /* Write chunk bits */
4248 nBytes = nBlocks * dev->chunkBitmapStride;
4249 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
4255 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4257 yaffs_CheckpointDevice cp;
4259 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4263 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4267 if(cp.structType != sizeof(cp))
4271 yaffs_CheckpointDeviceToDevice(dev,&cp);
4273 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4275 ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
4279 nBytes = nBlocks * dev->chunkBitmapStride;
4281 ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
4286 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4290 cp->objectId = obj->objectId;
4291 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4292 cp->hdrChunk = obj->hdrChunk;
4293 cp->variantType = obj->variantType;
4294 cp->deleted = obj->deleted;
4295 cp->softDeleted = obj->softDeleted;
4296 cp->unlinked = obj->unlinked;
4297 cp->fake = obj->fake;
4298 cp->renameAllowed = obj->renameAllowed;
4299 cp->unlinkAllowed = obj->unlinkAllowed;
4300 cp->serial = obj->serial;
4301 cp->nDataChunks = obj->nDataChunks;
4303 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4304 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4305 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4306 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4309 static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
4312 yaffs_Object *parent;
4314 obj->objectId = cp->objectId;
4317 parent = yaffs_FindOrCreateObjectByNumber(
4320 YAFFS_OBJECT_TYPE_DIRECTORY);
4325 yaffs_AddObjectToDirectory(parent, obj);
4327 obj->hdrChunk = cp->hdrChunk;
4328 obj->variantType = cp->variantType;
4329 obj->deleted = cp->deleted;
4330 obj->softDeleted = cp->softDeleted;
4331 obj->unlinked = cp->unlinked;
4332 obj->fake = cp->fake;
4333 obj->renameAllowed = cp->renameAllowed;
4334 obj->unlinkAllowed = cp->unlinkAllowed;
4335 obj->serial = cp->serial;
4336 obj->nDataChunks = cp->nDataChunks;
4338 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4339 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4340 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4341 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4343 if(obj->hdrChunk > 0)
4344 obj->lazyLoaded = 1;
4349 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
4350 __u32 level, int chunkOffset)
4353 yaffs_Device *dev = in->myDev;
4355 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4357 if(tnodeSize < sizeof(yaffs_Tnode))
4358 tnodeSize = sizeof(yaffs_Tnode);
4364 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
4365 if (tn->internal[i]) {
4366 ok = yaffs_CheckpointTnodeWorker(in,
4369 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4372 } else if (level == 0) {
4373 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4374 ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
4376 ok = (yaffs_CheckpointWrite(dev,tn,tnodeSize) == tnodeSize);
4384 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4386 __u32 endMarker = ~0;
4389 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4390 ok = yaffs_CheckpointTnodeWorker(obj,
4391 obj->variant.fileVariant.top,
4392 obj->variant.fileVariant.topLevel,
4395 ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) ==
4402 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4406 yaffs_Device *dev = obj->myDev;
4407 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4410 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4412 if(tnodeSize < sizeof(yaffs_Tnode))
4413 tnodeSize = sizeof(yaffs_Tnode);
4415 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4417 while(ok && (~baseChunk)){
4419 /* Read level 0 tnode */
4422 tn = yaffs_GetTnodeRaw(dev);
4424 ok = (yaffs_CheckpointRead(dev,tn,tnodeSize) == tnodeSize);
4429 ok = yaffs_AddOrFindLevel0Tnode(dev,
4437 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4441 T(YAFFS_TRACE_CHECKPOINT,(
4442 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4443 nread,baseChunk,ok));
4449 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4452 yaffs_CheckpointObject cp;
4455 struct ylist_head *lh;
4458 /* Iterate through the objects in each hash entry,
4459 * dumping them to the checkpointing stream.
4462 for(i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++){
4463 ylist_for_each(lh, &dev->objectBucket[i].list) {
4465 obj = ylist_entry(lh, yaffs_Object, hashLink);
4466 if (!obj->deferedFree) {
4467 yaffs_ObjectToCheckpointObject(&cp,obj);
4468 cp.structType = sizeof(cp);
4470 T(YAFFS_TRACE_CHECKPOINT,(
4471 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
4472 cp.objectId,cp.parentId,cp.variantType,cp.hdrChunk,(unsigned) obj));
4474 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4476 if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4477 ok = yaffs_WriteCheckpointTnodes(obj);
4484 /* Dump end of list */
4485 memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
4486 cp.structType = sizeof(cp);
4489 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4494 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4497 yaffs_CheckpointObject cp;
4500 yaffs_Object *hardList = NULL;
4502 while(ok && !done) {
4503 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4504 if(cp.structType != sizeof(cp)) {
4505 T(YAFFS_TRACE_CHECKPOINT,(TSTR("struct size %d instead of %d ok %d"TENDSTR),
4506 cp.structType,sizeof(cp),ok));
4510 T(YAFFS_TRACE_CHECKPOINT,(TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4511 cp.objectId,cp.parentId,cp.variantType,cp.hdrChunk));
4513 if(ok && cp.objectId == ~0)
4516 obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
4518 yaffs_CheckpointObjectToObject(obj,&cp);
4519 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4520 ok = yaffs_ReadCheckpointTnodes(obj);
4521 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4522 obj->hardLinks.next =
4523 (struct ylist_head *)
4533 yaffs_HardlinkFixup(dev,hardList);
4538 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4540 __u32 checkpointSum;
4543 yaffs_GetCheckpointSum(dev,&checkpointSum);
4545 ok = (yaffs_CheckpointWrite(dev,&checkpointSum,sizeof(checkpointSum)) == sizeof(checkpointSum));
4553 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4555 __u32 checkpointSum0;
4556 __u32 checkpointSum1;
4559 yaffs_GetCheckpointSum(dev,&checkpointSum0);
4561 ok = (yaffs_CheckpointRead(dev,&checkpointSum1,sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4566 if(checkpointSum0 != checkpointSum1)
4573 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4578 if(dev->skipCheckpointWrite || !dev->isYaffs2){
4579 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint write" TENDSTR)));
4584 ok = yaffs_CheckpointOpen(dev,1);
4587 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4588 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
4591 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint device" TENDSTR)));
4592 ok = yaffs_WriteCheckpointDevice(dev);
4595 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint objects" TENDSTR)));
4596 ok = yaffs_WriteCheckpointObjects(dev);
4599 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4600 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
4604 ok = yaffs_WriteCheckpointSum(dev);
4608 if(!yaffs_CheckpointClose(dev))
4612 dev->isCheckpointed = 1;
4614 dev->isCheckpointed = 0;
4616 return dev->isCheckpointed;
4619 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4623 if(dev->skipCheckpointRead || !dev->isYaffs2){
4624 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint read" TENDSTR)));
4629 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
4632 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4633 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
4636 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint device" TENDSTR)));
4637 ok = yaffs_ReadCheckpointDevice(dev);
4640 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint objects" TENDSTR)));
4641 ok = yaffs_ReadCheckpointObjects(dev);
4644 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4645 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
4649 ok = yaffs_ReadCheckpointSum(dev);
4650 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint checksum %d" TENDSTR),ok));
4653 if(!yaffs_CheckpointClose(dev))
4657 dev->isCheckpointed = 1;
4659 dev->isCheckpointed = 0;
4665 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4667 if(dev->isCheckpointed ||
4668 dev->blocksInCheckpoint > 0){
4669 dev->isCheckpointed = 0;
4670 yaffs_CheckpointInvalidateStream(dev);
4671 if(dev->superBlock && dev->markSuperBlockDirty)
4672 dev->markSuperBlockDirty(dev->superBlock);
4677 int yaffs_CheckpointSave(yaffs_Device *dev)
4680 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4682 yaffs_VerifyObjects(dev);
4683 yaffs_VerifyBlocks(dev);
4684 yaffs_VerifyFreeChunks(dev);
4686 if(!dev->isCheckpointed) {
4687 yaffs_InvalidateCheckpoint(dev);
4688 yaffs_WriteCheckpointData(dev);
4691 T(YAFFS_TRACE_ALWAYS,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4693 return dev->isCheckpointed;
4696 int yaffs_CheckpointRestore(yaffs_Device *dev)
4699 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4701 retval = yaffs_ReadCheckpointData(dev);
4703 if(dev->isCheckpointed){
4704 yaffs_VerifyObjects(dev);
4705 yaffs_VerifyBlocks(dev);
4706 yaffs_VerifyFreeChunks(dev);
4709 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4714 /*--------------------- File read/write ------------------------
4715 * Read and write have very similar structures.
4716 * In general the read/write has three parts to it
4717 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4718 * Some complete chunks
4719 * An incomplete chunk to end off with
4721 * Curve-balls: the first chunk might also be the last chunk.
4724 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, loff_t offset,
4733 yaffs_ChunkCache *cache;
4740 //chunk = offset / dev->nDataBytesPerChunk + 1;
4741 //start = offset % dev->nDataBytesPerChunk;
4742 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4745 /* OK now check for the curveball where the start and end are in
4748 if ((start + n) < dev->nDataBytesPerChunk) {
4751 nToCopy = dev->nDataBytesPerChunk - start;
4754 cache = yaffs_FindChunkCache(in, chunk);
4756 /* If the chunk is already in the cache or it is less than a whole chunk
4757 * or we're using inband tags then use the cache (if there is caching)
4758 * else bypass the cache.
4760 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4761 if (dev->nShortOpCaches > 0) {
4763 /* If we can't find the data in the cache, then load it up. */
4766 cache = yaffs_GrabChunkCache(in->myDev);
4768 cache->chunkId = chunk;
4771 yaffs_ReadChunkDataFromObject(in, chunk,
4777 yaffs_UseChunkCache(dev, cache, 0);
4782 memcpy(buffer, &cache->data[start], nToCopy);
4786 /* Read into the local buffer then copy..*/
4789 yaffs_GetTempBuffer(dev, __LINE__);
4790 yaffs_ReadChunkDataFromObject(in, chunk,
4793 memcpy(buffer, &localBuffer[start], nToCopy);
4796 yaffs_ReleaseTempBuffer(dev, localBuffer,
4802 /* A full chunk. Read directly into the supplied buffer. */
4803 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4817 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, loff_t offset,
4818 int nBytes, int writeThrough)
4827 int startOfWrite = offset;
4828 int chunkWritten = 0;
4836 while (n > 0 && chunkWritten >= 0) {
4837 //chunk = offset / dev->nDataBytesPerChunk + 1;
4838 //start = offset % dev->nDataBytesPerChunk;
4839 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4841 if(chunk * dev->nDataBytesPerChunk + start != offset ||
4842 start >= dev->nDataBytesPerChunk){
4843 T(YAFFS_TRACE_ERROR,(TSTR("AddrToChunk of offset %d gives chunk %d start %d"TENDSTR),
4844 (int)offset, chunk,start));
4848 /* OK now check for the curveball where the start and end are in
4852 if ((start + n) < dev->nDataBytesPerChunk) {
4855 /* Now folks, to calculate how many bytes to write back....
4856 * If we're overwriting and not writing to then end of file then
4857 * we need to write back as much as was there before.
4860 chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
4862 if(chunkStart > in->variant.fileVariant.fileSize)
4863 nBytesRead = 0; /* Past end of file */
4865 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
4867 if (nBytesRead > dev->nDataBytesPerChunk) {
4868 nBytesRead = dev->nDataBytesPerChunk;
4873 (start + n)) ? nBytesRead : (start + n);
4875 if(nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
4879 nToCopy = dev->nDataBytesPerChunk - start;
4880 nToWriteBack = dev->nDataBytesPerChunk;
4883 if (nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4884 /* An incomplete start or end chunk (or maybe both start and end chunk),
4885 * or we're using inband tags, so we want to use the cache buffers.
4887 if (dev->nShortOpCaches > 0) {
4888 yaffs_ChunkCache *cache;
4889 /* If we can't find the data in the cache, then load the cache */
4890 cache = yaffs_FindChunkCache(in, chunk);
4893 && yaffs_CheckSpaceForAllocation(in->
4895 cache = yaffs_GrabChunkCache(in->myDev);
4897 cache->chunkId = chunk;
4900 yaffs_ReadChunkDataFromObject(in, chunk,
4906 !yaffs_CheckSpaceForAllocation(in->myDev)){
4907 /* Drop the cache if it was a read cache item and
4908 * no space check has been made for it.
4914 yaffs_UseChunkCache(dev, cache, 1);
4918 memcpy(&cache->data[start], buffer,
4923 cache->nBytes = nToWriteBack;
4927 yaffs_WriteChunkDataToObject
4930 cache->data, cache->nBytes,
4936 chunkWritten = -1; /* fail the write */
4939 /* An incomplete start or end chunk (or maybe both start and end chunk)
4940 * Read into the local buffer then copy, then copy over and write back.
4944 yaffs_GetTempBuffer(dev, __LINE__);
4946 yaffs_ReadChunkDataFromObject(in, chunk,
4951 memcpy(&localBuffer[start], buffer, nToCopy);
4954 yaffs_WriteChunkDataToObject(in, chunk,
4959 yaffs_ReleaseTempBuffer(dev, localBuffer,
4965 /* A full chunk. Write directly from the supplied buffer. */
4970 yaffs_WriteChunkDataToObject(in, chunk, buffer,
4971 dev->nDataBytesPerChunk,
4974 /* Since we've overwritten the cached data, we better invalidate it. */
4975 yaffs_InvalidateChunkCache(in, chunk);
4978 if (chunkWritten >= 0) {
4987 /* Update file object */
4989 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
4990 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4999 /* ---------------------- File resizing stuff ------------------ */
5001 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
5004 yaffs_Device *dev = in->myDev;
5005 int oldFileSize = in->variant.fileVariant.fileSize;
5007 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
5009 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
5010 dev->nDataBytesPerChunk;
5014 /* Delete backwards so that we don't end up with holes if
5015 * power is lost part-way through the operation.
5017 for (i = lastDel; i >= startDel; i--) {
5018 /* NB this could be optimised somewhat,
5019 * eg. could retrieve the tags and write them without
5020 * using yaffs_DeleteChunk
5023 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5026 (dev->internalStartBlock * dev->nChunksPerBlock)
5028 ((dev->internalEndBlock +
5029 1) * dev->nChunksPerBlock)) {
5030 T(YAFFS_TRACE_ALWAYS,
5031 (TSTR("Found daft chunkId %d for %d" TENDSTR),
5035 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5042 int yaffs_ResizeFile(yaffs_Object * in, loff_t newSize)
5045 int oldFileSize = in->variant.fileVariant.fileSize;
5046 __u32 newSizeOfPartialChunk;
5049 yaffs_Device *dev = in->myDev;
5051 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5053 yaffs_FlushFilesChunkCache(in);
5054 yaffs_InvalidateWholeChunkCache(in);
5056 yaffs_CheckGarbageCollection(dev);
5058 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
5062 if (newSize == oldFileSize) {
5066 if (newSize < oldFileSize) {
5068 yaffs_PruneResizedChunks(in, newSize);
5070 if (newSizeOfPartialChunk != 0) {
5071 int lastChunk = 1 + newFullChunks;
5073 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5075 /* Got to read and rewrite the last chunk with its new size and zero pad */
5076 yaffs_ReadChunkDataFromObject(in, lastChunk,
5079 memset(localBuffer + newSizeOfPartialChunk, 0,
5080 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5082 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5083 newSizeOfPartialChunk, 1);
5085 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5088 in->variant.fileVariant.fileSize = newSize;
5090 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5092 /* newsSize > oldFileSize */
5093 in->variant.fileVariant.fileSize = newSize;
5098 /* Write a new object header.
5099 * show we've shrunk the file, if need be
5100 * Do this only if the file is not in the deleted directories.
5103 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5104 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
5105 yaffs_UpdateObjectHeader(in, NULL, 0,
5106 (newSize < oldFileSize) ? 1 : 0, 0);
5112 loff_t yaffs_GetFileSize(yaffs_Object * obj)
5114 obj = yaffs_GetEquivalentObject(obj);
5116 switch (obj->variantType) {
5117 case YAFFS_OBJECT_TYPE_FILE:
5118 return obj->variant.fileVariant.fileSize;
5119 case YAFFS_OBJECT_TYPE_SYMLINK:
5120 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5128 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
5132 yaffs_FlushFilesChunkCache(in);
5134 #ifdef CONFIG_YAFFS_WINCE
5135 yfsd_WinFileTimeNow(in->win_mtime);
5138 in->yst_mtime = Y_CURRENT_TIME;
5144 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5145 0) ? YAFFS_OK : YAFFS_FAIL;
5154 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
5157 /* First off, invalidate the file's data in the cache, without flushing. */
5158 yaffs_InvalidateWholeChunkCache(in);
5160 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5161 /* Move to the unlinked directory so we have a record that it was deleted. */
5162 yaffs_ChangeObjectName(in, in->myDev->deletedDir,_Y("deleted"), 0, 0);
5166 yaffs_RemoveObjectFromDirectory(in);
5167 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5170 yaffs_FreeObject(in);
5175 /* yaffs_DeleteFile deletes the whole file data
5176 * and the inode associated with the file.
5177 * It does not delete the links associated with the file.
5180 static int yaffs_UnlinkFile(yaffs_Object * in)
5184 int immediateDeletion = 0;
5188 immediateDeletion = 1;
5191 if (in->inUse <= 0) {
5192 immediateDeletion = 1;
5196 if (immediateDeletion) {
5198 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5199 _Y("deleted"), 0, 0);
5200 T(YAFFS_TRACE_TRACING,
5201 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5204 in->myDev->nDeletedFiles++;
5205 if (1 || in->myDev->isYaffs2) {
5206 yaffs_ResizeFile(in, 0);
5208 yaffs_SoftDeleteFile(in);
5211 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5212 _Y("unlinked"), 0, 0);
5219 int yaffs_DeleteFile(yaffs_Object * in)
5221 int retVal = YAFFS_OK;
5222 int deleted = in->deleted;
5224 yaffs_ResizeFile(in,0);
5226 if (in->nDataChunks > 0) {
5227 /* Use soft deletion if there is data in the file.
5228 * That won't be the case if it has been resized to zero.
5230 if (!in->unlinked) {
5231 retVal = yaffs_UnlinkFile(in);
5233 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5234 in->deleted = deleted = 1;
5235 in->myDev->nDeletedFiles++;
5236 yaffs_SoftDeleteFile(in);
5238 return deleted ? YAFFS_OK : YAFFS_FAIL;
5240 /* The file has no data chunks so we toss it immediately */
5241 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5242 in->variant.fileVariant.top = NULL;
5243 yaffs_DoGenericObjectDeletion(in);
5249 static int yaffs_DeleteDirectory(yaffs_Object * in)
5251 /* First check that the directory is empty. */
5252 if (ylist_empty(&in->variant.directoryVariant.children)) {
5253 return yaffs_DoGenericObjectDeletion(in);
5260 static int yaffs_DeleteSymLink(yaffs_Object * in)
5262 YFREE(in->variant.symLinkVariant.alias);
5264 return yaffs_DoGenericObjectDeletion(in);
5267 static int yaffs_DeleteHardLink(yaffs_Object * in)
5269 /* remove this hardlink from the list assocaited with the equivalent
5272 ylist_del_init(&in->hardLinks);
5273 return yaffs_DoGenericObjectDeletion(in);
5276 static void yaffs_DestroyObject(yaffs_Object * obj)
5278 switch (obj->variantType) {
5279 case YAFFS_OBJECT_TYPE_FILE:
5280 yaffs_DeleteFile(obj);
5282 case YAFFS_OBJECT_TYPE_DIRECTORY:
5283 yaffs_DeleteDirectory(obj);
5285 case YAFFS_OBJECT_TYPE_SYMLINK:
5286 yaffs_DeleteSymLink(obj);
5288 case YAFFS_OBJECT_TYPE_HARDLINK:
5289 yaffs_DeleteHardLink(obj);
5291 case YAFFS_OBJECT_TYPE_SPECIAL:
5292 yaffs_DoGenericObjectDeletion(obj);
5294 case YAFFS_OBJECT_TYPE_UNKNOWN:
5295 break; /* should not happen. */
5299 static int yaffs_UnlinkWorker(yaffs_Object * obj)
5302 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5303 return yaffs_DeleteHardLink(obj);
5304 } else if (!ylist_empty(&obj->hardLinks)) {
5305 /* Curve ball: We're unlinking an object that has a hardlink.
5307 * This problem arises because we are not strictly following
5308 * The Linux link/inode model.
5310 * We can't really delete the object.
5311 * Instead, we do the following:
5312 * - Select a hardlink.
5313 * - Unhook it from the hard links
5314 * - Unhook it from its parent directory (so that the rename can work)
5315 * - Rename the object to the hardlink's name.
5316 * - Delete the hardlink
5321 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5323 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5325 ylist_del_init(&hl->hardLinks);
5326 ylist_del_init(&hl->siblings);
5328 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5330 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
5332 if (retVal == YAFFS_OK) {
5333 retVal = yaffs_DoGenericObjectDeletion(hl);
5338 switch (obj->variantType) {
5339 case YAFFS_OBJECT_TYPE_FILE:
5340 return yaffs_UnlinkFile(obj);
5342 case YAFFS_OBJECT_TYPE_DIRECTORY:
5343 return yaffs_DeleteDirectory(obj);
5345 case YAFFS_OBJECT_TYPE_SYMLINK:
5346 return yaffs_DeleteSymLink(obj);
5348 case YAFFS_OBJECT_TYPE_SPECIAL:
5349 return yaffs_DoGenericObjectDeletion(obj);
5351 case YAFFS_OBJECT_TYPE_HARDLINK:
5352 case YAFFS_OBJECT_TYPE_UNKNOWN:
5360 static int yaffs_UnlinkObject( yaffs_Object *obj)
5363 if (obj && obj->unlinkAllowed) {
5364 return yaffs_UnlinkWorker(obj);
5370 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
5374 obj = yaffs_FindObjectByName(dir, name);
5375 return yaffs_UnlinkObject(obj);
5378 /*----------------------- Initialisation Scanning ---------------------- */
5380 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
5381 int backwardScanning)
5385 if (!backwardScanning) {
5386 /* Handle YAFFS1 forward scanning case
5387 * For YAFFS1 we always do the deletion
5391 /* Handle YAFFS2 case (backward scanning)
5392 * If the shadowed object exists then ignore.
5394 if (yaffs_FindObjectByNumber(dev, objId)) {
5399 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5400 * We put it in unlinked dir to be cleaned up after the scanning
5403 yaffs_FindOrCreateObjectByNumber(dev, objId,
5404 YAFFS_OBJECT_TYPE_FILE);
5405 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5406 obj->variant.fileVariant.shrinkSize = 0;
5407 obj->valid = 1; /* So that we don't read any other info for this file */
5417 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5424 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5426 in = yaffs_FindObjectByNumber(dev,
5427 hl->variant.hardLinkVariant.
5428 equivalentObjectId);
5431 /* Add the hardlink pointers */
5432 hl->variant.hardLinkVariant.equivalentObject = in;
5433 ylist_add(&hl->hardLinks, &in->hardLinks);
5435 /* Todo Need to report/handle this better.
5436 * Got a problem... hardlink to a non-existant object
5438 hl->variant.hardLinkVariant.equivalentObject = NULL;
5439 YINIT_LIST_HEAD(&hl->hardLinks);
5451 static int ybicmp(const void *a, const void *b){
5452 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5453 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5454 register int ablock = ((yaffs_BlockIndex *)a)->block;
5455 register int bblock = ((yaffs_BlockIndex *)b)->block;
5457 return ablock - bblock;
5464 struct yaffs_ShadowFixerStruct {
5467 struct yaffs_ShadowFixerStruct *next;
5471 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5474 * Sort out state of unlinked and deleted objects after scanning.
5476 struct ylist_head *i;
5477 struct ylist_head *n;
5480 /* Soft delete all the unlinked files */
5481 ylist_for_each_safe(i, n,
5482 &dev->unlinkedDir->variant.directoryVariant.children) {
5484 l = ylist_entry(i, yaffs_Object, siblings);
5485 yaffs_DestroyObject(l);
5489 ylist_for_each_safe(i, n,
5490 &dev->deletedDir->variant.directoryVariant.children) {
5492 l = ylist_entry(i, yaffs_Object, siblings);
5493 yaffs_DestroyObject(l);
5499 static int yaffs_Scan(yaffs_Device * dev)
5501 yaffs_ExtendedTags tags;
5511 yaffs_BlockState state;
5512 yaffs_Object *hardList = NULL;
5513 yaffs_BlockInfo *bi;
5514 __u32 sequenceNumber;
5515 yaffs_ObjectHeader *oh;
5517 yaffs_Object *parent;
5519 int alloc_failed = 0;
5521 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5529 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5530 dev->internalStartBlock, dev->internalEndBlock));
5532 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5534 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5536 /* Scan all the blocks to determine their state */
5537 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5538 bi = yaffs_GetBlockInfo(dev, blk);
5539 yaffs_ClearChunkBits(dev, blk);
5541 bi->softDeletions = 0;
5543 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5545 bi->blockState = state;
5546 bi->sequenceNumber = sequenceNumber;
5548 T(YAFFS_TRACE_SCAN_DEBUG,
5549 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5550 state, sequenceNumber));
5552 if (state == YAFFS_BLOCK_STATE_DEAD) {
5553 T(YAFFS_TRACE_BAD_BLOCKS,
5554 (TSTR("block %d is bad" TENDSTR), blk));
5555 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5556 T(YAFFS_TRACE_SCAN_DEBUG,
5557 (TSTR("Block empty " TENDSTR)));
5558 dev->nErasedBlocks++;
5559 dev->nFreeChunks += dev->nChunksPerBlock;
5563 startIterator = dev->internalStartBlock;
5564 endIterator = dev->internalEndBlock;
5566 /* For each block.... */
5567 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5574 blk = blockIterator;
5576 bi = yaffs_GetBlockInfo(dev, blk);
5577 state = bi->blockState;
5581 /* For each chunk in each block that needs scanning....*/
5582 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5583 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5584 /* Read the tags and decide what to do */
5585 chunk = blk * dev->nChunksPerBlock + c;
5587 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5590 /* Let's have a good look at this chunk... */
5592 if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
5598 /*T((" %d %d deleted\n",blk,c)); */
5599 } else if (!tags.chunkUsed) {
5600 /* An unassigned chunk in the block
5601 * This means that either the block is empty or
5602 * this is the one being allocated from
5606 /* We're looking at the first chunk in the block so the block is unused */
5607 state = YAFFS_BLOCK_STATE_EMPTY;
5608 dev->nErasedBlocks++;
5610 /* this is the block being allocated from */
5613 (" Allocating from %d %d" TENDSTR),
5615 state = YAFFS_BLOCK_STATE_ALLOCATING;
5616 dev->allocationBlock = blk;
5617 dev->allocationPage = c;
5618 dev->allocationBlockFinder = blk;
5619 /* Set it to here to encourage the allocator to go forth from here. */
5623 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5624 } else if (tags.chunkId > 0) {
5625 /* chunkId > 0 so it is a data chunk... */
5626 unsigned int endpos;
5628 yaffs_SetChunkBit(dev, blk, c);
5631 in = yaffs_FindOrCreateObjectByNumber(dev,
5634 YAFFS_OBJECT_TYPE_FILE);
5635 /* PutChunkIntoFile checks for a clash (two data chunks with
5636 * the same chunkId).
5643 if(!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,1))
5648 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5651 in->variantType == YAFFS_OBJECT_TYPE_FILE
5652 && in->variant.fileVariant.scannedFileSize <
5654 in->variant.fileVariant.
5655 scannedFileSize = endpos;
5656 if (!dev->useHeaderFileSize) {
5657 in->variant.fileVariant.
5659 in->variant.fileVariant.
5664 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
5666 /* chunkId == 0, so it is an ObjectHeader.
5667 * Thus, we read in the object header and make the object
5669 yaffs_SetChunkBit(dev, blk, c);
5672 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5676 oh = (yaffs_ObjectHeader *) chunkData;
5678 in = yaffs_FindObjectByNumber(dev,
5680 if (in && in->variantType != oh->type) {
5681 /* This should not happen, but somehow
5682 * Wev'e ended up with an objectId that has been reused but not yet
5683 * deleted, and worse still it has changed type. Delete the old object.
5686 yaffs_DestroyObject(in);
5691 in = yaffs_FindOrCreateObjectByNumber(dev,
5699 if (in && oh->shadowsObject > 0) {
5701 struct yaffs_ShadowFixerStruct *fixer;
5702 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
5704 fixer-> next = shadowFixerList;
5705 shadowFixerList = fixer;
5706 fixer->objectId = tags.objectId;
5707 fixer->shadowedId = oh->shadowsObject;
5712 if (in && in->valid) {
5713 /* We have already filled this one. We have a duplicate and need to resolve it. */
5715 unsigned existingSerial = in->serial;
5716 unsigned newSerial = tags.serialNumber;
5718 if (((existingSerial + 1) & 3) == newSerial) {
5719 /* Use new one - destroy the exisiting one */
5720 yaffs_DeleteChunk(dev,
5725 /* Use existing - destroy this one. */
5726 yaffs_DeleteChunk(dev, chunk, 1,
5731 if (in && !in->valid &&
5732 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5733 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5734 /* We only load some info, don't fiddle with directory structure */
5736 in->variantType = oh->type;
5738 in->yst_mode = oh->yst_mode;
5739 #ifdef CONFIG_YAFFS_WINCE
5740 in->win_atime[0] = oh->win_atime[0];
5741 in->win_ctime[0] = oh->win_ctime[0];
5742 in->win_mtime[0] = oh->win_mtime[0];
5743 in->win_atime[1] = oh->win_atime[1];
5744 in->win_ctime[1] = oh->win_ctime[1];
5745 in->win_mtime[1] = oh->win_mtime[1];
5747 in->yst_uid = oh->yst_uid;
5748 in->yst_gid = oh->yst_gid;
5749 in->yst_atime = oh->yst_atime;
5750 in->yst_mtime = oh->yst_mtime;
5751 in->yst_ctime = oh->yst_ctime;
5752 in->yst_rdev = oh->yst_rdev;
5754 in->hdrChunk = chunk;
5755 in->serial = tags.serialNumber;
5757 } else if (in && !in->valid) {
5758 /* we need to load this info */
5761 in->variantType = oh->type;
5763 in->yst_mode = oh->yst_mode;
5764 #ifdef CONFIG_YAFFS_WINCE
5765 in->win_atime[0] = oh->win_atime[0];
5766 in->win_ctime[0] = oh->win_ctime[0];
5767 in->win_mtime[0] = oh->win_mtime[0];
5768 in->win_atime[1] = oh->win_atime[1];
5769 in->win_ctime[1] = oh->win_ctime[1];
5770 in->win_mtime[1] = oh->win_mtime[1];
5772 in->yst_uid = oh->yst_uid;
5773 in->yst_gid = oh->yst_gid;
5774 in->yst_atime = oh->yst_atime;
5775 in->yst_mtime = oh->yst_mtime;
5776 in->yst_ctime = oh->yst_ctime;
5777 in->yst_rdev = oh->yst_rdev;
5779 in->hdrChunk = chunk;
5780 in->serial = tags.serialNumber;
5782 yaffs_SetObjectName(in, oh->name);
5785 /* directory stuff...
5790 yaffs_FindOrCreateObjectByNumber
5791 (dev, oh->parentObjectId,
5792 YAFFS_OBJECT_TYPE_DIRECTORY);
5793 if (parent->variantType ==
5794 YAFFS_OBJECT_TYPE_UNKNOWN) {
5795 /* Set up as a directory */
5796 parent->variantType =
5797 YAFFS_OBJECT_TYPE_DIRECTORY;
5798 YINIT_LIST_HEAD(&parent->variant.
5801 } else if (parent->variantType !=
5802 YAFFS_OBJECT_TYPE_DIRECTORY)
5804 /* Hoosterman, another problem....
5805 * We're trying to use a non-directory as a directory
5808 T(YAFFS_TRACE_ERROR,
5810 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
5812 parent = dev->lostNFoundDir;
5815 yaffs_AddObjectToDirectory(parent, in);
5817 if (0 && (parent == dev->deletedDir ||
5818 parent == dev->unlinkedDir)) {
5819 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
5820 dev->nDeletedFiles++;
5822 /* Note re hardlinks.
5823 * Since we might scan a hardlink before its equivalent object is scanned
5824 * we put them all in a list.
5825 * After scanning is complete, we should have all the objects, so we run through this
5826 * list and fix up all the chains.
5829 switch (in->variantType) {
5830 case YAFFS_OBJECT_TYPE_UNKNOWN:
5831 /* Todo got a problem */
5833 case YAFFS_OBJECT_TYPE_FILE:
5834 if (dev->useHeaderFileSize)
5836 in->variant.fileVariant.
5841 case YAFFS_OBJECT_TYPE_HARDLINK:
5842 in->variant.hardLinkVariant.
5843 equivalentObjectId =
5844 oh->equivalentObjectId;
5845 in->hardLinks.next =
5846 (struct ylist_head *)
5850 case YAFFS_OBJECT_TYPE_DIRECTORY:
5853 case YAFFS_OBJECT_TYPE_SPECIAL:
5856 case YAFFS_OBJECT_TYPE_SYMLINK:
5857 in->variant.symLinkVariant.alias =
5858 yaffs_CloneString(oh->alias);
5859 if(!in->variant.symLinkVariant.alias)
5865 if (parent == dev->deletedDir) {
5866 yaffs_DestroyObject(in);
5867 bi->hasShrinkHeader = 1;
5874 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5875 /* If we got this far while scanning, then the block is fully allocated.*/
5876 state = YAFFS_BLOCK_STATE_FULL;
5879 bi->blockState = state;
5881 /* Now let's see if it was dirty */
5882 if (bi->pagesInUse == 0 &&
5883 !bi->hasShrinkHeader &&
5884 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5885 yaffs_BlockBecameDirty(dev, blk);
5891 /* Ok, we've done all the scanning.
5892 * Fix up the hard link chains.
5893 * We should now have scanned all the objects, now it's time to add these
5897 yaffs_HardlinkFixup(dev,hardList);
5899 /* Fix up any shadowed objects */
5901 struct yaffs_ShadowFixerStruct *fixer;
5904 while(shadowFixerList){
5905 fixer = shadowFixerList;
5906 shadowFixerList = fixer->next;
5907 /* Complete the rename transaction by deleting the shadowed object
5908 * then setting the object header to unshadowed.
5910 obj = yaffs_FindObjectByNumber(dev,fixer->shadowedId);
5912 yaffs_DestroyObject(obj);
5914 obj = yaffs_FindObjectByNumber(dev,fixer->objectId);
5916 yaffs_UpdateObjectHeader(obj,NULL,1,0,0);
5923 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5929 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5935 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5938 yaffs_ObjectHeader *oh;
5940 yaffs_ExtendedTags tags;
5942 int alloc_failed = 0;
5950 T(YAFFS_TRACE_SCAN,(TSTR("details for object %d %s loaded" TENDSTR),
5952 in->lazyLoaded ? "not yet" : "already"));
5955 if(in->lazyLoaded && in->hdrChunk > 0){
5957 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5959 result = yaffs_ReadChunkWithTagsFromNAND(dev,in->hdrChunk,chunkData,&tags);
5960 oh = (yaffs_ObjectHeader *) chunkData;
5962 in->yst_mode = oh->yst_mode;
5963 #ifdef CONFIG_YAFFS_WINCE
5964 in->win_atime[0] = oh->win_atime[0];
5965 in->win_ctime[0] = oh->win_ctime[0];
5966 in->win_mtime[0] = oh->win_mtime[0];
5967 in->win_atime[1] = oh->win_atime[1];
5968 in->win_ctime[1] = oh->win_ctime[1];
5969 in->win_mtime[1] = oh->win_mtime[1];
5971 in->yst_uid = oh->yst_uid;
5972 in->yst_gid = oh->yst_gid;
5973 in->yst_atime = oh->yst_atime;
5974 in->yst_mtime = oh->yst_mtime;
5975 in->yst_ctime = oh->yst_ctime;
5976 in->yst_rdev = oh->yst_rdev;
5979 yaffs_SetObjectName(in, oh->name);
5981 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
5982 in->variant.symLinkVariant.alias =
5983 yaffs_CloneString(oh->alias);
5984 if(!in->variant.symLinkVariant.alias)
5985 alloc_failed = 1; /* Not returned to caller */
5988 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
5992 static int yaffs_ScanBackwards(yaffs_Device * dev)
5994 yaffs_ExtendedTags tags;
5999 int nBlocksToScan = 0;
6005 yaffs_BlockState state;
6006 yaffs_Object *hardList = NULL;
6007 yaffs_BlockInfo *bi;
6008 __u32 sequenceNumber;
6009 yaffs_ObjectHeader *oh;
6011 yaffs_Object *parent;
6012 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6018 int foundChunksInBlock;
6019 int equivalentObjectId;
6020 int alloc_failed = 0;
6023 yaffs_BlockIndex *blockIndex = NULL;
6024 int altBlockIndex = 0;
6026 if (!dev->isYaffs2) {
6028 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6034 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
6035 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6038 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6040 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6043 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6049 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6053 dev->blocksInCheckpoint = 0;
6055 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6057 /* Scan all the blocks to determine their state */
6058 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6059 bi = yaffs_GetBlockInfo(dev, blk);
6060 yaffs_ClearChunkBits(dev, blk);
6062 bi->softDeletions = 0;
6064 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6066 bi->blockState = state;
6067 bi->sequenceNumber = sequenceNumber;
6069 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6070 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6072 T(YAFFS_TRACE_SCAN_DEBUG,
6073 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6074 state, sequenceNumber));
6077 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
6078 dev->blocksInCheckpoint++;
6080 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6081 T(YAFFS_TRACE_BAD_BLOCKS,
6082 (TSTR("block %d is bad" TENDSTR), blk));
6083 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6084 T(YAFFS_TRACE_SCAN_DEBUG,
6085 (TSTR("Block empty " TENDSTR)));
6086 dev->nErasedBlocks++;
6087 dev->nFreeChunks += dev->nChunksPerBlock;
6088 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6090 /* Determine the highest sequence number */
6091 if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6092 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6094 blockIndex[nBlocksToScan].seq = sequenceNumber;
6095 blockIndex[nBlocksToScan].block = blk;
6099 if (sequenceNumber >= dev->sequenceNumber) {
6100 dev->sequenceNumber = sequenceNumber;
6103 /* TODO: Nasty sequence number! */
6106 ("Block scanning block %d has bad sequence number %d"
6107 TENDSTR), blk, sequenceNumber));
6114 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6120 /* Sort the blocks */
6121 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6123 /* Use qsort now. */
6124 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6128 /* Dungy old bubble sort... */
6130 yaffs_BlockIndex temp;
6134 for (i = 0; i < nBlocksToScan; i++)
6135 for (j = i + 1; j < nBlocksToScan; j++)
6136 if (blockIndex[i].seq > blockIndex[j].seq) {
6137 temp = blockIndex[j];
6138 blockIndex[j] = blockIndex[i];
6139 blockIndex[i] = temp;
6146 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6148 /* Now scan the blocks looking at the data. */
6150 endIterator = nBlocksToScan - 1;
6151 T(YAFFS_TRACE_SCAN_DEBUG,
6152 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6154 /* For each block.... backwards */
6155 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6157 /* Cooperative multitasking! This loop can run for so
6158 long that watchdog timers expire. */
6161 /* get the block to scan in the correct order */
6162 blk = blockIndex[blockIterator].block;
6164 bi = yaffs_GetBlockInfo(dev, blk);
6167 state = bi->blockState;
6171 /* For each chunk in each block that needs scanning.... */
6172 foundChunksInBlock = 0;
6173 for (c = dev->nChunksPerBlock - 1;
6174 !alloc_failed && c >= 0 &&
6175 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6176 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6177 /* Scan backwards...
6178 * Read the tags and decide what to do
6181 chunk = blk * dev->nChunksPerBlock + c;
6183 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6186 /* Let's have a good look at this chunk... */
6188 if (!tags.chunkUsed) {
6189 /* An unassigned chunk in the block.
6190 * If there are used chunks after this one, then
6191 * it is a chunk that was skipped due to failing the erased
6192 * check. Just skip it so that it can be deleted.
6193 * But, more typically, We get here when this is an unallocated
6194 * chunk and his means that either the block is empty or
6195 * this is the one being allocated from
6198 if(foundChunksInBlock)
6200 /* This is a chunk that was skipped due to failing the erased check */
6202 } else if (c == 0) {
6203 /* We're looking at the first chunk in the block so the block is unused */
6204 state = YAFFS_BLOCK_STATE_EMPTY;
6205 dev->nErasedBlocks++;
6207 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6208 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6209 if(dev->sequenceNumber == bi->sequenceNumber) {
6210 /* this is the block being allocated from */
6214 (" Allocating from %d %d"
6217 state = YAFFS_BLOCK_STATE_ALLOCATING;
6218 dev->allocationBlock = blk;
6219 dev->allocationPage = c;
6220 dev->allocationBlockFinder = blk;
6223 /* This is a partially written block that is not
6224 * the current allocation block. This block must have
6225 * had a write failure, so set up for retirement.
6228 /* bi->needsRetiring = 1; ??? TODO */
6229 bi->gcPrioritise = 1;
6231 T(YAFFS_TRACE_ALWAYS,
6232 (TSTR("Partially written block %d detected" TENDSTR),
6242 } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED){
6244 (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
6249 }else if (tags.chunkId > 0) {
6250 /* chunkId > 0 so it is a data chunk... */
6251 unsigned int endpos;
6253 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6255 foundChunksInBlock = 1;
6258 yaffs_SetChunkBit(dev, blk, c);
6261 in = yaffs_FindOrCreateObjectByNumber(dev,
6264 YAFFS_OBJECT_TYPE_FILE);
6271 in->variantType == YAFFS_OBJECT_TYPE_FILE
6273 in->variant.fileVariant.shrinkSize) {
6274 /* This has not been invalidated by a resize */
6275 if(!yaffs_PutChunkIntoFile(in, tags.chunkId,
6280 /* File size is calculated by looking at the data chunks if we have not
6281 * seen an object header yet. Stop this practice once we find an object header.
6285 1) * dev->nDataBytesPerChunk +
6288 if (!in->valid && /* have not got an object header yet */
6289 in->variant.fileVariant.
6290 scannedFileSize < endpos) {
6291 in->variant.fileVariant.
6292 scannedFileSize = endpos;
6293 in->variant.fileVariant.
6295 in->variant.fileVariant.
6300 /* This chunk has been invalidated by a resize, so delete */
6301 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6305 /* chunkId == 0, so it is an ObjectHeader.
6306 * Thus, we read in the object header and make the object
6308 foundChunksInBlock = 1;
6310 yaffs_SetChunkBit(dev, blk, c);
6316 if (tags.extraHeaderInfoAvailable) {
6317 in = yaffs_FindOrCreateObjectByNumber
6318 (dev, tags.objectId,
6319 tags.extraObjectType);
6323 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
6326 tags.extraShadows ||
6328 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6329 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
6332 /* If we don't have valid info then we need to read the chunk
6333 * TODO In future we can probably defer reading the chunk and
6334 * living with invalid data until needed.
6337 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6342 oh = (yaffs_ObjectHeader *) chunkData;
6344 if(dev->inbandTags){
6345 /* Fix up the header if they got corrupted by inband tags */
6346 oh->shadowsObject = oh->inbandShadowsObject;
6347 oh->isShrink = oh->inbandIsShrink;
6351 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6356 /* TODO Hoosterman we have a problem! */
6357 T(YAFFS_TRACE_ERROR,
6359 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6360 TENDSTR), tags.objectId, chunk));
6365 /* We have already filled this one.
6366 * We have a duplicate that will be discarded, but
6367 * we first have to suck out resize info if it is a file.
6370 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6372 oh-> type == YAFFS_OBJECT_TYPE_FILE)||
6373 (tags.extraHeaderInfoAvailable &&
6374 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
6377 (oh) ? oh->fileSize : tags.
6379 __u32 parentObjectId =
6381 parentObjectId : tags.
6382 extraParentObjectId;
6386 (oh) ? oh->isShrink : tags.
6387 extraIsShrinkHeader;
6389 /* If it is deleted (unlinked at start also means deleted)
6390 * we treat the file size as being zeroed at this point.
6392 if (parentObjectId ==
6393 YAFFS_OBJECTID_DELETED
6394 || parentObjectId ==
6395 YAFFS_OBJECTID_UNLINKED) {
6401 in->variant.fileVariant.
6402 shrinkSize > thisSize) {
6403 in->variant.fileVariant.
6409 bi->hasShrinkHeader = 1;
6413 /* Use existing - destroy this one. */
6414 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6419 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6421 YAFFS_OBJECTID_LOSTNFOUND)) {
6422 /* We only load some info, don't fiddle with directory structure */
6426 in->variantType = oh->type;
6428 in->yst_mode = oh->yst_mode;
6429 #ifdef CONFIG_YAFFS_WINCE
6430 in->win_atime[0] = oh->win_atime[0];
6431 in->win_ctime[0] = oh->win_ctime[0];
6432 in->win_mtime[0] = oh->win_mtime[0];
6433 in->win_atime[1] = oh->win_atime[1];
6434 in->win_ctime[1] = oh->win_ctime[1];
6435 in->win_mtime[1] = oh->win_mtime[1];
6437 in->yst_uid = oh->yst_uid;
6438 in->yst_gid = oh->yst_gid;
6439 in->yst_atime = oh->yst_atime;
6440 in->yst_mtime = oh->yst_mtime;
6441 in->yst_ctime = oh->yst_ctime;
6442 in->yst_rdev = oh->yst_rdev;
6446 in->variantType = tags.extraObjectType;
6450 in->hdrChunk = chunk;
6452 } else if (!in->valid) {
6453 /* we need to load this info */
6456 in->hdrChunk = chunk;
6459 in->variantType = oh->type;
6461 in->yst_mode = oh->yst_mode;
6462 #ifdef CONFIG_YAFFS_WINCE
6463 in->win_atime[0] = oh->win_atime[0];
6464 in->win_ctime[0] = oh->win_ctime[0];
6465 in->win_mtime[0] = oh->win_mtime[0];
6466 in->win_atime[1] = oh->win_atime[1];
6467 in->win_ctime[1] = oh->win_ctime[1];
6468 in->win_mtime[1] = oh->win_mtime[1];
6470 in->yst_uid = oh->yst_uid;
6471 in->yst_gid = oh->yst_gid;
6472 in->yst_atime = oh->yst_atime;
6473 in->yst_mtime = oh->yst_mtime;
6474 in->yst_ctime = oh->yst_ctime;
6475 in->yst_rdev = oh->yst_rdev;
6478 if (oh->shadowsObject > 0)
6479 yaffs_HandleShadowedObject(dev,
6485 yaffs_SetObjectName(in, oh->name);
6487 yaffs_FindOrCreateObjectByNumber
6488 (dev, oh->parentObjectId,
6489 YAFFS_OBJECT_TYPE_DIRECTORY);
6491 fileSize = oh->fileSize;
6492 isShrink = oh->isShrink;
6493 equivalentObjectId = oh->equivalentObjectId;
6497 in->variantType = tags.extraObjectType;
6499 yaffs_FindOrCreateObjectByNumber
6500 (dev, tags.extraParentObjectId,
6501 YAFFS_OBJECT_TYPE_DIRECTORY);
6502 fileSize = tags.extraFileLength;
6503 isShrink = tags.extraIsShrinkHeader;
6504 equivalentObjectId = tags.extraEquivalentObjectId;
6510 /* directory stuff...
6514 if (parent->variantType ==
6515 YAFFS_OBJECT_TYPE_UNKNOWN) {
6516 /* Set up as a directory */
6517 parent->variantType =
6518 YAFFS_OBJECT_TYPE_DIRECTORY;
6519 YINIT_LIST_HEAD(&parent->variant.
6522 } else if (parent->variantType !=
6523 YAFFS_OBJECT_TYPE_DIRECTORY)
6525 /* Hoosterman, another problem....
6526 * We're trying to use a non-directory as a directory
6529 T(YAFFS_TRACE_ERROR,
6531 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6533 parent = dev->lostNFoundDir;
6536 yaffs_AddObjectToDirectory(parent, in);
6538 itsUnlinked = (parent == dev->deletedDir) ||
6539 (parent == dev->unlinkedDir);
6542 /* Mark the block as having a shrinkHeader */
6543 bi->hasShrinkHeader = 1;
6546 /* Note re hardlinks.
6547 * Since we might scan a hardlink before its equivalent object is scanned
6548 * we put them all in a list.
6549 * After scanning is complete, we should have all the objects, so we run
6550 * through this list and fix up all the chains.
6553 switch (in->variantType) {
6554 case YAFFS_OBJECT_TYPE_UNKNOWN:
6555 /* Todo got a problem */
6557 case YAFFS_OBJECT_TYPE_FILE:
6559 if (in->variant.fileVariant.
6560 scannedFileSize < fileSize) {
6561 /* This covers the case where the file size is greater
6562 * than where the data is
6563 * This will happen if the file is resized to be larger
6564 * than its current data extents.
6566 in->variant.fileVariant.fileSize = fileSize;
6567 in->variant.fileVariant.scannedFileSize =
6568 in->variant.fileVariant.fileSize;
6572 in->variant.fileVariant.shrinkSize > fileSize) {
6573 in->variant.fileVariant.shrinkSize = fileSize;
6577 case YAFFS_OBJECT_TYPE_HARDLINK:
6579 in->variant.hardLinkVariant.equivalentObjectId =
6581 in->hardLinks.next =
6582 (struct ylist_head *) hardList;
6586 case YAFFS_OBJECT_TYPE_DIRECTORY:
6589 case YAFFS_OBJECT_TYPE_SPECIAL:
6592 case YAFFS_OBJECT_TYPE_SYMLINK:
6594 in->variant.symLinkVariant.alias =
6595 yaffs_CloneString(oh->
6597 if(!in->variant.symLinkVariant.alias)
6607 } /* End of scanning for each chunk */
6609 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6610 /* If we got this far while scanning, then the block is fully allocated. */
6611 state = YAFFS_BLOCK_STATE_FULL;
6614 bi->blockState = state;
6616 /* Now let's see if it was dirty */
6617 if (bi->pagesInUse == 0 &&
6618 !bi->hasShrinkHeader &&
6619 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6620 yaffs_BlockBecameDirty(dev, blk);
6626 YFREE_ALT(blockIndex);
6630 /* Ok, we've done all the scanning.
6631 * Fix up the hard link chains.
6632 * We should now have scanned all the objects, now it's time to add these
6635 yaffs_HardlinkFixup(dev,hardList);
6638 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6644 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6649 /*------------------------------ Directory Functions ----------------------------- */
6651 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
6653 struct ylist_head *lh;
6654 yaffs_Object *listObj;
6659 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
6663 if(yaffs_SkipVerification(obj->myDev))
6667 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
6671 if(obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
6672 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
6676 /* Iterate through the objects in each hash entry */
6678 ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
6680 listObj = ylist_entry(lh, yaffs_Object, siblings);
6681 yaffs_VerifyObject(listObj);
6688 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR),count));
6694 static void yaffs_VerifyDirectory(yaffs_Object *directory)
6697 struct ylist_head *lh;
6698 yaffs_Object *listObj;
6703 if(yaffs_SkipFullVerification(directory->myDev))
6707 if(directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
6708 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR),directory->variantType));
6712 /* Iterate through the objects in each hash entry */
6714 ylist_for_each(lh, &directory->variant.directoryVariant.children) {
6716 listObj = ylist_entry(lh, yaffs_Object, siblings);
6717 if(listObj->parent != directory){
6718 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR),listObj->parent));
6721 yaffs_VerifyObjectInDirectory(listObj);
6728 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
6730 yaffs_Device *dev = obj->myDev;
6731 yaffs_Object *parent;
6733 yaffs_VerifyObjectInDirectory(obj);
6734 parent = obj->parent;
6736 yaffs_VerifyDirectory(parent);
6738 if(dev && dev->removeObjectCallback)
6739 dev->removeObjectCallback(obj);
6742 ylist_del_init(&obj->siblings);
6745 yaffs_VerifyDirectory(parent);
6750 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
6755 T(YAFFS_TRACE_ALWAYS,
6757 ("tragedy: Trying to add an object to a null pointer directory"
6761 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6762 T(YAFFS_TRACE_ALWAYS,
6764 ("tragedy: Trying to add an object to a non-directory"
6769 if (obj->siblings.prev == NULL) {
6770 /* Not initialised */
6773 } else if (ylist_empty(&obj->siblings)) {
6778 yaffs_VerifyDirectory(directory);
6780 yaffs_RemoveObjectFromDirectory(obj);
6784 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
6785 obj->parent = directory;
6787 if (directory == obj->myDev->unlinkedDir
6788 || directory == obj->myDev->deletedDir) {
6790 obj->myDev->nUnlinkedFiles++;
6791 obj->renameAllowed = 0;
6794 yaffs_VerifyDirectory(directory);
6795 yaffs_VerifyObjectInDirectory(obj);
6800 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
6805 struct ylist_head *i;
6806 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
6815 T(YAFFS_TRACE_ALWAYS,
6817 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6821 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6822 T(YAFFS_TRACE_ALWAYS,
6824 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6828 sum = yaffs_CalcNameSum(name);
6830 ylist_for_each(i, &directory->variant.directoryVariant.children) {
6832 l = ylist_entry(i, yaffs_Object, siblings);
6834 if(l->parent != directory)
6837 yaffs_CheckObjectDetailsLoaded(l);
6839 /* Special case for lost-n-found */
6840 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6841 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
6844 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0){
6845 /* LostnFound chunk called Objxxx
6848 yaffs_GetObjectName(l, buffer,
6849 YAFFS_MAX_NAME_LENGTH);
6850 if (yaffs_strncmp(name, buffer,YAFFS_MAX_NAME_LENGTH) == 0) {
6863 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
6864 int (*fn) (yaffs_Object *))
6866 struct ylist_head *i;
6870 T(YAFFS_TRACE_ALWAYS,
6872 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6876 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6877 T(YAFFS_TRACE_ALWAYS,
6879 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6883 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
6885 l = ylist_entry(i, yaffs_Object, siblings);
6897 /* GetEquivalentObject dereferences any hard links to get to the
6901 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
6903 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
6904 /* We want the object id of the equivalent object, not this one */
6905 obj = obj->variant.hardLinkVariant.equivalentObject;
6906 yaffs_CheckObjectDetailsLoaded(obj);
6912 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
6914 memset(name, 0, buffSize * sizeof(YCHAR));
6916 yaffs_CheckObjectDetailsLoaded(obj);
6918 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6919 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
6920 } else if (obj->hdrChunk <= 0) {
6922 YCHAR numString[20];
6923 YCHAR *x = &numString[19];
6924 unsigned v = obj->objectId;
6928 *x = '0' + (v % 10);
6931 /* make up a name */
6932 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
6933 yaffs_strcat(locName,x);
6934 yaffs_strncpy(name, locName, buffSize - 1);
6937 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
6938 else if (obj->shortName[0]) {
6939 yaffs_strcpy(name, obj->shortName);
6944 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
6946 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
6948 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
6950 if (obj->hdrChunk > 0) {
6951 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
6952 obj->hdrChunk, buffer,
6955 yaffs_strncpy(name, oh->name, buffSize - 1);
6957 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
6960 return yaffs_strlen(name);
6963 int yaffs_GetObjectFileLength(yaffs_Object * obj)
6966 /* Dereference any hard linking */
6967 obj = yaffs_GetEquivalentObject(obj);
6969 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
6970 return obj->variant.fileVariant.fileSize;
6972 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6973 return yaffs_strlen(obj->variant.symLinkVariant.alias);
6975 /* Only a directory should drop through to here */
6976 return obj->myDev->nDataBytesPerChunk;
6980 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
6983 struct ylist_head *i;
6985 if (!obj->unlinked) {
6986 count++; /* the object itself */
6988 ylist_for_each(i, &obj->hardLinks) {
6989 count++; /* add the hard links; */
6995 int yaffs_GetObjectInode(yaffs_Object * obj)
6997 obj = yaffs_GetEquivalentObject(obj);
6999 return obj->objectId;
7002 unsigned yaffs_GetObjectType(yaffs_Object * obj)
7004 obj = yaffs_GetEquivalentObject(obj);
7006 switch (obj->variantType) {
7007 case YAFFS_OBJECT_TYPE_FILE:
7010 case YAFFS_OBJECT_TYPE_DIRECTORY:
7013 case YAFFS_OBJECT_TYPE_SYMLINK:
7016 case YAFFS_OBJECT_TYPE_HARDLINK:
7019 case YAFFS_OBJECT_TYPE_SPECIAL:
7020 if (S_ISFIFO(obj->yst_mode))
7022 if (S_ISCHR(obj->yst_mode))
7024 if (S_ISBLK(obj->yst_mode))
7026 if (S_ISSOCK(obj->yst_mode))
7034 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
7036 obj = yaffs_GetEquivalentObject(obj);
7037 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
7038 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7040 return yaffs_CloneString(_Y(""));
7044 #ifndef CONFIG_YAFFS_WINCE
7046 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
7048 unsigned int valid = attr->ia_valid;
7050 if (valid & ATTR_MODE)
7051 obj->yst_mode = attr->ia_mode;
7052 if (valid & ATTR_UID)
7053 obj->yst_uid = attr->ia_uid;
7054 if (valid & ATTR_GID)
7055 obj->yst_gid = attr->ia_gid;
7057 if (valid & ATTR_ATIME)
7058 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7059 if (valid & ATTR_CTIME)
7060 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7061 if (valid & ATTR_MTIME)
7062 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7064 if (valid & ATTR_SIZE)
7065 yaffs_ResizeFile(obj, attr->ia_size);
7067 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7072 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
7074 unsigned int valid = 0;
7076 attr->ia_mode = obj->yst_mode;
7078 attr->ia_uid = obj->yst_uid;
7080 attr->ia_gid = obj->yst_gid;
7083 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7084 valid |= ATTR_ATIME;
7085 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7086 valid |= ATTR_CTIME;
7087 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7088 valid |= ATTR_MTIME;
7090 attr->ia_size = yaffs_GetFileSize(obj);
7093 attr->ia_valid = valid;
7102 int yaffs_DumpObject(yaffs_Object * obj)
7106 yaffs_GetObjectName(obj, name, 256);
7108 T(YAFFS_TRACE_ALWAYS,
7110 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7111 " chunk %d type %d size %d\n"
7112 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7113 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7114 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7120 /*---------------------------- Initialisation code -------------------------------------- */
7122 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
7125 /* Common functions, gotta have */
7126 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
7129 #ifdef CONFIG_YAFFS_YAFFS2
7131 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7132 if (dev->writeChunkWithTagsToNAND &&
7133 dev->readChunkWithTagsFromNAND &&
7134 !dev->writeChunkToNAND &&
7135 !dev->readChunkFromNAND &&
7136 dev->markNANDBlockBad && dev->queryNANDBlock)
7140 /* Can use the "spare" style interface for yaffs1 */
7141 if (!dev->isYaffs2 &&
7142 !dev->writeChunkWithTagsToNAND &&
7143 !dev->readChunkWithTagsFromNAND &&
7144 dev->writeChunkToNAND &&
7145 dev->readChunkFromNAND &&
7146 !dev->markNANDBlockBad && !dev->queryNANDBlock)
7153 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7155 /* Initialise the unlinked, deleted, root and lost and found directories */
7157 dev->lostNFoundDir = dev->rootDir = NULL;
7158 dev->unlinkedDir = dev->deletedDir = NULL;
7161 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7164 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7167 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7168 YAFFS_ROOT_MODE | S_IFDIR);
7169 dev->lostNFoundDir =
7170 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7171 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7173 if(dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir){
7174 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7181 int yaffs_GutsInitialise(yaffs_Device * dev)
7183 int init_failed = 0;
7187 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7189 /* Check stuff that must be set */
7192 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7196 dev->internalStartBlock = dev->startBlock;
7197 dev->internalEndBlock = dev->endBlock;
7198 dev->blockOffset = 0;
7199 dev->chunkOffset = 0;
7200 dev->nFreeChunks = 0;
7204 if (dev->startBlock == 0) {
7205 dev->internalStartBlock = dev->startBlock + 1;
7206 dev->internalEndBlock = dev->endBlock + 1;
7207 dev->blockOffset = 1;
7208 dev->chunkOffset = dev->nChunksPerBlock;
7211 /* Check geometry parameters. */
7213 if ((!dev->inbandTags && dev->isYaffs2 && dev->totalBytesPerChunk < 1024) ||
7214 (!dev->isYaffs2 && dev->totalBytesPerChunk < 512) ||
7215 (dev->inbandTags && !dev->isYaffs2 ) ||
7216 dev->nChunksPerBlock < 2 ||
7217 dev->nReservedBlocks < 2 ||
7218 dev->internalStartBlock <= 0 ||
7219 dev->internalEndBlock <= 0 ||
7220 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
7222 T(YAFFS_TRACE_ALWAYS,
7224 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7225 TENDSTR), dev->totalBytesPerChunk, dev->isYaffs2 ? "2" : "", dev->inbandTags));
7229 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7230 T(YAFFS_TRACE_ALWAYS,
7231 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7235 /* Sort out space for inband tags, if required */
7237 dev->nDataBytesPerChunk = dev->totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7239 dev->nDataBytesPerChunk = dev->totalBytesPerChunk;
7241 /* Got the right mix of functions? */
7242 if (!yaffs_CheckDevFunctions(dev)) {
7243 /* Function missing */
7244 T(YAFFS_TRACE_ALWAYS,
7246 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7251 /* This is really a compilation check. */
7252 if (!yaffs_CheckStructures()) {
7253 T(YAFFS_TRACE_ALWAYS,
7254 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7258 if (dev->isMounted) {
7259 T(YAFFS_TRACE_ALWAYS,
7260 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7264 /* Finished with most checks. One or two more checks happen later on too. */
7268 /* OK now calculate a few things for the device */
7271 * Calculate all the chunk size manipulation numbers:
7273 x = dev->nDataBytesPerChunk;
7274 /* We always use dev->chunkShift and dev->chunkDiv */
7275 dev->chunkShift = Shifts(x);
7276 x >>= dev->chunkShift;
7278 /* We only use chunk mask if chunkDiv is 1 */
7279 dev->chunkMask = (1<<dev->chunkShift) - 1;
7282 * Calculate chunkGroupBits.
7283 * We need to find the next power of 2 > than internalEndBlock
7286 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7290 /* Set up tnode width if wide tnodes are enabled. */
7291 if(!dev->wideTnodesDisabled){
7292 /* bits must be even so that we end up with 32-bit words */
7296 dev->tnodeWidth = 16;
7298 dev->tnodeWidth = bits;
7301 dev->tnodeWidth = 16;
7303 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7305 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7306 * so if the bitwidth of the
7307 * chunk range we're using is greater than 16 we need
7308 * to figure out chunk shift and chunkGroupSize
7311 if (bits <= dev->tnodeWidth)
7312 dev->chunkGroupBits = 0;
7314 dev->chunkGroupBits = bits - dev->tnodeWidth;
7317 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7319 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7320 /* We have a problem because the soft delete won't work if
7321 * the chunk group size > chunks per block.
7322 * This can be remedied by using larger "virtual blocks".
7324 T(YAFFS_TRACE_ALWAYS,
7325 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7330 /* OK, we've finished verifying the device, lets continue with initialisation */
7332 /* More device initialisation */
7333 dev->garbageCollections = 0;
7334 dev->passiveGarbageCollections = 0;
7335 dev->currentDirtyChecker = 0;
7336 dev->bufferedBlock = -1;
7337 dev->doingBufferedBlockRewrite = 0;
7338 dev->nDeletedFiles = 0;
7339 dev->nBackgroundDeletions = 0;
7340 dev->nUnlinkedFiles = 0;
7342 dev->eccUnfixed = 0;
7343 dev->tagsEccFixed = 0;
7344 dev->tagsEccUnfixed = 0;
7345 dev->nErasureFailures = 0;
7346 dev->nErasedBlocks = 0;
7348 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7350 /* Initialise temporary buffers and caches. */
7351 if(!yaffs_InitialiseTempBuffers(dev))
7354 dev->srCache = NULL;
7355 dev->gcCleanupList = NULL;
7359 dev->nShortOpCaches > 0) {
7362 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7364 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
7365 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7368 dev->srCache = YMALLOC(srCacheBytes);
7370 buf = (__u8 *) dev->srCache;
7373 memset(dev->srCache,0,srCacheBytes);
7375 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7376 dev->srCache[i].object = NULL;
7377 dev->srCache[i].lastUse = 0;
7378 dev->srCache[i].dirty = 0;
7379 dev->srCache[i].data = buf = YMALLOC_DMA(dev->totalBytesPerChunk);
7390 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7391 if(!dev->gcCleanupList)
7395 if (dev->isYaffs2) {
7396 dev->useHeaderFileSize = 1;
7398 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7401 yaffs_InitialiseTnodes(dev);
7402 yaffs_InitialiseObjects(dev);
7404 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7409 /* Now scan the flash. */
7410 if (dev->isYaffs2) {
7411 if(yaffs_CheckpointRestore(dev)) {
7412 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7413 T(YAFFS_TRACE_ALWAYS,
7414 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7417 /* Clean up the mess caused by an aborted checkpoint load
7418 * and scan backwards.
7420 yaffs_DeinitialiseBlocks(dev);
7421 yaffs_DeinitialiseTnodes(dev);
7422 yaffs_DeinitialiseObjects(dev);
7425 dev->nErasedBlocks = 0;
7426 dev->nFreeChunks = 0;
7427 dev->allocationBlock = -1;
7428 dev->allocationPage = -1;
7429 dev->nDeletedFiles = 0;
7430 dev->nUnlinkedFiles = 0;
7431 dev->nBackgroundDeletions = 0;
7432 dev->oldestDirtySequence = 0;
7434 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7437 yaffs_InitialiseTnodes(dev);
7438 yaffs_InitialiseObjects(dev);
7440 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7443 if(!init_failed && !yaffs_ScanBackwards(dev))
7447 if(!yaffs_Scan(dev))
7450 yaffs_StripDeletedObjects(dev);
7454 /* Clean up the mess */
7455 T(YAFFS_TRACE_TRACING,
7456 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7458 yaffs_Deinitialise(dev);
7462 /* Zero out stats */
7463 dev->nPageReads = 0;
7464 dev->nPageWrites = 0;
7465 dev->nBlockErasures = 0;
7467 dev->nRetriedWrites = 0;
7469 dev->nRetiredBlocks = 0;
7471 yaffs_VerifyFreeChunks(dev);
7472 yaffs_VerifyBlocks(dev);
7475 T(YAFFS_TRACE_TRACING,
7476 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7481 void yaffs_Deinitialise(yaffs_Device * dev)
7483 if (dev->isMounted) {
7486 yaffs_DeinitialiseBlocks(dev);
7487 yaffs_DeinitialiseTnodes(dev);
7488 yaffs_DeinitialiseObjects(dev);
7489 if (dev->nShortOpCaches > 0 &&
7492 for (i = 0; i < dev->nShortOpCaches; i++) {
7493 if(dev->srCache[i].data)
7494 YFREE(dev->srCache[i].data);
7495 dev->srCache[i].data = NULL;
7498 YFREE(dev->srCache);
7499 dev->srCache = NULL;
7502 YFREE(dev->gcCleanupList);
7504 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
7505 YFREE(dev->tempBuffer[i].buffer);
7511 if(dev->deinitialiseNAND)
7512 dev->deinitialiseNAND(dev);
7517 static int yaffs_CountFreeChunks(yaffs_Device * dev)
7522 yaffs_BlockInfo *blk;
7524 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7526 blk = yaffs_GetBlockInfo(dev, b);
7528 switch (blk->blockState) {
7529 case YAFFS_BLOCK_STATE_EMPTY:
7530 case YAFFS_BLOCK_STATE_ALLOCATING:
7531 case YAFFS_BLOCK_STATE_COLLECTING:
7532 case YAFFS_BLOCK_STATE_FULL:
7534 (dev->nChunksPerBlock - blk->pagesInUse +
7535 blk->softDeletions);
7546 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
7548 /* This is what we report to the outside world */
7551 int nDirtyCacheChunks;
7552 int blocksForCheckpoint;
7555 nFree = dev->nFreeChunks;
7557 nFree = yaffs_CountFreeChunks(dev);
7560 nFree += dev->nDeletedFiles;
7562 /* Now count the number of dirty chunks in the cache and subtract those */
7566 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7567 if (dev->srCache[i].dirty)
7568 nDirtyCacheChunks++;
7572 nFree -= nDirtyCacheChunks;
7574 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7576 /* Now we figure out how much to reserve for the checkpoint and report that... */
7577 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7578 if(blocksForCheckpoint < 0)
7579 blocksForCheckpoint = 0;
7581 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7590 static int yaffs_freeVerificationFailures;
7592 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
7597 if(yaffs_SkipVerification(dev))
7600 counted = yaffs_CountFreeChunks(dev);
7602 difference = dev->nFreeChunks - counted;
7605 T(YAFFS_TRACE_ALWAYS,
7606 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7607 dev->nFreeChunks, counted, difference));
7608 yaffs_freeVerificationFailures++;
7612 /*---------------------------------------- YAFFS test code ----------------------*/
7614 #define yaffs_CheckStruct(structure,syze, name) \
7616 if(sizeof(structure) != syze) \
7618 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
7619 name,syze,sizeof(structure))); \
7620 return YAFFS_FAIL; \
7624 static int yaffs_CheckStructures(void)
7626 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
7627 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
7628 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
7629 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7630 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode");
7632 #ifndef CONFIG_YAFFS_WINCE
7633 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");