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.58 2008-07-03 20:06:05 charles Exp $";
19 #include "yaffsinterface.h"
20 #include "yaffs_guts.h"
21 #include "yaffs_tagsvalidity.h"
22 #include "yaffs_getblockinfo.h"
24 #include "yaffs_tagscompat.h"
25 #ifndef CONFIG_YAFFS_USE_OWN_SORT
26 #include "yaffs_qsort.h"
28 #include "yaffs_nand.h"
30 #include "yaffs_checkptrw.h"
32 #include "yaffs_nand.h"
33 #include "yaffs_packedtags2.h"
36 #ifdef CONFIG_YAFFS_WINCE
37 void yfsd_LockYAFFS(BOOL fsLockOnly);
38 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
41 #define YAFFS_PASSIVE_GC_CHUNKS 2
43 #include "yaffs_ecc.h"
46 /* Robustification (if it ever comes about...) */
47 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
48 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk);
49 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
51 const yaffs_ExtendedTags * tags);
52 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
53 const yaffs_ExtendedTags * tags);
55 /* Other local prototypes */
56 static int yaffs_UnlinkObject( yaffs_Object *obj);
57 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
59 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
61 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
63 yaffs_ExtendedTags * tags,
65 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
66 int chunkInNAND, int inScan);
68 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
69 yaffs_ObjectType type);
70 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
72 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
73 int force, int isShrink, int shadows);
74 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
75 static int yaffs_CheckStructures(void);
76 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
77 int chunkOffset, int *limit);
78 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
80 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
83 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
86 static int yaffs_UnlinkWorker(yaffs_Object * obj);
87 static void yaffs_DestroyObject(yaffs_Object * obj);
89 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
92 loff_t yaffs_GetFileSize(yaffs_Object * obj);
94 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr);
96 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
98 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
100 #ifdef YAFFS_PARANOID
101 static int yaffs_CheckFileSanity(yaffs_Object * in);
103 #define yaffs_CheckFileSanity(in)
106 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
107 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
109 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
111 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
112 yaffs_ExtendedTags * tags);
114 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos);
115 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
116 yaffs_FileStructure * fStruct,
120 /* Function to calculate chunk and offset */
122 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut, __u32 *offsetOut)
127 chunk = (__u32)(addr >> dev->chunkShift);
129 if(dev->chunkDiv == 1)
131 /* easy power of 2 case */
132 offset = (__u32)(addr & dev->chunkMask);
136 /* Non power-of-2 case */
140 chunk /= dev->chunkDiv;
142 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
143 offset = (__u32)(addr - chunkBase);
150 /* Function to return the number of shifts for a power of 2 greater than or equal
151 * to the given number
152 * Note we don't try to cater for all possible numbers and this does not have to
153 * be hellishly efficient.
156 static __u32 ShiftsGE(__u32 x)
161 nShifts = extraBits = 0;
164 if(x & 1) extraBits++;
175 /* Function to return the number of shifts to get a 1 in bit 0
178 static __u32 Shifts(__u32 x)
197 * Temporary buffer manipulations.
200 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
203 __u8 *buf = (__u8 *)1;
205 memset(dev->tempBuffer,0,sizeof(dev->tempBuffer));
207 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
208 dev->tempBuffer[i].line = 0; /* not in use */
209 dev->tempBuffer[i].buffer = buf =
210 YMALLOC_DMA(dev->totalBytesPerChunk);
213 return buf ? YAFFS_OK : YAFFS_FAIL;
217 __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
222 if(dev->tempInUse > dev->maxTemp)
223 dev->maxTemp = dev->tempInUse;
225 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
226 if (dev->tempBuffer[i].line == 0) {
227 dev->tempBuffer[i].line = lineNo;
228 if ((i + 1) > dev->maxTemp) {
229 dev->maxTemp = i + 1;
230 for (j = 0; j <= i; j++)
231 dev->tempBuffer[j].maxLine =
232 dev->tempBuffer[j].line;
235 return dev->tempBuffer[i].buffer;
239 T(YAFFS_TRACE_BUFFERS,
240 (TSTR("Out of temp buffers at line %d, other held by lines:"),
242 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
243 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
245 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
248 * If we got here then we have to allocate an unmanaged one
252 dev->unmanagedTempAllocations++;
253 return YMALLOC(dev->nDataBytesPerChunk);
257 void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
264 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
265 if (dev->tempBuffer[i].buffer == buffer) {
266 dev->tempBuffer[i].line = 0;
272 /* assume it is an unmanaged one. */
273 T(YAFFS_TRACE_BUFFERS,
274 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
277 dev->unmanagedTempDeallocations++;
283 * Determine if we have a managed buffer.
285 int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
288 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
289 if (dev->tempBuffer[i].buffer == buffer)
294 for (i = 0; i < dev->nShortOpCaches; i++) {
295 if( dev->srCache[i].data == buffer )
300 if (buffer == dev->checkpointBuffer)
303 T(YAFFS_TRACE_ALWAYS,
304 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
311 * Chunk bitmap manipulations
314 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
316 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
318 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
322 return dev->chunkBits +
323 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
326 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
328 if(blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
329 chunk < 0 || chunk >= dev->nChunksPerBlock) {
331 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),blk,chunk));
336 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
338 __u8 *blkBits = yaffs_BlockBits(dev, blk);
340 memset(blkBits, 0, dev->chunkBitmapStride);
343 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
345 __u8 *blkBits = yaffs_BlockBits(dev, blk);
347 yaffs_VerifyChunkBitId(dev,blk,chunk);
349 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
352 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
354 __u8 *blkBits = yaffs_BlockBits(dev, blk);
356 yaffs_VerifyChunkBitId(dev,blk,chunk);
358 blkBits[chunk / 8] |= (1 << (chunk & 7));
361 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
363 __u8 *blkBits = yaffs_BlockBits(dev, blk);
364 yaffs_VerifyChunkBitId(dev,blk,chunk);
366 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
369 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
371 __u8 *blkBits = yaffs_BlockBits(dev, blk);
373 for (i = 0; i < dev->chunkBitmapStride; i++) {
381 static int yaffs_CountChunkBits(yaffs_Device * dev, int blk)
383 __u8 *blkBits = yaffs_BlockBits(dev, blk);
386 for (i = 0; i < dev->chunkBitmapStride; i++) {
403 static int yaffs_SkipVerification(yaffs_Device *dev)
405 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
409 static int yaffs_SkipFullVerification(yaffs_Device *dev)
411 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
416 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
418 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
421 static const char * blockStateName[] = {
434 static void yaffs_VerifyBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
439 if(yaffs_SkipVerification(dev))
442 /* Report illegal runtime states */
443 if(bi->blockState <0 || bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
444 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has undefined state %d"TENDSTR),n,bi->blockState));
446 switch(bi->blockState){
447 case YAFFS_BLOCK_STATE_UNKNOWN:
448 case YAFFS_BLOCK_STATE_SCANNING:
449 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
450 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has bad run-state %s"TENDSTR),
451 n,blockStateName[bi->blockState]));
454 /* Check pages in use and soft deletions are legal */
456 actuallyUsed = bi->pagesInUse - bi->softDeletions;
458 if(bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
459 bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
460 actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock)
461 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
462 n,bi->pagesInUse,bi->softDeletions));
465 /* Check chunk bitmap legal */
466 inUse = yaffs_CountChunkBits(dev,n);
467 if(inUse != bi->pagesInUse)
468 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
469 n,bi->pagesInUse,inUse));
471 /* Check that the sequence number is valid.
472 * Ten million is legal, but is very unlikely
475 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
476 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000 ))
477 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has suspect sequence number of %d"TENDSTR),
478 n,bi->sequenceNumber));
482 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
484 yaffs_VerifyBlock(dev,bi,n);
486 /* After collection the block should be in the erased state */
487 /* TODO: This will need to change if we do partial gc */
489 if(bi->blockState != YAFFS_BLOCK_STATE_EMPTY){
490 T(YAFFS_TRACE_ERROR,(TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
495 static void yaffs_VerifyBlocks(yaffs_Device *dev)
498 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
499 int nIllegalBlockStates = 0;
502 if(yaffs_SkipVerification(dev))
505 memset(nBlocksPerState,0,sizeof(nBlocksPerState));
508 for(i = dev->internalStartBlock; i <= dev->internalEndBlock; i++){
509 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
510 yaffs_VerifyBlock(dev,bi,i);
512 if(bi->blockState >=0 && bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
513 nBlocksPerState[bi->blockState]++;
515 nIllegalBlockStates++;
519 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
520 T(YAFFS_TRACE_VERIFY,(TSTR("Block summary"TENDSTR)));
522 T(YAFFS_TRACE_VERIFY,(TSTR("%d blocks have illegal states"TENDSTR),nIllegalBlockStates));
523 if(nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
524 T(YAFFS_TRACE_VERIFY,(TSTR("Too many allocating blocks"TENDSTR)));
526 for(i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
527 T(YAFFS_TRACE_VERIFY,
528 (TSTR("%s %d blocks"TENDSTR),
529 blockStateName[i],nBlocksPerState[i]));
531 if(dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
532 T(YAFFS_TRACE_VERIFY,
533 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
534 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
536 if(dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
537 T(YAFFS_TRACE_VERIFY,
538 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
539 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
541 if(nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
542 T(YAFFS_TRACE_VERIFY,
543 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
544 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
546 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
551 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
552 * case those tests will not be performed.
554 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
556 if(yaffs_SkipVerification(obj->myDev))
559 if(!(tags && obj && oh)){
560 T(YAFFS_TRACE_VERIFY,
561 (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR),
562 (__u32)tags,(__u32)obj,(__u32)oh));
566 if(oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
567 oh->type > YAFFS_OBJECT_TYPE_MAX)
568 T(YAFFS_TRACE_VERIFY,
569 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
570 tags->objectId, oh->type));
572 if(tags->objectId != obj->objectId)
573 T(YAFFS_TRACE_VERIFY,
574 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
575 tags->objectId, obj->objectId));
579 * Check that the object's parent ids match if parentCheck requested.
581 * Tests do not apply to the root object.
584 if(parentCheck && tags->objectId > 1 && !obj->parent)
585 T(YAFFS_TRACE_VERIFY,
586 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
587 tags->objectId, oh->parentObjectId));
590 if(parentCheck && obj->parent &&
591 oh->parentObjectId != obj->parent->objectId &&
592 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
593 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
594 T(YAFFS_TRACE_VERIFY,
595 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
596 tags->objectId, oh->parentObjectId, obj->parent->objectId));
599 if(tags->objectId > 1 && oh->name[0] == 0) /* Null name */
600 T(YAFFS_TRACE_VERIFY,
601 (TSTR("Obj %d header name is NULL"TENDSTR),
604 if(tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
605 T(YAFFS_TRACE_VERIFY,
606 (TSTR("Obj %d header name is 0xFF"TENDSTR),
612 static int yaffs_VerifyTnodeWorker(yaffs_Object * obj, yaffs_Tnode * tn,
613 __u32 level, int chunkOffset)
616 yaffs_Device *dev = obj->myDev;
622 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
623 if (tn->internal[i]) {
624 ok = yaffs_VerifyTnodeWorker(obj,
627 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
630 } else if (level == 0) {
632 yaffs_ExtendedTags tags;
633 __u32 objectId = obj->objectId;
635 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
637 for(i = 0; i < YAFFS_NTNODES_LEVEL0; i++){
638 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
641 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
642 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
643 if(tags.objectId != objectId || tags.chunkId != chunkOffset){
644 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
645 objectId, chunkOffset, theChunk,
646 tags.objectId, tags.chunkId));
659 static void yaffs_VerifyFile(yaffs_Object *obj)
661 int requiredTallness;
667 yaffs_ExtendedTags tags;
671 if(obj && yaffs_SkipVerification(obj->myDev))
675 objectId = obj->objectId;
677 /* Check file size is consistent with tnode depth */
678 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
679 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
680 requiredTallness = 0;
682 x >>= YAFFS_TNODES_INTERNAL_BITS;
686 actualTallness = obj->variant.fileVariant.topLevel;
688 if(requiredTallness > actualTallness )
689 T(YAFFS_TRACE_VERIFY,
690 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
691 obj->objectId,actualTallness, requiredTallness));
694 /* Check that the chunks in the tnode tree are all correct.
695 * We do this by scanning through the tnode tree and
696 * checking the tags for every chunk match.
699 if(yaffs_SkipNANDVerification(dev))
702 for(i = 1; i <= lastChunk; i++){
703 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant,i);
706 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
708 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
709 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
710 if(tags.objectId != objectId || tags.chunkId != i){
711 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
712 objectId, i, theChunk,
713 tags.objectId, tags.chunkId));
722 static void yaffs_VerifyDirectory(yaffs_Object *obj)
724 if(obj && yaffs_SkipVerification(obj->myDev))
729 static void yaffs_VerifyHardLink(yaffs_Object *obj)
731 if(obj && yaffs_SkipVerification(obj->myDev))
734 /* Verify sane equivalent object */
737 static void yaffs_VerifySymlink(yaffs_Object *obj)
739 if(obj && yaffs_SkipVerification(obj->myDev))
742 /* Verify symlink string */
745 static void yaffs_VerifySpecial(yaffs_Object *obj)
747 if(obj && yaffs_SkipVerification(obj->myDev))
751 static void yaffs_VerifyObject(yaffs_Object *obj)
766 if(yaffs_SkipVerification(dev))
769 /* Check sane object header chunk */
771 chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
772 chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
774 chunkIdOk = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
775 chunkIsLive = chunkIdOk &&
776 yaffs_CheckChunkBit(dev,
777 obj->hdrChunk / dev->nChunksPerBlock,
778 obj->hdrChunk % dev->nChunksPerBlock);
780 (!chunkIdOk || !chunkIsLive)) {
781 T(YAFFS_TRACE_VERIFY,
782 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
783 obj->objectId,obj->hdrChunk,
784 chunkIdOk ? "" : ",out of range",
785 chunkIsLive || !chunkIdOk ? "" : ",marked as deleted"));
788 if(chunkIdOk && chunkIsLive &&!yaffs_SkipNANDVerification(dev)) {
789 yaffs_ExtendedTags tags;
790 yaffs_ObjectHeader *oh;
791 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
793 oh = (yaffs_ObjectHeader *)buffer;
795 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk,buffer, &tags);
797 yaffs_VerifyObjectHeader(obj,oh,&tags,1);
799 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
802 /* Verify it has a parent */
803 if(obj && !obj->fake &&
804 (!obj->parent || obj->parent->myDev != dev)){
805 T(YAFFS_TRACE_VERIFY,
806 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
807 obj->objectId,obj->parent));
810 /* Verify parent is a directory */
811 if(obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
812 T(YAFFS_TRACE_VERIFY,
813 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
814 obj->objectId,obj->parent->variantType));
817 switch(obj->variantType){
818 case YAFFS_OBJECT_TYPE_FILE:
819 yaffs_VerifyFile(obj);
821 case YAFFS_OBJECT_TYPE_SYMLINK:
822 yaffs_VerifySymlink(obj);
824 case YAFFS_OBJECT_TYPE_DIRECTORY:
825 yaffs_VerifyDirectory(obj);
827 case YAFFS_OBJECT_TYPE_HARDLINK:
828 yaffs_VerifyHardLink(obj);
830 case YAFFS_OBJECT_TYPE_SPECIAL:
831 yaffs_VerifySpecial(obj);
833 case YAFFS_OBJECT_TYPE_UNKNOWN:
835 T(YAFFS_TRACE_VERIFY,
836 (TSTR("Obj %d has illegaltype %d"TENDSTR),
837 obj->objectId,obj->variantType));
844 static void yaffs_VerifyObjects(yaffs_Device *dev)
848 struct ylist_head *lh;
850 if(yaffs_SkipVerification(dev))
853 /* Iterate through the objects in each hash entry */
855 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++){
856 ylist_for_each(lh, &dev->objectBucket[i].list) {
858 obj = ylist_entry(lh, yaffs_Object, hashLink);
859 yaffs_VerifyObject(obj);
868 * Simple hash function. Needs to have a reasonable spread
871 static Y_INLINE int yaffs_HashFunction(int n)
874 return (n % YAFFS_NOBJECT_BUCKETS);
878 * Access functions to useful fake objects.
879 * Note that root might have a presence in NAND if permissions are set.
882 yaffs_Object *yaffs_Root(yaffs_Device * dev)
887 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
889 return dev->lostNFoundDir;
894 * Erased NAND checking functions
897 int yaffs_CheckFF(__u8 * buffer, int nBytes)
899 /* Horrible, slow implementation */
908 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
912 int retval = YAFFS_OK;
913 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
914 yaffs_ExtendedTags tags;
917 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
919 if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
923 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
924 T(YAFFS_TRACE_NANDACCESS,
925 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
929 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
935 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
937 yaffs_ExtendedTags * tags,
944 yaffs_InvalidateCheckpoint(dev);
947 yaffs_BlockInfo *bi = 0;
950 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
956 /* First check this chunk is erased, if it needs
957 * checking. The checking policy (unless forced
958 * always on) is as follows:
960 * Check the first page we try to write in a block.
961 * If the check passes then we don't need to check any
962 * more. If the check fails, we check again...
963 * If the block has been erased, we don't need to check.
965 * However, if the block has been prioritised for gc,
966 * then we think there might be something odd about
967 * this block and stop using it.
969 * Rationale: We should only ever see chunks that have
970 * not been erased if there was a partially written
971 * chunk due to power loss. This checking policy should
972 * catch that case with very few checks and thus save a
973 * lot of checks that are most likely not needed.
975 if (bi->gcPrioritise) {
976 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
977 /* try another chunk */
981 /* let's give it a try */
984 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
985 bi->skipErasedCheck = 0;
987 if (!bi->skipErasedCheck) {
988 erasedOk = yaffs_CheckChunkErased(dev, chunk);
989 if (erasedOk != YAFFS_OK) {
991 (TSTR ("**>> yaffs chunk %d was not erased"
994 /* try another chunk */
997 bi->skipErasedCheck = 1;
1000 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
1002 if (writeOk != YAFFS_OK) {
1003 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
1004 /* try another chunk */
1008 /* Copy the data into the robustification buffer */
1009 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1011 } while (writeOk != YAFFS_OK &&
1012 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1018 T(YAFFS_TRACE_ERROR,
1019 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1022 dev->nRetriedWrites += (attempts - 1);
1029 * Block retiring for handling a broken block.
1032 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
1034 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1036 yaffs_InvalidateCheckpoint(dev);
1038 yaffs_MarkBlockBad(dev, blockInNAND);
1040 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1041 bi->gcPrioritise = 0;
1042 bi->needsRetiring = 0;
1044 dev->nRetiredBlocks++;
1048 * Functions for robustisizing TODO
1052 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
1054 const yaffs_ExtendedTags * tags)
1058 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
1059 const yaffs_ExtendedTags * tags)
1063 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1065 if(!bi->gcPrioritise){
1066 bi->gcPrioritise = 1;
1067 dev->hasPendingPrioritisedGCs = 1;
1068 bi->chunkErrorStrikes ++;
1070 if(bi->chunkErrorStrikes > 3){
1071 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1072 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1079 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
1082 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1083 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1085 yaffs_HandleChunkError(dev,bi);
1089 /* Was an actual write failure, so mark the block for retirement */
1090 bi->needsRetiring = 1;
1091 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1092 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1097 /* Delete the chunk */
1098 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1102 /*---------------- Name handling functions ------------*/
1104 static __u16 yaffs_CalcNameSum(const YCHAR * name)
1109 YUCHAR *bname = (YUCHAR *) name;
1111 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1113 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1114 sum += yaffs_toupper(*bname) * i;
1116 sum += (*bname) * i;
1125 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
1127 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1128 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
1129 yaffs_strcpy(obj->shortName, name);
1131 obj->shortName[0] = _Y('\0');
1134 obj->sum = yaffs_CalcNameSum(name);
1137 /*-------------------- TNODES -------------------
1139 * List of spare tnodes
1140 * The list is hooked together using the first pointer
1144 /* yaffs_CreateTnodes creates a bunch more tnodes and
1145 * adds them to the tnode free list.
1146 * Don't use this function directly
1149 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
1153 yaffs_Tnode *newTnodes;
1157 yaffs_TnodeList *tnl;
1162 /* Calculate the tnode size in bytes for variable width tnode support.
1163 * Must be a multiple of 32-bits */
1164 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1166 if(tnodeSize < sizeof(yaffs_Tnode))
1167 tnodeSize = sizeof(yaffs_Tnode);
1170 /* make these things */
1172 newTnodes = YMALLOC(nTnodes * tnodeSize);
1173 mem = (__u8 *)newTnodes;
1176 T(YAFFS_TRACE_ERROR,
1177 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1181 /* Hook them into the free list */
1183 for (i = 0; i < nTnodes - 1; i++) {
1184 newTnodes[i].internal[0] = &newTnodes[i + 1];
1185 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1186 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1190 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1191 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1192 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1194 dev->freeTnodes = newTnodes;
1196 /* New hookup for wide tnodes */
1197 for(i = 0; i < nTnodes -1; i++) {
1198 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1199 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1200 curr->internal[0] = next;
1203 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1204 curr->internal[0] = dev->freeTnodes;
1205 dev->freeTnodes = (yaffs_Tnode *)mem;
1210 dev->nFreeTnodes += nTnodes;
1211 dev->nTnodesCreated += nTnodes;
1213 /* Now add this bunch of tnodes to a list for freeing up.
1214 * NB If we can't add this to the management list it isn't fatal
1215 * but it just means we can't free this bunch of tnodes later.
1218 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1220 T(YAFFS_TRACE_ERROR,
1222 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1226 tnl->tnodes = newTnodes;
1227 tnl->next = dev->allocatedTnodeList;
1228 dev->allocatedTnodeList = tnl;
1231 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1236 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1238 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
1240 yaffs_Tnode *tn = NULL;
1242 /* If there are none left make more */
1243 if (!dev->freeTnodes) {
1244 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1247 if (dev->freeTnodes) {
1248 tn = dev->freeTnodes;
1249 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1250 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1251 /* Hoosterman, this thing looks like it isn't in the list */
1252 T(YAFFS_TRACE_ALWAYS,
1253 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1256 dev->freeTnodes = dev->freeTnodes->internal[0];
1260 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1265 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
1267 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1268 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1270 if(tnodeSize < sizeof(yaffs_Tnode))
1271 tnodeSize = sizeof(yaffs_Tnode);
1274 memset(tn, 0, tnodeSize);
1279 /* FreeTnode frees up a tnode and puts it back on the free list */
1280 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
1283 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1284 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1285 /* Hoosterman, this thing looks like it is already in the list */
1286 T(YAFFS_TRACE_ALWAYS,
1287 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1289 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1291 tn->internal[0] = dev->freeTnodes;
1292 dev->freeTnodes = tn;
1295 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1299 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
1301 /* Free the list of allocated tnodes */
1302 yaffs_TnodeList *tmp;
1304 while (dev->allocatedTnodeList) {
1305 tmp = dev->allocatedTnodeList->next;
1307 YFREE(dev->allocatedTnodeList->tnodes);
1308 YFREE(dev->allocatedTnodeList);
1309 dev->allocatedTnodeList = tmp;
1313 dev->freeTnodes = NULL;
1314 dev->nFreeTnodes = 0;
1317 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
1319 dev->allocatedTnodeList = NULL;
1320 dev->freeTnodes = NULL;
1321 dev->nFreeTnodes = 0;
1322 dev->nTnodesCreated = 0;
1327 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
1329 __u32 *map = (__u32 *)tn;
1335 pos &= YAFFS_TNODES_LEVEL0_MASK;
1336 val >>= dev->chunkGroupBits;
1338 bitInMap = pos * dev->tnodeWidth;
1339 wordInMap = bitInMap /32;
1340 bitInWord = bitInMap & (32 -1);
1342 mask = dev->tnodeMask << bitInWord;
1344 map[wordInMap] &= ~mask;
1345 map[wordInMap] |= (mask & (val << bitInWord));
1347 if(dev->tnodeWidth > (32-bitInWord)) {
1348 bitInWord = (32 - bitInWord);
1350 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1351 map[wordInMap] &= ~mask;
1352 map[wordInMap] |= (mask & (val >> bitInWord));
1356 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
1358 __u32 *map = (__u32 *)tn;
1364 pos &= YAFFS_TNODES_LEVEL0_MASK;
1366 bitInMap = pos * dev->tnodeWidth;
1367 wordInMap = bitInMap /32;
1368 bitInWord = bitInMap & (32 -1);
1370 val = map[wordInMap] >> bitInWord;
1372 if(dev->tnodeWidth > (32-bitInWord)) {
1373 bitInWord = (32 - bitInWord);
1375 val |= (map[wordInMap] << bitInWord);
1378 val &= dev->tnodeMask;
1379 val <<= dev->chunkGroupBits;
1384 /* ------------------- End of individual tnode manipulation -----------------*/
1386 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1387 * The look up tree is represented by the top tnode and the number of topLevel
1388 * in the tree. 0 means only the level 0 tnode is in the tree.
1391 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1392 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
1393 yaffs_FileStructure * fStruct,
1397 yaffs_Tnode *tn = fStruct->top;
1399 int requiredTallness;
1400 int level = fStruct->topLevel;
1402 /* Check sane level and chunk Id */
1403 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
1407 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1411 /* First check we're tall enough (ie enough topLevel) */
1413 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1414 requiredTallness = 0;
1416 i >>= YAFFS_TNODES_INTERNAL_BITS;
1420 if (requiredTallness > fStruct->topLevel) {
1421 /* Not tall enough, so we can't find it, return NULL. */
1425 /* Traverse down to level 0 */
1426 while (level > 0 && tn) {
1428 internal[(chunkId >>
1429 ( YAFFS_TNODES_LEVEL0_BITS +
1431 YAFFS_TNODES_INTERNAL_BITS)
1433 YAFFS_TNODES_INTERNAL_MASK];
1441 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1442 * This happens in two steps:
1443 * 1. If the tree isn't tall enough, then make it taller.
1444 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1446 * Used when modifying the tree.
1448 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1449 * be plugged into the ttree.
1452 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
1453 yaffs_FileStructure * fStruct,
1455 yaffs_Tnode *passedTn)
1458 int requiredTallness;
1466 /* Check sane level and page Id */
1467 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
1471 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1475 /* First check we're tall enough (ie enough topLevel) */
1477 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1478 requiredTallness = 0;
1480 x >>= YAFFS_TNODES_INTERNAL_BITS;
1485 if (requiredTallness > fStruct->topLevel) {
1486 /* Not tall enough,gotta make the tree taller */
1487 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1489 tn = yaffs_GetTnode(dev);
1492 tn->internal[0] = fStruct->top;
1495 T(YAFFS_TRACE_ERROR,
1496 (TSTR("yaffs: no more tnodes" TENDSTR)));
1500 fStruct->topLevel = requiredTallness;
1503 /* Traverse down to level 0, adding anything we need */
1505 l = fStruct->topLevel;
1509 while (l > 0 && tn) {
1511 ( YAFFS_TNODES_LEVEL0_BITS +
1512 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1513 YAFFS_TNODES_INTERNAL_MASK;
1516 if((l>1) && !tn->internal[x]){
1517 /* Add missing non-level-zero tnode */
1518 tn->internal[x] = yaffs_GetTnode(dev);
1521 /* Looking from level 1 at level 0 */
1523 /* If we already have one, then release it.*/
1525 yaffs_FreeTnode(dev,tn->internal[x]);
1526 tn->internal[x] = passedTn;
1528 } else if(!tn->internal[x]) {
1529 /* Don't have one, none passed in */
1530 tn->internal[x] = yaffs_GetTnode(dev);
1534 tn = tn->internal[x];
1538 /* top is level 0 */
1540 memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1541 yaffs_FreeTnode(dev,passedTn);
1548 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1549 yaffs_ExtendedTags * tags, int objectId,
1554 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1555 if (yaffs_CheckChunkBit
1556 (dev, theChunk / dev->nChunksPerBlock,
1557 theChunk % dev->nChunksPerBlock)) {
1558 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1560 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1572 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1573 * chunks and tnodes in the file
1574 * Returns 1 if the tree was deleted.
1575 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1578 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1579 int chunkOffset, int *limit)
1584 yaffs_ExtendedTags tags;
1586 yaffs_Device *dev = in->myDev;
1593 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1595 if (tn->internal[i]) {
1596 if (limit && (*limit) < 0) {
1600 yaffs_DeleteWorker(in,
1608 YAFFS_TNODES_INTERNAL_BITS)
1613 yaffs_FreeTnode(dev,
1616 tn->internal[i] = NULL;
1621 return (allDone) ? 1 : 0;
1622 } else if (level == 0) {
1625 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1627 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1632 YAFFS_TNODES_LEVEL0_BITS) + i;
1635 yaffs_FindChunkInGroup(dev,
1641 if (foundChunk > 0) {
1642 yaffs_DeleteChunk(dev,
1647 *limit = *limit - 1;
1655 yaffs_PutLevel0Tnode(dev,tn,i,0);
1659 return (i < 0) ? 1 : 0;
1669 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1672 yaffs_BlockInfo *theBlock;
1674 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1676 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1678 theBlock->softDeletions++;
1683 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1684 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1686 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1689 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1690 __u32 level, int chunkOffset)
1695 yaffs_Device *dev = in->myDev;
1700 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1702 if (tn->internal[i]) {
1704 yaffs_SoftDeleteWorker(in,
1710 YAFFS_TNODES_INTERNAL_BITS)
1713 yaffs_FreeTnode(dev,
1716 tn->internal[i] = NULL;
1718 /* Hoosterman... how could this happen? */
1722 return (allDone) ? 1 : 0;
1723 } else if (level == 0) {
1725 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1726 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1728 /* Note this does not find the real chunk, only the chunk group.
1729 * We make an assumption that a chunk group is not larger than
1732 yaffs_SoftDeleteChunk(dev, theChunk);
1733 yaffs_PutLevel0Tnode(dev,tn,i,0);
1747 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1750 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1751 if (obj->nDataChunks <= 0) {
1752 /* Empty file with no duplicate object headers, just delete it immediately */
1753 yaffs_FreeTnode(obj->myDev,
1754 obj->variant.fileVariant.top);
1755 obj->variant.fileVariant.top = NULL;
1756 T(YAFFS_TRACE_TRACING,
1757 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1759 yaffs_DoGenericObjectDeletion(obj);
1761 yaffs_SoftDeleteWorker(obj,
1762 obj->variant.fileVariant.top,
1763 obj->variant.fileVariant.
1765 obj->softDeleted = 1;
1770 /* Pruning removes any part of the file structure tree that is beyond the
1771 * bounds of the file (ie that does not point to chunks).
1773 * A file should only get pruned when its size is reduced.
1775 * Before pruning, the chunks must be pulled from the tree and the
1776 * level 0 tnode entries must be zeroed out.
1777 * Could also use this for file deletion, but that's probably better handled
1778 * by a special case.
1781 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1782 __u32 level, int del0)
1790 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1791 if (tn->internal[i] && level > 0) {
1793 yaffs_PruneWorker(dev, tn->internal[i],
1795 (i == 0) ? del0 : 1);
1798 if (tn->internal[i]) {
1803 if (hasData == 0 && del0) {
1804 /* Free and return NULL */
1806 yaffs_FreeTnode(dev, tn);
1816 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1817 yaffs_FileStructure * fStruct)
1824 if (fStruct->topLevel > 0) {
1826 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1828 /* Now we have a tree with all the non-zero branches NULL but the height
1829 * is the same as it was.
1830 * Let's see if we can trim internal tnodes to shorten the tree.
1831 * We can do this if only the 0th element in the tnode is in use
1832 * (ie all the non-zero are NULL)
1835 while (fStruct->topLevel && !done) {
1839 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1840 if (tn->internal[i]) {
1846 fStruct->top = tn->internal[0];
1847 fStruct->topLevel--;
1848 yaffs_FreeTnode(dev, tn);
1858 /*-------------------- End of File Structure functions.-------------------*/
1860 /* yaffs_CreateFreeObjects creates a bunch more objects and
1861 * adds them to the object free list.
1863 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1866 yaffs_Object *newObjects;
1867 yaffs_ObjectList *list;
1872 /* make these things */
1873 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1874 list = YMALLOC(sizeof(yaffs_ObjectList));
1876 if (!newObjects || !list) {
1881 T(YAFFS_TRACE_ALLOCATE,
1882 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1886 /* Hook them into the free list */
1887 for (i = 0; i < nObjects - 1; i++) {
1888 newObjects[i].siblings.next =
1889 (struct ylist_head *)(&newObjects[i + 1]);
1892 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1893 dev->freeObjects = newObjects;
1894 dev->nFreeObjects += nObjects;
1895 dev->nObjectsCreated += nObjects;
1897 /* Now add this bunch of Objects to a list for freeing up. */
1899 list->objects = newObjects;
1900 list->next = dev->allocatedObjectList;
1901 dev->allocatedObjectList = list;
1907 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1908 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1910 yaffs_Object *tn = NULL;
1912 /* If there are none left make more */
1913 if (!dev->freeObjects) {
1914 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1917 if (dev->freeObjects) {
1918 tn = dev->freeObjects;
1920 (yaffs_Object *) (dev->freeObjects->siblings.next);
1921 dev->nFreeObjects--;
1923 /* Now sweeten it up... */
1925 memset(tn, 0, sizeof(yaffs_Object));
1928 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1929 YINIT_LIST_HEAD(&(tn->hardLinks));
1930 YINIT_LIST_HEAD(&(tn->hashLink));
1931 YINIT_LIST_HEAD(&tn->siblings);
1933 /* Add it to the lost and found directory.
1934 * NB Can't put root or lostNFound in lostNFound so
1935 * check if lostNFound exists first
1937 if (dev->lostNFoundDir) {
1938 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1942 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1947 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1952 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1954 obj->fake = 1; /* it is fake so it might have no NAND presence... */
1955 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1956 obj->unlinkAllowed = 0; /* ... or unlink it */
1959 obj->yst_mode = mode;
1961 obj->hdrChunk = 0; /* Not a valid chunk. */
1968 static void yaffs_UnhashObject(yaffs_Object * tn)
1971 yaffs_Device *dev = tn->myDev;
1973 /* If it is still linked into the bucket list, free from the list */
1974 if (!ylist_empty(&tn->hashLink)) {
1975 ylist_del_init(&tn->hashLink);
1976 bucket = yaffs_HashFunction(tn->objectId);
1977 dev->objectBucket[bucket].count--;
1982 /* FreeObject frees up a Object and puts it back on the free list */
1983 static void yaffs_FreeObject(yaffs_Object * tn)
1986 yaffs_Device *dev = tn->myDev;
1990 /* We're still hooked up to a cached inode.
1991 * Don't delete now, but mark for later deletion
1993 tn->deferedFree = 1;
1998 yaffs_UnhashObject(tn);
2000 /* Link into the free list. */
2001 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2002 dev->freeObjects = tn;
2003 dev->nFreeObjects++;
2005 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2011 void yaffs_HandleDeferedFree(yaffs_Object * obj)
2013 if (obj->deferedFree) {
2014 yaffs_FreeObject(obj);
2020 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
2022 /* Free the list of allocated Objects */
2024 yaffs_ObjectList *tmp;
2026 while (dev->allocatedObjectList) {
2027 tmp = dev->allocatedObjectList->next;
2028 YFREE(dev->allocatedObjectList->objects);
2029 YFREE(dev->allocatedObjectList);
2031 dev->allocatedObjectList = tmp;
2034 dev->freeObjects = NULL;
2035 dev->nFreeObjects = 0;
2038 static void yaffs_InitialiseObjects(yaffs_Device * dev)
2042 dev->allocatedObjectList = NULL;
2043 dev->freeObjects = NULL;
2044 dev->nFreeObjects = 0;
2046 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2047 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2048 dev->objectBucket[i].count = 0;
2053 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
2058 int lowest = 999999;
2060 /* First let's see if we can find one that's empty. */
2062 for (i = 0; i < 10 && lowest > 0; i++) {
2064 x %= YAFFS_NOBJECT_BUCKETS;
2065 if (dev->objectBucket[x].count < lowest) {
2066 lowest = dev->objectBucket[x].count;
2072 /* If we didn't find an empty list, then try
2073 * looking a bit further for a short one
2076 for (i = 0; i < 10 && lowest > 3; i++) {
2078 x %= YAFFS_NOBJECT_BUCKETS;
2079 if (dev->objectBucket[x].count < lowest) {
2080 lowest = dev->objectBucket[x].count;
2089 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
2091 int bucket = yaffs_FindNiceObjectBucket(dev);
2093 /* Now find an object value that has not already been taken
2094 * by scanning the list.
2098 struct ylist_head *i;
2100 __u32 n = (__u32) bucket;
2102 /* yaffs_CheckObjectHashSanity(); */
2106 n += YAFFS_NOBJECT_BUCKETS;
2107 if (1 || dev->objectBucket[bucket].count > 0) {
2108 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2109 /* If there is already one in the list */
2111 && ylist_entry(i, yaffs_Object,
2112 hashLink)->objectId == n) {
2123 static void yaffs_HashObject(yaffs_Object * in)
2125 int bucket = yaffs_HashFunction(in->objectId);
2126 yaffs_Device *dev = in->myDev;
2128 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2129 dev->objectBucket[bucket].count++;
2133 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
2135 int bucket = yaffs_HashFunction(number);
2136 struct ylist_head *i;
2139 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2140 /* Look if it is in the list */
2142 in = ylist_entry(i, yaffs_Object, hashLink);
2143 if (in->objectId == number) {
2145 /* Don't tell the VFS about this one if it is defered free */
2146 if (in->deferedFree)
2158 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
2159 yaffs_ObjectType type)
2162 yaffs_Object *theObject;
2163 yaffs_Tnode *tn = NULL;
2166 number = yaffs_CreateNewObjectNumber(dev);
2169 theObject = yaffs_AllocateEmptyObject(dev);
2173 if(type == YAFFS_OBJECT_TYPE_FILE){
2174 tn = yaffs_GetTnode(dev);
2176 yaffs_FreeObject(theObject);
2184 theObject->fake = 0;
2185 theObject->renameAllowed = 1;
2186 theObject->unlinkAllowed = 1;
2187 theObject->objectId = number;
2188 yaffs_HashObject(theObject);
2189 theObject->variantType = type;
2190 #ifdef CONFIG_YAFFS_WINCE
2191 yfsd_WinFileTimeNow(theObject->win_atime);
2192 theObject->win_ctime[0] = theObject->win_mtime[0] =
2193 theObject->win_atime[0];
2194 theObject->win_ctime[1] = theObject->win_mtime[1] =
2195 theObject->win_atime[1];
2199 theObject->yst_atime = theObject->yst_mtime =
2200 theObject->yst_ctime = Y_CURRENT_TIME;
2203 case YAFFS_OBJECT_TYPE_FILE:
2204 theObject->variant.fileVariant.fileSize = 0;
2205 theObject->variant.fileVariant.scannedFileSize = 0;
2206 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2207 theObject->variant.fileVariant.topLevel = 0;
2208 theObject->variant.fileVariant.top = tn;
2210 case YAFFS_OBJECT_TYPE_DIRECTORY:
2211 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2214 case YAFFS_OBJECT_TYPE_SYMLINK:
2215 case YAFFS_OBJECT_TYPE_HARDLINK:
2216 case YAFFS_OBJECT_TYPE_SPECIAL:
2217 /* No action required */
2219 case YAFFS_OBJECT_TYPE_UNKNOWN:
2220 /* todo this should not happen */
2228 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
2230 yaffs_ObjectType type)
2232 yaffs_Object *theObject = NULL;
2235 theObject = yaffs_FindObjectByNumber(dev, number);
2239 theObject = yaffs_CreateNewObject(dev, number, type);
2247 static YCHAR *yaffs_CloneString(const YCHAR * str)
2249 YCHAR *newStr = NULL;
2252 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2254 yaffs_strcpy(newStr, str);
2262 * Mknod (create) a new object.
2263 * equivalentObject only has meaning for a hard link;
2264 * aliasString only has meaning for a sumlink.
2265 * rdev only has meaning for devices (a subset of special objects)
2268 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2269 yaffs_Object * parent,
2274 yaffs_Object * equivalentObject,
2275 const YCHAR * aliasString, __u32 rdev)
2280 yaffs_Device *dev = parent->myDev;
2282 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2283 if (yaffs_FindObjectByName(parent, name)) {
2287 in = yaffs_CreateNewObject(dev, -1, type);
2289 if(type == YAFFS_OBJECT_TYPE_SYMLINK){
2290 str = yaffs_CloneString(aliasString);
2292 yaffs_FreeObject(in);
2302 in->variantType = type;
2304 in->yst_mode = mode;
2306 #ifdef CONFIG_YAFFS_WINCE
2307 yfsd_WinFileTimeNow(in->win_atime);
2308 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2309 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2312 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2314 in->yst_rdev = rdev;
2318 in->nDataChunks = 0;
2320 yaffs_SetObjectName(in, name);
2323 yaffs_AddObjectToDirectory(parent, in);
2325 in->myDev = parent->myDev;
2328 case YAFFS_OBJECT_TYPE_SYMLINK:
2329 in->variant.symLinkVariant.alias = str;
2331 case YAFFS_OBJECT_TYPE_HARDLINK:
2332 in->variant.hardLinkVariant.equivalentObject =
2334 in->variant.hardLinkVariant.equivalentObjectId =
2335 equivalentObject->objectId;
2336 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2338 case YAFFS_OBJECT_TYPE_FILE:
2339 case YAFFS_OBJECT_TYPE_DIRECTORY:
2340 case YAFFS_OBJECT_TYPE_SPECIAL:
2341 case YAFFS_OBJECT_TYPE_UNKNOWN:
2346 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2347 /* Could not create the object header, fail the creation */
2348 yaffs_DestroyObject(in);
2357 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
2358 __u32 mode, __u32 uid, __u32 gid)
2360 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2361 uid, gid, NULL, NULL, 0);
2364 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
2365 __u32 mode, __u32 uid, __u32 gid)
2367 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2368 mode, uid, gid, NULL, NULL, 0);
2371 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
2372 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2374 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2375 uid, gid, NULL, NULL, rdev);
2378 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
2379 __u32 mode, __u32 uid, __u32 gid,
2380 const YCHAR * alias)
2382 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2383 uid, gid, NULL, alias, 0);
2386 /* yaffs_Link returns the object id of the equivalent object.*/
2387 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
2388 yaffs_Object * equivalentObject)
2390 /* Get the real object in case we were fed a hard link as an equivalent object */
2391 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2393 if (yaffs_MknodObject
2394 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2395 equivalentObject, NULL, 0)) {
2396 return equivalentObject;
2403 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
2404 const YCHAR * newName, int force, int shadows)
2409 yaffs_Object *existingTarget;
2411 if (newDir == NULL) {
2412 newDir = obj->parent; /* use the old directory */
2415 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2416 T(YAFFS_TRACE_ALWAYS,
2418 ("tragendy: yaffs_ChangeObjectName: newDir is not a directory"
2423 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2424 if (obj->myDev->isYaffs2) {
2425 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2427 unlinkOp = (newDir == obj->myDev->unlinkedDir
2428 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2431 deleteOp = (newDir == obj->myDev->deletedDir);
2433 existingTarget = yaffs_FindObjectByName(newDir, newName);
2435 /* If the object is a file going into the unlinked directory,
2436 * then it is OK to just stuff it in since duplicate names are allowed.
2437 * else only proceed if the new name does not exist and if we're putting
2438 * it into a directory.
2445 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2446 yaffs_SetObjectName(obj, newName);
2449 yaffs_AddObjectToDirectory(newDir, obj);
2454 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2455 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
2462 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
2463 yaffs_Object * newDir, const YCHAR * newName)
2466 yaffs_Object *existingTarget;
2469 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2470 /* Special case for case insemsitive systems (eg. WinCE).
2471 * While look-up is case insensitive, the name isn't.
2472 * Therefore we might want to change x.txt to X.txt
2474 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
2479 obj = yaffs_FindObjectByName(oldDir, oldName);
2480 /* Check new name to long. */
2481 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK &&
2482 yaffs_strlen(newName) > YAFFS_MAX_ALIAS_LENGTH)
2485 else if (obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK &&
2486 yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2490 if (obj && obj->renameAllowed) {
2492 /* Now do the handling for an existing target, if there is one */
2494 existingTarget = yaffs_FindObjectByName(newDir, newName);
2495 if (existingTarget &&
2496 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2497 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2498 /* There is a target that is a non-empty directory, so we fail */
2499 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2500 } else if (existingTarget && existingTarget != obj) {
2501 /* Nuke the target first, using shadowing,
2502 * but only if it isn't the same object
2504 yaffs_ChangeObjectName(obj, newDir, newName, force,
2505 existingTarget->objectId);
2506 yaffs_UnlinkObject(existingTarget);
2509 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2514 /*------------------------- Block Management and Page Allocation ----------------*/
2516 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
2518 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2520 dev->blockInfo = NULL;
2521 dev->chunkBits = NULL;
2523 dev->allocationBlock = -1; /* force it to get a new one */
2525 /* If the first allocation strategy fails, thry the alternate one */
2526 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2527 if(!dev->blockInfo){
2528 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2529 dev->blockInfoAlt = 1;
2532 dev->blockInfoAlt = 0;
2536 /* Set up dynamic blockinfo stuff. */
2537 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2538 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2539 if(!dev->chunkBits){
2540 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2541 dev->chunkBitsAlt = 1;
2544 dev->chunkBitsAlt = 0;
2547 if (dev->blockInfo && dev->chunkBits) {
2548 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2549 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2557 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
2559 if(dev->blockInfoAlt && dev->blockInfo)
2560 YFREE_ALT(dev->blockInfo);
2561 else if(dev->blockInfo)
2562 YFREE(dev->blockInfo);
2564 dev->blockInfoAlt = 0;
2566 dev->blockInfo = NULL;
2568 if(dev->chunkBitsAlt && dev->chunkBits)
2569 YFREE_ALT(dev->chunkBits);
2570 else if(dev->chunkBits)
2571 YFREE(dev->chunkBits);
2572 dev->chunkBitsAlt = 0;
2573 dev->chunkBits = NULL;
2576 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
2577 yaffs_BlockInfo * bi)
2584 return 1; /* disqualification only applies to yaffs2. */
2586 if (!bi->hasShrinkHeader)
2587 return 1; /* can gc */
2589 /* Find the oldest dirty sequence number if we don't know it and save it
2590 * so we don't have to keep recomputing it.
2592 if (!dev->oldestDirtySequence) {
2593 seq = dev->sequenceNumber;
2595 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2597 b = yaffs_GetBlockInfo(dev, i);
2598 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2599 (b->pagesInUse - b->softDeletions) <
2600 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2601 seq = b->sequenceNumber;
2604 dev->oldestDirtySequence = seq;
2607 /* Can't do gc of this block if there are any blocks older than this one that have
2610 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2614 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2615 * for garbage collection.
2618 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2622 int b = dev->currentDirtyChecker;
2629 yaffs_BlockInfo *bi;
2630 int pendingPrioritisedExist = 0;
2632 /* First let's see if we need to grab a prioritised block */
2633 if(dev->hasPendingPrioritisedGCs){
2634 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2636 bi = yaffs_GetBlockInfo(dev, i);
2637 //yaffs_VerifyBlock(dev,bi,i);
2639 if(bi->gcPrioritise) {
2640 pendingPrioritisedExist = 1;
2641 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2642 yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2643 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2646 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2651 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2652 dev->hasPendingPrioritisedGCs = 0;
2655 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2657 * else (we're doing a leasurely gc), then we only bother to do this if the
2658 * block has only a few pages in use.
2661 dev->nonAggressiveSkip--;
2663 if (!aggressive && (dev->nonAggressiveSkip > 0)) {
2669 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2673 dev->internalEndBlock - dev->internalStartBlock + 1;
2676 dev->internalEndBlock - dev->internalStartBlock + 1;
2677 iterations = iterations / 16;
2678 if (iterations > 200) {
2683 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2685 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2686 b = dev->internalStartBlock;
2689 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2690 T(YAFFS_TRACE_ERROR,
2691 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2695 bi = yaffs_GetBlockInfo(dev, b);
2698 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2705 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2706 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2707 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2709 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2713 dev->currentDirtyChecker = b;
2717 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2718 dev->nChunksPerBlock - pagesInUse,prioritised));
2721 dev->oldestDirtySequence = 0;
2724 dev->nonAggressiveSkip = 4;
2730 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2732 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2736 /* If the block is still healthy erase it and mark as clean.
2737 * If the block has had a data failure, then retire it.
2740 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2741 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2742 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2744 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2746 if (!bi->needsRetiring) {
2747 yaffs_InvalidateCheckpoint(dev);
2748 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2750 dev->nErasureFailures++;
2751 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2752 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2757 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2759 for (i = 0; i < dev->nChunksPerBlock; i++) {
2760 if (!yaffs_CheckChunkErased
2761 (dev, blockNo * dev->nChunksPerBlock + i)) {
2762 T(YAFFS_TRACE_ERROR,
2764 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2765 TENDSTR), blockNo, i));
2771 /* Clean it up... */
2772 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2773 dev->nErasedBlocks++;
2775 bi->softDeletions = 0;
2776 bi->hasShrinkHeader = 0;
2777 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2778 bi->gcPrioritise = 0;
2779 yaffs_ClearChunkBits(dev, blockNo);
2781 T(YAFFS_TRACE_ERASE,
2782 (TSTR("Erased block %d" TENDSTR), blockNo));
2784 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2786 yaffs_RetireBlock(dev, blockNo);
2787 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2788 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2792 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2796 yaffs_BlockInfo *bi;
2798 if (dev->nErasedBlocks < 1) {
2799 /* Hoosterman we've got a problem.
2800 * Can't get space to gc
2802 T(YAFFS_TRACE_ERROR,
2803 (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2808 /* Find an empty block. */
2810 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2811 dev->allocationBlockFinder++;
2812 if (dev->allocationBlockFinder < dev->internalStartBlock
2813 || dev->allocationBlockFinder > dev->internalEndBlock) {
2814 dev->allocationBlockFinder = dev->internalStartBlock;
2817 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2819 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2820 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2821 dev->sequenceNumber++;
2822 bi->sequenceNumber = dev->sequenceNumber;
2823 dev->nErasedBlocks--;
2824 T(YAFFS_TRACE_ALLOCATE,
2825 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2826 dev->allocationBlockFinder, dev->sequenceNumber,
2827 dev->nErasedBlocks));
2828 return dev->allocationBlockFinder;
2832 T(YAFFS_TRACE_ALWAYS,
2834 ("yaffs tragedy: no more eraased blocks, but there should have been %d"
2835 TENDSTR), dev->nErasedBlocks));
2842 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2844 if(!dev->nCheckpointBlocksRequired){
2845 /* Not a valid value so recalculate */
2848 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2851 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2853 if(tnodeSize < sizeof(yaffs_Tnode))
2854 tnodeSize = sizeof(yaffs_Tnode);
2856 nBytes += sizeof(yaffs_CheckpointValidity);
2857 nBytes += sizeof(yaffs_CheckpointDevice);
2858 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2859 nBytes += devBlocks * dev->chunkBitmapStride;
2860 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2861 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2862 nBytes += sizeof(yaffs_CheckpointValidity);
2863 nBytes += sizeof(__u32); /* checksum*/
2865 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2867 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2869 dev->nCheckpointBlocksRequired = nBlocks;
2872 return dev->nCheckpointBlocksRequired;
2875 // Check if there's space to allocate...
2876 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2877 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2880 int reservedBlocks = dev->nReservedBlocks;
2881 int checkpointBlocks;
2883 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
2884 if(checkpointBlocks < 0)
2885 checkpointBlocks = 0;
2887 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2889 return (dev->nFreeChunks > reservedChunks);
2892 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2895 yaffs_BlockInfo *bi;
2897 if (dev->allocationBlock < 0) {
2898 /* Get next block to allocate off */
2899 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2900 dev->allocationPage = 0;
2903 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2904 /* Not enough space to allocate unless we're allowed to use the reserve. */
2908 if (dev->nErasedBlocks < dev->nReservedBlocks
2909 && dev->allocationPage == 0) {
2910 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2913 /* Next page please.... */
2914 if (dev->allocationBlock >= 0) {
2915 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2917 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2918 dev->allocationPage;
2920 yaffs_SetChunkBit(dev, dev->allocationBlock,
2921 dev->allocationPage);
2923 dev->allocationPage++;
2927 /* If the block is full set the state to full */
2928 if (dev->allocationPage >= dev->nChunksPerBlock) {
2929 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2930 dev->allocationBlock = -1;
2939 T(YAFFS_TRACE_ERROR,
2940 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2945 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2949 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2951 if (dev->allocationBlock > 0) {
2952 n += (dev->nChunksPerBlock - dev->allocationPage);
2959 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2965 int retVal = YAFFS_OK;
2968 int isCheckpointBlock;
2971 int chunksBefore = yaffs_GetErasedChunks(dev);
2974 yaffs_ExtendedTags tags;
2976 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2978 yaffs_Object *object;
2980 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2982 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2984 T(YAFFS_TRACE_TRACING,
2985 (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2986 bi->pagesInUse, bi->hasShrinkHeader));
2988 /*yaffs_VerifyFreeChunks(dev); */
2990 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2992 /* Take off the number of soft deleted entries because
2993 * they're going to get really deleted during GC.
2995 dev->nFreeChunks -= bi->softDeletions;
2999 if (isCheckpointBlock ||
3000 !yaffs_StillSomeChunkBits(dev, block)) {
3001 T(YAFFS_TRACE_TRACING,
3003 ("Collecting block %d that has no chunks in use" TENDSTR),
3005 yaffs_BlockBecameDirty(dev, block);
3008 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3010 yaffs_VerifyBlock(dev,bi,block);
3012 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
3013 chunkInBlock < dev->nChunksPerBlock
3014 && yaffs_StillSomeChunkBits(dev, block);
3015 chunkInBlock++, oldChunk++) {
3016 if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
3018 /* This page is in use and might need to be copied off */
3022 yaffs_InitialiseTags(&tags);
3024 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3028 yaffs_FindObjectByNumber(dev,
3031 T(YAFFS_TRACE_GC_DETAIL,
3033 ("Collecting page %d, %d %d %d " TENDSTR),
3034 chunkInBlock, tags.objectId, tags.chunkId,
3037 if(object && !yaffs_SkipVerification(dev)){
3038 if(tags.chunkId == 0)
3039 matchingChunk = object->hdrChunk;
3040 else if(object->softDeleted)
3041 matchingChunk = oldChunk; /* Defeat the test */
3043 matchingChunk = yaffs_FindChunkInFile(object,tags.chunkId,NULL);
3045 if(oldChunk != matchingChunk)
3046 T(YAFFS_TRACE_ERROR,
3047 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3048 oldChunk,matchingChunk,tags.objectId, tags.chunkId));
3053 T(YAFFS_TRACE_ERROR,
3055 ("page %d in gc has no object: %d %d %d "
3057 tags.objectId, tags.chunkId, tags.byteCount));
3060 if (object && object->deleted
3061 && tags.chunkId != 0) {
3062 /* Data chunk in a deleted file, throw it away
3063 * It's a soft deleted data chunk,
3064 * No need to copy this, just forget about it and
3065 * fix up the object.
3068 object->nDataChunks--;
3070 if (object->nDataChunks <= 0) {
3071 /* remeber to clean up the object */
3072 dev->gcCleanupList[cleanups] =
3078 /* Todo object && object->deleted && object->nDataChunks == 0 */
3080 /* Deleted object header with no data chunks.
3081 * Can be discarded and the file deleted.
3083 object->hdrChunk = 0;
3084 yaffs_FreeTnode(object->myDev,
3087 object->variant.fileVariant.top = NULL;
3088 yaffs_DoGenericObjectDeletion(object);
3090 } else if (object) {
3091 /* It's either a data chunk in a live file or
3092 * an ObjectHeader, so we're interested in it.
3093 * NB Need to keep the ObjectHeaders of deleted files
3094 * until the whole file has been deleted off
3096 tags.serialNumber++;
3100 if (tags.chunkId == 0) {
3101 /* It is an object Id,
3102 * We need to nuke the shrinkheader flags first
3103 * We no longer want the shrinkHeader flag since its work is done
3104 * and if it is left in place it will mess up scanning.
3105 * Also, clear out any shadowing stuff
3108 yaffs_ObjectHeader *oh;
3109 oh = (yaffs_ObjectHeader *)buffer;
3111 oh->shadowsObject = oh->inbandShadowsObject = -1;
3112 tags.extraShadows = 0;
3113 tags.extraIsShrinkHeader = 0;
3115 yaffs_VerifyObjectHeader(object,oh,&tags,1);
3119 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3122 retVal = YAFFS_FAIL;
3125 /* Ok, now fix up the Tnodes etc. */
3127 if (tags.chunkId == 0) {
3129 object->hdrChunk = newChunk;
3130 object->serial = tags.serialNumber;
3132 /* It's a data chunk */
3133 yaffs_PutChunkIntoFile
3141 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3146 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3149 /* Do any required cleanups */
3150 for (i = 0; i < cleanups; i++) {
3151 /* Time to delete the file too */
3153 yaffs_FindObjectByNumber(dev,
3154 dev->gcCleanupList[i]);
3156 yaffs_FreeTnode(dev,
3157 object->variant.fileVariant.
3159 object->variant.fileVariant.top = NULL;
3162 ("yaffs: About to finally delete object %d"
3163 TENDSTR), object->objectId));
3164 yaffs_DoGenericObjectDeletion(object);
3165 object->myDev->nDeletedFiles--;
3172 yaffs_VerifyCollectedBlock(dev,bi,block);
3174 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
3177 ("gc did not increase free chunks before %d after %d"
3178 TENDSTR), chunksBefore, chunksAfter));
3186 /* New garbage collector
3187 * If we're very low on erased blocks then we do aggressive garbage collection
3188 * otherwise we do "leasurely" garbage collection.
3189 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3190 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3192 * The idea is to help clear out space in a more spread-out manner.
3193 * Dunno if it really does anything useful.
3195 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
3199 int gcOk = YAFFS_OK;
3202 int checkpointBlockAdjust;
3204 if (dev->isDoingGC) {
3205 /* Bail out so we don't get recursive gc */
3209 /* This loop should pass the first time.
3210 * We'll only see looping here if the erase of the collected block fails.
3216 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3217 if(checkpointBlockAdjust < 0)
3218 checkpointBlockAdjust = 0;
3220 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3221 /* We need a block soon...*/
3224 /* We're in no hurry */
3228 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3231 dev->garbageCollections++;
3233 dev->passiveGarbageCollections++;
3238 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3239 dev->nErasedBlocks, aggressive));
3241 gcOk = yaffs_GarbageCollectBlock(dev, block);
3244 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3247 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3248 TENDSTR), dev->nErasedBlocks, maxTries, block));
3250 } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
3253 return aggressive ? gcOk : YAFFS_OK;
3256 /*------------------------- TAGS --------------------------------*/
3258 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
3261 return (tags->chunkId == chunkInObject &&
3262 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3267 /*-------------------- Data file manipulation -----------------*/
3269 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
3270 yaffs_ExtendedTags * tags)
3272 /*Get the Tnode, then get the level 0 offset chunk offset */
3275 yaffs_ExtendedTags localTags;
3278 yaffs_Device *dev = in->myDev;
3281 /* Passed a NULL, so use our own tags space */
3285 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3288 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3291 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3297 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
3298 yaffs_ExtendedTags * tags)
3300 /* Get the Tnode, then get the level 0 offset chunk offset */
3303 yaffs_ExtendedTags localTags;
3305 yaffs_Device *dev = in->myDev;
3309 /* Passed a NULL, so use our own tags space */
3313 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3317 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3320 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3323 /* Delete the entry in the filestructure (if found) */
3325 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
3328 /*T(("No level 0 found for %d\n", chunkInInode)); */
3332 /* T(("Could not find %d to delete\n",chunkInInode)); */
3337 #ifdef YAFFS_PARANOID
3339 static int yaffs_CheckFileSanity(yaffs_Object * in)
3347 yaffs_Tags localTags;
3348 yaffs_Tags *tags = &localTags;
3352 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3353 /* T(("Object not a file\n")); */
3357 objId = in->objectId;
3358 fSize = in->variant.fileVariant.fileSize;
3360 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3362 for (chunk = 1; chunk <= nChunks; chunk++) {
3363 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3368 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
3370 if (yaffs_CheckChunkBits
3371 (dev, theChunk / dev->nChunksPerBlock,
3372 theChunk % dev->nChunksPerBlock)) {
3374 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3378 (tags, in->objectId, chunk, chunkDeleted)) {
3388 /* T(("No level 0 found for %d\n", chunk)); */
3392 return failed ? YAFFS_FAIL : YAFFS_OK;
3397 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
3398 int chunkInNAND, int inScan)
3400 /* NB inScan is zero unless scanning.
3401 * For forward scanning, inScan is > 0;
3402 * for backward scanning inScan is < 0
3406 yaffs_Device *dev = in->myDev;
3408 yaffs_ExtendedTags existingTags;
3409 yaffs_ExtendedTags newTags;
3410 unsigned existingSerial, newSerial;
3412 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3413 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3414 * If it is not during Scanning then something went wrong!
3417 T(YAFFS_TRACE_ERROR,
3419 ("yaffs tragedy:attempt to put data chunk into a non-file"
3424 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3428 tn = yaffs_AddOrFindLevel0Tnode(dev,
3429 &in->variant.fileVariant,
3436 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3439 /* If we're scanning then we need to test for duplicates
3440 * NB This does not need to be efficient since it should only ever
3441 * happen when the power fails during a write, then only one
3442 * chunk should ever be affected.
3444 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3445 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3448 if (existingChunk > 0) {
3449 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3450 * thus we have to do a FindChunkInFile to get the real chunk id.
3452 * We have a duplicate now we need to decide which one to use:
3454 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3455 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3456 * YAFFS1: Get both sets of tags and compare serial numbers.
3460 /* Only do this for forward scanning */
3461 yaffs_ReadChunkWithTagsFromNAND(dev,
3465 /* Do a proper find */
3467 yaffs_FindChunkInFile(in, chunkInInode,
3471 if (existingChunk <= 0) {
3472 /*Hoosterman - how did this happen? */
3474 T(YAFFS_TRACE_ERROR,
3476 ("yaffs tragedy: existing chunk < 0 in scan"
3481 /* NB The deleted flags should be false, otherwise the chunks will
3482 * not be loaded during a scan
3485 newSerial = newTags.serialNumber;
3486 existingSerial = existingTags.serialNumber;
3489 (in->myDev->isYaffs2 ||
3490 existingChunk <= 0 ||
3491 ((existingSerial + 1) & 3) == newSerial)) {
3492 /* Forward scanning.
3494 * Delete the old one and drop through to update the tnode
3496 yaffs_DeleteChunk(dev, existingChunk, 1,
3499 /* Backward scanning or we want to use the existing one
3501 * Delete the new one and return early so that the tnode isn't changed
3503 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3511 if (existingChunk == 0) {
3515 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
3520 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
3523 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3525 if (chunkInNAND >= 0) {
3526 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3529 T(YAFFS_TRACE_NANDACCESS,
3530 (TSTR("Chunk %d not found zero instead" TENDSTR),
3532 /* get sane (zero) data if you read a hole */
3533 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3539 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
3543 yaffs_ExtendedTags tags;
3544 yaffs_BlockInfo *bi;
3551 block = chunkId / dev->nChunksPerBlock;
3552 page = chunkId % dev->nChunksPerBlock;
3555 if(!yaffs_CheckChunkBit(dev,block,page))
3556 T(YAFFS_TRACE_VERIFY,
3557 (TSTR("Deleting invalid chunk %d"TENDSTR),
3560 bi = yaffs_GetBlockInfo(dev, block);
3562 T(YAFFS_TRACE_DELETION,
3563 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3566 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3568 yaffs_InitialiseTags(&tags);
3570 tags.chunkDeleted = 1;
3572 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3573 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3575 dev->nUnmarkedDeletions++;
3578 /* Pull out of the management area.
3579 * If the whole block became dirty, this will kick off an erasure.
3581 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3582 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3583 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3584 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3587 yaffs_ClearChunkBit(dev, block, page);
3591 if (bi->pagesInUse == 0 &&
3592 !bi->hasShrinkHeader &&
3593 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3594 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3595 yaffs_BlockBecameDirty(dev, block);
3599 /* T(("Bad news deleting chunk %d\n",chunkId)); */
3604 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
3605 const __u8 * buffer, int nBytes,
3608 /* Find old chunk Need to do this to get serial number
3609 * Write new one and patch into tree.
3610 * Invalidate old tags.
3614 yaffs_ExtendedTags prevTags;
3617 yaffs_ExtendedTags newTags;
3619 yaffs_Device *dev = in->myDev;
3621 yaffs_CheckGarbageCollection(dev);
3623 /* Get the previous chunk at this location in the file if it exists */
3624 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3626 /* Set up new tags */
3627 yaffs_InitialiseTags(&newTags);
3629 newTags.chunkId = chunkInInode;
3630 newTags.objectId = in->objectId;
3631 newTags.serialNumber =
3632 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
3633 newTags.byteCount = nBytes;
3636 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3639 if (newChunkId >= 0) {
3640 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3642 if (prevChunkId >= 0) {
3643 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3647 yaffs_CheckFileSanity(in);
3653 /* UpdateObjectHeader updates the header on NAND for an object.
3654 * If name is not NULL, then that new name is used.
3656 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
3657 int isShrink, int shadows)
3660 yaffs_BlockInfo *bi;
3662 yaffs_Device *dev = in->myDev;
3669 yaffs_ExtendedTags newTags;
3670 yaffs_ExtendedTags oldTags;
3672 __u8 *buffer = NULL;
3673 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3675 yaffs_ObjectHeader *oh = NULL;
3677 yaffs_strcpy(oldName,_Y("silly old name"));
3681 in == dev->rootDir || /* The rootDir should also be saved */
3684 yaffs_CheckGarbageCollection(dev);
3685 yaffs_CheckObjectDetailsLoaded(in);
3687 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3688 oh = (yaffs_ObjectHeader *) buffer;
3690 prevChunkId = in->hdrChunk;
3692 if (prevChunkId > 0) {
3693 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3696 yaffs_VerifyObjectHeader(in,oh,&oldTags,0);
3698 memcpy(oldName, oh->name, sizeof(oh->name));
3701 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3703 oh->type = in->variantType;
3704 oh->yst_mode = in->yst_mode;
3705 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3707 #ifdef CONFIG_YAFFS_WINCE
3708 oh->win_atime[0] = in->win_atime[0];
3709 oh->win_ctime[0] = in->win_ctime[0];
3710 oh->win_mtime[0] = in->win_mtime[0];
3711 oh->win_atime[1] = in->win_atime[1];
3712 oh->win_ctime[1] = in->win_ctime[1];
3713 oh->win_mtime[1] = in->win_mtime[1];
3715 oh->yst_uid = in->yst_uid;
3716 oh->yst_gid = in->yst_gid;
3717 oh->yst_atime = in->yst_atime;
3718 oh->yst_mtime = in->yst_mtime;
3719 oh->yst_ctime = in->yst_ctime;
3720 oh->yst_rdev = in->yst_rdev;
3723 oh->parentObjectId = in->parent->objectId;
3725 oh->parentObjectId = 0;
3728 if (name && *name) {
3729 memset(oh->name, 0, sizeof(oh->name));
3730 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3731 } else if (prevChunkId>=0) {
3732 memcpy(oh->name, oldName, sizeof(oh->name));
3734 memset(oh->name, 0, sizeof(oh->name));
3737 oh->isShrink = isShrink;
3739 switch (in->variantType) {
3740 case YAFFS_OBJECT_TYPE_UNKNOWN:
3741 /* Should not happen */
3743 case YAFFS_OBJECT_TYPE_FILE:
3745 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3746 || oh->parentObjectId ==
3747 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3748 fileVariant.fileSize;
3750 case YAFFS_OBJECT_TYPE_HARDLINK:
3751 oh->equivalentObjectId =
3752 in->variant.hardLinkVariant.equivalentObjectId;
3754 case YAFFS_OBJECT_TYPE_SPECIAL:
3757 case YAFFS_OBJECT_TYPE_DIRECTORY:
3760 case YAFFS_OBJECT_TYPE_SYMLINK:
3761 yaffs_strncpy(oh->alias,
3762 in->variant.symLinkVariant.alias,
3763 YAFFS_MAX_ALIAS_LENGTH);
3764 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3769 yaffs_InitialiseTags(&newTags);
3771 newTags.chunkId = 0;
3772 newTags.objectId = in->objectId;
3773 newTags.serialNumber = in->serial;
3775 /* Add extra info for file header */
3777 newTags.extraHeaderInfoAvailable = 1;
3778 newTags.extraParentObjectId = oh->parentObjectId;
3779 newTags.extraFileLength = oh->fileSize;
3780 newTags.extraIsShrinkHeader = oh->isShrink;
3781 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3782 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3783 newTags.extraObjectType = in->variantType;
3785 yaffs_VerifyObjectHeader(in,oh,&newTags,1);
3787 /* Create new chunk in NAND */
3789 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3790 (prevChunkId >= 0) ? 1 : 0);
3792 if (newChunkId >= 0) {
3794 in->hdrChunk = newChunkId;
3796 if (prevChunkId >= 0) {
3797 yaffs_DeleteChunk(dev, prevChunkId, 1,
3801 if(!yaffs_ObjectHasCachedWriteData(in))
3804 /* If this was a shrink, then mark the block that the chunk lives on */
3806 bi = yaffs_GetBlockInfo(in->myDev,
3807 newChunkId /in->myDev-> nChunksPerBlock);
3808 bi->hasShrinkHeader = 1;
3813 retVal = newChunkId;
3818 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3823 /*------------------------ Short Operations Cache ----------------------------------------
3824 * In many situations where there is no high level buffering (eg WinCE) a lot of
3825 * reads might be short sequential reads, and a lot of writes may be short
3826 * sequential writes. eg. scanning/writing a jpeg file.
3827 * In these cases, a short read/write cache can provide a huge perfomance benefit
3828 * with dumb-as-a-rock code.
3829 * In Linux, the page cache provides read buffering aand the short op cache provides write
3832 * There are a limited number (~10) of cache chunks per device so that we don't
3833 * need a very intelligent search.
3836 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3838 yaffs_Device *dev = obj->myDev;
3840 yaffs_ChunkCache *cache;
3841 int nCaches = obj->myDev->nShortOpCaches;
3843 for(i = 0; i < nCaches; i++){
3844 cache = &dev->srCache[i];
3845 if (cache->object == obj &&
3854 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3856 yaffs_Device *dev = obj->myDev;
3857 int lowest = -99; /* Stop compiler whining. */
3859 yaffs_ChunkCache *cache;
3860 int chunkWritten = 0;
3861 int nCaches = obj->myDev->nShortOpCaches;
3867 /* Find the dirty cache for this object with the lowest chunk id. */
3868 for (i = 0; i < nCaches; i++) {
3869 if (dev->srCache[i].object == obj &&
3870 dev->srCache[i].dirty) {
3872 || dev->srCache[i].chunkId <
3874 cache = &dev->srCache[i];
3875 lowest = cache->chunkId;
3880 if (cache && !cache->locked) {
3881 /* Write it out and free it up */
3884 yaffs_WriteChunkDataToObject(cache->object,
3890 cache->object = NULL;
3893 } while (cache && chunkWritten > 0);
3896 /* Hoosterman, disk full while writing cache out. */
3897 T(YAFFS_TRACE_ERROR,
3898 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3905 /*yaffs_FlushEntireDeviceCache(dev)
3910 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3913 int nCaches = dev->nShortOpCaches;
3916 /* Find a dirty object in the cache and flush it...
3917 * until there are no further dirty objects.
3921 for( i = 0; i < nCaches && !obj; i++) {
3922 if (dev->srCache[i].object &&
3923 dev->srCache[i].dirty)
3924 obj = dev->srCache[i].object;
3928 yaffs_FlushFilesChunkCache(obj);
3935 /* Grab us a cache chunk for use.
3936 * First look for an empty one.
3937 * Then look for the least recently used non-dirty one.
3938 * Then look for the least recently used dirty one...., flush and look again.
3940 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
3946 if (dev->nShortOpCaches > 0) {
3947 for (i = 0; i < dev->nShortOpCaches; i++) {
3948 if (!dev->srCache[i].object)
3949 return &dev->srCache[i];
3955 usage = 0; /* just to stop the compiler grizzling */
3957 for (i = 0; i < dev->nShortOpCaches; i++) {
3958 if (!dev->srCache[i].dirty &&
3959 ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
3961 usage = dev->srCache[i].lastUse;
3967 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3974 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
3976 yaffs_ChunkCache *cache;
3977 yaffs_Object *theObj;
3982 if (dev->nShortOpCaches > 0) {
3983 /* Try find a non-dirty one... */
3985 cache = yaffs_GrabChunkCacheWorker(dev);
3988 /* They were all dirty, find the last recently used object and flush
3989 * its cache, then find again.
3990 * NB what's here is not very accurate, we actually flush the object
3991 * the last recently used page.
3994 /* With locking we can't assume we can use entry zero */
4001 for (i = 0; i < dev->nShortOpCaches; i++) {
4002 if (dev->srCache[i].object &&
4003 !dev->srCache[i].locked &&
4004 (dev->srCache[i].lastUse < usage || !cache))
4006 usage = dev->srCache[i].lastUse;
4007 theObj = dev->srCache[i].object;
4008 cache = &dev->srCache[i];
4013 if (!cache || cache->dirty) {
4014 /* Flush and try again */
4015 yaffs_FlushFilesChunkCache(theObj);
4016 cache = yaffs_GrabChunkCacheWorker(dev);
4026 /* Find a cached chunk */
4027 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
4030 yaffs_Device *dev = obj->myDev;
4032 if (dev->nShortOpCaches > 0) {
4033 for (i = 0; i < dev->nShortOpCaches; i++) {
4034 if (dev->srCache[i].object == obj &&
4035 dev->srCache[i].chunkId == chunkId) {
4038 return &dev->srCache[i];
4045 /* Mark the chunk for the least recently used algorithym */
4046 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
4050 if (dev->nShortOpCaches > 0) {
4051 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4052 /* Reset the cache usages */
4054 for (i = 1; i < dev->nShortOpCaches; i++) {
4055 dev->srCache[i].lastUse = 0;
4062 cache->lastUse = dev->srLastUse;
4070 /* Invalidate a single cache page.
4071 * Do this when a whole page gets written,
4072 * ie the short cache for this page is no longer valid.
4074 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
4076 if (object->myDev->nShortOpCaches > 0) {
4077 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4080 cache->object = NULL;
4085 /* Invalidate all the cache pages associated with this object
4086 * Do this whenever ther file is deleted or resized.
4088 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
4091 yaffs_Device *dev = in->myDev;
4093 if (dev->nShortOpCaches > 0) {
4094 /* Invalidate it. */
4095 for (i = 0; i < dev->nShortOpCaches; i++) {
4096 if (dev->srCache[i].object == in) {
4097 dev->srCache[i].object = NULL;
4103 /*--------------------- Checkpointing --------------------*/
4106 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
4108 yaffs_CheckpointValidity cp;
4110 memset(&cp,0,sizeof(cp));
4112 cp.structType = sizeof(cp);
4113 cp.magic = YAFFS_MAGIC;
4114 cp.version = YAFFS_CHECKPOINT_VERSION;
4115 cp.head = (head) ? 1 : 0;
4117 return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
4121 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4123 yaffs_CheckpointValidity cp;
4126 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4129 ok = (cp.structType == sizeof(cp)) &&
4130 (cp.magic == YAFFS_MAGIC) &&
4131 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4132 (cp.head == ((head) ? 1 : 0));
4136 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4139 cp->nErasedBlocks = dev->nErasedBlocks;
4140 cp->allocationBlock = dev->allocationBlock;
4141 cp->allocationPage = dev->allocationPage;
4142 cp->nFreeChunks = dev->nFreeChunks;
4144 cp->nDeletedFiles = dev->nDeletedFiles;
4145 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4146 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4147 cp->sequenceNumber = dev->sequenceNumber;
4148 cp->oldestDirtySequence = dev->oldestDirtySequence;
4152 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4153 yaffs_CheckpointDevice *cp)
4155 dev->nErasedBlocks = cp->nErasedBlocks;
4156 dev->allocationBlock = cp->allocationBlock;
4157 dev->allocationPage = cp->allocationPage;
4158 dev->nFreeChunks = cp->nFreeChunks;
4160 dev->nDeletedFiles = cp->nDeletedFiles;
4161 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4162 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4163 dev->sequenceNumber = cp->sequenceNumber;
4164 dev->oldestDirtySequence = cp->oldestDirtySequence;
4168 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4170 yaffs_CheckpointDevice cp;
4172 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4176 /* Write device runtime values*/
4177 yaffs_DeviceToCheckpointDevice(&cp,dev);
4178 cp.structType = sizeof(cp);
4180 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4182 /* Write block info */
4184 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4185 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
4188 /* Write chunk bits */
4190 nBytes = nBlocks * dev->chunkBitmapStride;
4191 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
4197 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4199 yaffs_CheckpointDevice cp;
4201 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4205 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4209 if(cp.structType != sizeof(cp))
4213 yaffs_CheckpointDeviceToDevice(dev,&cp);
4215 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4217 ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
4221 nBytes = nBlocks * dev->chunkBitmapStride;
4223 ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
4228 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4232 cp->objectId = obj->objectId;
4233 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4234 cp->hdrChunk = obj->hdrChunk;
4235 cp->variantType = obj->variantType;
4236 cp->deleted = obj->deleted;
4237 cp->softDeleted = obj->softDeleted;
4238 cp->unlinked = obj->unlinked;
4239 cp->fake = obj->fake;
4240 cp->renameAllowed = obj->renameAllowed;
4241 cp->unlinkAllowed = obj->unlinkAllowed;
4242 cp->serial = obj->serial;
4243 cp->nDataChunks = obj->nDataChunks;
4245 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4246 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4247 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4248 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4251 static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
4254 yaffs_Object *parent;
4256 obj->objectId = cp->objectId;
4259 parent = yaffs_FindOrCreateObjectByNumber(
4262 YAFFS_OBJECT_TYPE_DIRECTORY);
4267 yaffs_AddObjectToDirectory(parent, obj);
4269 obj->hdrChunk = cp->hdrChunk;
4270 obj->variantType = cp->variantType;
4271 obj->deleted = cp->deleted;
4272 obj->softDeleted = cp->softDeleted;
4273 obj->unlinked = cp->unlinked;
4274 obj->fake = cp->fake;
4275 obj->renameAllowed = cp->renameAllowed;
4276 obj->unlinkAllowed = cp->unlinkAllowed;
4277 obj->serial = cp->serial;
4278 obj->nDataChunks = cp->nDataChunks;
4280 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4281 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4282 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4283 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4285 if(obj->hdrChunk > 0)
4286 obj->lazyLoaded = 1;
4291 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
4292 __u32 level, int chunkOffset)
4295 yaffs_Device *dev = in->myDev;
4297 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4299 if(tnodeSize < sizeof(yaffs_Tnode))
4300 tnodeSize = sizeof(yaffs_Tnode);
4306 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
4307 if (tn->internal[i]) {
4308 ok = yaffs_CheckpointTnodeWorker(in,
4311 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4314 } else if (level == 0) {
4315 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4316 /* printf("write tnode at %d\n",baseOffset); */
4317 ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
4319 ok = (yaffs_CheckpointWrite(dev,tn,tnodeSize) == tnodeSize);
4327 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4329 __u32 endMarker = ~0;
4332 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4333 ok = yaffs_CheckpointTnodeWorker(obj,
4334 obj->variant.fileVariant.top,
4335 obj->variant.fileVariant.topLevel,
4338 ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) ==
4345 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4349 yaffs_Device *dev = obj->myDev;
4350 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4353 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4355 if(tnodeSize < sizeof(yaffs_Tnode))
4356 tnodeSize = sizeof(yaffs_Tnode);
4358 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4360 while(ok && (~baseChunk)){
4362 /* Read level 0 tnode */
4365 /* printf("read tnode at %d\n",baseChunk); */
4366 tn = yaffs_GetTnodeRaw(dev);
4368 ok = (yaffs_CheckpointRead(dev,tn,tnodeSize) == tnodeSize);
4373 ok = yaffs_AddOrFindLevel0Tnode(dev,
4381 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4385 T(YAFFS_TRACE_CHECKPOINT,(
4386 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4387 nread,baseChunk,ok));
4393 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4396 yaffs_CheckpointObject cp;
4399 struct ylist_head *lh;
4402 /* Iterate through the objects in each hash entry,
4403 * dumping them to the checkpointing stream.
4406 for(i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++){
4407 ylist_for_each(lh, &dev->objectBucket[i].list) {
4409 obj = ylist_entry(lh, yaffs_Object, hashLink);
4410 if (!obj->deferedFree) {
4411 yaffs_ObjectToCheckpointObject(&cp,obj);
4412 cp.structType = sizeof(cp);
4414 T(YAFFS_TRACE_CHECKPOINT,(
4415 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
4416 cp.objectId,cp.parentId,cp.variantType,cp.hdrChunk,(unsigned) obj));
4418 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4420 if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4421 ok = yaffs_WriteCheckpointTnodes(obj);
4428 /* Dump end of list */
4429 memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
4430 cp.structType = sizeof(cp);
4433 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4438 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4441 yaffs_CheckpointObject cp;
4444 yaffs_Object *hardList = NULL;
4446 while(ok && !done) {
4447 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4448 if(cp.structType != sizeof(cp)) {
4449 T(YAFFS_TRACE_CHECKPOINT,(TSTR("struct size %d instead of %d ok %d"TENDSTR),
4450 cp.structType,sizeof(cp),ok));
4454 T(YAFFS_TRACE_CHECKPOINT,(TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4455 cp.objectId,cp.parentId,cp.variantType,cp.hdrChunk));
4457 if(ok && cp.objectId == ~0)
4460 obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
4462 yaffs_CheckpointObjectToObject(obj,&cp);
4463 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4464 ok = yaffs_ReadCheckpointTnodes(obj);
4465 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4466 obj->hardLinks.next =
4467 (struct ylist_head *)
4477 yaffs_HardlinkFixup(dev,hardList);
4482 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4484 __u32 checkpointSum;
4487 yaffs_GetCheckpointSum(dev,&checkpointSum);
4489 ok = (yaffs_CheckpointWrite(dev,&checkpointSum,sizeof(checkpointSum)) == sizeof(checkpointSum));
4497 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4499 __u32 checkpointSum0;
4500 __u32 checkpointSum1;
4503 yaffs_GetCheckpointSum(dev,&checkpointSum0);
4505 ok = (yaffs_CheckpointRead(dev,&checkpointSum1,sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4510 if(checkpointSum0 != checkpointSum1)
4517 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4522 if(dev->skipCheckpointWrite || !dev->isYaffs2){
4523 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint write" TENDSTR)));
4528 ok = yaffs_CheckpointOpen(dev,1);
4531 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4532 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
4535 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint device" TENDSTR)));
4536 ok = yaffs_WriteCheckpointDevice(dev);
4539 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint objects" TENDSTR)));
4540 ok = yaffs_WriteCheckpointObjects(dev);
4543 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4544 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
4548 ok = yaffs_WriteCheckpointSum(dev);
4552 if(!yaffs_CheckpointClose(dev))
4556 dev->isCheckpointed = 1;
4558 dev->isCheckpointed = 0;
4560 return dev->isCheckpointed;
4563 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4567 if(dev->skipCheckpointRead || !dev->isYaffs2){
4568 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint read" TENDSTR)));
4573 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
4576 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4577 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
4580 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint device" TENDSTR)));
4581 ok = yaffs_ReadCheckpointDevice(dev);
4584 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint objects" TENDSTR)));
4585 ok = yaffs_ReadCheckpointObjects(dev);
4588 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4589 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
4593 ok = yaffs_ReadCheckpointSum(dev);
4594 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint checksum %d" TENDSTR),ok));
4597 if(!yaffs_CheckpointClose(dev))
4601 dev->isCheckpointed = 1;
4603 dev->isCheckpointed = 0;
4609 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4611 if(dev->isCheckpointed ||
4612 dev->blocksInCheckpoint > 0){
4613 dev->isCheckpointed = 0;
4614 yaffs_CheckpointInvalidateStream(dev);
4615 if(dev->superBlock && dev->markSuperBlockDirty)
4616 dev->markSuperBlockDirty(dev->superBlock);
4621 int yaffs_CheckpointSave(yaffs_Device *dev)
4624 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4626 yaffs_VerifyObjects(dev);
4627 yaffs_VerifyBlocks(dev);
4628 yaffs_VerifyFreeChunks(dev);
4630 if(!dev->isCheckpointed) {
4631 yaffs_InvalidateCheckpoint(dev);
4632 yaffs_WriteCheckpointData(dev);
4635 T(YAFFS_TRACE_ALWAYS,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4637 return dev->isCheckpointed;
4640 int yaffs_CheckpointRestore(yaffs_Device *dev)
4643 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4645 retval = yaffs_ReadCheckpointData(dev);
4647 if(dev->isCheckpointed){
4648 yaffs_VerifyObjects(dev);
4649 yaffs_VerifyBlocks(dev);
4650 yaffs_VerifyFreeChunks(dev);
4653 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4658 /*--------------------- File read/write ------------------------
4659 * Read and write have very similar structures.
4660 * In general the read/write has three parts to it
4661 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4662 * Some complete chunks
4663 * An incomplete chunk to end off with
4665 * Curve-balls: the first chunk might also be the last chunk.
4668 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, loff_t offset,
4677 yaffs_ChunkCache *cache;
4684 //chunk = offset / dev->nDataBytesPerChunk + 1;
4685 //start = offset % dev->nDataBytesPerChunk;
4686 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4689 /* OK now check for the curveball where the start and end are in
4692 if ((start + n) < dev->nDataBytesPerChunk) {
4695 nToCopy = dev->nDataBytesPerChunk - start;
4698 cache = yaffs_FindChunkCache(in, chunk);
4700 /* If the chunk is already in the cache or it is less than a whole chunk
4701 * or we're using inband tags then use the cache (if there is caching)
4702 * else bypass the cache.
4704 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4705 if (dev->nShortOpCaches > 0) {
4707 /* If we can't find the data in the cache, then load it up. */
4710 cache = yaffs_GrabChunkCache(in->myDev);
4712 cache->chunkId = chunk;
4715 yaffs_ReadChunkDataFromObject(in, chunk,
4721 yaffs_UseChunkCache(dev, cache, 0);
4725 #ifdef CONFIG_YAFFS_WINCE
4726 yfsd_UnlockYAFFS(TRUE);
4728 memcpy(buffer, &cache->data[start], nToCopy);
4730 #ifdef CONFIG_YAFFS_WINCE
4731 yfsd_LockYAFFS(TRUE);
4735 /* Read into the local buffer then copy..*/
4738 yaffs_GetTempBuffer(dev, __LINE__);
4739 yaffs_ReadChunkDataFromObject(in, chunk,
4741 #ifdef CONFIG_YAFFS_WINCE
4742 yfsd_UnlockYAFFS(TRUE);
4744 memcpy(buffer, &localBuffer[start], nToCopy);
4746 #ifdef CONFIG_YAFFS_WINCE
4747 yfsd_LockYAFFS(TRUE);
4749 yaffs_ReleaseTempBuffer(dev, localBuffer,
4754 #ifdef CONFIG_YAFFS_WINCE
4755 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4757 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4758 * This is because we otherwise screw up WinCE's memory mapper
4760 yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
4762 #ifdef CONFIG_YAFFS_WINCE
4763 yfsd_UnlockYAFFS(TRUE);
4765 memcpy(buffer, localBuffer, dev->nDataBytesPerChunk);
4767 #ifdef CONFIG_YAFFS_WINCE
4768 yfsd_LockYAFFS(TRUE);
4769 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4773 /* A full chunk. Read directly into the supplied buffer. */
4774 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4788 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, loff_t offset,
4789 int nBytes, int writeThrough)
4798 int startOfWrite = offset;
4799 int chunkWritten = 0;
4806 while (n > 0 && chunkWritten >= 0) {
4807 //chunk = offset / dev->nDataBytesPerChunk + 1;
4808 //start = offset % dev->nDataBytesPerChunk;
4809 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4812 /* OK now check for the curveball where the start and end are in
4816 if ((start + n) < dev->nDataBytesPerChunk) {
4819 /* Now folks, to calculate how many bytes to write back....
4820 * If we're overwriting and not writing to then end of file then
4821 * we need to write back as much as was there before.
4825 in->variant.fileVariant.fileSize -
4826 ((chunk - 1) * dev->nDataBytesPerChunk);
4828 if (nBytesRead > dev->nDataBytesPerChunk) {
4829 nBytesRead = dev->nDataBytesPerChunk;
4834 (start + n)) ? nBytesRead : (start + n);
4837 nToCopy = dev->nDataBytesPerChunk - start;
4838 nToWriteBack = dev->nDataBytesPerChunk;
4841 if (nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4842 /* An incomplete start or end chunk (or maybe both start and end chunk),
4843 * or we're using inband tags, so we want to use the cache buffers.
4845 if (dev->nShortOpCaches > 0) {
4846 yaffs_ChunkCache *cache;
4847 /* If we can't find the data in the cache, then load the cache */
4848 cache = yaffs_FindChunkCache(in, chunk);
4851 && yaffs_CheckSpaceForAllocation(in->
4853 cache = yaffs_GrabChunkCache(in->myDev);
4855 cache->chunkId = chunk;
4858 yaffs_ReadChunkDataFromObject(in, chunk,
4864 !yaffs_CheckSpaceForAllocation(in->myDev)){
4865 /* Drop the cache if it was a read cache item and
4866 * no space check has been made for it.
4872 yaffs_UseChunkCache(dev, cache, 1);
4874 #ifdef CONFIG_YAFFS_WINCE
4875 yfsd_UnlockYAFFS(TRUE);
4878 memcpy(&cache->data[start], buffer,
4881 #ifdef CONFIG_YAFFS_WINCE
4882 yfsd_LockYAFFS(TRUE);
4885 cache->nBytes = nToWriteBack;
4889 yaffs_WriteChunkDataToObject
4892 cache->data, cache->nBytes,
4898 chunkWritten = -1; /* fail the write */
4901 /* An incomplete start or end chunk (or maybe both start and end chunk)
4902 * Read into the local buffer then copy, then copy over and write back.
4906 yaffs_GetTempBuffer(dev, __LINE__);
4908 yaffs_ReadChunkDataFromObject(in, chunk,
4911 #ifdef CONFIG_YAFFS_WINCE
4912 yfsd_UnlockYAFFS(TRUE);
4915 memcpy(&localBuffer[start], buffer, nToCopy);
4917 #ifdef CONFIG_YAFFS_WINCE
4918 yfsd_LockYAFFS(TRUE);
4921 yaffs_WriteChunkDataToObject(in, chunk,
4926 yaffs_ReleaseTempBuffer(dev, localBuffer,
4932 /* A full chunk. Write directly from the supplied buffer. */
4934 #ifdef CONFIG_YAFFS_WINCE
4935 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4936 * This is because we otherwise screw up WinCE's memory mapper
4938 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4939 #ifdef CONFIG_YAFFS_WINCE
4940 yfsd_UnlockYAFFS(TRUE);
4942 memcpy(localBuffer, buffer, dev->nDataBytesPerChunk);
4943 #ifdef CONFIG_YAFFS_WINCE
4944 yfsd_LockYAFFS(TRUE);
4947 yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
4948 dev->nDataBytesPerChunk,
4950 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4954 yaffs_WriteChunkDataToObject(in, chunk, buffer,
4955 dev->nDataBytesPerChunk,
4958 /* Since we've overwritten the cached data, we better invalidate it. */
4959 yaffs_InvalidateChunkCache(in, chunk);
4962 if (chunkWritten >= 0) {
4971 /* Update file object */
4973 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
4974 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4983 /* ---------------------- File resizing stuff ------------------ */
4985 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
4988 yaffs_Device *dev = in->myDev;
4989 int oldFileSize = in->variant.fileVariant.fileSize;
4991 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
4993 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
4994 dev->nDataBytesPerChunk;
4998 /* Delete backwards so that we don't end up with holes if
4999 * power is lost part-way through the operation.
5001 for (i = lastDel; i >= startDel; i--) {
5002 /* NB this could be optimised somewhat,
5003 * eg. could retrieve the tags and write them without
5004 * using yaffs_DeleteChunk
5007 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5010 (dev->internalStartBlock * dev->nChunksPerBlock)
5012 ((dev->internalEndBlock +
5013 1) * dev->nChunksPerBlock)) {
5014 T(YAFFS_TRACE_ALWAYS,
5015 (TSTR("Found daft chunkId %d for %d" TENDSTR),
5019 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5026 int yaffs_ResizeFile(yaffs_Object * in, loff_t newSize)
5029 int oldFileSize = in->variant.fileVariant.fileSize;
5030 __u32 newSizeOfPartialChunk;
5033 yaffs_Device *dev = in->myDev;
5035 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5037 yaffs_FlushFilesChunkCache(in);
5038 yaffs_InvalidateWholeChunkCache(in);
5040 yaffs_CheckGarbageCollection(dev);
5042 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
5046 if (newSize == oldFileSize) {
5050 if (newSize < oldFileSize) {
5052 yaffs_PruneResizedChunks(in, newSize);
5054 if (newSizeOfPartialChunk != 0) {
5055 int lastChunk = 1 + newFullChunks;
5057 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5059 /* Got to read and rewrite the last chunk with its new size and zero pad */
5060 yaffs_ReadChunkDataFromObject(in, lastChunk,
5063 memset(localBuffer + newSizeOfPartialChunk, 0,
5064 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5066 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5067 newSizeOfPartialChunk, 1);
5069 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5072 in->variant.fileVariant.fileSize = newSize;
5074 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5076 /* newsSize > oldFileSize */
5077 in->variant.fileVariant.fileSize = newSize;
5082 /* Write a new object header.
5083 * show we've shrunk the file, if need be
5084 * Do this only if the file is not in the deleted directories.
5086 if (in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5087 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
5088 yaffs_UpdateObjectHeader(in, NULL, 0,
5089 (newSize < oldFileSize) ? 1 : 0, 0);
5095 loff_t yaffs_GetFileSize(yaffs_Object * obj)
5097 obj = yaffs_GetEquivalentObject(obj);
5099 switch (obj->variantType) {
5100 case YAFFS_OBJECT_TYPE_FILE:
5101 return obj->variant.fileVariant.fileSize;
5102 case YAFFS_OBJECT_TYPE_SYMLINK:
5103 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5111 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
5115 yaffs_FlushFilesChunkCache(in);
5117 #ifdef CONFIG_YAFFS_WINCE
5118 yfsd_WinFileTimeNow(in->win_mtime);
5121 in->yst_mtime = Y_CURRENT_TIME;
5127 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5128 0) ? YAFFS_OK : YAFFS_FAIL;
5137 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
5140 /* First off, invalidate the file's data in the cache, without flushing. */
5141 yaffs_InvalidateWholeChunkCache(in);
5143 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5144 /* Move to the unlinked directory so we have a record that it was deleted. */
5145 yaffs_ChangeObjectName(in, in->myDev->deletedDir,_Y("deleted"), 0, 0);
5149 yaffs_RemoveObjectFromDirectory(in);
5150 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5153 yaffs_FreeObject(in);
5158 /* yaffs_DeleteFile deletes the whole file data
5159 * and the inode associated with the file.
5160 * It does not delete the links associated with the file.
5162 static int yaffs_UnlinkFile(yaffs_Object * in)
5166 int immediateDeletion = 0;
5171 immediateDeletion = 1;
5175 if (in->inUse <= 0) {
5176 immediateDeletion = 1;
5180 if (immediateDeletion) {
5182 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5183 _Y("deleted"), 0, 0);
5184 T(YAFFS_TRACE_TRACING,
5185 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5188 in->myDev->nDeletedFiles++;
5189 if (0 && in->myDev->isYaffs2) {
5190 yaffs_ResizeFile(in, 0);
5192 yaffs_SoftDeleteFile(in);
5195 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5196 _Y("unlinked"), 0, 0);
5203 int yaffs_DeleteFile(yaffs_Object * in)
5205 int retVal = YAFFS_OK;
5207 if (in->nDataChunks > 0) {
5208 /* Use soft deletion if there is data in the file */
5209 if (!in->unlinked) {
5210 retVal = yaffs_UnlinkFile(in);
5212 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5214 in->myDev->nDeletedFiles++;
5215 yaffs_SoftDeleteFile(in);
5217 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
5219 /* The file has no data chunks so we toss it immediately */
5220 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5221 in->variant.fileVariant.top = NULL;
5222 yaffs_DoGenericObjectDeletion(in);
5228 static int yaffs_DeleteDirectory(yaffs_Object * in)
5230 /* First check that the directory is empty. */
5231 if (ylist_empty(&in->variant.directoryVariant.children)) {
5232 return yaffs_DoGenericObjectDeletion(in);
5239 static int yaffs_DeleteSymLink(yaffs_Object * in)
5241 YFREE(in->variant.symLinkVariant.alias);
5243 return yaffs_DoGenericObjectDeletion(in);
5246 static int yaffs_DeleteHardLink(yaffs_Object * in)
5248 /* remove this hardlink from the list assocaited with the equivalent
5251 ylist_del(&in->hardLinks);
5252 return yaffs_DoGenericObjectDeletion(in);
5255 static void yaffs_DestroyObject(yaffs_Object * obj)
5257 switch (obj->variantType) {
5258 case YAFFS_OBJECT_TYPE_FILE:
5259 yaffs_DeleteFile(obj);
5261 case YAFFS_OBJECT_TYPE_DIRECTORY:
5262 yaffs_DeleteDirectory(obj);
5264 case YAFFS_OBJECT_TYPE_SYMLINK:
5265 yaffs_DeleteSymLink(obj);
5267 case YAFFS_OBJECT_TYPE_HARDLINK:
5268 yaffs_DeleteHardLink(obj);
5270 case YAFFS_OBJECT_TYPE_SPECIAL:
5271 yaffs_DoGenericObjectDeletion(obj);
5273 case YAFFS_OBJECT_TYPE_UNKNOWN:
5274 break; /* should not happen. */
5278 static int yaffs_UnlinkWorker(yaffs_Object * obj)
5281 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5282 return yaffs_DeleteHardLink(obj);
5283 } else if (!ylist_empty(&obj->hardLinks)) {
5284 /* Curve ball: We're unlinking an object that has a hardlink.
5286 * This problem arises because we are not strictly following
5287 * The Linux link/inode model.
5289 * We can't really delete the object.
5290 * Instead, we do the following:
5291 * - Select a hardlink.
5292 * - Unhook it from the hard links
5293 * - Unhook it from its parent directory (so that the rename can work)
5294 * - Rename the object to the hardlink's name.
5295 * - Delete the hardlink
5300 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5302 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5304 ylist_del_init(&hl->hardLinks);
5305 ylist_del_init(&hl->siblings);
5307 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5309 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
5311 if (retVal == YAFFS_OK) {
5312 retVal = yaffs_DoGenericObjectDeletion(hl);
5317 switch (obj->variantType) {
5318 case YAFFS_OBJECT_TYPE_FILE:
5319 return yaffs_UnlinkFile(obj);
5321 case YAFFS_OBJECT_TYPE_DIRECTORY:
5322 return yaffs_DeleteDirectory(obj);
5324 case YAFFS_OBJECT_TYPE_SYMLINK:
5325 return yaffs_DeleteSymLink(obj);
5327 case YAFFS_OBJECT_TYPE_SPECIAL:
5328 return yaffs_DoGenericObjectDeletion(obj);
5330 case YAFFS_OBJECT_TYPE_HARDLINK:
5331 case YAFFS_OBJECT_TYPE_UNKNOWN:
5339 static int yaffs_UnlinkObject( yaffs_Object *obj)
5342 if (obj && obj->unlinkAllowed) {
5343 return yaffs_UnlinkWorker(obj);
5349 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
5353 obj = yaffs_FindObjectByName(dir, name);
5354 return yaffs_UnlinkObject(obj);
5357 /*----------------------- Initialisation Scanning ---------------------- */
5359 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
5360 int backwardScanning)
5364 if (!backwardScanning) {
5365 /* Handle YAFFS1 forward scanning case
5366 * For YAFFS1 we always do the deletion
5370 /* Handle YAFFS2 case (backward scanning)
5371 * If the shadowed object exists then ignore.
5373 if (yaffs_FindObjectByNumber(dev, objId)) {
5378 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5379 * We put it in unlinked dir to be cleaned up after the scanning
5382 yaffs_FindOrCreateObjectByNumber(dev, objId,
5383 YAFFS_OBJECT_TYPE_FILE);
5384 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5385 obj->variant.fileVariant.shrinkSize = 0;
5386 obj->valid = 1; /* So that we don't read any other info for this file */
5396 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5403 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5405 in = yaffs_FindObjectByNumber(dev,
5406 hl->variant.hardLinkVariant.
5407 equivalentObjectId);
5410 /* Add the hardlink pointers */
5411 hl->variant.hardLinkVariant.equivalentObject = in;
5412 ylist_add(&hl->hardLinks, &in->hardLinks);
5414 /* Todo Need to report/handle this better.
5415 * Got a problem... hardlink to a non-existant object
5417 hl->variant.hardLinkVariant.equivalentObject = NULL;
5418 YINIT_LIST_HEAD(&hl->hardLinks);
5430 static int ybicmp(const void *a, const void *b){
5431 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5432 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5433 register int ablock = ((yaffs_BlockIndex *)a)->block;
5434 register int bblock = ((yaffs_BlockIndex *)b)->block;
5436 return ablock - bblock;
5443 struct yaffs_ShadowFixerStruct {
5446 struct yaffs_ShadowFixerStruct *next;
5449 static int yaffs_Scan(yaffs_Device * dev)
5451 yaffs_ExtendedTags tags;
5461 yaffs_BlockState state;
5462 yaffs_Object *hardList = NULL;
5463 yaffs_BlockInfo *bi;
5464 __u32 sequenceNumber;
5465 yaffs_ObjectHeader *oh;
5467 yaffs_Object *parent;
5469 int alloc_failed = 0;
5471 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5477 //TODO Throw all the yaffs2 stuuf out of yaffs_Scan since it is only for yaffs1 format.
5480 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5481 dev->internalStartBlock, dev->internalEndBlock));
5483 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5485 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5487 /* Scan all the blocks to determine their state */
5488 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5489 bi = yaffs_GetBlockInfo(dev, blk);
5490 yaffs_ClearChunkBits(dev, blk);
5492 bi->softDeletions = 0;
5494 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5496 bi->blockState = state;
5497 bi->sequenceNumber = sequenceNumber;
5499 T(YAFFS_TRACE_SCAN_DEBUG,
5500 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5501 state, sequenceNumber));
5503 if (state == YAFFS_BLOCK_STATE_DEAD) {
5504 T(YAFFS_TRACE_BAD_BLOCKS,
5505 (TSTR("block %d is bad" TENDSTR), blk));
5506 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5507 T(YAFFS_TRACE_SCAN_DEBUG,
5508 (TSTR("Block empty " TENDSTR)));
5509 dev->nErasedBlocks++;
5510 dev->nFreeChunks += dev->nChunksPerBlock;
5514 startIterator = dev->internalStartBlock;
5515 endIterator = dev->internalEndBlock;
5517 /* For each block.... */
5518 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5525 blk = blockIterator;
5527 bi = yaffs_GetBlockInfo(dev, blk);
5528 state = bi->blockState;
5532 /* For each chunk in each block that needs scanning....*/
5533 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5534 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5535 /* Read the tags and decide what to do */
5536 chunk = blk * dev->nChunksPerBlock + c;
5538 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5541 /* Let's have a good look at this chunk... */
5543 if (!dev->isYaffs2 && tags.chunkDeleted) {
5549 /*T((" %d %d deleted\n",blk,c)); */
5550 } else if (!tags.chunkUsed) {
5551 /* An unassigned chunk in the block
5552 * This means that either the block is empty or
5553 * this is the one being allocated from
5557 /* We're looking at the first chunk in the block so the block is unused */
5558 state = YAFFS_BLOCK_STATE_EMPTY;
5559 dev->nErasedBlocks++;
5561 /* this is the block being allocated from */
5564 (" Allocating from %d %d" TENDSTR),
5566 state = YAFFS_BLOCK_STATE_ALLOCATING;
5567 dev->allocationBlock = blk;
5568 dev->allocationPage = c;
5569 dev->allocationBlockFinder = blk;
5570 /* Set it to here to encourage the allocator to go forth from here. */
5572 /* Yaffs2 sanity check:
5573 * This should be the one with the highest sequence number
5576 && (dev->sequenceNumber !=
5577 bi->sequenceNumber)) {
5578 T(YAFFS_TRACE_ALWAYS,
5580 ("yaffs: Allocation block %d was not highest sequence id: block seq = %d, dev seq = %d"
5581 TENDSTR), blk,bi->sequenceNumber,dev->sequenceNumber));
5585 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5586 } else if (tags.chunkId > 0) {
5587 /* chunkId > 0 so it is a data chunk... */
5588 unsigned int endpos;
5590 yaffs_SetChunkBit(dev, blk, c);
5593 in = yaffs_FindOrCreateObjectByNumber(dev,
5596 YAFFS_OBJECT_TYPE_FILE);
5597 /* PutChunkIntoFile checks for a clash (two data chunks with
5598 * the same chunkId).
5605 if(!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,1))
5610 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5613 in->variantType == YAFFS_OBJECT_TYPE_FILE
5614 && in->variant.fileVariant.scannedFileSize <
5616 in->variant.fileVariant.
5617 scannedFileSize = endpos;
5618 if (!dev->useHeaderFileSize) {
5619 in->variant.fileVariant.
5621 in->variant.fileVariant.
5626 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
5628 /* chunkId == 0, so it is an ObjectHeader.
5629 * Thus, we read in the object header and make the object
5631 yaffs_SetChunkBit(dev, blk, c);
5634 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5638 oh = (yaffs_ObjectHeader *) chunkData;
5640 in = yaffs_FindObjectByNumber(dev,
5642 if (in && in->variantType != oh->type) {
5643 /* This should not happen, but somehow
5644 * Wev'e ended up with an objectId that has been reused but not yet
5645 * deleted, and worse still it has changed type. Delete the old object.
5648 yaffs_DestroyObject(in);
5653 in = yaffs_FindOrCreateObjectByNumber(dev,
5661 if (in && oh->shadowsObject > 0) {
5663 struct yaffs_ShadowFixerStruct *fixer;
5664 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
5666 fixer-> next = shadowFixerList;
5667 shadowFixerList = fixer;
5668 fixer->objectId = tags.objectId;
5669 fixer->shadowedId = oh->shadowsObject;
5674 if (in && in->valid) {
5675 /* We have already filled this one. We have a duplicate and need to resolve it. */
5677 unsigned existingSerial = in->serial;
5678 unsigned newSerial = tags.serialNumber;
5680 if (dev->isYaffs2 ||
5681 ((existingSerial + 1) & 3) ==
5683 /* Use new one - destroy the exisiting one */
5684 yaffs_DeleteChunk(dev,
5689 /* Use existing - destroy this one. */
5690 yaffs_DeleteChunk(dev, chunk, 1,
5695 if (in && !in->valid &&
5696 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5697 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5698 /* We only load some info, don't fiddle with directory structure */
5700 in->variantType = oh->type;
5702 in->yst_mode = oh->yst_mode;
5703 #ifdef CONFIG_YAFFS_WINCE
5704 in->win_atime[0] = oh->win_atime[0];
5705 in->win_ctime[0] = oh->win_ctime[0];
5706 in->win_mtime[0] = oh->win_mtime[0];
5707 in->win_atime[1] = oh->win_atime[1];
5708 in->win_ctime[1] = oh->win_ctime[1];
5709 in->win_mtime[1] = oh->win_mtime[1];
5711 in->yst_uid = oh->yst_uid;
5712 in->yst_gid = oh->yst_gid;
5713 in->yst_atime = oh->yst_atime;
5714 in->yst_mtime = oh->yst_mtime;
5715 in->yst_ctime = oh->yst_ctime;
5716 in->yst_rdev = oh->yst_rdev;
5718 in->hdrChunk = chunk;
5720 } else if (in && !in->valid) {
5721 /* we need to load this info */
5724 in->variantType = oh->type;
5726 in->yst_mode = oh->yst_mode;
5727 #ifdef CONFIG_YAFFS_WINCE
5728 in->win_atime[0] = oh->win_atime[0];
5729 in->win_ctime[0] = oh->win_ctime[0];
5730 in->win_mtime[0] = oh->win_mtime[0];
5731 in->win_atime[1] = oh->win_atime[1];
5732 in->win_ctime[1] = oh->win_ctime[1];
5733 in->win_mtime[1] = oh->win_mtime[1];
5735 in->yst_uid = oh->yst_uid;
5736 in->yst_gid = oh->yst_gid;
5737 in->yst_atime = oh->yst_atime;
5738 in->yst_mtime = oh->yst_mtime;
5739 in->yst_ctime = oh->yst_ctime;
5740 in->yst_rdev = oh->yst_rdev;
5742 in->hdrChunk = chunk;
5744 yaffs_SetObjectName(in, oh->name);
5747 /* directory stuff...
5752 yaffs_FindOrCreateObjectByNumber
5753 (dev, oh->parentObjectId,
5754 YAFFS_OBJECT_TYPE_DIRECTORY);
5755 if (parent->variantType ==
5756 YAFFS_OBJECT_TYPE_UNKNOWN) {
5757 /* Set up as a directory */
5758 parent->variantType =
5759 YAFFS_OBJECT_TYPE_DIRECTORY;
5760 YINIT_LIST_HEAD(&parent->variant.
5763 } else if (parent->variantType !=
5764 YAFFS_OBJECT_TYPE_DIRECTORY)
5766 /* Hoosterman, another problem....
5767 * We're trying to use a non-directory as a directory
5770 T(YAFFS_TRACE_ERROR,
5772 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
5774 parent = dev->lostNFoundDir;
5777 yaffs_AddObjectToDirectory(parent, in);
5779 if (0 && (parent == dev->deletedDir ||
5780 parent == dev->unlinkedDir)) {
5781 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
5782 dev->nDeletedFiles++;
5784 /* Note re hardlinks.
5785 * Since we might scan a hardlink before its equivalent object is scanned
5786 * we put them all in a list.
5787 * After scanning is complete, we should have all the objects, so we run through this
5788 * list and fix up all the chains.
5791 switch (in->variantType) {
5792 case YAFFS_OBJECT_TYPE_UNKNOWN:
5793 /* Todo got a problem */
5795 case YAFFS_OBJECT_TYPE_FILE:
5798 /* Prune back the shrunken chunks */
5799 yaffs_PruneResizedChunks
5801 /* Mark the block as having a shrinkHeader */
5802 bi->hasShrinkHeader = 1;
5805 if (dev->useHeaderFileSize)
5807 in->variant.fileVariant.
5812 case YAFFS_OBJECT_TYPE_HARDLINK:
5813 in->variant.hardLinkVariant.
5814 equivalentObjectId =
5815 oh->equivalentObjectId;
5816 in->hardLinks.next =
5817 (struct ylist_head *)
5821 case YAFFS_OBJECT_TYPE_DIRECTORY:
5824 case YAFFS_OBJECT_TYPE_SPECIAL:
5827 case YAFFS_OBJECT_TYPE_SYMLINK:
5828 in->variant.symLinkVariant.alias =
5829 yaffs_CloneString(oh->alias);
5830 if(!in->variant.symLinkVariant.alias)
5835 if (parent == dev->deletedDir) {
5836 yaffs_DestroyObject(in);
5837 bi->hasShrinkHeader = 1;
5843 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5844 /* If we got this far while scanning, then the block is fully allocated.*/
5845 state = YAFFS_BLOCK_STATE_FULL;
5848 bi->blockState = state;
5850 /* Now let's see if it was dirty */
5851 if (bi->pagesInUse == 0 &&
5852 !bi->hasShrinkHeader &&
5853 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5854 yaffs_BlockBecameDirty(dev, blk);
5860 /* Ok, we've done all the scanning.
5861 * Fix up the hard link chains.
5862 * We should now have scanned all the objects, now it's time to add these
5866 yaffs_HardlinkFixup(dev,hardList);
5868 /* Handle the unlinked files. Since they were left in an unlinked state we should
5872 struct ylist_head *i;
5873 struct ylist_head *n;
5876 /* Soft delete all the unlinked files */
5877 ylist_for_each_safe(i, n,
5878 &dev->unlinkedDir->variant.directoryVariant.
5881 l = ylist_entry(i, yaffs_Object, siblings);
5882 yaffs_DestroyObject(l);
5887 /* Fix up any shadowed objects */
5889 struct yaffs_ShadowFixerStruct *fixer;
5892 while(shadowFixerList){
5893 fixer = shadowFixerList;
5894 shadowFixerList = fixer->next;
5895 /* Complete the rename transaction by deleting the shadowed object
5896 * then setting the object header to unshadowed.
5898 obj = yaffs_FindObjectByNumber(dev,fixer->shadowedId);
5900 yaffs_DestroyObject(obj);
5902 obj = yaffs_FindObjectByNumber(dev,fixer->objectId);
5904 yaffs_UpdateObjectHeader(obj,NULL,1,0,0);
5911 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5917 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5923 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5926 yaffs_ObjectHeader *oh;
5927 yaffs_Device *dev = in->myDev;
5928 yaffs_ExtendedTags tags;
5930 int alloc_failed = 0;
5936 T(YAFFS_TRACE_SCAN,(TSTR("details for object %d %s loaded" TENDSTR),
5938 in->lazyLoaded ? "not yet" : "already"));
5941 if(in->lazyLoaded && in->hdrChunk > 0){
5943 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5945 result = yaffs_ReadChunkWithTagsFromNAND(dev,in->hdrChunk,chunkData,&tags);
5946 oh = (yaffs_ObjectHeader *) chunkData;
5948 in->yst_mode = oh->yst_mode;
5949 #ifdef CONFIG_YAFFS_WINCE
5950 in->win_atime[0] = oh->win_atime[0];
5951 in->win_ctime[0] = oh->win_ctime[0];
5952 in->win_mtime[0] = oh->win_mtime[0];
5953 in->win_atime[1] = oh->win_atime[1];
5954 in->win_ctime[1] = oh->win_ctime[1];
5955 in->win_mtime[1] = oh->win_mtime[1];
5957 in->yst_uid = oh->yst_uid;
5958 in->yst_gid = oh->yst_gid;
5959 in->yst_atime = oh->yst_atime;
5960 in->yst_mtime = oh->yst_mtime;
5961 in->yst_ctime = oh->yst_ctime;
5962 in->yst_rdev = oh->yst_rdev;
5965 yaffs_SetObjectName(in, oh->name);
5967 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
5968 in->variant.symLinkVariant.alias =
5969 yaffs_CloneString(oh->alias);
5970 if(!in->variant.symLinkVariant.alias)
5971 alloc_failed = 1; /* Not returned to caller */
5974 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
5978 static int yaffs_ScanBackwards(yaffs_Device * dev)
5980 yaffs_ExtendedTags tags;
5985 int nBlocksToScan = 0;
5991 yaffs_BlockState state;
5992 yaffs_Object *hardList = NULL;
5993 yaffs_BlockInfo *bi;
5994 __u32 sequenceNumber;
5995 yaffs_ObjectHeader *oh;
5997 yaffs_Object *parent;
5998 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6004 int foundChunksInBlock;
6005 int equivalentObjectId;
6006 int alloc_failed = 0;
6009 yaffs_BlockIndex *blockIndex = NULL;
6010 int altBlockIndex = 0;
6012 if (!dev->isYaffs2) {
6014 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6020 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
6021 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6024 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6026 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6029 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6035 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6039 dev->blocksInCheckpoint = 0;
6041 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6043 /* Scan all the blocks to determine their state */
6044 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6045 bi = yaffs_GetBlockInfo(dev, blk);
6046 yaffs_ClearChunkBits(dev, blk);
6048 bi->softDeletions = 0;
6050 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6052 bi->blockState = state;
6053 bi->sequenceNumber = sequenceNumber;
6055 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6056 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6058 T(YAFFS_TRACE_SCAN_DEBUG,
6059 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6060 state, sequenceNumber));
6063 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
6064 dev->blocksInCheckpoint++;
6066 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6067 T(YAFFS_TRACE_BAD_BLOCKS,
6068 (TSTR("block %d is bad" TENDSTR), blk));
6069 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6070 T(YAFFS_TRACE_SCAN_DEBUG,
6071 (TSTR("Block empty " TENDSTR)));
6072 dev->nErasedBlocks++;
6073 dev->nFreeChunks += dev->nChunksPerBlock;
6074 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6076 /* Determine the highest sequence number */
6077 if (dev->isYaffs2 &&
6078 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6079 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6081 blockIndex[nBlocksToScan].seq = sequenceNumber;
6082 blockIndex[nBlocksToScan].block = blk;
6086 if (sequenceNumber >= dev->sequenceNumber) {
6087 dev->sequenceNumber = sequenceNumber;
6089 } else if (dev->isYaffs2) {
6090 /* TODO: Nasty sequence number! */
6093 ("Block scanning block %d has bad sequence number %d"
6094 TENDSTR), blk, sequenceNumber));
6101 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6107 /* Sort the blocks */
6108 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6110 /* Use qsort now. */
6111 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6115 /* Dungy old bubble sort... */
6117 yaffs_BlockIndex temp;
6121 for (i = 0; i < nBlocksToScan; i++)
6122 for (j = i + 1; j < nBlocksToScan; j++)
6123 if (blockIndex[i].seq > blockIndex[j].seq) {
6124 temp = blockIndex[j];
6125 blockIndex[j] = blockIndex[i];
6126 blockIndex[i] = temp;
6133 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6135 /* Now scan the blocks looking at the data. */
6137 endIterator = nBlocksToScan - 1;
6138 T(YAFFS_TRACE_SCAN_DEBUG,
6139 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6141 /* For each block.... backwards */
6142 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6144 /* Cooperative multitasking! This loop can run for so
6145 long that watchdog timers expire. */
6148 /* get the block to scan in the correct order */
6149 blk = blockIndex[blockIterator].block;
6151 bi = yaffs_GetBlockInfo(dev, blk);
6154 state = bi->blockState;
6158 /* For each chunk in each block that needs scanning.... */
6159 foundChunksInBlock = 0;
6160 for (c = dev->nChunksPerBlock - 1;
6161 !alloc_failed && c >= 0 &&
6162 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6163 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6164 /* Scan backwards...
6165 * Read the tags and decide what to do
6168 chunk = blk * dev->nChunksPerBlock + c;
6170 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6173 /* Let's have a good look at this chunk... */
6175 if (!tags.chunkUsed) {
6176 /* An unassigned chunk in the block.
6177 * If there are used chunks after this one, then
6178 * it is a chunk that was skipped due to failing the erased
6179 * check. Just skip it so that it can be deleted.
6180 * But, more typically, We get here when this is an unallocated
6181 * chunk and his means that either the block is empty or
6182 * this is the one being allocated from
6185 if(foundChunksInBlock)
6187 /* This is a chunk that was skipped due to failing the erased check */
6189 } else if (c == 0) {
6190 /* We're looking at the first chunk in the block so the block is unused */
6191 state = YAFFS_BLOCK_STATE_EMPTY;
6192 dev->nErasedBlocks++;
6194 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6195 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6196 if(dev->sequenceNumber == bi->sequenceNumber) {
6197 /* this is the block being allocated from */
6201 (" Allocating from %d %d"
6204 state = YAFFS_BLOCK_STATE_ALLOCATING;
6205 dev->allocationBlock = blk;
6206 dev->allocationPage = c;
6207 dev->allocationBlockFinder = blk;
6210 /* This is a partially written block that is not
6211 * the current allocation block. This block must have
6212 * had a write failure, so set up for retirement.
6215 bi->needsRetiring = 1;
6216 bi->gcPrioritise = 1;
6218 T(YAFFS_TRACE_ALWAYS,
6219 (TSTR("Partially written block %d being set for retirement" TENDSTR),
6229 } else if (tags.chunkId > 0) {
6230 /* chunkId > 0 so it is a data chunk... */
6231 unsigned int endpos;
6233 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6235 foundChunksInBlock = 1;
6238 yaffs_SetChunkBit(dev, blk, c);
6241 in = yaffs_FindOrCreateObjectByNumber(dev,
6244 YAFFS_OBJECT_TYPE_FILE);
6251 in->variantType == YAFFS_OBJECT_TYPE_FILE
6253 in->variant.fileVariant.shrinkSize) {
6254 /* This has not been invalidated by a resize */
6255 if(!yaffs_PutChunkIntoFile(in, tags.chunkId,
6260 /* File size is calculated by looking at the data chunks if we have not
6261 * seen an object header yet. Stop this practice once we find an object header.
6265 1) * dev->nDataBytesPerChunk +
6268 if (!in->valid && /* have not got an object header yet */
6269 in->variant.fileVariant.
6270 scannedFileSize < endpos) {
6271 in->variant.fileVariant.
6272 scannedFileSize = endpos;
6273 in->variant.fileVariant.
6275 in->variant.fileVariant.
6280 /* This chunk has been invalidated by a resize, so delete */
6281 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6285 /* chunkId == 0, so it is an ObjectHeader.
6286 * Thus, we read in the object header and make the object
6288 foundChunksInBlock = 1;
6290 yaffs_SetChunkBit(dev, blk, c);
6296 if (tags.extraHeaderInfoAvailable) {
6297 in = yaffs_FindOrCreateObjectByNumber
6298 (dev, tags.objectId,
6299 tags.extraObjectType);
6303 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
6306 tags.extraShadows ||
6308 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6309 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
6312 /* If we don't have valid info then we need to read the chunk
6313 * TODO In future we can probably defer reading the chunk and
6314 * living with invalid data until needed.
6317 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6322 oh = (yaffs_ObjectHeader *) chunkData;
6324 if(dev->inbandTags){
6325 /* Fix up the header if they got corrupted by inband tags */
6326 oh->shadowsObject = oh->inbandShadowsObject;
6327 oh->isShrink = oh->inbandIsShrink;
6331 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6336 /* TODO Hoosterman we have a problem! */
6337 T(YAFFS_TRACE_ERROR,
6339 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6340 TENDSTR), tags.objectId, chunk));
6345 /* We have already filled this one.
6346 * We have a duplicate that will be discarded, but
6347 * we first have to suck out resize info if it is a file.
6350 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6352 oh-> type == YAFFS_OBJECT_TYPE_FILE)||
6353 (tags.extraHeaderInfoAvailable &&
6354 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
6357 (oh) ? oh->fileSize : tags.
6359 __u32 parentObjectId =
6361 parentObjectId : tags.
6362 extraParentObjectId;
6364 (oh) ? oh->isShrink : tags.
6365 extraIsShrinkHeader;
6367 /* If it is deleted (unlinked at start also means deleted)
6368 * we treat the file size as being zeroed at this point.
6370 if (parentObjectId ==
6371 YAFFS_OBJECTID_DELETED
6372 || parentObjectId ==
6373 YAFFS_OBJECTID_UNLINKED) {
6379 in->variant.fileVariant.
6380 shrinkSize > thisSize) {
6381 in->variant.fileVariant.
6387 bi->hasShrinkHeader = 1;
6391 /* Use existing - destroy this one. */
6392 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6397 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6399 YAFFS_OBJECTID_LOSTNFOUND)) {
6400 /* We only load some info, don't fiddle with directory structure */
6404 in->variantType = oh->type;
6406 in->yst_mode = oh->yst_mode;
6407 #ifdef CONFIG_YAFFS_WINCE
6408 in->win_atime[0] = oh->win_atime[0];
6409 in->win_ctime[0] = oh->win_ctime[0];
6410 in->win_mtime[0] = oh->win_mtime[0];
6411 in->win_atime[1] = oh->win_atime[1];
6412 in->win_ctime[1] = oh->win_ctime[1];
6413 in->win_mtime[1] = oh->win_mtime[1];
6415 in->yst_uid = oh->yst_uid;
6416 in->yst_gid = oh->yst_gid;
6417 in->yst_atime = oh->yst_atime;
6418 in->yst_mtime = oh->yst_mtime;
6419 in->yst_ctime = oh->yst_ctime;
6420 in->yst_rdev = oh->yst_rdev;
6424 in->variantType = tags.extraObjectType;
6428 in->hdrChunk = chunk;
6430 } else if (!in->valid) {
6431 /* we need to load this info */
6434 in->hdrChunk = chunk;
6437 in->variantType = oh->type;
6439 in->yst_mode = oh->yst_mode;
6440 #ifdef CONFIG_YAFFS_WINCE
6441 in->win_atime[0] = oh->win_atime[0];
6442 in->win_ctime[0] = oh->win_ctime[0];
6443 in->win_mtime[0] = oh->win_mtime[0];
6444 in->win_atime[1] = oh->win_atime[1];
6445 in->win_ctime[1] = oh->win_ctime[1];
6446 in->win_mtime[1] = oh->win_mtime[1];
6448 in->yst_uid = oh->yst_uid;
6449 in->yst_gid = oh->yst_gid;
6450 in->yst_atime = oh->yst_atime;
6451 in->yst_mtime = oh->yst_mtime;
6452 in->yst_ctime = oh->yst_ctime;
6453 in->yst_rdev = oh->yst_rdev;
6456 if (oh->shadowsObject > 0)
6457 yaffs_HandleShadowedObject(dev,
6463 yaffs_SetObjectName(in, oh->name);
6465 yaffs_FindOrCreateObjectByNumber
6466 (dev, oh->parentObjectId,
6467 YAFFS_OBJECT_TYPE_DIRECTORY);
6469 fileSize = oh->fileSize;
6470 isShrink = oh->isShrink;
6471 equivalentObjectId = oh->equivalentObjectId;
6475 in->variantType = tags.extraObjectType;
6477 yaffs_FindOrCreateObjectByNumber
6478 (dev, tags.extraParentObjectId,
6479 YAFFS_OBJECT_TYPE_DIRECTORY);
6480 fileSize = tags.extraFileLength;
6481 isShrink = tags.extraIsShrinkHeader;
6482 equivalentObjectId = tags.extraEquivalentObjectId;
6488 /* directory stuff...
6492 if (parent->variantType ==
6493 YAFFS_OBJECT_TYPE_UNKNOWN) {
6494 /* Set up as a directory */
6495 parent->variantType =
6496 YAFFS_OBJECT_TYPE_DIRECTORY;
6497 YINIT_LIST_HEAD(&parent->variant.
6500 } else if (parent->variantType !=
6501 YAFFS_OBJECT_TYPE_DIRECTORY)
6503 /* Hoosterman, another problem....
6504 * We're trying to use a non-directory as a directory
6507 T(YAFFS_TRACE_ERROR,
6509 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6511 parent = dev->lostNFoundDir;
6514 yaffs_AddObjectToDirectory(parent, in);
6516 itsUnlinked = (parent == dev->deletedDir) ||
6517 (parent == dev->unlinkedDir);
6520 /* Mark the block as having a shrinkHeader */
6521 bi->hasShrinkHeader = 1;
6524 /* Note re hardlinks.
6525 * Since we might scan a hardlink before its equivalent object is scanned
6526 * we put them all in a list.
6527 * After scanning is complete, we should have all the objects, so we run
6528 * through this list and fix up all the chains.
6531 switch (in->variantType) {
6532 case YAFFS_OBJECT_TYPE_UNKNOWN:
6533 /* Todo got a problem */
6535 case YAFFS_OBJECT_TYPE_FILE:
6537 if (in->variant.fileVariant.
6538 scannedFileSize < fileSize) {
6539 /* This covers the case where the file size is greater
6540 * than where the data is
6541 * This will happen if the file is resized to be larger
6542 * than its current data extents.
6544 in->variant.fileVariant.fileSize = fileSize;
6545 in->variant.fileVariant.scannedFileSize =
6546 in->variant.fileVariant.fileSize;
6550 in->variant.fileVariant.shrinkSize > fileSize) {
6551 in->variant.fileVariant.shrinkSize = fileSize;
6555 case YAFFS_OBJECT_TYPE_HARDLINK:
6557 in->variant.hardLinkVariant.equivalentObjectId =
6559 in->hardLinks.next =
6560 (struct ylist_head *) hardList;
6564 case YAFFS_OBJECT_TYPE_DIRECTORY:
6567 case YAFFS_OBJECT_TYPE_SPECIAL:
6570 case YAFFS_OBJECT_TYPE_SYMLINK:
6572 in->variant.symLinkVariant.alias =
6573 yaffs_CloneString(oh->
6575 if(!in->variant.symLinkVariant.alias)
6585 } /* End of scanning for each chunk */
6587 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6588 /* If we got this far while scanning, then the block is fully allocated. */
6589 state = YAFFS_BLOCK_STATE_FULL;
6592 bi->blockState = state;
6594 /* Now let's see if it was dirty */
6595 if (bi->pagesInUse == 0 &&
6596 !bi->hasShrinkHeader &&
6597 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6598 yaffs_BlockBecameDirty(dev, blk);
6604 YFREE_ALT(blockIndex);
6608 /* Ok, we've done all the scanning.
6609 * Fix up the hard link chains.
6610 * We should now have scanned all the objects, now it's time to add these
6613 yaffs_HardlinkFixup(dev,hardList);
6617 * Sort out state of unlinked and deleted objects.
6620 struct ylist_head *i;
6621 struct ylist_head *n;
6625 /* Soft delete all the unlinked files */
6626 ylist_for_each_safe(i, n,
6627 &dev->unlinkedDir->variant.directoryVariant.
6630 l = ylist_entry(i, yaffs_Object, siblings);
6631 yaffs_DestroyObject(l);
6635 /* Soft delete all the deletedDir files */
6636 ylist_for_each_safe(i, n,
6637 &dev->deletedDir->variant.directoryVariant.
6640 l = ylist_entry(i, yaffs_Object, siblings);
6641 yaffs_DestroyObject(l);
6647 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6653 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6658 /*------------------------------ Directory Functions ----------------------------- */
6660 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
6662 yaffs_Device *dev = obj->myDev;
6664 if(dev && dev->removeObjectCallback)
6665 dev->removeObjectCallback(obj);
6667 ylist_del_init(&obj->siblings);
6672 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
6677 T(YAFFS_TRACE_ALWAYS,
6679 ("tragedy: Trying to add an object to a null pointer directory"
6683 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6684 T(YAFFS_TRACE_ALWAYS,
6686 ("tragedy: Trying to add an object to a non-directory"
6691 if (obj->siblings.prev == NULL) {
6692 /* Not initialised */
6693 YINIT_LIST_HEAD(&obj->siblings);
6695 } else if (!ylist_empty(&obj->siblings)) {
6696 /* If it is holed up somewhere else, un hook it */
6697 yaffs_RemoveObjectFromDirectory(obj);
6700 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
6701 obj->parent = directory;
6703 if (directory == obj->myDev->unlinkedDir
6704 || directory == obj->myDev->deletedDir) {
6706 obj->myDev->nUnlinkedFiles++;
6707 obj->renameAllowed = 0;
6711 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
6716 struct ylist_head *i;
6717 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
6726 T(YAFFS_TRACE_ALWAYS,
6728 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6732 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6733 T(YAFFS_TRACE_ALWAYS,
6735 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6739 sum = yaffs_CalcNameSum(name);
6741 ylist_for_each(i, &directory->variant.directoryVariant.children) {
6743 l = ylist_entry(i, yaffs_Object, siblings);
6745 yaffs_CheckObjectDetailsLoaded(l);
6747 /* Special case for lost-n-found */
6748 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6749 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
6752 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0){
6753 /* LostnFound chunk called Objxxx
6756 yaffs_GetObjectName(l, buffer,
6757 YAFFS_MAX_NAME_LENGTH);
6758 if (yaffs_strncmp(name, buffer,YAFFS_MAX_NAME_LENGTH) == 0) {
6771 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
6772 int (*fn) (yaffs_Object *))
6774 struct ylist_head *i;
6778 T(YAFFS_TRACE_ALWAYS,
6780 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6784 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6785 T(YAFFS_TRACE_ALWAYS,
6787 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6791 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
6793 l = ylist_entry(i, yaffs_Object, siblings);
6805 /* GetEquivalentObject dereferences any hard links to get to the
6809 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
6811 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
6812 /* We want the object id of the equivalent object, not this one */
6813 obj = obj->variant.hardLinkVariant.equivalentObject;
6814 yaffs_CheckObjectDetailsLoaded(obj);
6820 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
6822 memset(name, 0, buffSize * sizeof(YCHAR));
6824 yaffs_CheckObjectDetailsLoaded(obj);
6826 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6827 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
6828 } else if (obj->hdrChunk <= 0) {
6830 /* make up a name */
6831 yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX,
6833 yaffs_strncpy(name, locName, buffSize - 1);
6836 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
6837 else if (obj->shortName[0]) {
6838 yaffs_strcpy(name, obj->shortName);
6843 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
6845 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
6847 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
6849 if (obj->hdrChunk > 0) {
6850 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
6851 obj->hdrChunk, buffer,
6854 yaffs_strncpy(name, oh->name, buffSize - 1);
6856 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
6859 return yaffs_strlen(name);
6862 int yaffs_GetObjectFileLength(yaffs_Object * obj)
6865 /* Dereference any hard linking */
6866 obj = yaffs_GetEquivalentObject(obj);
6868 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
6869 return obj->variant.fileVariant.fileSize;
6871 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6872 return yaffs_strlen(obj->variant.symLinkVariant.alias);
6874 /* Only a directory should drop through to here */
6875 return obj->myDev->nDataBytesPerChunk;
6879 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
6882 struct ylist_head *i;
6884 if (!obj->unlinked) {
6885 count++; /* the object itself */
6887 ylist_for_each(i, &obj->hardLinks) {
6888 count++; /* add the hard links; */
6894 int yaffs_GetObjectInode(yaffs_Object * obj)
6896 obj = yaffs_GetEquivalentObject(obj);
6898 return obj->objectId;
6901 unsigned yaffs_GetObjectType(yaffs_Object * obj)
6903 obj = yaffs_GetEquivalentObject(obj);
6905 switch (obj->variantType) {
6906 case YAFFS_OBJECT_TYPE_FILE:
6909 case YAFFS_OBJECT_TYPE_DIRECTORY:
6912 case YAFFS_OBJECT_TYPE_SYMLINK:
6915 case YAFFS_OBJECT_TYPE_HARDLINK:
6918 case YAFFS_OBJECT_TYPE_SPECIAL:
6919 if (S_ISFIFO(obj->yst_mode))
6921 if (S_ISCHR(obj->yst_mode))
6923 if (S_ISBLK(obj->yst_mode))
6925 if (S_ISSOCK(obj->yst_mode))
6933 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
6935 obj = yaffs_GetEquivalentObject(obj);
6936 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6937 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
6939 return yaffs_CloneString(_Y(""));
6943 #ifndef CONFIG_YAFFS_WINCE
6945 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
6947 unsigned int valid = attr->ia_valid;
6949 if (valid & ATTR_MODE)
6950 obj->yst_mode = attr->ia_mode;
6951 if (valid & ATTR_UID)
6952 obj->yst_uid = attr->ia_uid;
6953 if (valid & ATTR_GID)
6954 obj->yst_gid = attr->ia_gid;
6956 if (valid & ATTR_ATIME)
6957 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
6958 if (valid & ATTR_CTIME)
6959 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
6960 if (valid & ATTR_MTIME)
6961 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
6963 if (valid & ATTR_SIZE)
6964 yaffs_ResizeFile(obj, attr->ia_size);
6966 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6971 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
6973 unsigned int valid = 0;
6975 attr->ia_mode = obj->yst_mode;
6977 attr->ia_uid = obj->yst_uid;
6979 attr->ia_gid = obj->yst_gid;
6982 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
6983 valid |= ATTR_ATIME;
6984 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
6985 valid |= ATTR_CTIME;
6986 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
6987 valid |= ATTR_MTIME;
6989 attr->ia_size = yaffs_GetFileSize(obj);
6992 attr->ia_valid = valid;
7001 int yaffs_DumpObject(yaffs_Object * obj)
7005 yaffs_GetObjectName(obj, name, 256);
7007 T(YAFFS_TRACE_ALWAYS,
7009 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7010 " chunk %d type %d size %d\n"
7011 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7012 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7013 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7019 /*---------------------------- Initialisation code -------------------------------------- */
7021 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
7024 /* Common functions, gotta have */
7025 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
7028 #ifdef CONFIG_YAFFS_YAFFS2
7030 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7031 if (dev->writeChunkWithTagsToNAND &&
7032 dev->readChunkWithTagsFromNAND &&
7033 !dev->writeChunkToNAND &&
7034 !dev->readChunkFromNAND &&
7035 dev->markNANDBlockBad && dev->queryNANDBlock)
7039 /* Can use the "spare" style interface for yaffs1 */
7040 if (!dev->isYaffs2 &&
7041 !dev->writeChunkWithTagsToNAND &&
7042 !dev->readChunkWithTagsFromNAND &&
7043 dev->writeChunkToNAND &&
7044 dev->readChunkFromNAND &&
7045 !dev->markNANDBlockBad && !dev->queryNANDBlock)
7052 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7054 /* Initialise the unlinked, deleted, root and lost and found directories */
7056 dev->lostNFoundDir = dev->rootDir = NULL;
7057 dev->unlinkedDir = dev->deletedDir = NULL;
7060 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7063 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7066 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7067 YAFFS_ROOT_MODE | S_IFDIR);
7068 dev->lostNFoundDir =
7069 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7070 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7072 if(dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir){
7073 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7080 int yaffs_GutsInitialise(yaffs_Device * dev)
7082 int init_failed = 0;
7086 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7088 /* Check stuff that must be set */
7091 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7095 dev->internalStartBlock = dev->startBlock;
7096 dev->internalEndBlock = dev->endBlock;
7097 dev->blockOffset = 0;
7098 dev->chunkOffset = 0;
7099 dev->nFreeChunks = 0;
7101 if (dev->startBlock == 0) {
7102 dev->internalStartBlock = dev->startBlock + 1;
7103 dev->internalEndBlock = dev->endBlock + 1;
7104 dev->blockOffset = 1;
7105 dev->chunkOffset = dev->nChunksPerBlock;
7108 /* Check geometry parameters. */
7110 if ((!dev->inbandTags && dev->isYaffs2 && dev->totalBytesPerChunk < 1024) ||
7111 (!dev->isYaffs2 && dev->totalBytesPerChunk != 512) ||
7112 (dev->inbandTags && !dev->isYaffs2 ) ||
7113 dev->nChunksPerBlock < 2 ||
7114 dev->nReservedBlocks < 2 ||
7115 dev->internalStartBlock <= 0 ||
7116 dev->internalEndBlock <= 0 ||
7117 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
7119 T(YAFFS_TRACE_ALWAYS,
7121 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7122 TENDSTR), dev->totalBytesPerChunk, dev->isYaffs2 ? "2" : "", dev->inbandTags));
7126 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7127 T(YAFFS_TRACE_ALWAYS,
7128 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7132 /* Sort out space for inband tags, if required */
7134 dev->nDataBytesPerChunk = dev->totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7136 dev->nDataBytesPerChunk = dev->totalBytesPerChunk;
7138 /* Got the right mix of functions? */
7139 if (!yaffs_CheckDevFunctions(dev)) {
7140 /* Function missing */
7141 T(YAFFS_TRACE_ALWAYS,
7143 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7148 /* This is really a compilation check. */
7149 if (!yaffs_CheckStructures()) {
7150 T(YAFFS_TRACE_ALWAYS,
7151 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7155 if (dev->isMounted) {
7156 T(YAFFS_TRACE_ALWAYS,
7157 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7161 /* Finished with most checks. One or two more checks happen later on too. */
7167 /* OK now calculate a few things for the device */
7170 * Calculate all the chunk size manipulation numbers:
7173 __u32 x = dev->nDataBytesPerChunk;
7174 /* We always use dev->chunkShift and dev->chunkDiv */
7175 dev->chunkShift = Shifts(x);
7176 x >>= dev->chunkShift;
7178 /* We only use chunk mask if chunkDiv is 1 */
7179 dev->chunkMask = (1<<dev->chunkShift) - 1;
7184 * Calculate chunkGroupBits.
7185 * We need to find the next power of 2 > than internalEndBlock
7188 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7192 /* Set up tnode width if wide tnodes are enabled. */
7193 if(!dev->wideTnodesDisabled){
7194 /* bits must be even so that we end up with 32-bit words */
7198 dev->tnodeWidth = 16;
7200 dev->tnodeWidth = bits;
7203 dev->tnodeWidth = 16;
7205 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7207 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7208 * so if the bitwidth of the
7209 * chunk range we're using is greater than 16 we need
7210 * to figure out chunk shift and chunkGroupSize
7213 if (bits <= dev->tnodeWidth)
7214 dev->chunkGroupBits = 0;
7216 dev->chunkGroupBits = bits - dev->tnodeWidth;
7219 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7221 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7222 /* We have a problem because the soft delete won't work if
7223 * the chunk group size > chunks per block.
7224 * This can be remedied by using larger "virtual blocks".
7226 T(YAFFS_TRACE_ALWAYS,
7227 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7232 /* OK, we've finished verifying the device, lets continue with initialisation */
7234 /* More device initialisation */
7235 dev->garbageCollections = 0;
7236 dev->passiveGarbageCollections = 0;
7237 dev->currentDirtyChecker = 0;
7238 dev->bufferedBlock = -1;
7239 dev->doingBufferedBlockRewrite = 0;
7240 dev->nDeletedFiles = 0;
7241 dev->nBackgroundDeletions = 0;
7242 dev->nUnlinkedFiles = 0;
7244 dev->eccUnfixed = 0;
7245 dev->tagsEccFixed = 0;
7246 dev->tagsEccUnfixed = 0;
7247 dev->nErasureFailures = 0;
7248 dev->nErasedBlocks = 0;
7250 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7252 /* Initialise temporary buffers and caches. */
7253 if(!yaffs_InitialiseTempBuffers(dev))
7256 dev->srCache = NULL;
7257 dev->gcCleanupList = NULL;
7261 dev->nShortOpCaches > 0) {
7264 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7266 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
7267 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7270 buf = dev->srCache = YMALLOC(srCacheBytes);
7273 memset(dev->srCache,0,srCacheBytes);
7275 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7276 dev->srCache[i].object = NULL;
7277 dev->srCache[i].lastUse = 0;
7278 dev->srCache[i].dirty = 0;
7279 dev->srCache[i].data = buf = YMALLOC_DMA(dev->totalBytesPerChunk);
7290 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7291 if(!dev->gcCleanupList)
7295 if (dev->isYaffs2) {
7296 dev->useHeaderFileSize = 1;
7298 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7301 yaffs_InitialiseTnodes(dev);
7302 yaffs_InitialiseObjects(dev);
7304 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7309 /* Now scan the flash. */
7310 if (dev->isYaffs2) {
7311 if(yaffs_CheckpointRestore(dev)) {
7312 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7313 T(YAFFS_TRACE_ALWAYS,
7314 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7317 /* Clean up the mess caused by an aborted checkpoint load
7318 * and scan backwards.
7320 yaffs_DeinitialiseBlocks(dev);
7321 yaffs_DeinitialiseTnodes(dev);
7322 yaffs_DeinitialiseObjects(dev);
7325 dev->nErasedBlocks = 0;
7326 dev->nFreeChunks = 0;
7327 dev->allocationBlock = -1;
7328 dev->allocationPage = -1;
7329 dev->nDeletedFiles = 0;
7330 dev->nUnlinkedFiles = 0;
7331 dev->nBackgroundDeletions = 0;
7332 dev->oldestDirtySequence = 0;
7334 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7337 yaffs_InitialiseTnodes(dev);
7338 yaffs_InitialiseObjects(dev);
7340 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7343 if(!init_failed && !yaffs_ScanBackwards(dev))
7347 if(!yaffs_Scan(dev))
7352 /* Clean up the mess */
7353 T(YAFFS_TRACE_TRACING,
7354 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7356 yaffs_Deinitialise(dev);
7360 /* Zero out stats */
7361 dev->nPageReads = 0;
7362 dev->nPageWrites = 0;
7363 dev->nBlockErasures = 0;
7365 dev->nRetriedWrites = 0;
7367 dev->nRetiredBlocks = 0;
7369 yaffs_VerifyFreeChunks(dev);
7370 yaffs_VerifyBlocks(dev);
7373 T(YAFFS_TRACE_TRACING,
7374 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7379 void yaffs_Deinitialise(yaffs_Device * dev)
7381 if (dev->isMounted) {
7384 yaffs_DeinitialiseBlocks(dev);
7385 yaffs_DeinitialiseTnodes(dev);
7386 yaffs_DeinitialiseObjects(dev);
7387 if (dev->nShortOpCaches > 0 &&
7390 for (i = 0; i < dev->nShortOpCaches; i++) {
7391 if(dev->srCache[i].data)
7392 YFREE(dev->srCache[i].data);
7393 dev->srCache[i].data = NULL;
7396 YFREE(dev->srCache);
7397 dev->srCache = NULL;
7400 YFREE(dev->gcCleanupList);
7402 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
7403 YFREE(dev->tempBuffer[i].buffer);
7412 static int yaffs_CountFreeChunks(yaffs_Device * dev)
7417 yaffs_BlockInfo *blk;
7419 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7421 blk = yaffs_GetBlockInfo(dev, b);
7423 switch (blk->blockState) {
7424 case YAFFS_BLOCK_STATE_EMPTY:
7425 case YAFFS_BLOCK_STATE_ALLOCATING:
7426 case YAFFS_BLOCK_STATE_COLLECTING:
7427 case YAFFS_BLOCK_STATE_FULL:
7429 (dev->nChunksPerBlock - blk->pagesInUse +
7430 blk->softDeletions);
7441 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
7443 /* This is what we report to the outside world */
7446 int nDirtyCacheChunks;
7447 int blocksForCheckpoint;
7450 nFree = dev->nFreeChunks;
7452 nFree = yaffs_CountFreeChunks(dev);
7455 nFree += dev->nDeletedFiles;
7457 /* Now count the number of dirty chunks in the cache and subtract those */
7461 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7462 if (dev->srCache[i].dirty)
7463 nDirtyCacheChunks++;
7467 nFree -= nDirtyCacheChunks;
7469 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7471 /* Now we figure out how much to reserve for the checkpoint and report that... */
7472 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7473 if(blocksForCheckpoint < 0)
7474 blocksForCheckpoint = 0;
7476 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7485 static int yaffs_freeVerificationFailures;
7487 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
7492 if(yaffs_SkipVerification(dev))
7495 counted = yaffs_CountFreeChunks(dev);
7497 difference = dev->nFreeChunks - counted;
7500 T(YAFFS_TRACE_ALWAYS,
7501 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7502 dev->nFreeChunks, counted, difference));
7503 yaffs_freeVerificationFailures++;
7507 /*---------------------------------------- YAFFS test code ----------------------*/
7509 #define yaffs_CheckStruct(structure,syze, name) \
7511 if(sizeof(structure) != syze) \
7513 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
7514 name,syze,sizeof(structure))); \
7515 return YAFFS_FAIL; \
7519 static int yaffs_CheckStructures(void)
7521 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
7522 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
7523 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
7524 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7525 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode");
7527 #ifndef CONFIG_YAFFS_WINCE
7528 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");