2 * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
4 * Copyright (C) 2002-2007 Aleph One Ltd.
5 * for Toby Churchill Ltd and Brightstar Engineering
7 * Created by Charles Manning <charles@aleph1.co.uk>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2 as
11 * published by the Free Software Foundation.
14 const char *yaffs_guts_c_version =
15 "$Id: yaffs_guts.c,v 1.53 2007-12-03 03:21:48 charles Exp $";
19 #include "yaffsinterface.h"
20 #include "yaffs_guts.h"
21 #include "yaffs_tagsvalidity.h"
23 #include "yaffs_tagscompat.h"
24 #ifndef CONFIG_YAFFS_USE_OWN_SORT
25 #include "yaffs_qsort.h"
27 #include "yaffs_nand.h"
29 #include "yaffs_checkptrw.h"
31 #include "yaffs_nand.h"
32 #include "yaffs_packedtags2.h"
35 #ifdef CONFIG_YAFFS_WINCE
36 void yfsd_LockYAFFS(BOOL fsLockOnly);
37 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
40 #define YAFFS_PASSIVE_GC_CHUNKS 2
42 #include "yaffs_ecc.h"
45 /* Robustification (if it ever comes about...) */
46 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
47 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk);
48 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
50 const yaffs_ExtendedTags * tags);
51 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
52 const yaffs_ExtendedTags * tags);
54 /* Other local prototypes */
55 static int yaffs_UnlinkObject( yaffs_Object *obj);
56 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
58 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
60 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
62 yaffs_ExtendedTags * tags,
64 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
65 int chunkInNAND, int inScan);
67 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
68 yaffs_ObjectType type);
69 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
71 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
72 int force, int isShrink, int shadows);
73 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
74 static int yaffs_CheckStructures(void);
75 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
76 int chunkOffset, int *limit);
77 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
79 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
81 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo);
82 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
85 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
88 static int yaffs_UnlinkWorker(yaffs_Object * obj);
89 static void yaffs_DestroyObject(yaffs_Object * obj);
91 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
94 loff_t yaffs_GetFileSize(yaffs_Object * obj);
96 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr);
98 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
100 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
102 #ifdef YAFFS_PARANOID
103 static int yaffs_CheckFileSanity(yaffs_Object * in);
105 #define yaffs_CheckFileSanity(in)
108 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
109 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
111 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
113 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
114 yaffs_ExtendedTags * tags);
116 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos);
117 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
118 yaffs_FileStructure * fStruct,
122 /* Function to calculate chunk and offset */
124 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, __u32 *chunk, __u32 *offset)
127 /* Easy-peasy power of 2 case */
128 *chunk = (__u32)(addr >> dev->chunkShift);
129 *offset = (__u32)(addr & dev->chunkMask);
131 else if(dev->crumbsPerChunk)
133 /* Case where we're using "crumbs" */
134 *offset = (__u32)(addr & dev->crumbMask);
135 addr >>= dev->crumbShift;
136 *chunk = ((__u32)addr)/dev->crumbsPerChunk;
137 *offset += ((addr - (*chunk * dev->crumbsPerChunk)) << dev->crumbShift);
143 /* Function to return the number of shifts for a power of 2 greater than or equal
144 * to the given number
145 * Note we don't try to cater for all possible numbers and this does not have to
146 * be hellishly efficient.
149 static __u32 ShiftsGE(__u32 x)
154 nShifts = extraBits = 0;
157 if(x & 1) extraBits++;
168 /* Function to return the number of shifts to get a 1 in bit 0
171 static __u32 ShiftDiv(__u32 x)
190 * Temporary buffer manipulations.
193 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
196 __u8 *buf = (__u8 *)1;
198 memset(dev->tempBuffer,0,sizeof(dev->tempBuffer));
200 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
201 dev->tempBuffer[i].line = 0; /* not in use */
202 dev->tempBuffer[i].buffer = buf =
203 YMALLOC_DMA(dev->nDataBytesPerChunk);
206 return buf ? YAFFS_OK : YAFFS_FAIL;
210 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
213 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
214 if (dev->tempBuffer[i].line == 0) {
215 dev->tempBuffer[i].line = lineNo;
216 if ((i + 1) > dev->maxTemp) {
217 dev->maxTemp = i + 1;
218 for (j = 0; j <= i; j++)
219 dev->tempBuffer[j].maxLine =
220 dev->tempBuffer[j].line;
223 return dev->tempBuffer[i].buffer;
227 T(YAFFS_TRACE_BUFFERS,
228 (TSTR("Out of temp buffers at line %d, other held by lines:"),
230 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
231 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
233 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
236 * If we got here then we have to allocate an unmanaged one
240 dev->unmanagedTempAllocations++;
241 return YMALLOC(dev->nDataBytesPerChunk);
245 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
249 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
250 if (dev->tempBuffer[i].buffer == buffer) {
251 dev->tempBuffer[i].line = 0;
257 /* assume it is an unmanaged one. */
258 T(YAFFS_TRACE_BUFFERS,
259 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
262 dev->unmanagedTempDeallocations++;
268 * Determine if we have a managed buffer.
270 int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
273 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
274 if (dev->tempBuffer[i].buffer == buffer)
279 for (i = 0; i < dev->nShortOpCaches; i++) {
280 if( dev->srCache[i].data == buffer )
285 if (buffer == dev->checkpointBuffer)
288 T(YAFFS_TRACE_ALWAYS,
289 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
296 * Chunk bitmap manipulations
299 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
301 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
303 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
307 return dev->chunkBits +
308 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
311 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
313 if(blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
314 chunk < 0 || chunk >= dev->nChunksPerBlock) {
316 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),blk,chunk));
321 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
323 __u8 *blkBits = yaffs_BlockBits(dev, blk);
325 memset(blkBits, 0, dev->chunkBitmapStride);
328 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
330 __u8 *blkBits = yaffs_BlockBits(dev, blk);
332 yaffs_VerifyChunkBitId(dev,blk,chunk);
334 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
337 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
339 __u8 *blkBits = yaffs_BlockBits(dev, blk);
341 yaffs_VerifyChunkBitId(dev,blk,chunk);
343 blkBits[chunk / 8] |= (1 << (chunk & 7));
346 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
348 __u8 *blkBits = yaffs_BlockBits(dev, blk);
349 yaffs_VerifyChunkBitId(dev,blk,chunk);
351 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
354 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
356 __u8 *blkBits = yaffs_BlockBits(dev, blk);
358 for (i = 0; i < dev->chunkBitmapStride; i++) {
366 static int yaffs_CountChunkBits(yaffs_Device * dev, int blk)
368 __u8 *blkBits = yaffs_BlockBits(dev, blk);
371 for (i = 0; i < dev->chunkBitmapStride; i++) {
388 static int yaffs_SkipVerification(yaffs_Device *dev)
390 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
393 static int yaffs_SkipFullVerification(yaffs_Device *dev)
395 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
398 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
400 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
403 static const char * blockStateName[] = {
416 static void yaffs_VerifyBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
421 if(yaffs_SkipVerification(dev))
424 /* Report illegal runtime states */
425 if(bi->blockState <0 || bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
426 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has undefined state %d"TENDSTR),n,bi->blockState));
428 switch(bi->blockState){
429 case YAFFS_BLOCK_STATE_UNKNOWN:
430 case YAFFS_BLOCK_STATE_SCANNING:
431 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
432 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has bad run-state %s"TENDSTR),
433 n,blockStateName[bi->blockState]));
436 /* Check pages in use and soft deletions are legal */
438 actuallyUsed = bi->pagesInUse - bi->softDeletions;
440 if(bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
441 bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
442 actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock)
443 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
444 n,bi->pagesInUse,bi->softDeletions));
447 /* Check chunk bitmap legal */
448 inUse = yaffs_CountChunkBits(dev,n);
449 if(inUse != bi->pagesInUse)
450 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
451 n,bi->pagesInUse,inUse));
453 /* Check that the sequence number is valid.
454 * Ten million is legal, but is very unlikely
457 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
458 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000 ))
459 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has suspect sequence number of %d"TENDSTR),
460 n,bi->sequenceNumber));
464 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
466 yaffs_VerifyBlock(dev,bi,n);
468 /* After collection the block should be in the erased state */
469 /* TODO: This will need to change if we do partial gc */
471 if(bi->blockState != YAFFS_BLOCK_STATE_EMPTY){
472 T(YAFFS_TRACE_ERROR,(TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
477 static void yaffs_VerifyBlocks(yaffs_Device *dev)
480 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
481 int nIllegalBlockStates = 0;
484 if(yaffs_SkipVerification(dev))
487 memset(nBlocksPerState,0,sizeof(nBlocksPerState));
490 for(i = dev->internalStartBlock; i <= dev->internalEndBlock; i++){
491 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
492 yaffs_VerifyBlock(dev,bi,i);
494 if(bi->blockState >=0 && bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
495 nBlocksPerState[bi->blockState]++;
497 nIllegalBlockStates++;
501 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
502 T(YAFFS_TRACE_VERIFY,(TSTR("Block summary"TENDSTR)));
504 T(YAFFS_TRACE_VERIFY,(TSTR("%d blocks have illegal states"TENDSTR),nIllegalBlockStates));
505 if(nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
506 T(YAFFS_TRACE_VERIFY,(TSTR("Too many allocating blocks"TENDSTR)));
508 for(i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
509 T(YAFFS_TRACE_VERIFY,
510 (TSTR("%s %d blocks"TENDSTR),
511 blockStateName[i],nBlocksPerState[i]));
513 if(dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
514 T(YAFFS_TRACE_VERIFY,
515 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
516 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
518 if(dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
519 T(YAFFS_TRACE_VERIFY,
520 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
521 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
523 if(nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
524 T(YAFFS_TRACE_VERIFY,
525 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
526 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
528 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
533 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
534 * case those tests will not be performed.
536 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
538 if(yaffs_SkipVerification(obj->myDev))
541 if(!(tags && obj && oh)){
542 T(YAFFS_TRACE_VERIFY,
543 (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR),
544 (__u32)tags,(__u32)obj,(__u32)oh));
548 if(oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
549 oh->type > YAFFS_OBJECT_TYPE_MAX)
550 T(YAFFS_TRACE_VERIFY,
551 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
552 tags->objectId, oh->type));
554 if(tags->objectId != obj->objectId)
555 T(YAFFS_TRACE_VERIFY,
556 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
557 tags->objectId, obj->objectId));
561 * Check that the object's parent ids match if parentCheck requested.
563 * Tests do not apply to the root object.
566 if(parentCheck && tags->objectId > 1 && !obj->parent)
567 T(YAFFS_TRACE_VERIFY,
568 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
569 tags->objectId, oh->parentObjectId));
572 if(parentCheck && obj->parent &&
573 oh->parentObjectId != obj->parent->objectId &&
574 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
575 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
576 T(YAFFS_TRACE_VERIFY,
577 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
578 tags->objectId, oh->parentObjectId, obj->parent->objectId));
581 if(tags->objectId > 1 && oh->name[0] == 0) /* Null name */
582 T(YAFFS_TRACE_VERIFY,
583 (TSTR("Obj %d header name is NULL"TENDSTR),
586 if(tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
587 T(YAFFS_TRACE_VERIFY,
588 (TSTR("Obj %d header name is 0xFF"TENDSTR),
594 static int yaffs_VerifyTnodeWorker(yaffs_Object * obj, yaffs_Tnode * tn,
595 __u32 level, int chunkOffset)
598 yaffs_Device *dev = obj->myDev;
600 int nTnodeBytes = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
605 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
606 if (tn->internal[i]) {
607 ok = yaffs_VerifyTnodeWorker(obj,
610 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
613 } else if (level == 0) {
615 yaffs_ExtendedTags tags;
616 __u32 objectId = obj->objectId;
618 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
620 for(i = 0; i < YAFFS_NTNODES_LEVEL0; i++){
621 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
624 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
625 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
626 if(tags.objectId != objectId || tags.chunkId != chunkOffset){
627 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
628 objectId, chunkOffset, theChunk,
629 tags.objectId, tags.chunkId));
642 static void yaffs_VerifyFile(yaffs_Object *obj)
644 int requiredTallness;
651 yaffs_ExtendedTags tags;
655 if(obj && yaffs_SkipVerification(obj->myDev))
659 objectId = obj->objectId;
661 /* Check file size is consistent with tnode depth */
662 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
663 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
664 requiredTallness = 0;
666 x >>= YAFFS_TNODES_INTERNAL_BITS;
670 actualTallness = obj->variant.fileVariant.topLevel;
672 if(requiredTallness > actualTallness )
673 T(YAFFS_TRACE_VERIFY,
674 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
675 obj->objectId,actualTallness, requiredTallness));
678 /* Check that the chunks in the tnode tree are all correct.
679 * We do this by scanning through the tnode tree and
680 * checking the tags for every chunk match.
683 if(yaffs_SkipNANDVerification(dev))
686 for(i = 1; i <= lastChunk; i++){
687 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant,i);
690 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
692 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
693 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
694 if(tags.objectId != objectId || tags.chunkId != i){
695 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
696 objectId, i, theChunk,
697 tags.objectId, tags.chunkId));
706 static void yaffs_VerifyDirectory(yaffs_Object *obj)
708 if(obj && yaffs_SkipVerification(obj->myDev))
713 static void yaffs_VerifyHardLink(yaffs_Object *obj)
715 if(obj && yaffs_SkipVerification(obj->myDev))
718 /* Verify sane equivalent object */
721 static void yaffs_VerifySymlink(yaffs_Object *obj)
723 if(obj && yaffs_SkipVerification(obj->myDev))
726 /* Verify symlink string */
729 static void yaffs_VerifySpecial(yaffs_Object *obj)
731 if(obj && yaffs_SkipVerification(obj->myDev))
735 static void yaffs_VerifyObject(yaffs_Object *obj)
750 if(yaffs_SkipVerification(dev))
753 /* Check sane object header chunk */
755 chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
756 chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
758 chunkIdOk = (obj->chunkId >= chunkMin && obj->chunkId <= chunkMax);
759 chunkIsLive = chunkIdOk &&
760 yaffs_CheckChunkBit(dev,
761 obj->chunkId / dev->nChunksPerBlock,
762 obj->chunkId % dev->nChunksPerBlock);
764 (!chunkIdOk || !chunkIsLive)) {
765 T(YAFFS_TRACE_VERIFY,
766 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
767 obj->objectId,obj->chunkId,
768 chunkIdOk ? "" : ",out of range",
769 chunkIsLive || !chunkIdOk ? "" : ",marked as deleted"));
772 if(chunkIdOk && chunkIsLive &&!yaffs_SkipNANDVerification(dev)) {
773 yaffs_ExtendedTags tags;
774 yaffs_ObjectHeader *oh;
775 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
777 oh = (yaffs_ObjectHeader *)buffer;
779 yaffs_ReadChunkWithTagsFromNAND(dev, obj->chunkId,buffer, &tags);
781 yaffs_VerifyObjectHeader(obj,oh,&tags,1);
783 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
786 /* Verify it has a parent */
787 if(obj && !obj->fake &&
788 (!obj->parent || obj->parent->myDev != dev)){
789 T(YAFFS_TRACE_VERIFY,
790 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
791 obj->objectId,obj->parent));
794 /* Verify parent is a directory */
795 if(obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
796 T(YAFFS_TRACE_VERIFY,
797 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
798 obj->objectId,obj->parent->variantType));
801 switch(obj->variantType){
802 case YAFFS_OBJECT_TYPE_FILE:
803 yaffs_VerifyFile(obj);
805 case YAFFS_OBJECT_TYPE_SYMLINK:
806 yaffs_VerifySymlink(obj);
808 case YAFFS_OBJECT_TYPE_DIRECTORY:
809 yaffs_VerifyDirectory(obj);
811 case YAFFS_OBJECT_TYPE_HARDLINK:
812 yaffs_VerifyHardLink(obj);
814 case YAFFS_OBJECT_TYPE_SPECIAL:
815 yaffs_VerifySpecial(obj);
817 case YAFFS_OBJECT_TYPE_UNKNOWN:
819 T(YAFFS_TRACE_VERIFY,
820 (TSTR("Obj %d has illegaltype %d"TENDSTR),
821 obj->objectId,obj->variantType));
828 static void yaffs_VerifyObjects(yaffs_Device *dev)
832 struct list_head *lh;
834 if(yaffs_SkipVerification(dev))
837 /* Iterate through the objects in each hash entry */
839 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++){
840 list_for_each(lh, &dev->objectBucket[i].list) {
842 obj = list_entry(lh, yaffs_Object, hashLink);
843 yaffs_VerifyObject(obj);
852 * Simple hash function. Needs to have a reasonable spread
855 static Y_INLINE int yaffs_HashFunction(int n)
858 return (n % YAFFS_NOBJECT_BUCKETS);
862 * Access functions to useful fake objects
865 yaffs_Object *yaffs_Root(yaffs_Device * dev)
870 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
872 return dev->lostNFoundDir;
877 * Erased NAND checking functions
880 int yaffs_CheckFF(__u8 * buffer, int nBytes)
882 /* Horrible, slow implementation */
891 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
895 int retval = YAFFS_OK;
896 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
897 yaffs_ExtendedTags tags;
900 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
902 if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
906 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
907 T(YAFFS_TRACE_NANDACCESS,
908 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
912 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
918 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
920 yaffs_ExtendedTags * tags,
927 yaffs_InvalidateCheckpoint(dev);
930 yaffs_BlockInfo *bi = 0;
933 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
939 /* First check this chunk is erased, if it needs
940 * checking. The checking policy (unless forced
941 * always on) is as follows:
943 * Check the first page we try to write in a block.
944 * If the check passes then we don't need to check any
945 * more. If the check fails, we check again...
946 * If the block has been erased, we don't need to check.
948 * However, if the block has been prioritised for gc,
949 * then we think there might be something odd about
950 * this block and stop using it.
952 * Rationale: We should only ever see chunks that have
953 * not been erased if there was a partially written
954 * chunk due to power loss. This checking policy should
955 * catch that case with very few checks and thus save a
956 * lot of checks that are most likely not needed.
958 if (bi->gcPrioritise) {
959 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
960 /* try another chunk */
964 /* let's give it a try */
967 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
968 bi->skipErasedCheck = 0;
970 if (!bi->skipErasedCheck) {
971 erasedOk = yaffs_CheckChunkErased(dev, chunk);
972 if (erasedOk != YAFFS_OK) {
974 (TSTR ("**>> yaffs chunk %d was not erased"
977 /* try another chunk */
980 bi->skipErasedCheck = 1;
983 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
985 if (writeOk != YAFFS_OK) {
986 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
987 /* try another chunk */
991 /* Copy the data into the robustification buffer */
992 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
994 } while (writeOk != YAFFS_OK &&
995 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1001 T(YAFFS_TRACE_ERROR,
1002 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1005 dev->nRetriedWrites += (attempts - 1);
1012 * Block retiring for handling a broken block.
1015 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
1017 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1019 yaffs_InvalidateCheckpoint(dev);
1021 yaffs_MarkBlockBad(dev, blockInNAND);
1023 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1024 bi->gcPrioritise = 0;
1025 bi->needsRetiring = 0;
1027 dev->nRetiredBlocks++;
1031 * Functions for robustisizing TODO
1035 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
1037 const yaffs_ExtendedTags * tags)
1041 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
1042 const yaffs_ExtendedTags * tags)
1046 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1048 if(!bi->gcPrioritise){
1049 bi->gcPrioritise = 1;
1050 dev->hasPendingPrioritisedGCs = 1;
1051 bi->chunkErrorStrikes ++;
1053 if(bi->chunkErrorStrikes > 3){
1054 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1055 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1062 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
1065 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1066 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1068 yaffs_HandleChunkError(dev,bi);
1072 /* Was an actual write failure, so mark the block for retirement */
1073 bi->needsRetiring = 1;
1074 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1075 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1080 /* Delete the chunk */
1081 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1085 /*---------------- Name handling functions ------------*/
1087 static __u16 yaffs_CalcNameSum(const YCHAR * name)
1092 YUCHAR *bname = (YUCHAR *) name;
1094 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1096 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1097 sum += yaffs_toupper(*bname) * i;
1099 sum += (*bname) * i;
1108 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
1110 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1111 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
1112 yaffs_strcpy(obj->shortName, name);
1114 obj->shortName[0] = _Y('\0');
1117 obj->sum = yaffs_CalcNameSum(name);
1120 /*-------------------- TNODES -------------------
1122 * List of spare tnodes
1123 * The list is hooked together using the first pointer
1127 /* yaffs_CreateTnodes creates a bunch more tnodes and
1128 * adds them to the tnode free list.
1129 * Don't use this function directly
1132 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
1136 yaffs_Tnode *newTnodes;
1140 yaffs_TnodeList *tnl;
1145 /* Calculate the tnode size in bytes for variable width tnode support.
1146 * Must be a multiple of 32-bits */
1147 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1149 if(tnodeSize < sizeof(yaffs_Tnode))
1150 tnodeSize = sizeof(yaffs_Tnode);
1153 /* make these things */
1155 newTnodes = YMALLOC(nTnodes * tnodeSize);
1156 mem = (__u8 *)newTnodes;
1159 T(YAFFS_TRACE_ERROR,
1160 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1164 /* Hook them into the free list */
1166 for (i = 0; i < nTnodes - 1; i++) {
1167 newTnodes[i].internal[0] = &newTnodes[i + 1];
1168 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1169 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1173 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1174 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1175 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1177 dev->freeTnodes = newTnodes;
1179 /* New hookup for wide tnodes */
1180 for(i = 0; i < nTnodes -1; i++) {
1181 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1182 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1183 curr->internal[0] = next;
1186 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1187 curr->internal[0] = dev->freeTnodes;
1188 dev->freeTnodes = (yaffs_Tnode *)mem;
1193 dev->nFreeTnodes += nTnodes;
1194 dev->nTnodesCreated += nTnodes;
1196 /* Now add this bunch of tnodes to a list for freeing up.
1197 * NB If we can't add this to the management list it isn't fatal
1198 * but it just means we can't free this bunch of tnodes later.
1201 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1203 T(YAFFS_TRACE_ERROR,
1205 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1209 tnl->tnodes = newTnodes;
1210 tnl->next = dev->allocatedTnodeList;
1211 dev->allocatedTnodeList = tnl;
1214 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1219 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1221 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
1223 yaffs_Tnode *tn = NULL;
1225 /* If there are none left make more */
1226 if (!dev->freeTnodes) {
1227 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1230 if (dev->freeTnodes) {
1231 tn = dev->freeTnodes;
1232 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1233 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1234 /* Hoosterman, this thing looks like it isn't in the list */
1235 T(YAFFS_TRACE_ALWAYS,
1236 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1239 dev->freeTnodes = dev->freeTnodes->internal[0];
1243 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1248 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
1250 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1251 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1253 if(tnodeSize < sizeof(yaffs_Tnode))
1254 tnodeSize = sizeof(yaffs_Tnode);
1257 memset(tn, 0, tnodeSize);
1262 /* FreeTnode frees up a tnode and puts it back on the free list */
1263 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
1266 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1267 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1268 /* Hoosterman, this thing looks like it is already in the list */
1269 T(YAFFS_TRACE_ALWAYS,
1270 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1272 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1274 tn->internal[0] = dev->freeTnodes;
1275 dev->freeTnodes = tn;
1278 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1282 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
1284 /* Free the list of allocated tnodes */
1285 yaffs_TnodeList *tmp;
1287 while (dev->allocatedTnodeList) {
1288 tmp = dev->allocatedTnodeList->next;
1290 YFREE(dev->allocatedTnodeList->tnodes);
1291 YFREE(dev->allocatedTnodeList);
1292 dev->allocatedTnodeList = tmp;
1296 dev->freeTnodes = NULL;
1297 dev->nFreeTnodes = 0;
1300 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
1302 dev->allocatedTnodeList = NULL;
1303 dev->freeTnodes = NULL;
1304 dev->nFreeTnodes = 0;
1305 dev->nTnodesCreated = 0;
1310 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
1312 __u32 *map = (__u32 *)tn;
1318 pos &= YAFFS_TNODES_LEVEL0_MASK;
1319 val >>= dev->chunkGroupBits;
1321 bitInMap = pos * dev->tnodeWidth;
1322 wordInMap = bitInMap /32;
1323 bitInWord = bitInMap & (32 -1);
1325 mask = dev->tnodeMask << bitInWord;
1327 map[wordInMap] &= ~mask;
1328 map[wordInMap] |= (mask & (val << bitInWord));
1330 if(dev->tnodeWidth > (32-bitInWord)) {
1331 bitInWord = (32 - bitInWord);
1333 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1334 map[wordInMap] &= ~mask;
1335 map[wordInMap] |= (mask & (val >> bitInWord));
1339 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
1341 __u32 *map = (__u32 *)tn;
1347 pos &= YAFFS_TNODES_LEVEL0_MASK;
1349 bitInMap = pos * dev->tnodeWidth;
1350 wordInMap = bitInMap /32;
1351 bitInWord = bitInMap & (32 -1);
1353 val = map[wordInMap] >> bitInWord;
1355 if(dev->tnodeWidth > (32-bitInWord)) {
1356 bitInWord = (32 - bitInWord);
1358 val |= (map[wordInMap] << bitInWord);
1361 val &= dev->tnodeMask;
1362 val <<= dev->chunkGroupBits;
1367 /* ------------------- End of individual tnode manipulation -----------------*/
1369 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1370 * The look up tree is represented by the top tnode and the number of topLevel
1371 * in the tree. 0 means only the level 0 tnode is in the tree.
1374 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1375 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
1376 yaffs_FileStructure * fStruct,
1380 yaffs_Tnode *tn = fStruct->top;
1382 int requiredTallness;
1383 int level = fStruct->topLevel;
1385 /* Check sane level and chunk Id */
1386 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
1390 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1394 /* First check we're tall enough (ie enough topLevel) */
1396 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1397 requiredTallness = 0;
1399 i >>= YAFFS_TNODES_INTERNAL_BITS;
1403 if (requiredTallness > fStruct->topLevel) {
1404 /* Not tall enough, so we can't find it, return NULL. */
1408 /* Traverse down to level 0 */
1409 while (level > 0 && tn) {
1411 internal[(chunkId >>
1412 ( YAFFS_TNODES_LEVEL0_BITS +
1414 YAFFS_TNODES_INTERNAL_BITS)
1416 YAFFS_TNODES_INTERNAL_MASK];
1424 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1425 * This happens in two steps:
1426 * 1. If the tree isn't tall enough, then make it taller.
1427 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1429 * Used when modifying the tree.
1431 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1432 * be plugged into the ttree.
1435 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
1436 yaffs_FileStructure * fStruct,
1438 yaffs_Tnode *passedTn)
1441 int requiredTallness;
1449 /* Check sane level and page Id */
1450 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
1454 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1458 /* First check we're tall enough (ie enough topLevel) */
1460 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1461 requiredTallness = 0;
1463 x >>= YAFFS_TNODES_INTERNAL_BITS;
1468 if (requiredTallness > fStruct->topLevel) {
1469 /* Not tall enough,gotta make the tree taller */
1470 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1472 tn = yaffs_GetTnode(dev);
1475 tn->internal[0] = fStruct->top;
1478 T(YAFFS_TRACE_ERROR,
1479 (TSTR("yaffs: no more tnodes" TENDSTR)));
1483 fStruct->topLevel = requiredTallness;
1486 /* Traverse down to level 0, adding anything we need */
1488 l = fStruct->topLevel;
1492 while (l > 0 && tn) {
1494 ( YAFFS_TNODES_LEVEL0_BITS +
1495 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1496 YAFFS_TNODES_INTERNAL_MASK;
1499 if((l>1) && !tn->internal[x]){
1500 /* Add missing non-level-zero tnode */
1501 tn->internal[x] = yaffs_GetTnode(dev);
1504 /* Looking from level 1 at level 0 */
1506 /* If we already have one, then release it.*/
1508 yaffs_FreeTnode(dev,tn->internal[x]);
1509 tn->internal[x] = passedTn;
1511 } else if(!tn->internal[x]) {
1512 /* Don't have one, none passed in */
1513 tn->internal[x] = yaffs_GetTnode(dev);
1517 tn = tn->internal[x];
1521 /* top is level 0 */
1523 memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1524 yaffs_FreeTnode(dev,passedTn);
1531 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1532 yaffs_ExtendedTags * tags, int objectId,
1537 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1538 if (yaffs_CheckChunkBit
1539 (dev, theChunk / dev->nChunksPerBlock,
1540 theChunk % dev->nChunksPerBlock)) {
1541 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1543 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1555 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1556 * chunks and tnodes in the file
1557 * Returns 1 if the tree was deleted.
1558 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1561 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1562 int chunkOffset, int *limit)
1567 yaffs_ExtendedTags tags;
1569 yaffs_Device *dev = in->myDev;
1576 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1578 if (tn->internal[i]) {
1579 if (limit && (*limit) < 0) {
1583 yaffs_DeleteWorker(in,
1591 YAFFS_TNODES_INTERNAL_BITS)
1596 yaffs_FreeTnode(dev,
1599 tn->internal[i] = NULL;
1604 return (allDone) ? 1 : 0;
1605 } else if (level == 0) {
1608 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1610 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1615 YAFFS_TNODES_LEVEL0_BITS) + i;
1618 yaffs_FindChunkInGroup(dev,
1624 if (foundChunk > 0) {
1625 yaffs_DeleteChunk(dev,
1630 *limit = *limit - 1;
1638 yaffs_PutLevel0Tnode(dev,tn,i,0);
1642 return (i < 0) ? 1 : 0;
1652 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1655 yaffs_BlockInfo *theBlock;
1657 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1659 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1661 theBlock->softDeletions++;
1666 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1667 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1669 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1672 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1673 __u32 level, int chunkOffset)
1678 yaffs_Device *dev = in->myDev;
1683 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1685 if (tn->internal[i]) {
1687 yaffs_SoftDeleteWorker(in,
1693 YAFFS_TNODES_INTERNAL_BITS)
1696 yaffs_FreeTnode(dev,
1699 tn->internal[i] = NULL;
1701 /* Hoosterman... how could this happen? */
1705 return (allDone) ? 1 : 0;
1706 } else if (level == 0) {
1708 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1709 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1711 /* Note this does not find the real chunk, only the chunk group.
1712 * We make an assumption that a chunk group is not larger than
1715 yaffs_SoftDeleteChunk(dev, theChunk);
1716 yaffs_PutLevel0Tnode(dev,tn,i,0);
1730 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1733 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1734 if (obj->nDataChunks <= 0) {
1735 /* Empty file with no duplicate object headers, just delete it immediately */
1736 yaffs_FreeTnode(obj->myDev,
1737 obj->variant.fileVariant.top);
1738 obj->variant.fileVariant.top = NULL;
1739 T(YAFFS_TRACE_TRACING,
1740 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1742 yaffs_DoGenericObjectDeletion(obj);
1744 yaffs_SoftDeleteWorker(obj,
1745 obj->variant.fileVariant.top,
1746 obj->variant.fileVariant.
1748 obj->softDeleted = 1;
1753 /* Pruning removes any part of the file structure tree that is beyond the
1754 * bounds of the file (ie that does not point to chunks).
1756 * A file should only get pruned when its size is reduced.
1758 * Before pruning, the chunks must be pulled from the tree and the
1759 * level 0 tnode entries must be zeroed out.
1760 * Could also use this for file deletion, but that's probably better handled
1761 * by a special case.
1764 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1765 __u32 level, int del0)
1773 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1774 if (tn->internal[i] && level > 0) {
1776 yaffs_PruneWorker(dev, tn->internal[i],
1778 (i == 0) ? del0 : 1);
1781 if (tn->internal[i]) {
1786 if (hasData == 0 && del0) {
1787 /* Free and return NULL */
1789 yaffs_FreeTnode(dev, tn);
1799 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1800 yaffs_FileStructure * fStruct)
1807 if (fStruct->topLevel > 0) {
1809 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1811 /* Now we have a tree with all the non-zero branches NULL but the height
1812 * is the same as it was.
1813 * Let's see if we can trim internal tnodes to shorten the tree.
1814 * We can do this if only the 0th element in the tnode is in use
1815 * (ie all the non-zero are NULL)
1818 while (fStruct->topLevel && !done) {
1822 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1823 if (tn->internal[i]) {
1829 fStruct->top = tn->internal[0];
1830 fStruct->topLevel--;
1831 yaffs_FreeTnode(dev, tn);
1841 /*-------------------- End of File Structure functions.-------------------*/
1843 /* yaffs_CreateFreeObjects creates a bunch more objects and
1844 * adds them to the object free list.
1846 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1849 yaffs_Object *newObjects;
1850 yaffs_ObjectList *list;
1855 /* make these things */
1856 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1857 list = YMALLOC(sizeof(yaffs_ObjectList));
1859 if (!newObjects || !list) {
1864 T(YAFFS_TRACE_ALLOCATE,
1865 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1869 /* Hook them into the free list */
1870 for (i = 0; i < nObjects - 1; i++) {
1871 newObjects[i].siblings.next =
1872 (struct list_head *)(&newObjects[i + 1]);
1875 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1876 dev->freeObjects = newObjects;
1877 dev->nFreeObjects += nObjects;
1878 dev->nObjectsCreated += nObjects;
1880 /* Now add this bunch of Objects to a list for freeing up. */
1882 list->objects = newObjects;
1883 list->next = dev->allocatedObjectList;
1884 dev->allocatedObjectList = list;
1890 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1891 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1893 yaffs_Object *tn = NULL;
1895 /* If there are none left make more */
1896 if (!dev->freeObjects) {
1897 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1900 if (dev->freeObjects) {
1901 tn = dev->freeObjects;
1903 (yaffs_Object *) (dev->freeObjects->siblings.next);
1904 dev->nFreeObjects--;
1906 /* Now sweeten it up... */
1908 memset(tn, 0, sizeof(yaffs_Object));
1911 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1912 INIT_LIST_HEAD(&(tn->hardLinks));
1913 INIT_LIST_HEAD(&(tn->hashLink));
1914 INIT_LIST_HEAD(&tn->siblings);
1916 /* Add it to the lost and found directory.
1917 * NB Can't put root or lostNFound in lostNFound so
1918 * check if lostNFound exists first
1920 if (dev->lostNFoundDir) {
1921 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1925 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1930 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1935 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1937 obj->fake = 1; /* it is fake so it has no NAND presence... */
1938 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1939 obj->unlinkAllowed = 0; /* ... or unlink it */
1942 obj->yst_mode = mode;
1944 obj->chunkId = 0; /* Not a valid chunk. */
1951 static void yaffs_UnhashObject(yaffs_Object * tn)
1954 yaffs_Device *dev = tn->myDev;
1956 /* If it is still linked into the bucket list, free from the list */
1957 if (!list_empty(&tn->hashLink)) {
1958 list_del_init(&tn->hashLink);
1959 bucket = yaffs_HashFunction(tn->objectId);
1960 dev->objectBucket[bucket].count--;
1965 /* FreeObject frees up a Object and puts it back on the free list */
1966 static void yaffs_FreeObject(yaffs_Object * tn)
1969 yaffs_Device *dev = tn->myDev;
1973 /* We're still hooked up to a cached inode.
1974 * Don't delete now, but mark for later deletion
1976 tn->deferedFree = 1;
1981 yaffs_UnhashObject(tn);
1983 /* Link into the free list. */
1984 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1985 dev->freeObjects = tn;
1986 dev->nFreeObjects++;
1988 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1994 void yaffs_HandleDeferedFree(yaffs_Object * obj)
1996 if (obj->deferedFree) {
1997 yaffs_FreeObject(obj);
2003 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
2005 /* Free the list of allocated Objects */
2007 yaffs_ObjectList *tmp;
2009 while (dev->allocatedObjectList) {
2010 tmp = dev->allocatedObjectList->next;
2011 YFREE(dev->allocatedObjectList->objects);
2012 YFREE(dev->allocatedObjectList);
2014 dev->allocatedObjectList = tmp;
2017 dev->freeObjects = NULL;
2018 dev->nFreeObjects = 0;
2021 static void yaffs_InitialiseObjects(yaffs_Device * dev)
2025 dev->allocatedObjectList = NULL;
2026 dev->freeObjects = NULL;
2027 dev->nFreeObjects = 0;
2029 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2030 INIT_LIST_HEAD(&dev->objectBucket[i].list);
2031 dev->objectBucket[i].count = 0;
2036 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
2041 int lowest = 999999;
2043 /* First let's see if we can find one that's empty. */
2045 for (i = 0; i < 10 && lowest > 0; i++) {
2047 x %= YAFFS_NOBJECT_BUCKETS;
2048 if (dev->objectBucket[x].count < lowest) {
2049 lowest = dev->objectBucket[x].count;
2055 /* If we didn't find an empty list, then try
2056 * looking a bit further for a short one
2059 for (i = 0; i < 10 && lowest > 3; i++) {
2061 x %= YAFFS_NOBJECT_BUCKETS;
2062 if (dev->objectBucket[x].count < lowest) {
2063 lowest = dev->objectBucket[x].count;
2072 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
2074 int bucket = yaffs_FindNiceObjectBucket(dev);
2076 /* Now find an object value that has not already been taken
2077 * by scanning the list.
2081 struct list_head *i;
2083 __u32 n = (__u32) bucket;
2085 /* yaffs_CheckObjectHashSanity(); */
2089 n += YAFFS_NOBJECT_BUCKETS;
2090 if (1 || dev->objectBucket[bucket].count > 0) {
2091 list_for_each(i, &dev->objectBucket[bucket].list) {
2092 /* If there is already one in the list */
2094 && list_entry(i, yaffs_Object,
2095 hashLink)->objectId == n) {
2106 static void yaffs_HashObject(yaffs_Object * in)
2108 int bucket = yaffs_HashFunction(in->objectId);
2109 yaffs_Device *dev = in->myDev;
2111 list_add(&in->hashLink, &dev->objectBucket[bucket].list);
2112 dev->objectBucket[bucket].count++;
2116 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
2118 int bucket = yaffs_HashFunction(number);
2119 struct list_head *i;
2122 list_for_each(i, &dev->objectBucket[bucket].list) {
2123 /* Look if it is in the list */
2125 in = list_entry(i, yaffs_Object, hashLink);
2126 if (in->objectId == number) {
2128 /* Don't tell the VFS about this one if it is defered free */
2129 if (in->deferedFree)
2141 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
2142 yaffs_ObjectType type)
2145 yaffs_Object *theObject;
2149 number = yaffs_CreateNewObjectNumber(dev);
2152 theObject = yaffs_AllocateEmptyObject(dev);
2156 if(type == YAFFS_OBJECT_TYPE_FILE){
2157 tn = yaffs_GetTnode(dev);
2159 yaffs_FreeObject(theObject);
2167 theObject->fake = 0;
2168 theObject->renameAllowed = 1;
2169 theObject->unlinkAllowed = 1;
2170 theObject->objectId = number;
2171 yaffs_HashObject(theObject);
2172 theObject->variantType = type;
2173 #ifdef CONFIG_YAFFS_WINCE
2174 yfsd_WinFileTimeNow(theObject->win_atime);
2175 theObject->win_ctime[0] = theObject->win_mtime[0] =
2176 theObject->win_atime[0];
2177 theObject->win_ctime[1] = theObject->win_mtime[1] =
2178 theObject->win_atime[1];
2182 theObject->yst_atime = theObject->yst_mtime =
2183 theObject->yst_ctime = Y_CURRENT_TIME;
2186 case YAFFS_OBJECT_TYPE_FILE:
2187 theObject->variant.fileVariant.fileSize = 0;
2188 theObject->variant.fileVariant.scannedFileSize = 0;
2189 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2190 theObject->variant.fileVariant.topLevel = 0;
2191 theObject->variant.fileVariant.top = tn;
2193 case YAFFS_OBJECT_TYPE_DIRECTORY:
2194 INIT_LIST_HEAD(&theObject->variant.directoryVariant.
2197 case YAFFS_OBJECT_TYPE_SYMLINK:
2198 case YAFFS_OBJECT_TYPE_HARDLINK:
2199 case YAFFS_OBJECT_TYPE_SPECIAL:
2200 /* No action required */
2202 case YAFFS_OBJECT_TYPE_UNKNOWN:
2203 /* todo this should not happen */
2211 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
2213 yaffs_ObjectType type)
2215 yaffs_Object *theObject = NULL;
2218 theObject = yaffs_FindObjectByNumber(dev, number);
2222 theObject = yaffs_CreateNewObject(dev, number, type);
2230 static YCHAR *yaffs_CloneString(const YCHAR * str)
2232 YCHAR *newStr = NULL;
2235 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2237 yaffs_strcpy(newStr, str);
2245 * Mknod (create) a new object.
2246 * equivalentObject only has meaning for a hard link;
2247 * aliasString only has meaning for a sumlink.
2248 * rdev only has meaning for devices (a subset of special objects)
2251 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2252 yaffs_Object * parent,
2257 yaffs_Object * equivalentObject,
2258 const YCHAR * aliasString, __u32 rdev)
2263 yaffs_Device *dev = parent->myDev;
2265 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2266 if (yaffs_FindObjectByName(parent, name)) {
2270 in = yaffs_CreateNewObject(dev, -1, type);
2272 if(type == YAFFS_OBJECT_TYPE_SYMLINK){
2273 str = yaffs_CloneString(aliasString);
2275 yaffs_FreeObject(in);
2285 in->variantType = type;
2287 in->yst_mode = mode;
2289 #ifdef CONFIG_YAFFS_WINCE
2290 yfsd_WinFileTimeNow(in->win_atime);
2291 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2292 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2295 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2297 in->yst_rdev = rdev;
2301 in->nDataChunks = 0;
2303 yaffs_SetObjectName(in, name);
2306 yaffs_AddObjectToDirectory(parent, in);
2308 in->myDev = parent->myDev;
2311 case YAFFS_OBJECT_TYPE_SYMLINK:
2312 in->variant.symLinkVariant.alias = str;
2314 case YAFFS_OBJECT_TYPE_HARDLINK:
2315 in->variant.hardLinkVariant.equivalentObject =
2317 in->variant.hardLinkVariant.equivalentObjectId =
2318 equivalentObject->objectId;
2319 list_add(&in->hardLinks, &equivalentObject->hardLinks);
2321 case YAFFS_OBJECT_TYPE_FILE:
2322 case YAFFS_OBJECT_TYPE_DIRECTORY:
2323 case YAFFS_OBJECT_TYPE_SPECIAL:
2324 case YAFFS_OBJECT_TYPE_UNKNOWN:
2329 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2330 /* Could not create the object header, fail the creation */
2331 yaffs_DestroyObject(in);
2340 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
2341 __u32 mode, __u32 uid, __u32 gid)
2343 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2344 uid, gid, NULL, NULL, 0);
2347 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
2348 __u32 mode, __u32 uid, __u32 gid)
2350 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2351 mode, uid, gid, NULL, NULL, 0);
2354 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
2355 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2357 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2358 uid, gid, NULL, NULL, rdev);
2361 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
2362 __u32 mode, __u32 uid, __u32 gid,
2363 const YCHAR * alias)
2365 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2366 uid, gid, NULL, alias, 0);
2369 /* yaffs_Link returns the object id of the equivalent object.*/
2370 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
2371 yaffs_Object * equivalentObject)
2373 /* Get the real object in case we were fed a hard link as an equivalent object */
2374 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2376 if (yaffs_MknodObject
2377 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2378 equivalentObject, NULL, 0)) {
2379 return equivalentObject;
2386 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
2387 const YCHAR * newName, int force, int shadows)
2392 yaffs_Object *existingTarget;
2394 if (newDir == NULL) {
2395 newDir = obj->parent; /* use the old directory */
2398 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2399 T(YAFFS_TRACE_ALWAYS,
2401 ("tragendy: yaffs_ChangeObjectName: newDir is not a directory"
2406 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2407 if (obj->myDev->isYaffs2) {
2408 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2410 unlinkOp = (newDir == obj->myDev->unlinkedDir
2411 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2414 deleteOp = (newDir == obj->myDev->deletedDir);
2416 existingTarget = yaffs_FindObjectByName(newDir, newName);
2418 /* If the object is a file going into the unlinked directory,
2419 * then it is OK to just stuff it in since duplicate names are allowed.
2420 * else only proceed if the new name does not exist and if we're putting
2421 * it into a directory.
2428 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2429 yaffs_SetObjectName(obj, newName);
2432 yaffs_AddObjectToDirectory(newDir, obj);
2437 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2438 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
2445 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
2446 yaffs_Object * newDir, const YCHAR * newName)
2449 yaffs_Object *existingTarget;
2452 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2453 /* Special case for case insemsitive systems (eg. WinCE).
2454 * While look-up is case insensitive, the name isn't.
2455 * Therefore we might want to change x.txt to X.txt
2457 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
2462 obj = yaffs_FindObjectByName(oldDir, oldName);
2463 /* Check new name to long. */
2464 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK &&
2465 yaffs_strlen(newName) > YAFFS_MAX_ALIAS_LENGTH)
2468 else if (obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK &&
2469 yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2473 if (obj && obj->renameAllowed) {
2475 /* Now do the handling for an existing target, if there is one */
2477 existingTarget = yaffs_FindObjectByName(newDir, newName);
2478 if (existingTarget &&
2479 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2480 !list_empty(&existingTarget->variant.directoryVariant.children)) {
2481 /* There is a target that is a non-empty directory, so we fail */
2482 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2483 } else if (existingTarget && existingTarget != obj) {
2484 /* Nuke the target first, using shadowing,
2485 * but only if it isn't the same object
2487 yaffs_ChangeObjectName(obj, newDir, newName, force,
2488 existingTarget->objectId);
2489 yaffs_UnlinkObject(existingTarget);
2492 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2497 /*------------------------- Block Management and Page Allocation ----------------*/
2499 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
2501 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2503 dev->blockInfo = NULL;
2504 dev->chunkBits = NULL;
2506 dev->allocationBlock = -1; /* force it to get a new one */
2508 /* If the first allocation strategy fails, thry the alternate one */
2509 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2510 if(!dev->blockInfo){
2511 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2512 dev->blockInfoAlt = 1;
2515 dev->blockInfoAlt = 0;
2519 /* Set up dynamic blockinfo stuff. */
2520 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2521 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2522 if(!dev->chunkBits){
2523 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2524 dev->chunkBitsAlt = 1;
2527 dev->chunkBitsAlt = 0;
2530 if (dev->blockInfo && dev->chunkBits) {
2531 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2532 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2540 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
2542 if(dev->blockInfoAlt && dev->blockInfo)
2543 YFREE_ALT(dev->blockInfo);
2544 else if(dev->blockInfo)
2545 YFREE(dev->blockInfo);
2547 dev->blockInfoAlt = 0;
2549 dev->blockInfo = NULL;
2551 if(dev->chunkBitsAlt && dev->chunkBits)
2552 YFREE_ALT(dev->chunkBits);
2553 else if(dev->chunkBits)
2554 YFREE(dev->chunkBits);
2555 dev->chunkBitsAlt = 0;
2556 dev->chunkBits = NULL;
2559 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
2560 yaffs_BlockInfo * bi)
2567 return 1; /* disqualification only applies to yaffs2. */
2569 if (!bi->hasShrinkHeader)
2570 return 1; /* can gc */
2572 /* Find the oldest dirty sequence number if we don't know it and save it
2573 * so we don't have to keep recomputing it.
2575 if (!dev->oldestDirtySequence) {
2576 seq = dev->sequenceNumber;
2578 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2580 b = yaffs_GetBlockInfo(dev, i);
2581 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2582 (b->pagesInUse - b->softDeletions) <
2583 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2584 seq = b->sequenceNumber;
2587 dev->oldestDirtySequence = seq;
2590 /* Can't do gc of this block if there are any blocks older than this one that have
2593 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2597 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2598 * for garbage collection.
2601 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2605 int b = dev->currentDirtyChecker;
2612 yaffs_BlockInfo *bi;
2613 int pendingPrioritisedExist = 0;
2615 /* First let's see if we need to grab a prioritised block */
2616 if(dev->hasPendingPrioritisedGCs){
2617 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2619 bi = yaffs_GetBlockInfo(dev, i);
2620 //yaffs_VerifyBlock(dev,bi,i);
2622 if(bi->gcPrioritise) {
2623 pendingPrioritisedExist = 1;
2624 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2625 yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2626 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2629 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2634 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2635 dev->hasPendingPrioritisedGCs = 0;
2638 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2640 * else (we're doing a leasurely gc), then we only bother to do this if the
2641 * block has only a few pages in use.
2644 dev->nonAggressiveSkip--;
2646 if (!aggressive && (dev->nonAggressiveSkip > 0)) {
2652 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2656 dev->internalEndBlock - dev->internalStartBlock + 1;
2659 dev->internalEndBlock - dev->internalStartBlock + 1;
2660 iterations = iterations / 16;
2661 if (iterations > 200) {
2666 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2668 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2669 b = dev->internalStartBlock;
2672 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2673 T(YAFFS_TRACE_ERROR,
2674 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2678 bi = yaffs_GetBlockInfo(dev, b);
2681 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2688 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2689 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2690 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2692 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2696 dev->currentDirtyChecker = b;
2700 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2701 dev->nChunksPerBlock - pagesInUse,prioritised));
2704 dev->oldestDirtySequence = 0;
2707 dev->nonAggressiveSkip = 4;
2713 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2715 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2719 /* If the block is still healthy erase it and mark as clean.
2720 * If the block has had a data failure, then retire it.
2723 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2724 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2725 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2727 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2729 if (!bi->needsRetiring) {
2730 yaffs_InvalidateCheckpoint(dev);
2731 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2733 dev->nErasureFailures++;
2734 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2735 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2740 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2742 for (i = 0; i < dev->nChunksPerBlock; i++) {
2743 if (!yaffs_CheckChunkErased
2744 (dev, blockNo * dev->nChunksPerBlock + i)) {
2745 T(YAFFS_TRACE_ERROR,
2747 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2748 TENDSTR), blockNo, i));
2754 /* Clean it up... */
2755 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2756 dev->nErasedBlocks++;
2758 bi->softDeletions = 0;
2759 bi->hasShrinkHeader = 0;
2760 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2761 bi->gcPrioritise = 0;
2762 yaffs_ClearChunkBits(dev, blockNo);
2764 T(YAFFS_TRACE_ERASE,
2765 (TSTR("Erased block %d" TENDSTR), blockNo));
2767 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2769 yaffs_RetireBlock(dev, blockNo);
2770 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2771 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2775 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2779 yaffs_BlockInfo *bi;
2781 if (dev->nErasedBlocks < 1) {
2782 /* Hoosterman we've got a problem.
2783 * Can't get space to gc
2785 T(YAFFS_TRACE_ERROR,
2786 (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2791 /* Find an empty block. */
2793 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2794 dev->allocationBlockFinder++;
2795 if (dev->allocationBlockFinder < dev->internalStartBlock
2796 || dev->allocationBlockFinder > dev->internalEndBlock) {
2797 dev->allocationBlockFinder = dev->internalStartBlock;
2800 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2802 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2803 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2804 dev->sequenceNumber++;
2805 bi->sequenceNumber = dev->sequenceNumber;
2806 dev->nErasedBlocks--;
2807 T(YAFFS_TRACE_ALLOCATE,
2808 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2809 dev->allocationBlockFinder, dev->sequenceNumber,
2810 dev->nErasedBlocks));
2811 return dev->allocationBlockFinder;
2815 T(YAFFS_TRACE_ALWAYS,
2817 ("yaffs tragedy: no more eraased blocks, but there should have been %d"
2818 TENDSTR), dev->nErasedBlocks));
2825 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2827 if(!dev->nCheckpointBlocksRequired){
2828 /* Not a valid value so recalculate */
2831 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2834 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2836 if(tnodeSize < sizeof(yaffs_Tnode))
2837 tnodeSize = sizeof(yaffs_Tnode);
2839 nBytes += sizeof(yaffs_CheckpointValidity);
2840 nBytes += sizeof(yaffs_CheckpointDevice);
2841 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2842 nBytes += devBlocks * dev->chunkBitmapStride;
2843 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2844 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2845 nBytes += sizeof(yaffs_CheckpointValidity);
2846 nBytes += sizeof(__u32); /* checksum*/
2848 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2850 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2852 dev->nCheckpointBlocksRequired = nBlocks;
2855 return dev->nCheckpointBlocksRequired;
2858 // Check if there's space to allocate...
2859 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2860 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2863 int reservedBlocks = dev->nReservedBlocks;
2864 int checkpointBlocks;
2866 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
2867 if(checkpointBlocks < 0)
2868 checkpointBlocks = 0;
2870 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2872 return (dev->nFreeChunks > reservedChunks);
2875 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2878 yaffs_BlockInfo *bi;
2880 if (dev->allocationBlock < 0) {
2881 /* Get next block to allocate off */
2882 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2883 dev->allocationPage = 0;
2886 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2887 /* Not enough space to allocate unless we're allowed to use the reserve. */
2891 if (dev->nErasedBlocks < dev->nReservedBlocks
2892 && dev->allocationPage == 0) {
2893 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2896 /* Next page please.... */
2897 if (dev->allocationBlock >= 0) {
2898 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2900 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2901 dev->allocationPage;
2903 yaffs_SetChunkBit(dev, dev->allocationBlock,
2904 dev->allocationPage);
2906 dev->allocationPage++;
2910 /* If the block is full set the state to full */
2911 if (dev->allocationPage >= dev->nChunksPerBlock) {
2912 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2913 dev->allocationBlock = -1;
2922 T(YAFFS_TRACE_ERROR,
2923 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2928 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2932 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2934 if (dev->allocationBlock > 0) {
2935 n += (dev->nChunksPerBlock - dev->allocationPage);
2942 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2948 int retVal = YAFFS_OK;
2951 int isCheckpointBlock;
2954 int chunksBefore = yaffs_GetErasedChunks(dev);
2957 yaffs_ExtendedTags tags;
2959 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2961 yaffs_Object *object;
2963 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2965 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2967 T(YAFFS_TRACE_TRACING,
2968 (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2969 bi->pagesInUse, bi->hasShrinkHeader));
2971 /*yaffs_VerifyFreeChunks(dev); */
2973 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2975 /* Take off the number of soft deleted entries because
2976 * they're going to get really deleted during GC.
2978 dev->nFreeChunks -= bi->softDeletions;
2982 if (isCheckpointBlock ||
2983 !yaffs_StillSomeChunkBits(dev, block)) {
2984 T(YAFFS_TRACE_TRACING,
2986 ("Collecting block %d that has no chunks in use" TENDSTR),
2988 yaffs_BlockBecameDirty(dev, block);
2991 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2993 yaffs_VerifyBlock(dev,bi,block);
2995 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
2996 chunkInBlock < dev->nChunksPerBlock
2997 && yaffs_StillSomeChunkBits(dev, block);
2998 chunkInBlock++, oldChunk++) {
2999 if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
3001 /* This page is in use and might need to be copied off */
3005 yaffs_InitialiseTags(&tags);
3007 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3011 yaffs_FindObjectByNumber(dev,
3014 T(YAFFS_TRACE_GC_DETAIL,
3016 ("Collecting page %d, %d %d %d " TENDSTR),
3017 chunkInBlock, tags.objectId, tags.chunkId,
3020 if(object && !yaffs_SkipVerification(dev)){
3021 if(tags.chunkId == 0)
3022 matchingChunk = object->chunkId;
3023 else if(object->softDeleted)
3024 matchingChunk = oldChunk; /* Defeat the test */
3026 matchingChunk = yaffs_FindChunkInFile(object,tags.chunkId,NULL);
3028 if(oldChunk != matchingChunk)
3029 T(YAFFS_TRACE_ERROR,
3030 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3031 oldChunk,matchingChunk,tags.objectId, tags.chunkId));
3036 T(YAFFS_TRACE_ERROR,
3038 ("page %d in gc has no object: %d %d %d "
3040 tags.objectId, tags.chunkId, tags.byteCount));
3043 if (object && object->deleted
3044 && tags.chunkId != 0) {
3045 /* Data chunk in a deleted file, throw it away
3046 * It's a soft deleted data chunk,
3047 * No need to copy this, just forget about it and
3048 * fix up the object.
3051 object->nDataChunks--;
3053 if (object->nDataChunks <= 0) {
3054 /* remeber to clean up the object */
3055 dev->gcCleanupList[cleanups] =
3061 /* Todo object && object->deleted && object->nDataChunks == 0 */
3063 /* Deleted object header with no data chunks.
3064 * Can be discarded and the file deleted.
3066 object->chunkId = 0;
3067 yaffs_FreeTnode(object->myDev,
3070 object->variant.fileVariant.top = NULL;
3071 yaffs_DoGenericObjectDeletion(object);
3073 } else if (object) {
3074 /* It's either a data chunk in a live file or
3075 * an ObjectHeader, so we're interested in it.
3076 * NB Need to keep the ObjectHeaders of deleted files
3077 * until the whole file has been deleted off
3079 tags.serialNumber++;
3083 if (tags.chunkId == 0) {
3084 /* It is an object Id,
3085 * We need to nuke the shrinkheader flags first
3086 * We no longer want the shrinkHeader flag since its work is done
3087 * and if it is left in place it will mess up scanning.
3088 * Also, clear out any shadowing stuff
3091 yaffs_ObjectHeader *oh;
3092 oh = (yaffs_ObjectHeader *)buffer;
3094 oh->shadowsObject = -1;
3095 tags.extraShadows = 0;
3096 tags.extraIsShrinkHeader = 0;
3098 yaffs_VerifyObjectHeader(object,oh,&tags,1);
3102 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3105 retVal = YAFFS_FAIL;
3108 /* Ok, now fix up the Tnodes etc. */
3110 if (tags.chunkId == 0) {
3112 object->chunkId = newChunk;
3113 object->serial = tags.serialNumber;
3115 /* It's a data chunk */
3116 yaffs_PutChunkIntoFile
3124 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3129 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3132 /* Do any required cleanups */
3133 for (i = 0; i < cleanups; i++) {
3134 /* Time to delete the file too */
3136 yaffs_FindObjectByNumber(dev,
3137 dev->gcCleanupList[i]);
3139 yaffs_FreeTnode(dev,
3140 object->variant.fileVariant.
3142 object->variant.fileVariant.top = NULL;
3145 ("yaffs: About to finally delete object %d"
3146 TENDSTR), object->objectId));
3147 yaffs_DoGenericObjectDeletion(object);
3148 object->myDev->nDeletedFiles--;
3155 yaffs_VerifyCollectedBlock(dev,bi,block);
3157 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
3160 ("gc did not increase free chunks before %d after %d"
3161 TENDSTR), chunksBefore, chunksAfter));
3169 /* New garbage collector
3170 * If we're very low on erased blocks then we do aggressive garbage collection
3171 * otherwise we do "leasurely" garbage collection.
3172 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3173 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3175 * The idea is to help clear out space in a more spread-out manner.
3176 * Dunno if it really does anything useful.
3178 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
3182 int gcOk = YAFFS_OK;
3185 int checkpointBlockAdjust;
3187 if (dev->isDoingGC) {
3188 /* Bail out so we don't get recursive gc */
3192 /* This loop should pass the first time.
3193 * We'll only see looping here if the erase of the collected block fails.
3199 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3200 if(checkpointBlockAdjust < 0)
3201 checkpointBlockAdjust = 0;
3203 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3204 /* We need a block soon...*/
3207 /* We're in no hurry */
3211 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3214 dev->garbageCollections++;
3216 dev->passiveGarbageCollections++;
3221 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3222 dev->nErasedBlocks, aggressive));
3224 gcOk = yaffs_GarbageCollectBlock(dev, block);
3227 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3230 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3231 TENDSTR), dev->nErasedBlocks, maxTries, block));
3233 } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
3236 return aggressive ? gcOk : YAFFS_OK;
3239 /*------------------------- TAGS --------------------------------*/
3241 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
3244 return (tags->chunkId == chunkInObject &&
3245 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3250 /*-------------------- Data file manipulation -----------------*/
3252 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
3253 yaffs_ExtendedTags * tags)
3255 /*Get the Tnode, then get the level 0 offset chunk offset */
3258 yaffs_ExtendedTags localTags;
3261 yaffs_Device *dev = in->myDev;
3264 /* Passed a NULL, so use our own tags space */
3268 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3271 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3274 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3280 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
3281 yaffs_ExtendedTags * tags)
3283 /* Get the Tnode, then get the level 0 offset chunk offset */
3286 yaffs_ExtendedTags localTags;
3288 yaffs_Device *dev = in->myDev;
3292 /* Passed a NULL, so use our own tags space */
3296 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3300 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3303 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3306 /* Delete the entry in the filestructure (if found) */
3308 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
3311 /*T(("No level 0 found for %d\n", chunkInInode)); */
3315 /* T(("Could not find %d to delete\n",chunkInInode)); */
3320 #ifdef YAFFS_PARANOID
3322 static int yaffs_CheckFileSanity(yaffs_Object * in)
3330 yaffs_Tags localTags;
3331 yaffs_Tags *tags = &localTags;
3335 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3336 /* T(("Object not a file\n")); */
3340 objId = in->objectId;
3341 fSize = in->variant.fileVariant.fileSize;
3343 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3345 for (chunk = 1; chunk <= nChunks; chunk++) {
3346 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3351 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
3353 if (yaffs_CheckChunkBits
3354 (dev, theChunk / dev->nChunksPerBlock,
3355 theChunk % dev->nChunksPerBlock)) {
3357 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3361 (tags, in->objectId, chunk, chunkDeleted)) {
3371 /* T(("No level 0 found for %d\n", chunk)); */
3375 return failed ? YAFFS_FAIL : YAFFS_OK;
3380 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
3381 int chunkInNAND, int inScan)
3383 /* NB inScan is zero unless scanning.
3384 * For forward scanning, inScan is > 0;
3385 * for backward scanning inScan is < 0
3389 yaffs_Device *dev = in->myDev;
3391 yaffs_ExtendedTags existingTags;
3392 yaffs_ExtendedTags newTags;
3393 unsigned existingSerial, newSerial;
3395 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3396 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3397 * If it is not during Scanning then something went wrong!
3400 T(YAFFS_TRACE_ERROR,
3402 ("yaffs tragedy:attempt to put data chunk into a non-file"
3407 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3411 tn = yaffs_AddOrFindLevel0Tnode(dev,
3412 &in->variant.fileVariant,
3419 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3422 /* If we're scanning then we need to test for duplicates
3423 * NB This does not need to be efficient since it should only ever
3424 * happen when the power fails during a write, then only one
3425 * chunk should ever be affected.
3427 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3428 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3431 if (existingChunk != 0) {
3432 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3433 * thus we have to do a FindChunkInFile to get the real chunk id.
3435 * We have a duplicate now we need to decide which one to use:
3437 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3438 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3439 * YAFFS1: Get both sets of tags and compare serial numbers.
3443 /* Only do this for forward scanning */
3444 yaffs_ReadChunkWithTagsFromNAND(dev,
3448 /* Do a proper find */
3450 yaffs_FindChunkInFile(in, chunkInInode,
3454 if (existingChunk <= 0) {
3455 /*Hoosterman - how did this happen? */
3457 T(YAFFS_TRACE_ERROR,
3459 ("yaffs tragedy: existing chunk < 0 in scan"
3464 /* NB The deleted flags should be false, otherwise the chunks will
3465 * not be loaded during a scan
3468 newSerial = newTags.serialNumber;
3469 existingSerial = existingTags.serialNumber;
3472 (in->myDev->isYaffs2 ||
3473 existingChunk <= 0 ||
3474 ((existingSerial + 1) & 3) == newSerial)) {
3475 /* Forward scanning.
3477 * Delete the old one and drop through to update the tnode
3479 yaffs_DeleteChunk(dev, existingChunk, 1,
3482 /* Backward scanning or we want to use the existing one
3484 * Delete the new one and return early so that the tnode isn't changed
3486 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3494 if (existingChunk == 0) {
3498 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
3503 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
3506 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3508 if (chunkInNAND >= 0) {
3509 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3512 T(YAFFS_TRACE_NANDACCESS,
3513 (TSTR("Chunk %d not found zero instead" TENDSTR),
3515 /* get sane (zero) data if you read a hole */
3516 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3522 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
3526 yaffs_ExtendedTags tags;
3527 yaffs_BlockInfo *bi;
3534 block = chunkId / dev->nChunksPerBlock;
3535 page = chunkId % dev->nChunksPerBlock;
3538 if(!yaffs_CheckChunkBit(dev,block,page))
3539 T(YAFFS_TRACE_VERIFY,
3540 (TSTR("Deleting invalid chunk %d"TENDSTR),
3543 bi = yaffs_GetBlockInfo(dev, block);
3545 T(YAFFS_TRACE_DELETION,
3546 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3549 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3551 yaffs_InitialiseTags(&tags);
3553 tags.chunkDeleted = 1;
3555 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3556 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3558 dev->nUnmarkedDeletions++;
3561 /* Pull out of the management area.
3562 * If the whole block became dirty, this will kick off an erasure.
3564 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3565 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3566 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3567 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3570 yaffs_ClearChunkBit(dev, block, page);
3574 if (bi->pagesInUse == 0 &&
3575 !bi->hasShrinkHeader &&
3576 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3577 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3578 yaffs_BlockBecameDirty(dev, block);
3582 /* T(("Bad news deleting chunk %d\n",chunkId)); */
3587 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
3588 const __u8 * buffer, int nBytes,
3591 /* Find old chunk Need to do this to get serial number
3592 * Write new one and patch into tree.
3593 * Invalidate old tags.
3597 yaffs_ExtendedTags prevTags;
3600 yaffs_ExtendedTags newTags;
3602 yaffs_Device *dev = in->myDev;
3604 yaffs_CheckGarbageCollection(dev);
3606 /* Get the previous chunk at this location in the file if it exists */
3607 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3609 /* Set up new tags */
3610 yaffs_InitialiseTags(&newTags);
3612 newTags.chunkId = chunkInInode;
3613 newTags.objectId = in->objectId;
3614 newTags.serialNumber =
3615 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
3616 newTags.byteCount = nBytes;
3619 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3622 if (newChunkId >= 0) {
3623 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3625 if (prevChunkId >= 0) {
3626 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3630 yaffs_CheckFileSanity(in);
3636 /* UpdateObjectHeader updates the header on NAND for an object.
3637 * If name is not NULL, then that new name is used.
3639 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
3640 int isShrink, int shadows)
3643 yaffs_BlockInfo *bi;
3645 yaffs_Device *dev = in->myDev;
3652 yaffs_ExtendedTags newTags;
3653 yaffs_ExtendedTags oldTags;
3655 __u8 *buffer = NULL;
3656 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3658 yaffs_ObjectHeader *oh = NULL;
3660 yaffs_strcpy(oldName,"silly old name");
3662 if (!in->fake || force) {
3664 yaffs_CheckGarbageCollection(dev);
3665 yaffs_CheckObjectDetailsLoaded(in);
3667 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3668 oh = (yaffs_ObjectHeader *) buffer;
3670 prevChunkId = in->chunkId;
3672 if (prevChunkId >= 0) {
3673 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3676 yaffs_VerifyObjectHeader(in,oh,&oldTags,0);
3678 memcpy(oldName, oh->name, sizeof(oh->name));
3681 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3683 oh->type = in->variantType;
3684 oh->yst_mode = in->yst_mode;
3685 oh->shadowsObject = shadows;
3687 #ifdef CONFIG_YAFFS_WINCE
3688 oh->win_atime[0] = in->win_atime[0];
3689 oh->win_ctime[0] = in->win_ctime[0];
3690 oh->win_mtime[0] = in->win_mtime[0];
3691 oh->win_atime[1] = in->win_atime[1];
3692 oh->win_ctime[1] = in->win_ctime[1];
3693 oh->win_mtime[1] = in->win_mtime[1];
3695 oh->yst_uid = in->yst_uid;
3696 oh->yst_gid = in->yst_gid;
3697 oh->yst_atime = in->yst_atime;
3698 oh->yst_mtime = in->yst_mtime;
3699 oh->yst_ctime = in->yst_ctime;
3700 oh->yst_rdev = in->yst_rdev;
3703 oh->parentObjectId = in->parent->objectId;
3705 oh->parentObjectId = 0;
3708 if (name && *name) {
3709 memset(oh->name, 0, sizeof(oh->name));
3710 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3711 } else if (prevChunkId>=0) {
3712 memcpy(oh->name, oldName, sizeof(oh->name));
3714 memset(oh->name, 0, sizeof(oh->name));
3717 oh->isShrink = isShrink;
3719 switch (in->variantType) {
3720 case YAFFS_OBJECT_TYPE_UNKNOWN:
3721 /* Should not happen */
3723 case YAFFS_OBJECT_TYPE_FILE:
3725 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3726 || oh->parentObjectId ==
3727 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3728 fileVariant.fileSize;
3730 case YAFFS_OBJECT_TYPE_HARDLINK:
3731 oh->equivalentObjectId =
3732 in->variant.hardLinkVariant.equivalentObjectId;
3734 case YAFFS_OBJECT_TYPE_SPECIAL:
3737 case YAFFS_OBJECT_TYPE_DIRECTORY:
3740 case YAFFS_OBJECT_TYPE_SYMLINK:
3741 yaffs_strncpy(oh->alias,
3742 in->variant.symLinkVariant.alias,
3743 YAFFS_MAX_ALIAS_LENGTH);
3744 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3749 yaffs_InitialiseTags(&newTags);
3751 newTags.chunkId = 0;
3752 newTags.objectId = in->objectId;
3753 newTags.serialNumber = in->serial;
3755 /* Add extra info for file header */
3757 newTags.extraHeaderInfoAvailable = 1;
3758 newTags.extraParentObjectId = oh->parentObjectId;
3759 newTags.extraFileLength = oh->fileSize;
3760 newTags.extraIsShrinkHeader = oh->isShrink;
3761 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3762 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3763 newTags.extraObjectType = in->variantType;
3765 yaffs_VerifyObjectHeader(in,oh,&newTags,1);
3767 /* Create new chunk in NAND */
3769 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3770 (prevChunkId >= 0) ? 1 : 0);
3772 if (newChunkId >= 0) {
3774 in->chunkId = newChunkId;
3776 if (prevChunkId >= 0) {
3777 yaffs_DeleteChunk(dev, prevChunkId, 1,
3781 if(!yaffs_ObjectHasCachedWriteData(in))
3784 /* If this was a shrink, then mark the block that the chunk lives on */
3786 bi = yaffs_GetBlockInfo(in->myDev,
3787 newChunkId /in->myDev-> nChunksPerBlock);
3788 bi->hasShrinkHeader = 1;
3793 retVal = newChunkId;
3798 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3803 /*------------------------ Short Operations Cache ----------------------------------------
3804 * In many situations where there is no high level buffering (eg WinCE) a lot of
3805 * reads might be short sequential reads, and a lot of writes may be short
3806 * sequential writes. eg. scanning/writing a jpeg file.
3807 * In these cases, a short read/write cache can provide a huge perfomance benefit
3808 * with dumb-as-a-rock code.
3809 * In Linux, the page cache provides read buffering aand the short op cache provides write
3812 * There are a limited number (~10) of cache chunks per device so that we don't
3813 * need a very intelligent search.
3816 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3818 yaffs_Device *dev = obj->myDev;
3820 yaffs_ChunkCache *cache;
3821 int nCaches = obj->myDev->nShortOpCaches;
3823 for(i = 0; i < nCaches; i++){
3824 cache = &dev->srCache[i];
3825 if (cache->object == obj &&
3834 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3836 yaffs_Device *dev = obj->myDev;
3837 int lowest = -99; /* Stop compiler whining. */
3839 yaffs_ChunkCache *cache;
3840 int chunkWritten = 0;
3841 int nCaches = obj->myDev->nShortOpCaches;
3847 /* Find the dirty cache for this object with the lowest chunk id. */
3848 for (i = 0; i < nCaches; i++) {
3849 if (dev->srCache[i].object == obj &&
3850 dev->srCache[i].dirty) {
3852 || dev->srCache[i].chunkId <
3854 cache = &dev->srCache[i];
3855 lowest = cache->chunkId;
3860 if (cache && !cache->locked) {
3861 /* Write it out and free it up */
3864 yaffs_WriteChunkDataToObject(cache->object,
3870 cache->object = NULL;
3873 } while (cache && chunkWritten > 0);
3876 /* Hoosterman, disk full while writing cache out. */
3877 T(YAFFS_TRACE_ERROR,
3878 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3885 /*yaffs_FlushEntireDeviceCache(dev)
3890 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3893 int nCaches = dev->nShortOpCaches;
3896 /* Find a dirty object in the cache and flush it...
3897 * until there are no further dirty objects.
3901 for( i = 0; i < nCaches && !obj; i++) {
3902 if (dev->srCache[i].object &&
3903 dev->srCache[i].dirty)
3904 obj = dev->srCache[i].object;
3908 yaffs_FlushFilesChunkCache(obj);
3915 /* Grab us a cache chunk for use.
3916 * First look for an empty one.
3917 * Then look for the least recently used non-dirty one.
3918 * Then look for the least recently used dirty one...., flush and look again.
3920 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
3926 if (dev->nShortOpCaches > 0) {
3927 for (i = 0; i < dev->nShortOpCaches; i++) {
3928 if (!dev->srCache[i].object)
3929 return &dev->srCache[i];
3935 usage = 0; /* just to stop the compiler grizzling */
3937 for (i = 0; i < dev->nShortOpCaches; i++) {
3938 if (!dev->srCache[i].dirty &&
3939 ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
3941 usage = dev->srCache[i].lastUse;
3947 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3954 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
3956 yaffs_ChunkCache *cache;
3957 yaffs_Object *theObj;
3962 if (dev->nShortOpCaches > 0) {
3963 /* Try find a non-dirty one... */
3965 cache = yaffs_GrabChunkCacheWorker(dev);
3968 /* They were all dirty, find the last recently used object and flush
3969 * its cache, then find again.
3970 * NB what's here is not very accurate, we actually flush the object
3971 * the last recently used page.
3974 /* With locking we can't assume we can use entry zero */
3981 for (i = 0; i < dev->nShortOpCaches; i++) {
3982 if (dev->srCache[i].object &&
3983 !dev->srCache[i].locked &&
3984 (dev->srCache[i].lastUse < usage || !cache))
3986 usage = dev->srCache[i].lastUse;
3987 theObj = dev->srCache[i].object;
3988 cache = &dev->srCache[i];
3993 if (!cache || cache->dirty) {
3994 /* Flush and try again */
3995 yaffs_FlushFilesChunkCache(theObj);
3996 cache = yaffs_GrabChunkCacheWorker(dev);
4006 /* Find a cached chunk */
4007 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
4010 yaffs_Device *dev = obj->myDev;
4012 if (dev->nShortOpCaches > 0) {
4013 for (i = 0; i < dev->nShortOpCaches; i++) {
4014 if (dev->srCache[i].object == obj &&
4015 dev->srCache[i].chunkId == chunkId) {
4018 return &dev->srCache[i];
4025 /* Mark the chunk for the least recently used algorithym */
4026 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
4030 if (dev->nShortOpCaches > 0) {
4031 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4032 /* Reset the cache usages */
4034 for (i = 1; i < dev->nShortOpCaches; i++) {
4035 dev->srCache[i].lastUse = 0;
4042 cache->lastUse = dev->srLastUse;
4050 /* Invalidate a single cache page.
4051 * Do this when a whole page gets written,
4052 * ie the short cache for this page is no longer valid.
4054 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
4056 if (object->myDev->nShortOpCaches > 0) {
4057 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4060 cache->object = NULL;
4065 /* Invalidate all the cache pages associated with this object
4066 * Do this whenever ther file is deleted or resized.
4068 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
4071 yaffs_Device *dev = in->myDev;
4073 if (dev->nShortOpCaches > 0) {
4074 /* Invalidate it. */
4075 for (i = 0; i < dev->nShortOpCaches; i++) {
4076 if (dev->srCache[i].object == in) {
4077 dev->srCache[i].object = NULL;
4083 /*--------------------- Checkpointing --------------------*/
4086 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
4088 yaffs_CheckpointValidity cp;
4090 memset(&cp,0,sizeof(cp));
4092 cp.structType = sizeof(cp);
4093 cp.magic = YAFFS_MAGIC;
4094 cp.version = YAFFS_CHECKPOINT_VERSION;
4095 cp.head = (head) ? 1 : 0;
4097 return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
4101 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4103 yaffs_CheckpointValidity cp;
4106 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4109 ok = (cp.structType == sizeof(cp)) &&
4110 (cp.magic == YAFFS_MAGIC) &&
4111 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4112 (cp.head == ((head) ? 1 : 0));
4116 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4119 cp->nErasedBlocks = dev->nErasedBlocks;
4120 cp->allocationBlock = dev->allocationBlock;
4121 cp->allocationPage = dev->allocationPage;
4122 cp->nFreeChunks = dev->nFreeChunks;
4124 cp->nDeletedFiles = dev->nDeletedFiles;
4125 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4126 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4127 cp->sequenceNumber = dev->sequenceNumber;
4128 cp->oldestDirtySequence = dev->oldestDirtySequence;
4132 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4133 yaffs_CheckpointDevice *cp)
4135 dev->nErasedBlocks = cp->nErasedBlocks;
4136 dev->allocationBlock = cp->allocationBlock;
4137 dev->allocationPage = cp->allocationPage;
4138 dev->nFreeChunks = cp->nFreeChunks;
4140 dev->nDeletedFiles = cp->nDeletedFiles;
4141 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4142 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4143 dev->sequenceNumber = cp->sequenceNumber;
4144 dev->oldestDirtySequence = cp->oldestDirtySequence;
4148 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4150 yaffs_CheckpointDevice cp;
4152 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4156 /* Write device runtime values*/
4157 yaffs_DeviceToCheckpointDevice(&cp,dev);
4158 cp.structType = sizeof(cp);
4160 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4162 /* Write block info */
4164 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4165 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
4168 /* Write chunk bits */
4170 nBytes = nBlocks * dev->chunkBitmapStride;
4171 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
4177 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4179 yaffs_CheckpointDevice cp;
4181 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4185 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4189 if(cp.structType != sizeof(cp))
4193 yaffs_CheckpointDeviceToDevice(dev,&cp);
4195 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4197 ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
4201 nBytes = nBlocks * dev->chunkBitmapStride;
4203 ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
4208 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4212 cp->objectId = obj->objectId;
4213 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4214 cp->chunkId = obj->chunkId;
4215 cp->variantType = obj->variantType;
4216 cp->deleted = obj->deleted;
4217 cp->softDeleted = obj->softDeleted;
4218 cp->unlinked = obj->unlinked;
4219 cp->fake = obj->fake;
4220 cp->renameAllowed = obj->renameAllowed;
4221 cp->unlinkAllowed = obj->unlinkAllowed;
4222 cp->serial = obj->serial;
4223 cp->nDataChunks = obj->nDataChunks;
4225 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4226 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4227 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4228 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4231 static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
4234 yaffs_Object *parent;
4236 obj->objectId = cp->objectId;
4239 parent = yaffs_FindOrCreateObjectByNumber(
4242 YAFFS_OBJECT_TYPE_DIRECTORY);
4247 yaffs_AddObjectToDirectory(parent, obj);
4249 obj->chunkId = cp->chunkId;
4250 obj->variantType = cp->variantType;
4251 obj->deleted = cp->deleted;
4252 obj->softDeleted = cp->softDeleted;
4253 obj->unlinked = cp->unlinked;
4254 obj->fake = cp->fake;
4255 obj->renameAllowed = cp->renameAllowed;
4256 obj->unlinkAllowed = cp->unlinkAllowed;
4257 obj->serial = cp->serial;
4258 obj->nDataChunks = cp->nDataChunks;
4260 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4261 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4262 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4263 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4265 if(obj->objectId >= YAFFS_NOBJECT_BUCKETS)
4266 obj->lazyLoaded = 1;
4271 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
4272 __u32 level, int chunkOffset)
4275 yaffs_Device *dev = in->myDev;
4277 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4279 if(tnodeSize < sizeof(yaffs_Tnode))
4280 tnodeSize = sizeof(yaffs_Tnode);
4286 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
4287 if (tn->internal[i]) {
4288 ok = yaffs_CheckpointTnodeWorker(in,
4291 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4294 } else if (level == 0) {
4295 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4296 /* printf("write tnode at %d\n",baseOffset); */
4297 ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
4299 ok = (yaffs_CheckpointWrite(dev,tn,tnodeSize) == tnodeSize);
4307 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4309 __u32 endMarker = ~0;
4312 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4313 ok = yaffs_CheckpointTnodeWorker(obj,
4314 obj->variant.fileVariant.top,
4315 obj->variant.fileVariant.topLevel,
4318 ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) ==
4325 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4329 yaffs_Device *dev = obj->myDev;
4330 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4333 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4335 if(tnodeSize < sizeof(yaffs_Tnode))
4336 tnodeSize = sizeof(yaffs_Tnode);
4338 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4340 while(ok && (~baseChunk)){
4342 /* Read level 0 tnode */
4345 /* printf("read tnode at %d\n",baseChunk); */
4346 tn = yaffs_GetTnodeRaw(dev);
4348 ok = (yaffs_CheckpointRead(dev,tn,tnodeSize) == tnodeSize);
4353 ok = yaffs_AddOrFindLevel0Tnode(dev,
4361 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4365 T(YAFFS_TRACE_CHECKPOINT,(
4366 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4367 nread,baseChunk,ok));
4373 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4376 yaffs_CheckpointObject cp;
4379 struct list_head *lh;
4382 /* Iterate through the objects in each hash entry,
4383 * dumping them to the checkpointing stream.
4386 for(i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++){
4387 list_for_each(lh, &dev->objectBucket[i].list) {
4389 obj = list_entry(lh, yaffs_Object, hashLink);
4390 if (!obj->deferedFree) {
4391 yaffs_ObjectToCheckpointObject(&cp,obj);
4392 cp.structType = sizeof(cp);
4394 T(YAFFS_TRACE_CHECKPOINT,(
4395 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
4396 cp.objectId,cp.parentId,cp.variantType,cp.chunkId,(unsigned) obj));
4398 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4400 if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4401 ok = yaffs_WriteCheckpointTnodes(obj);
4408 /* Dump end of list */
4409 memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
4410 cp.structType = sizeof(cp);
4413 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4418 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4421 yaffs_CheckpointObject cp;
4424 yaffs_Object *hardList = NULL;
4426 while(ok && !done) {
4427 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4428 if(cp.structType != sizeof(cp)) {
4429 T(YAFFS_TRACE_CHECKPOINT,(TSTR("struct size %d instead of %d ok %d"TENDSTR),
4430 cp.structType,sizeof(cp),ok));
4434 T(YAFFS_TRACE_CHECKPOINT,(TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4435 cp.objectId,cp.parentId,cp.variantType,cp.chunkId));
4437 if(ok && cp.objectId == ~0)
4440 obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
4442 yaffs_CheckpointObjectToObject(obj,&cp);
4443 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4444 ok = yaffs_ReadCheckpointTnodes(obj);
4445 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4446 obj->hardLinks.next =
4447 (struct list_head *)
4457 yaffs_HardlinkFixup(dev,hardList);
4462 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4464 __u32 checkpointSum;
4467 yaffs_GetCheckpointSum(dev,&checkpointSum);
4469 ok = (yaffs_CheckpointWrite(dev,&checkpointSum,sizeof(checkpointSum)) == sizeof(checkpointSum));
4477 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4479 __u32 checkpointSum0;
4480 __u32 checkpointSum1;
4483 yaffs_GetCheckpointSum(dev,&checkpointSum0);
4485 ok = (yaffs_CheckpointRead(dev,&checkpointSum1,sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4490 if(checkpointSum0 != checkpointSum1)
4497 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4502 if(dev->skipCheckpointWrite || !dev->isYaffs2){
4503 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint write" TENDSTR)));
4508 ok = yaffs_CheckpointOpen(dev,1);
4511 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4512 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
4515 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint device" TENDSTR)));
4516 ok = yaffs_WriteCheckpointDevice(dev);
4519 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint objects" TENDSTR)));
4520 ok = yaffs_WriteCheckpointObjects(dev);
4523 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4524 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
4528 ok = yaffs_WriteCheckpointSum(dev);
4532 if(!yaffs_CheckpointClose(dev))
4536 dev->isCheckpointed = 1;
4538 dev->isCheckpointed = 0;
4540 return dev->isCheckpointed;
4543 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4547 if(dev->skipCheckpointRead || !dev->isYaffs2){
4548 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint read" TENDSTR)));
4553 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
4556 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4557 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
4560 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint device" TENDSTR)));
4561 ok = yaffs_ReadCheckpointDevice(dev);
4564 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint objects" TENDSTR)));
4565 ok = yaffs_ReadCheckpointObjects(dev);
4568 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4569 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
4573 ok = yaffs_ReadCheckpointSum(dev);
4574 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint checksum %d" TENDSTR),ok));
4577 if(!yaffs_CheckpointClose(dev))
4581 dev->isCheckpointed = 1;
4583 dev->isCheckpointed = 0;
4589 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4591 if(dev->isCheckpointed ||
4592 dev->blocksInCheckpoint > 0){
4593 dev->isCheckpointed = 0;
4594 yaffs_CheckpointInvalidateStream(dev);
4595 if(dev->superBlock && dev->markSuperBlockDirty)
4596 dev->markSuperBlockDirty(dev->superBlock);
4601 int yaffs_CheckpointSave(yaffs_Device *dev)
4604 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4606 yaffs_VerifyObjects(dev);
4607 yaffs_VerifyBlocks(dev);
4608 yaffs_VerifyFreeChunks(dev);
4610 if(!dev->isCheckpointed) {
4611 yaffs_InvalidateCheckpoint(dev);
4612 yaffs_WriteCheckpointData(dev);
4615 T(YAFFS_TRACE_ALWAYS,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4617 return dev->isCheckpointed;
4620 int yaffs_CheckpointRestore(yaffs_Device *dev)
4623 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4625 retval = yaffs_ReadCheckpointData(dev);
4627 if(dev->isCheckpointed){
4628 yaffs_VerifyObjects(dev);
4629 yaffs_VerifyBlocks(dev);
4630 yaffs_VerifyFreeChunks(dev);
4633 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4638 /*--------------------- File read/write ------------------------
4639 * Read and write have very similar structures.
4640 * In general the read/write has three parts to it
4641 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4642 * Some complete chunks
4643 * An incomplete chunk to end off with
4645 * Curve-balls: the first chunk might also be the last chunk.
4648 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, loff_t offset,
4657 yaffs_ChunkCache *cache;
4664 //chunk = offset / dev->nDataBytesPerChunk + 1;
4665 //start = offset % dev->nDataBytesPerChunk;
4666 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4669 /* OK now check for the curveball where the start and end are in
4672 if ((start + n) < dev->nDataBytesPerChunk) {
4675 nToCopy = dev->nDataBytesPerChunk - start;
4678 cache = yaffs_FindChunkCache(in, chunk);
4680 /* If the chunk is already in the cache or it is less than a whole chunk
4681 * then use the cache (if there is caching)
4682 * else bypass the cache.
4684 if (cache || nToCopy != dev->nDataBytesPerChunk) {
4685 if (dev->nShortOpCaches > 0) {
4687 /* If we can't find the data in the cache, then load it up. */
4690 cache = yaffs_GrabChunkCache(in->myDev);
4692 cache->chunkId = chunk;
4695 yaffs_ReadChunkDataFromObject(in, chunk,
4701 yaffs_UseChunkCache(dev, cache, 0);
4705 #ifdef CONFIG_YAFFS_WINCE
4706 yfsd_UnlockYAFFS(TRUE);
4708 memcpy(buffer, &cache->data[start], nToCopy);
4710 #ifdef CONFIG_YAFFS_WINCE
4711 yfsd_LockYAFFS(TRUE);
4715 /* Read into the local buffer then copy..*/
4718 yaffs_GetTempBuffer(dev, __LINE__);
4719 yaffs_ReadChunkDataFromObject(in, chunk,
4721 #ifdef CONFIG_YAFFS_WINCE
4722 yfsd_UnlockYAFFS(TRUE);
4724 memcpy(buffer, &localBuffer[start], nToCopy);
4726 #ifdef CONFIG_YAFFS_WINCE
4727 yfsd_LockYAFFS(TRUE);
4729 yaffs_ReleaseTempBuffer(dev, localBuffer,
4734 #ifdef CONFIG_YAFFS_WINCE
4735 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4737 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4738 * This is because we otherwise screw up WinCE's memory mapper
4740 yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
4742 #ifdef CONFIG_YAFFS_WINCE
4743 yfsd_UnlockYAFFS(TRUE);
4745 memcpy(buffer, localBuffer, dev->nDataBytesPerChunk);
4747 #ifdef CONFIG_YAFFS_WINCE
4748 yfsd_LockYAFFS(TRUE);
4749 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4753 /* A full chunk. Read directly into the supplied buffer. */
4754 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4768 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, loff_t offset,
4769 int nBytes, int writeThrough)
4778 int startOfWrite = offset;
4779 int chunkWritten = 0;
4786 while (n > 0 && chunkWritten >= 0) {
4787 //chunk = offset / dev->nDataBytesPerChunk + 1;
4788 //start = offset % dev->nDataBytesPerChunk;
4789 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4792 /* OK now check for the curveball where the start and end are in
4796 if ((start + n) < dev->nDataBytesPerChunk) {
4799 /* Now folks, to calculate how many bytes to write back....
4800 * If we're overwriting and not writing to then end of file then
4801 * we need to write back as much as was there before.
4805 in->variant.fileVariant.fileSize -
4806 ((chunk - 1) * dev->nDataBytesPerChunk);
4808 if (nBytesRead > dev->nDataBytesPerChunk) {
4809 nBytesRead = dev->nDataBytesPerChunk;
4814 (start + n)) ? nBytesRead : (start + n);
4817 nToCopy = dev->nDataBytesPerChunk - start;
4818 nToWriteBack = dev->nDataBytesPerChunk;
4821 if (nToCopy != dev->nDataBytesPerChunk) {
4822 /* An incomplete start or end chunk (or maybe both start and end chunk) */
4823 if (dev->nShortOpCaches > 0) {
4824 yaffs_ChunkCache *cache;
4825 /* If we can't find the data in the cache, then load the cache */
4826 cache = yaffs_FindChunkCache(in, chunk);
4829 && yaffs_CheckSpaceForAllocation(in->
4831 cache = yaffs_GrabChunkCache(in->myDev);
4833 cache->chunkId = chunk;
4836 yaffs_ReadChunkDataFromObject(in, chunk,
4842 !yaffs_CheckSpaceForAllocation(in->myDev)){
4843 /* Drop the cache if it was a read cache item and
4844 * no space check has been made for it.
4850 yaffs_UseChunkCache(dev, cache, 1);
4852 #ifdef CONFIG_YAFFS_WINCE
4853 yfsd_UnlockYAFFS(TRUE);
4856 memcpy(&cache->data[start], buffer,
4859 #ifdef CONFIG_YAFFS_WINCE
4860 yfsd_LockYAFFS(TRUE);
4863 cache->nBytes = nToWriteBack;
4867 yaffs_WriteChunkDataToObject
4870 cache->data, cache->nBytes,
4876 chunkWritten = -1; /* fail the write */
4879 /* An incomplete start or end chunk (or maybe both start and end chunk)
4880 * Read into the local buffer then copy, then copy over and write back.
4884 yaffs_GetTempBuffer(dev, __LINE__);
4886 yaffs_ReadChunkDataFromObject(in, chunk,
4889 #ifdef CONFIG_YAFFS_WINCE
4890 yfsd_UnlockYAFFS(TRUE);
4893 memcpy(&localBuffer[start], buffer, nToCopy);
4895 #ifdef CONFIG_YAFFS_WINCE
4896 yfsd_LockYAFFS(TRUE);
4899 yaffs_WriteChunkDataToObject(in, chunk,
4904 yaffs_ReleaseTempBuffer(dev, localBuffer,
4911 #ifdef CONFIG_YAFFS_WINCE
4912 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4913 * This is because we otherwise screw up WinCE's memory mapper
4915 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4916 #ifdef CONFIG_YAFFS_WINCE
4917 yfsd_UnlockYAFFS(TRUE);
4919 memcpy(localBuffer, buffer, dev->nDataBytesPerChunk);
4920 #ifdef CONFIG_YAFFS_WINCE
4921 yfsd_LockYAFFS(TRUE);
4924 yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
4925 dev->nDataBytesPerChunk,
4927 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4929 /* A full chunk. Write directly from the supplied buffer. */
4931 yaffs_WriteChunkDataToObject(in, chunk, buffer,
4932 dev->nDataBytesPerChunk,
4935 /* Since we've overwritten the cached data, we better invalidate it. */
4936 yaffs_InvalidateChunkCache(in, chunk);
4939 if (chunkWritten >= 0) {
4948 /* Update file object */
4950 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
4951 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4960 /* ---------------------- File resizing stuff ------------------ */
4962 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
4965 yaffs_Device *dev = in->myDev;
4966 int oldFileSize = in->variant.fileVariant.fileSize;
4968 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
4970 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
4971 dev->nDataBytesPerChunk;
4975 /* Delete backwards so that we don't end up with holes if
4976 * power is lost part-way through the operation.
4978 for (i = lastDel; i >= startDel; i--) {
4979 /* NB this could be optimised somewhat,
4980 * eg. could retrieve the tags and write them without
4981 * using yaffs_DeleteChunk
4984 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
4987 (dev->internalStartBlock * dev->nChunksPerBlock)
4989 ((dev->internalEndBlock +
4990 1) * dev->nChunksPerBlock)) {
4991 T(YAFFS_TRACE_ALWAYS,
4992 (TSTR("Found daft chunkId %d for %d" TENDSTR),
4996 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5003 int yaffs_ResizeFile(yaffs_Object * in, loff_t newSize)
5006 int oldFileSize = in->variant.fileVariant.fileSize;
5007 int newSizeOfPartialChunk;
5010 yaffs_Device *dev = in->myDev;
5012 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5014 yaffs_FlushFilesChunkCache(in);
5015 yaffs_InvalidateWholeChunkCache(in);
5017 yaffs_CheckGarbageCollection(dev);
5019 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
5020 return yaffs_GetFileSize(in);
5023 if (newSize == oldFileSize) {
5027 if (newSize < oldFileSize) {
5029 yaffs_PruneResizedChunks(in, newSize);
5031 if (newSizeOfPartialChunk != 0) {
5032 int lastChunk = 1 + newFullChunks;
5034 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5036 /* Got to read and rewrite the last chunk with its new size and zero pad */
5037 yaffs_ReadChunkDataFromObject(in, lastChunk,
5040 memset(localBuffer + newSizeOfPartialChunk, 0,
5041 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5043 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5044 newSizeOfPartialChunk, 1);
5046 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5049 in->variant.fileVariant.fileSize = newSize;
5051 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5053 /* newsSize > oldFileSize */
5054 in->variant.fileVariant.fileSize = newSize;
5059 /* Write a new object header.
5060 * show we've shrunk the file, if need be
5061 * Do this only if the file is not in the deleted directories.
5063 if (in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5064 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
5065 yaffs_UpdateObjectHeader(in, NULL, 0,
5066 (newSize < oldFileSize) ? 1 : 0, 0);
5072 loff_t yaffs_GetFileSize(yaffs_Object * obj)
5074 obj = yaffs_GetEquivalentObject(obj);
5076 switch (obj->variantType) {
5077 case YAFFS_OBJECT_TYPE_FILE:
5078 return obj->variant.fileVariant.fileSize;
5079 case YAFFS_OBJECT_TYPE_SYMLINK:
5080 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5088 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
5092 yaffs_FlushFilesChunkCache(in);
5094 #ifdef CONFIG_YAFFS_WINCE
5095 yfsd_WinFileTimeNow(in->win_mtime);
5098 in->yst_mtime = Y_CURRENT_TIME;
5104 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5105 0) ? YAFFS_OK : YAFFS_FAIL;
5114 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
5117 /* First off, invalidate the file's data in the cache, without flushing. */
5118 yaffs_InvalidateWholeChunkCache(in);
5120 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5121 /* Move to the unlinked directory so we have a record that it was deleted. */
5122 yaffs_ChangeObjectName(in, in->myDev->deletedDir,"deleted", 0, 0);
5126 yaffs_RemoveObjectFromDirectory(in);
5127 yaffs_DeleteChunk(in->myDev, in->chunkId, 1, __LINE__);
5130 yaffs_FreeObject(in);
5135 /* yaffs_DeleteFile deletes the whole file data
5136 * and the inode associated with the file.
5137 * It does not delete the links associated with the file.
5139 static int yaffs_UnlinkFile(yaffs_Object * in)
5143 int immediateDeletion = 0;
5148 immediateDeletion = 1;
5152 if (in->inUse <= 0) {
5153 immediateDeletion = 1;
5157 if (immediateDeletion) {
5159 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5161 T(YAFFS_TRACE_TRACING,
5162 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5165 in->myDev->nDeletedFiles++;
5166 if (0 && in->myDev->isYaffs2) {
5167 yaffs_ResizeFile(in, 0);
5169 yaffs_SoftDeleteFile(in);
5172 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5180 int yaffs_DeleteFile(yaffs_Object * in)
5182 int retVal = YAFFS_OK;
5184 if (in->nDataChunks > 0) {
5185 /* Use soft deletion if there is data in the file */
5186 if (!in->unlinked) {
5187 retVal = yaffs_UnlinkFile(in);
5189 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5191 in->myDev->nDeletedFiles++;
5192 yaffs_SoftDeleteFile(in);
5194 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
5196 /* The file has no data chunks so we toss it immediately */
5197 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5198 in->variant.fileVariant.top = NULL;
5199 yaffs_DoGenericObjectDeletion(in);
5205 static int yaffs_DeleteDirectory(yaffs_Object * in)
5207 /* First check that the directory is empty. */
5208 if (list_empty(&in->variant.directoryVariant.children)) {
5209 return yaffs_DoGenericObjectDeletion(in);
5216 static int yaffs_DeleteSymLink(yaffs_Object * in)
5218 YFREE(in->variant.symLinkVariant.alias);
5220 return yaffs_DoGenericObjectDeletion(in);
5223 static int yaffs_DeleteHardLink(yaffs_Object * in)
5225 /* remove this hardlink from the list assocaited with the equivalent
5228 list_del(&in->hardLinks);
5229 return yaffs_DoGenericObjectDeletion(in);
5232 static void yaffs_DestroyObject(yaffs_Object * obj)
5234 switch (obj->variantType) {
5235 case YAFFS_OBJECT_TYPE_FILE:
5236 yaffs_DeleteFile(obj);
5238 case YAFFS_OBJECT_TYPE_DIRECTORY:
5239 yaffs_DeleteDirectory(obj);
5241 case YAFFS_OBJECT_TYPE_SYMLINK:
5242 yaffs_DeleteSymLink(obj);
5244 case YAFFS_OBJECT_TYPE_HARDLINK:
5245 yaffs_DeleteHardLink(obj);
5247 case YAFFS_OBJECT_TYPE_SPECIAL:
5248 yaffs_DoGenericObjectDeletion(obj);
5250 case YAFFS_OBJECT_TYPE_UNKNOWN:
5251 break; /* should not happen. */
5255 static int yaffs_UnlinkWorker(yaffs_Object * obj)
5258 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5259 return yaffs_DeleteHardLink(obj);
5260 } else if (!list_empty(&obj->hardLinks)) {
5261 /* Curve ball: We're unlinking an object that has a hardlink.
5263 * This problem arises because we are not strictly following
5264 * The Linux link/inode model.
5266 * We can't really delete the object.
5267 * Instead, we do the following:
5268 * - Select a hardlink.
5269 * - Unhook it from the hard links
5270 * - Unhook it from its parent directory (so that the rename can work)
5271 * - Rename the object to the hardlink's name.
5272 * - Delete the hardlink
5277 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5279 hl = list_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5281 list_del_init(&hl->hardLinks);
5282 list_del_init(&hl->siblings);
5284 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5286 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
5288 if (retVal == YAFFS_OK) {
5289 retVal = yaffs_DoGenericObjectDeletion(hl);
5294 switch (obj->variantType) {
5295 case YAFFS_OBJECT_TYPE_FILE:
5296 return yaffs_UnlinkFile(obj);
5298 case YAFFS_OBJECT_TYPE_DIRECTORY:
5299 return yaffs_DeleteDirectory(obj);
5301 case YAFFS_OBJECT_TYPE_SYMLINK:
5302 return yaffs_DeleteSymLink(obj);
5304 case YAFFS_OBJECT_TYPE_SPECIAL:
5305 return yaffs_DoGenericObjectDeletion(obj);
5307 case YAFFS_OBJECT_TYPE_HARDLINK:
5308 case YAFFS_OBJECT_TYPE_UNKNOWN:
5316 static int yaffs_UnlinkObject( yaffs_Object *obj)
5319 if (obj && obj->unlinkAllowed) {
5320 return yaffs_UnlinkWorker(obj);
5326 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
5330 obj = yaffs_FindObjectByName(dir, name);
5331 return yaffs_UnlinkObject(obj);
5334 /*----------------------- Initialisation Scanning ---------------------- */
5336 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
5337 int backwardScanning)
5341 if (!backwardScanning) {
5342 /* Handle YAFFS1 forward scanning case
5343 * For YAFFS1 we always do the deletion
5347 /* Handle YAFFS2 case (backward scanning)
5348 * If the shadowed object exists then ignore.
5350 if (yaffs_FindObjectByNumber(dev, objId)) {
5355 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5356 * We put it in unlinked dir to be cleaned up after the scanning
5359 yaffs_FindOrCreateObjectByNumber(dev, objId,
5360 YAFFS_OBJECT_TYPE_FILE);
5361 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5362 obj->variant.fileVariant.shrinkSize = 0;
5363 obj->valid = 1; /* So that we don't read any other info for this file */
5373 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5380 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5382 in = yaffs_FindObjectByNumber(dev,
5383 hl->variant.hardLinkVariant.
5384 equivalentObjectId);
5387 /* Add the hardlink pointers */
5388 hl->variant.hardLinkVariant.equivalentObject = in;
5389 list_add(&hl->hardLinks, &in->hardLinks);
5391 /* Todo Need to report/handle this better.
5392 * Got a problem... hardlink to a non-existant object
5394 hl->variant.hardLinkVariant.equivalentObject = NULL;
5395 INIT_LIST_HEAD(&hl->hardLinks);
5407 static int ybicmp(const void *a, const void *b){
5408 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5409 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5410 register int ablock = ((yaffs_BlockIndex *)a)->block;
5411 register int bblock = ((yaffs_BlockIndex *)b)->block;
5413 return ablock - bblock;
5419 static int yaffs_Scan(yaffs_Device * dev)
5421 yaffs_ExtendedTags tags;
5426 int nBlocksToScan = 0;
5432 yaffs_BlockState state;
5433 yaffs_Object *hardList = NULL;
5434 yaffs_BlockInfo *bi;
5436 yaffs_ObjectHeader *oh;
5438 yaffs_Object *parent;
5439 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5441 int alloc_failed = 0;
5446 yaffs_BlockIndex *blockIndex = NULL;
5448 if (dev->isYaffs2) {
5450 (TSTR("yaffs_Scan is not for YAFFS2!" TENDSTR)));
5454 //TODO Throw all the yaffs2 stuuf out of yaffs_Scan since it is only for yaffs1 format.
5457 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5458 dev->internalStartBlock, dev->internalEndBlock));
5460 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5462 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5464 if (dev->isYaffs2) {
5465 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
5470 /* Scan all the blocks to determine their state */
5471 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5472 bi = yaffs_GetBlockInfo(dev, blk);
5473 yaffs_ClearChunkBits(dev, blk);
5475 bi->softDeletions = 0;
5477 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5479 bi->blockState = state;
5480 bi->sequenceNumber = sequenceNumber;
5482 T(YAFFS_TRACE_SCAN_DEBUG,
5483 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5484 state, sequenceNumber));
5486 if (state == YAFFS_BLOCK_STATE_DEAD) {
5487 T(YAFFS_TRACE_BAD_BLOCKS,
5488 (TSTR("block %d is bad" TENDSTR), blk));
5489 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5490 T(YAFFS_TRACE_SCAN_DEBUG,
5491 (TSTR("Block empty " TENDSTR)));
5492 dev->nErasedBlocks++;
5493 dev->nFreeChunks += dev->nChunksPerBlock;
5494 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5496 /* Determine the highest sequence number */
5497 if (dev->isYaffs2 &&
5498 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
5499 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
5501 blockIndex[nBlocksToScan].seq = sequenceNumber;
5502 blockIndex[nBlocksToScan].block = blk;
5506 if (sequenceNumber >= dev->sequenceNumber) {
5507 dev->sequenceNumber = sequenceNumber;
5509 } else if (dev->isYaffs2) {
5510 /* TODO: Nasty sequence number! */
5513 ("Block scanning block %d has bad sequence number %d"
5514 TENDSTR), blk, sequenceNumber));
5521 * Dungy old bubble sort for now...
5523 if (dev->isYaffs2) {
5524 yaffs_BlockIndex temp;
5528 for (i = 0; i < nBlocksToScan; i++)
5529 for (j = i + 1; j < nBlocksToScan; j++)
5530 if (blockIndex[i].seq > blockIndex[j].seq) {
5531 temp = blockIndex[j];
5532 blockIndex[j] = blockIndex[i];
5533 blockIndex[i] = temp;
5537 /* Now scan the blocks looking at the data. */
5538 if (dev->isYaffs2) {
5540 endIterator = nBlocksToScan - 1;
5541 T(YAFFS_TRACE_SCAN_DEBUG,
5542 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
5544 startIterator = dev->internalStartBlock;
5545 endIterator = dev->internalEndBlock;
5548 /* For each block.... */
5549 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5552 if (dev->isYaffs2) {
5553 /* get the block to scan in the correct order */
5554 blk = blockIndex[blockIterator].block;
5556 blk = blockIterator;
5559 bi = yaffs_GetBlockInfo(dev, blk);
5560 state = bi->blockState;
5564 /* For each chunk in each block that needs scanning....*/
5565 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5566 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5567 /* Read the tags and decide what to do */
5568 chunk = blk * dev->nChunksPerBlock + c;
5570 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5573 /* Let's have a good look at this chunk... */
5575 if (!dev->isYaffs2 && tags.chunkDeleted) {
5581 /*T((" %d %d deleted\n",blk,c)); */
5582 } else if (!tags.chunkUsed) {
5583 /* An unassigned chunk in the block
5584 * This means that either the block is empty or
5585 * this is the one being allocated from
5589 /* We're looking at the first chunk in the block so the block is unused */
5590 state = YAFFS_BLOCK_STATE_EMPTY;
5591 dev->nErasedBlocks++;
5593 /* this is the block being allocated from */
5596 (" Allocating from %d %d" TENDSTR),
5598 state = YAFFS_BLOCK_STATE_ALLOCATING;
5599 dev->allocationBlock = blk;
5600 dev->allocationPage = c;
5601 dev->allocationBlockFinder = blk;
5602 /* Set it to here to encourage the allocator to go forth from here. */
5604 /* Yaffs2 sanity check:
5605 * This should be the one with the highest sequence number
5608 && (dev->sequenceNumber !=
5609 bi->sequenceNumber)) {
5610 T(YAFFS_TRACE_ALWAYS,
5612 ("yaffs: Allocation block %d was not highest sequence id:"
5613 " block seq = %d, dev seq = %d"
5614 TENDSTR), blk,bi->sequenceNumber,dev->sequenceNumber));
5618 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5619 } else if (tags.chunkId > 0) {
5620 /* chunkId > 0 so it is a data chunk... */
5621 unsigned int endpos;
5623 yaffs_SetChunkBit(dev, blk, c);
5626 in = yaffs_FindOrCreateObjectByNumber(dev,
5629 YAFFS_OBJECT_TYPE_FILE);
5630 /* PutChunkIntoFile checks for a clash (two data chunks with
5631 * the same chunkId).
5638 if(!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,1))
5643 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5646 in->variantType == YAFFS_OBJECT_TYPE_FILE
5647 && in->variant.fileVariant.scannedFileSize <
5649 in->variant.fileVariant.
5650 scannedFileSize = endpos;
5651 if (!dev->useHeaderFileSize) {
5652 in->variant.fileVariant.
5654 in->variant.fileVariant.
5659 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
5661 /* chunkId == 0, so it is an ObjectHeader.
5662 * Thus, we read in the object header and make the object
5664 yaffs_SetChunkBit(dev, blk, c);
5667 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5671 oh = (yaffs_ObjectHeader *) chunkData;
5673 in = yaffs_FindObjectByNumber(dev,
5675 if (in && in->variantType != oh->type) {
5676 /* This should not happen, but somehow
5677 * Wev'e ended up with an objectId that has been reused but not yet
5678 * deleted, and worse still it has changed type. Delete the old object.
5681 yaffs_DestroyObject(in);
5686 in = yaffs_FindOrCreateObjectByNumber(dev,
5694 if (in && oh->shadowsObject > 0) {
5695 yaffs_HandleShadowedObject(dev,
5701 if (in && in->valid) {
5702 /* We have already filled this one. We have a duplicate and need to resolve it. */
5704 unsigned existingSerial = in->serial;
5705 unsigned newSerial = tags.serialNumber;
5707 if (dev->isYaffs2 ||
5708 ((existingSerial + 1) & 3) ==
5710 /* Use new one - destroy the exisiting one */
5711 yaffs_DeleteChunk(dev,
5716 /* Use existing - destroy this one. */
5717 yaffs_DeleteChunk(dev, chunk, 1,
5722 if (in && !in->valid &&
5723 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5724 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5725 /* We only load some info, don't fiddle with directory structure */
5727 in->variantType = oh->type;
5729 in->yst_mode = oh->yst_mode;
5730 #ifdef CONFIG_YAFFS_WINCE
5731 in->win_atime[0] = oh->win_atime[0];
5732 in->win_ctime[0] = oh->win_ctime[0];
5733 in->win_mtime[0] = oh->win_mtime[0];
5734 in->win_atime[1] = oh->win_atime[1];
5735 in->win_ctime[1] = oh->win_ctime[1];
5736 in->win_mtime[1] = oh->win_mtime[1];
5738 in->yst_uid = oh->yst_uid;
5739 in->yst_gid = oh->yst_gid;
5740 in->yst_atime = oh->yst_atime;
5741 in->yst_mtime = oh->yst_mtime;
5742 in->yst_ctime = oh->yst_ctime;
5743 in->yst_rdev = oh->yst_rdev;
5745 in->chunkId = chunk;
5747 } else if (in && !in->valid) {
5748 /* we need to load this info */
5751 in->variantType = oh->type;
5753 in->yst_mode = oh->yst_mode;
5754 #ifdef CONFIG_YAFFS_WINCE
5755 in->win_atime[0] = oh->win_atime[0];
5756 in->win_ctime[0] = oh->win_ctime[0];
5757 in->win_mtime[0] = oh->win_mtime[0];
5758 in->win_atime[1] = oh->win_atime[1];
5759 in->win_ctime[1] = oh->win_ctime[1];
5760 in->win_mtime[1] = oh->win_mtime[1];
5762 in->yst_uid = oh->yst_uid;
5763 in->yst_gid = oh->yst_gid;
5764 in->yst_atime = oh->yst_atime;
5765 in->yst_mtime = oh->yst_mtime;
5766 in->yst_ctime = oh->yst_ctime;
5767 in->yst_rdev = oh->yst_rdev;
5769 in->chunkId = chunk;
5771 yaffs_SetObjectName(in, oh->name);
5774 /* directory stuff...
5779 yaffs_FindOrCreateObjectByNumber
5780 (dev, oh->parentObjectId,
5781 YAFFS_OBJECT_TYPE_DIRECTORY);
5782 if (parent->variantType ==
5783 YAFFS_OBJECT_TYPE_UNKNOWN) {
5784 /* Set up as a directory */
5785 parent->variantType =
5786 YAFFS_OBJECT_TYPE_DIRECTORY;
5787 INIT_LIST_HEAD(&parent->variant.
5790 } else if (parent->variantType !=
5791 YAFFS_OBJECT_TYPE_DIRECTORY)
5793 /* Hoosterman, another problem....
5794 * We're trying to use a non-directory as a directory
5797 T(YAFFS_TRACE_ERROR,
5799 ("yaffs tragedy: attempting to use non-directory as"
5800 " a directory in scan. Put in lost+found."
5802 parent = dev->lostNFoundDir;
5805 yaffs_AddObjectToDirectory(parent, in);
5807 if (0 && (parent == dev->deletedDir ||
5808 parent == dev->unlinkedDir)) {
5809 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
5810 dev->nDeletedFiles++;
5812 /* Note re hardlinks.
5813 * Since we might scan a hardlink before its equivalent object is scanned
5814 * we put them all in a list.
5815 * After scanning is complete, we should have all the objects, so we run through this
5816 * list and fix up all the chains.
5819 switch (in->variantType) {
5820 case YAFFS_OBJECT_TYPE_UNKNOWN:
5821 /* Todo got a problem */
5823 case YAFFS_OBJECT_TYPE_FILE:
5826 /* Prune back the shrunken chunks */
5827 yaffs_PruneResizedChunks
5829 /* Mark the block as having a shrinkHeader */
5830 bi->hasShrinkHeader = 1;
5833 if (dev->useHeaderFileSize)
5835 in->variant.fileVariant.
5840 case YAFFS_OBJECT_TYPE_HARDLINK:
5841 in->variant.hardLinkVariant.
5842 equivalentObjectId =
5843 oh->equivalentObjectId;
5844 in->hardLinks.next =
5845 (struct list_head *)
5849 case YAFFS_OBJECT_TYPE_DIRECTORY:
5852 case YAFFS_OBJECT_TYPE_SPECIAL:
5855 case YAFFS_OBJECT_TYPE_SYMLINK:
5856 in->variant.symLinkVariant.alias =
5857 yaffs_CloneString(oh->alias);
5858 if(!in->variant.symLinkVariant.alias)
5863 if (parent == dev->deletedDir) {
5864 yaffs_DestroyObject(in);
5865 bi->hasShrinkHeader = 1;
5871 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5872 /* If we got this far while scanning, then the block is fully allocated.*/
5873 state = YAFFS_BLOCK_STATE_FULL;
5876 bi->blockState = state;
5878 /* Now let's see if it was dirty */
5879 if (bi->pagesInUse == 0 &&
5880 !bi->hasShrinkHeader &&
5881 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5882 yaffs_BlockBecameDirty(dev, blk);
5892 /* Ok, we've done all the scanning.
5893 * Fix up the hard link chains.
5894 * We should now have scanned all the objects, now it's time to add these
5898 yaffs_HardlinkFixup(dev,hardList);
5900 /* Handle the unlinked files. Since they were left in an unlinked state we should
5904 struct list_head *i;
5905 struct list_head *n;
5908 /* Soft delete all the unlinked files */
5909 list_for_each_safe(i, n,
5910 &dev->unlinkedDir->variant.directoryVariant.
5913 l = list_entry(i, yaffs_Object, siblings);
5914 yaffs_DestroyObject(l);
5919 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5925 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5931 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5934 yaffs_ObjectHeader *oh;
5935 yaffs_Device *dev = in->myDev;
5936 yaffs_ExtendedTags tags;
5938 int alloc_failed = 0;
5944 T(YAFFS_TRACE_SCAN,(TSTR("details for object %d %s loaded" TENDSTR),
5946 in->lazyLoaded ? "not yet" : "already"));
5951 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5953 result = yaffs_ReadChunkWithTagsFromNAND(dev,in->chunkId,chunkData,&tags);
5954 oh = (yaffs_ObjectHeader *) chunkData;
5956 in->yst_mode = oh->yst_mode;
5957 #ifdef CONFIG_YAFFS_WINCE
5958 in->win_atime[0] = oh->win_atime[0];
5959 in->win_ctime[0] = oh->win_ctime[0];
5960 in->win_mtime[0] = oh->win_mtime[0];
5961 in->win_atime[1] = oh->win_atime[1];
5962 in->win_ctime[1] = oh->win_ctime[1];
5963 in->win_mtime[1] = oh->win_mtime[1];
5965 in->yst_uid = oh->yst_uid;
5966 in->yst_gid = oh->yst_gid;
5967 in->yst_atime = oh->yst_atime;
5968 in->yst_mtime = oh->yst_mtime;
5969 in->yst_ctime = oh->yst_ctime;
5970 in->yst_rdev = oh->yst_rdev;
5973 yaffs_SetObjectName(in, oh->name);
5975 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
5976 in->variant.symLinkVariant.alias =
5977 yaffs_CloneString(oh->alias);
5978 if(!in->variant.symLinkVariant.alias)
5979 alloc_failed = 1; /* Not returned to caller */
5982 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
5986 static int yaffs_ScanBackwards(yaffs_Device * dev)
5988 yaffs_ExtendedTags tags;
5993 int nBlocksToScan = 0;
5999 yaffs_BlockState state;
6000 yaffs_Object *hardList = NULL;
6001 yaffs_BlockInfo *bi;
6003 yaffs_ObjectHeader *oh;
6005 yaffs_Object *parent;
6006 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6012 int foundChunksInBlock;
6013 int equivalentObjectId;
6014 int alloc_failed = 0;
6017 yaffs_BlockIndex *blockIndex = NULL;
6018 int altBlockIndex = 0;
6020 if (!dev->isYaffs2) {
6022 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6028 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
6029 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6032 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6034 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6037 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6043 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6047 dev->blocksInCheckpoint = 0;
6049 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6051 /* Scan all the blocks to determine their state */
6052 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6053 bi = yaffs_GetBlockInfo(dev, blk);
6054 yaffs_ClearChunkBits(dev, blk);
6056 bi->softDeletions = 0;
6058 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6060 bi->blockState = state;
6061 bi->sequenceNumber = sequenceNumber;
6063 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6064 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6066 T(YAFFS_TRACE_SCAN_DEBUG,
6067 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6068 state, sequenceNumber));
6071 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
6072 dev->blocksInCheckpoint++;
6074 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6075 T(YAFFS_TRACE_BAD_BLOCKS,
6076 (TSTR("block %d is bad" TENDSTR), blk));
6077 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6078 T(YAFFS_TRACE_SCAN_DEBUG,
6079 (TSTR("Block empty " TENDSTR)));
6080 dev->nErasedBlocks++;
6081 dev->nFreeChunks += dev->nChunksPerBlock;
6082 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6084 /* Determine the highest sequence number */
6085 if (dev->isYaffs2 &&
6086 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6087 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6089 blockIndex[nBlocksToScan].seq = sequenceNumber;
6090 blockIndex[nBlocksToScan].block = blk;
6094 if (sequenceNumber >= dev->sequenceNumber) {
6095 dev->sequenceNumber = sequenceNumber;
6097 } else if (dev->isYaffs2) {
6098 /* TODO: Nasty sequence number! */
6101 ("Block scanning block %d has bad sequence number %d"
6102 TENDSTR), blk, sequenceNumber));
6109 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6115 /* Sort the blocks */
6116 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6118 /* Use qsort now. */
6119 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6123 /* Dungy old bubble sort... */
6125 yaffs_BlockIndex temp;
6129 for (i = 0; i < nBlocksToScan; i++)
6130 for (j = i + 1; j < nBlocksToScan; j++)
6131 if (blockIndex[i].seq > blockIndex[j].seq) {
6132 temp = blockIndex[j];
6133 blockIndex[j] = blockIndex[i];
6134 blockIndex[i] = temp;
6141 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6143 /* Now scan the blocks looking at the data. */
6145 endIterator = nBlocksToScan - 1;
6146 T(YAFFS_TRACE_SCAN_DEBUG,
6147 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6149 /* For each block.... backwards */
6150 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6152 /* Cooperative multitasking! This loop can run for so
6153 long that watchdog timers expire. */
6156 /* get the block to scan in the correct order */
6157 blk = blockIndex[blockIterator].block;
6159 bi = yaffs_GetBlockInfo(dev, blk);
6162 state = bi->blockState;
6166 /* For each chunk in each block that needs scanning.... */
6167 foundChunksInBlock = 0;
6168 for (c = dev->nChunksPerBlock - 1;
6169 !alloc_failed && c >= 0 &&
6170 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6171 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6172 /* Scan backwards...
6173 * Read the tags and decide what to do
6176 chunk = blk * dev->nChunksPerBlock + c;
6178 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6181 /* Let's have a good look at this chunk... */
6183 if (!tags.chunkUsed) {
6184 /* An unassigned chunk in the block.
6185 * If there are used chunks after this one, then
6186 * it is a chunk that was skipped due to failing the erased
6187 * check. Just skip it so that it can be deleted.
6188 * But, more typically, We get here when this is an unallocated
6189 * chunk and his means that either the block is empty or
6190 * this is the one being allocated from
6193 if(foundChunksInBlock)
6195 /* This is a chunk that was skipped due to failing the erased check */
6197 } else if (c == 0) {
6198 /* We're looking at the first chunk in the block so the block is unused */
6199 state = YAFFS_BLOCK_STATE_EMPTY;
6200 dev->nErasedBlocks++;
6202 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6203 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6204 if(dev->sequenceNumber == bi->sequenceNumber) {
6205 /* this is the block being allocated from */
6209 (" Allocating from %d %d"
6212 state = YAFFS_BLOCK_STATE_ALLOCATING;
6213 dev->allocationBlock = blk;
6214 dev->allocationPage = c;
6215 dev->allocationBlockFinder = blk;
6218 /* This is a partially written block that is not
6219 * the current allocation block. This block must have
6220 * had a write failure, so set up for retirement.
6223 bi->needsRetiring = 1;
6224 bi->gcPrioritise = 1;
6226 T(YAFFS_TRACE_ALWAYS,
6227 (TSTR("Partially written block %d being set for retirement" TENDSTR),
6237 } else if (tags.chunkId > 0) {
6238 /* chunkId > 0 so it is a data chunk... */
6239 unsigned int endpos;
6241 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6243 foundChunksInBlock = 1;
6246 yaffs_SetChunkBit(dev, blk, c);
6249 in = yaffs_FindOrCreateObjectByNumber(dev,
6252 YAFFS_OBJECT_TYPE_FILE);
6259 in->variantType == YAFFS_OBJECT_TYPE_FILE
6261 in->variant.fileVariant.shrinkSize) {
6262 /* This has not been invalidated by a resize */
6263 if(!yaffs_PutChunkIntoFile(in, tags.chunkId,
6268 /* File size is calculated by looking at the data chunks if we have not
6269 * seen an object header yet. Stop this practice once we find an object header.
6273 1) * dev->nDataBytesPerChunk +
6276 if (!in->valid && /* have not got an object header yet */
6277 in->variant.fileVariant.
6278 scannedFileSize < endpos) {
6279 in->variant.fileVariant.
6280 scannedFileSize = endpos;
6281 in->variant.fileVariant.
6283 in->variant.fileVariant.
6288 /* This chunk has been invalidated by a resize, so delete */
6289 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6293 /* chunkId == 0, so it is an ObjectHeader.
6294 * Thus, we read in the object header and make the object
6296 foundChunksInBlock = 1;
6298 yaffs_SetChunkBit(dev, blk, c);
6304 if (tags.extraHeaderInfoAvailable) {
6305 in = yaffs_FindOrCreateObjectByNumber
6306 (dev, tags.objectId,
6307 tags.extraObjectType);
6311 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
6314 tags.extraShadows ||
6316 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6317 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
6320 /* If we don't have valid info then we need to read the chunk
6321 * TODO In future we can probably defer reading the chunk and
6322 * living with invalid data until needed.
6325 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6330 oh = (yaffs_ObjectHeader *) chunkData;
6333 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6338 /* TODO Hoosterman we have a problem! */
6339 T(YAFFS_TRACE_ERROR,
6341 ("yaffs tragedy: Could not make object for object %d "
6342 "at chunk %d during scan"
6343 TENDSTR), tags.objectId, chunk));
6348 /* We have already filled this one.
6349 * We have a duplicate that will be discarded, but
6350 * we first have to suck out resize info if it is a file.
6353 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6355 oh-> type == YAFFS_OBJECT_TYPE_FILE)||
6356 (tags.extraHeaderInfoAvailable &&
6357 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
6360 (oh) ? oh->fileSize : tags.
6362 __u32 parentObjectId =
6364 parentObjectId : tags.
6365 extraParentObjectId;
6367 (oh) ? oh->isShrink : tags.
6368 extraIsShrinkHeader;
6370 /* If it is deleted (unlinked at start also means deleted)
6371 * we treat the file size as being zeroed at this point.
6373 if (parentObjectId ==
6374 YAFFS_OBJECTID_DELETED
6375 || parentObjectId ==
6376 YAFFS_OBJECTID_UNLINKED) {
6382 in->variant.fileVariant.
6383 shrinkSize > thisSize) {
6384 in->variant.fileVariant.
6390 bi->hasShrinkHeader = 1;
6394 /* Use existing - destroy this one. */
6395 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6400 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6402 YAFFS_OBJECTID_LOSTNFOUND)) {
6403 /* We only load some info, don't fiddle with directory structure */
6407 in->variantType = oh->type;
6409 in->yst_mode = oh->yst_mode;
6410 #ifdef CONFIG_YAFFS_WINCE
6411 in->win_atime[0] = oh->win_atime[0];
6412 in->win_ctime[0] = oh->win_ctime[0];
6413 in->win_mtime[0] = oh->win_mtime[0];
6414 in->win_atime[1] = oh->win_atime[1];
6415 in->win_ctime[1] = oh->win_ctime[1];
6416 in->win_mtime[1] = oh->win_mtime[1];
6418 in->yst_uid = oh->yst_uid;
6419 in->yst_gid = oh->yst_gid;
6420 in->yst_atime = oh->yst_atime;
6421 in->yst_mtime = oh->yst_mtime;
6422 in->yst_ctime = oh->yst_ctime;
6423 in->yst_rdev = oh->yst_rdev;
6427 in->variantType = tags.extraObjectType;
6431 in->chunkId = chunk;
6433 } else if (!in->valid) {
6434 /* we need to load this info */
6437 in->chunkId = chunk;
6440 in->variantType = oh->type;
6442 in->yst_mode = oh->yst_mode;
6443 #ifdef CONFIG_YAFFS_WINCE
6444 in->win_atime[0] = oh->win_atime[0];
6445 in->win_ctime[0] = oh->win_ctime[0];
6446 in->win_mtime[0] = oh->win_mtime[0];
6447 in->win_atime[1] = oh->win_atime[1];
6448 in->win_ctime[1] = oh->win_ctime[1];
6449 in->win_mtime[1] = oh->win_mtime[1];
6451 in->yst_uid = oh->yst_uid;
6452 in->yst_gid = oh->yst_gid;
6453 in->yst_atime = oh->yst_atime;
6454 in->yst_mtime = oh->yst_mtime;
6455 in->yst_ctime = oh->yst_ctime;
6456 in->yst_rdev = oh->yst_rdev;
6459 if (oh->shadowsObject > 0)
6460 yaffs_HandleShadowedObject(dev,
6466 yaffs_SetObjectName(in, oh->name);
6468 yaffs_FindOrCreateObjectByNumber
6469 (dev, oh->parentObjectId,
6470 YAFFS_OBJECT_TYPE_DIRECTORY);
6472 fileSize = oh->fileSize;
6473 isShrink = oh->isShrink;
6474 equivalentObjectId = oh->equivalentObjectId;
6478 in->variantType = tags.extraObjectType;
6480 yaffs_FindOrCreateObjectByNumber
6481 (dev, tags.extraParentObjectId,
6482 YAFFS_OBJECT_TYPE_DIRECTORY);
6483 fileSize = tags.extraFileLength;
6484 isShrink = tags.extraIsShrinkHeader;
6485 equivalentObjectId = tags.extraEquivalentObjectId;
6491 /* directory stuff...
6495 if (parent->variantType ==
6496 YAFFS_OBJECT_TYPE_UNKNOWN) {
6497 /* Set up as a directory */
6498 parent->variantType =
6499 YAFFS_OBJECT_TYPE_DIRECTORY;
6500 INIT_LIST_HEAD(&parent->variant.
6503 } else if (parent->variantType !=
6504 YAFFS_OBJECT_TYPE_DIRECTORY)
6506 /* Hoosterman, another problem....
6507 * We're trying to use a non-directory as a directory
6510 T(YAFFS_TRACE_ERROR,
6512 ("yaffs tragedy: attempting to use non-directory as"
6513 " a directory in scan. Put in lost+found."
6515 parent = dev->lostNFoundDir;
6518 yaffs_AddObjectToDirectory(parent, in);
6520 itsUnlinked = (parent == dev->deletedDir) ||
6521 (parent == dev->unlinkedDir);
6524 /* Mark the block as having a shrinkHeader */
6525 bi->hasShrinkHeader = 1;
6528 /* Note re hardlinks.
6529 * Since we might scan a hardlink before its equivalent object is scanned
6530 * we put them all in a list.
6531 * After scanning is complete, we should have all the objects, so we run
6532 * through this list and fix up all the chains.
6535 switch (in->variantType) {
6536 case YAFFS_OBJECT_TYPE_UNKNOWN:
6537 /* Todo got a problem */
6539 case YAFFS_OBJECT_TYPE_FILE:
6541 if (in->variant.fileVariant.
6542 scannedFileSize < fileSize) {
6543 /* This covers the case where the file size is greater
6544 * than where the data is
6545 * This will happen if the file is resized to be larger
6546 * than its current data extents.
6548 in->variant.fileVariant.fileSize = fileSize;
6549 in->variant.fileVariant.scannedFileSize =
6550 in->variant.fileVariant.fileSize;
6554 in->variant.fileVariant.shrinkSize > fileSize) {
6555 in->variant.fileVariant.shrinkSize = fileSize;
6559 case YAFFS_OBJECT_TYPE_HARDLINK:
6561 in->variant.hardLinkVariant.equivalentObjectId =
6563 in->hardLinks.next =
6564 (struct list_head *) hardList;
6568 case YAFFS_OBJECT_TYPE_DIRECTORY:
6571 case YAFFS_OBJECT_TYPE_SPECIAL:
6574 case YAFFS_OBJECT_TYPE_SYMLINK:
6576 in->variant.symLinkVariant.alias =
6577 yaffs_CloneString(oh->
6579 if(!in->variant.symLinkVariant.alias)
6589 } /* End of scanning for each chunk */
6591 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6592 /* If we got this far while scanning, then the block is fully allocated. */
6593 state = YAFFS_BLOCK_STATE_FULL;
6596 bi->blockState = state;
6598 /* Now let's see if it was dirty */
6599 if (bi->pagesInUse == 0 &&
6600 !bi->hasShrinkHeader &&
6601 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6602 yaffs_BlockBecameDirty(dev, blk);
6608 YFREE_ALT(blockIndex);
6612 /* Ok, we've done all the scanning.
6613 * Fix up the hard link chains.
6614 * We should now have scanned all the objects, now it's time to add these
6617 yaffs_HardlinkFixup(dev,hardList);
6621 * Sort out state of unlinked and deleted objects.
6624 struct list_head *i;
6625 struct list_head *n;
6629 /* Soft delete all the unlinked files */
6630 list_for_each_safe(i, n,
6631 &dev->unlinkedDir->variant.directoryVariant.
6634 l = list_entry(i, yaffs_Object, siblings);
6635 yaffs_DestroyObject(l);
6639 /* Soft delete all the deletedDir files */
6640 list_for_each_safe(i, n,
6641 &dev->deletedDir->variant.directoryVariant.
6644 l = list_entry(i, yaffs_Object, siblings);
6645 yaffs_DestroyObject(l);
6651 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6657 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6662 /*------------------------------ Directory Functions ----------------------------- */
6664 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
6666 yaffs_Device *dev = obj->myDev;
6668 if(dev && dev->removeObjectCallback)
6669 dev->removeObjectCallback(obj);
6671 list_del_init(&obj->siblings);
6676 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
6681 T(YAFFS_TRACE_ALWAYS,
6683 ("tragedy: Trying to add an object to a null pointer directory"
6687 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6688 T(YAFFS_TRACE_ALWAYS,
6690 ("tragedy: Trying to add an object to a non-directory"
6695 if (obj->siblings.prev == NULL) {
6696 /* Not initialised */
6697 INIT_LIST_HEAD(&obj->siblings);
6699 } else if (!list_empty(&obj->siblings)) {
6700 /* If it is holed up somewhere else, un hook it */
6701 yaffs_RemoveObjectFromDirectory(obj);
6704 list_add(&obj->siblings, &directory->variant.directoryVariant.children);
6705 obj->parent = directory;
6707 if (directory == obj->myDev->unlinkedDir
6708 || directory == obj->myDev->deletedDir) {
6710 obj->myDev->nUnlinkedFiles++;
6711 obj->renameAllowed = 0;
6715 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
6720 struct list_head *i;
6721 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
6730 T(YAFFS_TRACE_ALWAYS,
6732 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6736 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6737 T(YAFFS_TRACE_ALWAYS,
6739 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6743 sum = yaffs_CalcNameSum(name);
6745 list_for_each(i, &directory->variant.directoryVariant.children) {
6747 l = list_entry(i, yaffs_Object, siblings);
6749 yaffs_CheckObjectDetailsLoaded(l);
6751 /* Special case for lost-n-found */
6752 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6753 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
6756 } else if (yaffs_SumCompare(l->sum, sum) || l->chunkId <= 0)
6758 /* LostnFound cunk called Objxxx
6761 yaffs_GetObjectName(l, buffer,
6762 YAFFS_MAX_NAME_LENGTH);
6763 if (yaffs_strncmp(name, buffer,YAFFS_MAX_NAME_LENGTH) == 0) {
6776 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
6777 int (*fn) (yaffs_Object *))
6779 struct list_head *i;
6783 T(YAFFS_TRACE_ALWAYS,
6785 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6789 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6790 T(YAFFS_TRACE_ALWAYS,
6792 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6796 list_for_each(i, &theDir->variant.directoryVariant.children) {
6798 l = list_entry(i, yaffs_Object, siblings);
6810 /* GetEquivalentObject dereferences any hard links to get to the
6814 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
6816 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
6817 /* We want the object id of the equivalent object, not this one */
6818 obj = obj->variant.hardLinkVariant.equivalentObject;
6819 yaffs_CheckObjectDetailsLoaded(obj);
6825 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
6827 memset(name, 0, buffSize * sizeof(YCHAR));
6829 yaffs_CheckObjectDetailsLoaded(obj);
6831 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6832 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
6833 } else if (obj->chunkId <= 0) {
6835 /* make up a name */
6836 yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX,
6838 yaffs_strncpy(name, locName, buffSize - 1);
6841 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
6842 else if (obj->shortName[0]) {
6843 yaffs_strcpy(name, obj->shortName);
6848 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
6850 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
6852 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
6854 if (obj->chunkId >= 0) {
6855 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
6856 obj->chunkId, buffer,
6859 yaffs_strncpy(name, oh->name, buffSize - 1);
6861 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
6864 return yaffs_strlen(name);
6867 int yaffs_GetObjectFileLength(yaffs_Object * obj)
6870 /* Dereference any hard linking */
6871 obj = yaffs_GetEquivalentObject(obj);
6873 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
6874 return obj->variant.fileVariant.fileSize;
6876 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6877 return yaffs_strlen(obj->variant.symLinkVariant.alias);
6879 /* Only a directory should drop through to here */
6880 return obj->myDev->nDataBytesPerChunk;
6884 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
6887 struct list_head *i;
6889 if (!obj->unlinked) {
6890 count++; /* the object itself */
6892 list_for_each(i, &obj->hardLinks) {
6893 count++; /* add the hard links; */
6899 int yaffs_GetObjectInode(yaffs_Object * obj)
6901 obj = yaffs_GetEquivalentObject(obj);
6903 return obj->objectId;
6906 unsigned yaffs_GetObjectType(yaffs_Object * obj)
6908 obj = yaffs_GetEquivalentObject(obj);
6910 switch (obj->variantType) {
6911 case YAFFS_OBJECT_TYPE_FILE:
6914 case YAFFS_OBJECT_TYPE_DIRECTORY:
6917 case YAFFS_OBJECT_TYPE_SYMLINK:
6920 case YAFFS_OBJECT_TYPE_HARDLINK:
6923 case YAFFS_OBJECT_TYPE_SPECIAL:
6924 if (S_ISFIFO(obj->yst_mode))
6926 if (S_ISCHR(obj->yst_mode))
6928 if (S_ISBLK(obj->yst_mode))
6930 if (S_ISSOCK(obj->yst_mode))
6938 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
6940 obj = yaffs_GetEquivalentObject(obj);
6941 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6942 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
6944 return yaffs_CloneString(_Y(""));
6948 #ifndef CONFIG_YAFFS_WINCE
6950 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
6952 unsigned int valid = attr->ia_valid;
6954 if (valid & ATTR_MODE)
6955 obj->yst_mode = attr->ia_mode;
6956 if (valid & ATTR_UID)
6957 obj->yst_uid = attr->ia_uid;
6958 if (valid & ATTR_GID)
6959 obj->yst_gid = attr->ia_gid;
6961 if (valid & ATTR_ATIME)
6962 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
6963 if (valid & ATTR_CTIME)
6964 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
6965 if (valid & ATTR_MTIME)
6966 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
6968 if (valid & ATTR_SIZE)
6969 yaffs_ResizeFile(obj, attr->ia_size);
6971 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6976 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
6978 unsigned int valid = 0;
6980 attr->ia_mode = obj->yst_mode;
6982 attr->ia_uid = obj->yst_uid;
6984 attr->ia_gid = obj->yst_gid;
6987 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
6988 valid |= ATTR_ATIME;
6989 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
6990 valid |= ATTR_CTIME;
6991 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
6992 valid |= ATTR_MTIME;
6994 attr->ia_size = yaffs_GetFileSize(obj);
6997 attr->ia_valid = valid;
7006 int yaffs_DumpObject(yaffs_Object * obj)
7010 yaffs_GetObjectName(obj, name, 256);
7012 T(YAFFS_TRACE_ALWAYS,
7014 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7015 " chunk %d type %d size %d\n"
7016 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7017 obj->dirty, obj->valid, obj->serial, obj->sum, obj->chunkId,
7018 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7024 /*---------------------------- Initialisation code -------------------------------------- */
7026 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
7029 /* Common functions, gotta have */
7030 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
7033 #ifdef CONFIG_YAFFS_YAFFS2
7035 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7036 if (dev->writeChunkWithTagsToNAND &&
7037 dev->readChunkWithTagsFromNAND &&
7038 !dev->writeChunkToNAND &&
7039 !dev->readChunkFromNAND &&
7040 dev->markNANDBlockBad && dev->queryNANDBlock)
7044 /* Can use the "spare" style interface for yaffs1 */
7045 if (!dev->isYaffs2 &&
7046 !dev->writeChunkWithTagsToNAND &&
7047 !dev->readChunkWithTagsFromNAND &&
7048 dev->writeChunkToNAND &&
7049 dev->readChunkFromNAND &&
7050 !dev->markNANDBlockBad && !dev->queryNANDBlock)
7057 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7059 /* Initialise the unlinked, deleted, root and lost and found directories */
7061 dev->lostNFoundDir = dev->rootDir = NULL;
7062 dev->unlinkedDir = dev->deletedDir = NULL;
7065 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7068 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7071 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7072 YAFFS_ROOT_MODE | S_IFDIR);
7073 dev->lostNFoundDir =
7074 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7075 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7077 if(dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir){
7078 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7085 int yaffs_GutsInitialise(yaffs_Device * dev)
7087 int init_failed = 0;
7091 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7093 /* Check stuff that must be set */
7096 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7100 dev->internalStartBlock = dev->startBlock;
7101 dev->internalEndBlock = dev->endBlock;
7102 dev->blockOffset = 0;
7103 dev->chunkOffset = 0;
7104 dev->nFreeChunks = 0;
7106 if (dev->startBlock == 0) {
7107 dev->internalStartBlock = dev->startBlock + 1;
7108 dev->internalEndBlock = dev->endBlock + 1;
7109 dev->blockOffset = 1;
7110 dev->chunkOffset = dev->nChunksPerBlock;
7113 /* Check geometry parameters. */
7115 if ((dev->isYaffs2 && dev->nDataBytesPerChunk < 1024) ||
7116 (!dev->isYaffs2 && dev->nDataBytesPerChunk != 512) ||
7117 dev->nChunksPerBlock < 2 ||
7118 dev->nReservedBlocks < 2 ||
7119 dev->internalStartBlock <= 0 ||
7120 dev->internalEndBlock <= 0 ||
7121 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
7123 T(YAFFS_TRACE_ALWAYS,
7125 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s "
7126 TENDSTR), dev->nDataBytesPerChunk, dev->isYaffs2 ? "2" : ""));
7130 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7131 T(YAFFS_TRACE_ALWAYS,
7132 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7136 /* Got the right mix of functions? */
7137 if (!yaffs_CheckDevFunctions(dev)) {
7138 /* Function missing */
7139 T(YAFFS_TRACE_ALWAYS,
7141 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7146 /* This is really a compilation check. */
7147 if (!yaffs_CheckStructures()) {
7148 T(YAFFS_TRACE_ALWAYS,
7149 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7153 if (dev->isMounted) {
7154 T(YAFFS_TRACE_ALWAYS,
7155 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7159 /* Finished with most checks. One or two more checks happen later on too. */
7165 /* OK now calculate a few things for the device */
7168 * Calculate all the chunk size manipulation numbers:
7170 /* Start off assuming it is a power of 2 */
7171 dev->chunkShift = ShiftDiv(dev->nDataBytesPerChunk);
7172 dev->chunkMask = (1<<dev->chunkShift) - 1;
7174 if(dev->nDataBytesPerChunk == (dev->chunkMask + 1)){
7175 /* Yes it is a power of 2, disable crumbs */
7177 dev->crumbShift = 0;
7178 dev->crumbsPerChunk = 0;
7180 /* Not a power of 2, use crumbs instead */
7181 dev->crumbShift = ShiftDiv(sizeof(yaffs_PackedTags2TagsPart));
7182 dev->crumbMask = (1<<dev->crumbShift)-1;
7183 dev->crumbsPerChunk = dev->nDataBytesPerChunk/(1 << dev->crumbShift);
7184 dev->chunkShift = 0;
7190 * Calculate chunkGroupBits.
7191 * We need to find the next power of 2 > than internalEndBlock
7194 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7198 /* Set up tnode width if wide tnodes are enabled. */
7199 if(!dev->wideTnodesDisabled){
7200 /* bits must be even so that we end up with 32-bit words */
7204 dev->tnodeWidth = 16;
7206 dev->tnodeWidth = bits;
7209 dev->tnodeWidth = 16;
7211 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7213 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7214 * so if the bitwidth of the
7215 * chunk range we're using is greater than 16 we need
7216 * to figure out chunk shift and chunkGroupSize
7219 if (bits <= dev->tnodeWidth)
7220 dev->chunkGroupBits = 0;
7222 dev->chunkGroupBits = bits - dev->tnodeWidth;
7225 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7227 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7228 /* We have a problem because the soft delete won't work if
7229 * the chunk group size > chunks per block.
7230 * This can be remedied by using larger "virtual blocks".
7232 T(YAFFS_TRACE_ALWAYS,
7233 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7238 /* OK, we've finished verifying the device, lets continue with initialisation */
7240 /* More device initialisation */
7241 dev->garbageCollections = 0;
7242 dev->passiveGarbageCollections = 0;
7243 dev->currentDirtyChecker = 0;
7244 dev->bufferedBlock = -1;
7245 dev->doingBufferedBlockRewrite = 0;
7246 dev->nDeletedFiles = 0;
7247 dev->nBackgroundDeletions = 0;
7248 dev->nUnlinkedFiles = 0;
7250 dev->eccUnfixed = 0;
7251 dev->tagsEccFixed = 0;
7252 dev->tagsEccUnfixed = 0;
7253 dev->nErasureFailures = 0;
7254 dev->nErasedBlocks = 0;
7256 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7258 /* Initialise temporary buffers and caches. */
7259 if(!yaffs_InitialiseTempBuffers(dev))
7262 dev->srCache = NULL;
7263 dev->gcCleanupList = NULL;
7267 dev->nShortOpCaches > 0) {
7270 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7272 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
7273 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7276 buf = dev->srCache = YMALLOC(srCacheBytes);
7279 memset(dev->srCache,0,srCacheBytes);
7281 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7282 dev->srCache[i].object = NULL;
7283 dev->srCache[i].lastUse = 0;
7284 dev->srCache[i].dirty = 0;
7285 dev->srCache[i].data = buf = YMALLOC_DMA(dev->nDataBytesPerChunk);
7296 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7297 if(!dev->gcCleanupList)
7301 if (dev->isYaffs2) {
7302 dev->useHeaderFileSize = 1;
7304 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7307 yaffs_InitialiseTnodes(dev);
7308 yaffs_InitialiseObjects(dev);
7310 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7315 /* Now scan the flash. */
7316 if (dev->isYaffs2) {
7317 if(yaffs_CheckpointRestore(dev)) {
7318 T(YAFFS_TRACE_ALWAYS,
7319 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7322 /* Clean up the mess caused by an aborted checkpoint load
7323 * and scan backwards.
7325 yaffs_DeinitialiseBlocks(dev);
7326 yaffs_DeinitialiseTnodes(dev);
7327 yaffs_DeinitialiseObjects(dev);
7330 dev->nErasedBlocks = 0;
7331 dev->nFreeChunks = 0;
7332 dev->allocationBlock = -1;
7333 dev->allocationPage = -1;
7334 dev->nDeletedFiles = 0;
7335 dev->nUnlinkedFiles = 0;
7336 dev->nBackgroundDeletions = 0;
7337 dev->oldestDirtySequence = 0;
7339 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7342 yaffs_InitialiseTnodes(dev);
7343 yaffs_InitialiseObjects(dev);
7345 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7348 if(!init_failed && !yaffs_ScanBackwards(dev))
7352 if(!yaffs_Scan(dev))
7357 /* Clean up the mess */
7358 T(YAFFS_TRACE_TRACING,
7359 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7361 yaffs_Deinitialise(dev);
7365 /* Zero out stats */
7366 dev->nPageReads = 0;
7367 dev->nPageWrites = 0;
7368 dev->nBlockErasures = 0;
7370 dev->nRetriedWrites = 0;
7372 dev->nRetiredBlocks = 0;
7374 yaffs_VerifyFreeChunks(dev);
7375 yaffs_VerifyBlocks(dev);
7378 T(YAFFS_TRACE_TRACING,
7379 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7384 void yaffs_Deinitialise(yaffs_Device * dev)
7386 if (dev->isMounted) {
7389 yaffs_DeinitialiseBlocks(dev);
7390 yaffs_DeinitialiseTnodes(dev);
7391 yaffs_DeinitialiseObjects(dev);
7392 if (dev->nShortOpCaches > 0 &&
7395 for (i = 0; i < dev->nShortOpCaches; i++) {
7396 if(dev->srCache[i].data)
7397 YFREE(dev->srCache[i].data);
7398 dev->srCache[i].data = NULL;
7401 YFREE(dev->srCache);
7402 dev->srCache = NULL;
7405 YFREE(dev->gcCleanupList);
7407 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
7408 YFREE(dev->tempBuffer[i].buffer);
7416 static int yaffs_CountFreeChunks(yaffs_Device * dev)
7421 yaffs_BlockInfo *blk;
7423 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7425 blk = yaffs_GetBlockInfo(dev, b);
7427 switch (blk->blockState) {
7428 case YAFFS_BLOCK_STATE_EMPTY:
7429 case YAFFS_BLOCK_STATE_ALLOCATING:
7430 case YAFFS_BLOCK_STATE_COLLECTING:
7431 case YAFFS_BLOCK_STATE_FULL:
7433 (dev->nChunksPerBlock - blk->pagesInUse +
7434 blk->softDeletions);
7445 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
7447 /* This is what we report to the outside world */
7450 int nDirtyCacheChunks;
7451 int blocksForCheckpoint;
7454 nFree = dev->nFreeChunks;
7456 nFree = yaffs_CountFreeChunks(dev);
7459 nFree += dev->nDeletedFiles;
7461 /* Now count the number of dirty chunks in the cache and subtract those */
7465 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7466 if (dev->srCache[i].dirty)
7467 nDirtyCacheChunks++;
7471 nFree -= nDirtyCacheChunks;
7473 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7475 /* Now we figure out how much to reserve for the checkpoint and report that... */
7476 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7477 if(blocksForCheckpoint < 0)
7478 blocksForCheckpoint = 0;
7480 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7489 static int yaffs_freeVerificationFailures;
7491 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
7496 if(yaffs_SkipVerification(dev))
7499 counted = yaffs_CountFreeChunks(dev);
7501 difference = dev->nFreeChunks - counted;
7504 T(YAFFS_TRACE_ALWAYS,
7505 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7506 dev->nFreeChunks, counted, difference));
7507 yaffs_freeVerificationFailures++;
7511 /*---------------------------------------- YAFFS test code ----------------------*/
7513 #define yaffs_CheckStruct(structure,syze, name) \
7514 if(sizeof(structure) != syze) \
7516 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
7517 name,syze,sizeof(structure))); \
7518 return YAFFS_FAIL; \
7521 static int yaffs_CheckStructures(void)
7523 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags") */
7524 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion") */
7525 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare") */
7526 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7527 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode")
7529 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader")