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.65 2008-11-26 20:42:04 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 static void yaffs_VerifyDirectory(yaffs_Object *directory);
101 #ifdef YAFFS_PARANOID
102 static int yaffs_CheckFileSanity(yaffs_Object * in);
104 #define yaffs_CheckFileSanity(in)
107 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
108 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
110 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
112 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
113 yaffs_ExtendedTags * tags);
115 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos);
116 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
117 yaffs_FileStructure * fStruct,
121 /* Function to calculate chunk and offset */
123 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut, __u32 *offsetOut)
128 chunk = (__u32)(addr >> dev->chunkShift);
130 if(dev->chunkDiv == 1)
132 /* easy power of 2 case */
133 offset = (__u32)(addr & dev->chunkMask);
137 /* Non power-of-2 case */
141 chunk /= dev->chunkDiv;
143 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
144 offset = (__u32)(addr - chunkBase);
151 /* Function to return the number of shifts for a power of 2 greater than or equal
152 * to the given number
153 * Note we don't try to cater for all possible numbers and this does not have to
154 * be hellishly efficient.
157 static __u32 ShiftsGE(__u32 x)
162 nShifts = extraBits = 0;
165 if(x & 1) extraBits++;
176 /* Function to return the number of shifts to get a 1 in bit 0
179 static __u32 Shifts(__u32 x)
198 * Temporary buffer manipulations.
201 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
204 __u8 *buf = (__u8 *)1;
206 memset(dev->tempBuffer,0,sizeof(dev->tempBuffer));
208 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
209 dev->tempBuffer[i].line = 0; /* not in use */
210 dev->tempBuffer[i].buffer = buf =
211 YMALLOC_DMA(dev->totalBytesPerChunk);
214 return buf ? YAFFS_OK : YAFFS_FAIL;
218 __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
223 if(dev->tempInUse > dev->maxTemp)
224 dev->maxTemp = dev->tempInUse;
226 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
227 if (dev->tempBuffer[i].line == 0) {
228 dev->tempBuffer[i].line = lineNo;
229 if ((i + 1) > dev->maxTemp) {
230 dev->maxTemp = i + 1;
231 for (j = 0; j <= i; j++)
232 dev->tempBuffer[j].maxLine =
233 dev->tempBuffer[j].line;
236 return dev->tempBuffer[i].buffer;
240 T(YAFFS_TRACE_BUFFERS,
241 (TSTR("Out of temp buffers at line %d, other held by lines:"),
243 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
244 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
246 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
249 * If we got here then we have to allocate an unmanaged one
253 dev->unmanagedTempAllocations++;
254 return YMALLOC(dev->nDataBytesPerChunk);
258 void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
265 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
266 if (dev->tempBuffer[i].buffer == buffer) {
267 dev->tempBuffer[i].line = 0;
273 /* assume it is an unmanaged one. */
274 T(YAFFS_TRACE_BUFFERS,
275 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
278 dev->unmanagedTempDeallocations++;
284 * Determine if we have a managed buffer.
286 int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
289 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
290 if (dev->tempBuffer[i].buffer == buffer)
295 for (i = 0; i < dev->nShortOpCaches; i++) {
296 if( dev->srCache[i].data == buffer )
301 if (buffer == dev->checkpointBuffer)
304 T(YAFFS_TRACE_ALWAYS,
305 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
312 * Chunk bitmap manipulations
315 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
317 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
319 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
323 return dev->chunkBits +
324 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
327 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
329 if(blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
330 chunk < 0 || chunk >= dev->nChunksPerBlock) {
332 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),blk,chunk));
337 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
339 __u8 *blkBits = yaffs_BlockBits(dev, blk);
341 memset(blkBits, 0, dev->chunkBitmapStride);
344 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
346 __u8 *blkBits = yaffs_BlockBits(dev, blk);
348 yaffs_VerifyChunkBitId(dev,blk,chunk);
350 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
353 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
355 __u8 *blkBits = yaffs_BlockBits(dev, blk);
357 yaffs_VerifyChunkBitId(dev,blk,chunk);
359 blkBits[chunk / 8] |= (1 << (chunk & 7));
362 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
364 __u8 *blkBits = yaffs_BlockBits(dev, blk);
365 yaffs_VerifyChunkBitId(dev,blk,chunk);
367 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
370 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
372 __u8 *blkBits = yaffs_BlockBits(dev, blk);
374 for (i = 0; i < dev->chunkBitmapStride; i++) {
382 static int yaffs_CountChunkBits(yaffs_Device * dev, int blk)
384 __u8 *blkBits = yaffs_BlockBits(dev, blk);
387 for (i = 0; i < dev->chunkBitmapStride; i++) {
404 static int yaffs_SkipVerification(yaffs_Device *dev)
406 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
410 static int yaffs_SkipFullVerification(yaffs_Device *dev)
412 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
417 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
419 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
422 static const char * blockStateName[] = {
435 static void yaffs_VerifyBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
440 if(yaffs_SkipVerification(dev))
443 /* Report illegal runtime states */
444 if(bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
445 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has undefined state %d"TENDSTR),n,bi->blockState));
447 switch(bi->blockState){
448 case YAFFS_BLOCK_STATE_UNKNOWN:
449 case YAFFS_BLOCK_STATE_SCANNING:
450 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
451 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has bad run-state %s"TENDSTR),
452 n,blockStateName[bi->blockState]));
455 /* Check pages in use and soft deletions are legal */
457 actuallyUsed = bi->pagesInUse - bi->softDeletions;
459 if(bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
460 bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
461 actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock)
462 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
463 n,bi->pagesInUse,bi->softDeletions));
466 /* Check chunk bitmap legal */
467 inUse = yaffs_CountChunkBits(dev,n);
468 if(inUse != bi->pagesInUse)
469 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
470 n,bi->pagesInUse,inUse));
472 /* Check that the sequence number is valid.
473 * Ten million is legal, but is very unlikely
476 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
477 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000 ))
478 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has suspect sequence number of %d"TENDSTR),
479 n,bi->sequenceNumber));
483 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
485 yaffs_VerifyBlock(dev,bi,n);
487 /* After collection the block should be in the erased state */
488 /* TODO: This will need to change if we do partial gc */
490 if(bi->blockState != YAFFS_BLOCK_STATE_EMPTY){
491 T(YAFFS_TRACE_ERROR,(TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
496 static void yaffs_VerifyBlocks(yaffs_Device *dev)
499 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
500 int nIllegalBlockStates = 0;
503 if(yaffs_SkipVerification(dev))
506 memset(nBlocksPerState,0,sizeof(nBlocksPerState));
509 for(i = dev->internalStartBlock; i <= dev->internalEndBlock; i++){
510 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
511 yaffs_VerifyBlock(dev,bi,i);
513 if(bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
514 nBlocksPerState[bi->blockState]++;
516 nIllegalBlockStates++;
520 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
521 T(YAFFS_TRACE_VERIFY,(TSTR("Block summary"TENDSTR)));
523 T(YAFFS_TRACE_VERIFY,(TSTR("%d blocks have illegal states"TENDSTR),nIllegalBlockStates));
524 if(nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
525 T(YAFFS_TRACE_VERIFY,(TSTR("Too many allocating blocks"TENDSTR)));
527 for(i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
528 T(YAFFS_TRACE_VERIFY,
529 (TSTR("%s %d blocks"TENDSTR),
530 blockStateName[i],nBlocksPerState[i]));
532 if(dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
533 T(YAFFS_TRACE_VERIFY,
534 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
535 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
537 if(dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
538 T(YAFFS_TRACE_VERIFY,
539 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
540 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
542 if(nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
543 T(YAFFS_TRACE_VERIFY,
544 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
545 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
547 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
552 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
553 * case those tests will not be performed.
555 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
557 if(obj && yaffs_SkipVerification(obj->myDev))
560 if(!(tags && obj && oh)){
561 T(YAFFS_TRACE_VERIFY,
562 (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR),
563 (__u32)tags,(__u32)obj,(__u32)oh));
567 if(oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
568 oh->type > YAFFS_OBJECT_TYPE_MAX)
569 T(YAFFS_TRACE_VERIFY,
570 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
571 tags->objectId, oh->type));
573 if(tags->objectId != obj->objectId)
574 T(YAFFS_TRACE_VERIFY,
575 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
576 tags->objectId, obj->objectId));
580 * Check that the object's parent ids match if parentCheck requested.
582 * Tests do not apply to the root object.
585 if(parentCheck && tags->objectId > 1 && !obj->parent)
586 T(YAFFS_TRACE_VERIFY,
587 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
588 tags->objectId, oh->parentObjectId));
591 if(parentCheck && obj->parent &&
592 oh->parentObjectId != obj->parent->objectId &&
593 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
594 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
595 T(YAFFS_TRACE_VERIFY,
596 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
597 tags->objectId, oh->parentObjectId, obj->parent->objectId));
600 if(tags->objectId > 1 && oh->name[0] == 0) /* Null name */
601 T(YAFFS_TRACE_VERIFY,
602 (TSTR("Obj %d header name is NULL"TENDSTR),
605 if(tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
606 T(YAFFS_TRACE_VERIFY,
607 (TSTR("Obj %d header name is 0xFF"TENDSTR),
613 static int yaffs_VerifyTnodeWorker(yaffs_Object * obj, yaffs_Tnode * tn,
614 __u32 level, int chunkOffset)
617 yaffs_Device *dev = obj->myDev;
623 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
624 if (tn->internal[i]) {
625 ok = yaffs_VerifyTnodeWorker(obj,
628 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
631 } 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;
674 if(yaffs_SkipVerification(obj->myDev))
678 objectId = obj->objectId;
680 /* Check file size is consistent with tnode depth */
681 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
682 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
683 requiredTallness = 0;
685 x >>= YAFFS_TNODES_INTERNAL_BITS;
689 actualTallness = obj->variant.fileVariant.topLevel;
691 if(requiredTallness > actualTallness )
692 T(YAFFS_TRACE_VERIFY,
693 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
694 obj->objectId,actualTallness, requiredTallness));
697 /* Check that the chunks in the tnode tree are all correct.
698 * We do this by scanning through the tnode tree and
699 * checking the tags for every chunk match.
702 if(yaffs_SkipNANDVerification(dev))
705 for(i = 1; i <= lastChunk; i++){
706 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant,i);
709 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
711 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
712 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
713 if(tags.objectId != objectId || tags.chunkId != i){
714 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
715 objectId, i, theChunk,
716 tags.objectId, tags.chunkId));
726 static void yaffs_VerifyHardLink(yaffs_Object *obj)
728 if(obj && yaffs_SkipVerification(obj->myDev))
731 /* Verify sane equivalent object */
734 static void yaffs_VerifySymlink(yaffs_Object *obj)
736 if(obj && yaffs_SkipVerification(obj->myDev))
739 /* Verify symlink string */
742 static void yaffs_VerifySpecial(yaffs_Object *obj)
744 if(obj && yaffs_SkipVerification(obj->myDev))
748 static void yaffs_VerifyObject(yaffs_Object *obj)
763 if(yaffs_SkipVerification(dev))
766 /* Check sane object header chunk */
768 chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
769 chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
771 chunkIdOk = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
772 chunkIsLive = chunkIdOk &&
773 yaffs_CheckChunkBit(dev,
774 obj->hdrChunk / dev->nChunksPerBlock,
775 obj->hdrChunk % dev->nChunksPerBlock);
777 (!chunkIdOk || !chunkIsLive)) {
778 T(YAFFS_TRACE_VERIFY,
779 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
780 obj->objectId,obj->hdrChunk,
781 chunkIdOk ? "" : ",out of range",
782 chunkIsLive || !chunkIdOk ? "" : ",marked as deleted"));
785 if(chunkIdOk && chunkIsLive &&!yaffs_SkipNANDVerification(dev)) {
786 yaffs_ExtendedTags tags;
787 yaffs_ObjectHeader *oh;
788 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
790 oh = (yaffs_ObjectHeader *)buffer;
792 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk,buffer, &tags);
794 yaffs_VerifyObjectHeader(obj,oh,&tags,1);
796 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
799 /* Verify it has a parent */
800 if(obj && !obj->fake &&
801 (!obj->parent || obj->parent->myDev != dev)){
802 T(YAFFS_TRACE_VERIFY,
803 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
804 obj->objectId,obj->parent));
807 /* Verify parent is a directory */
808 if(obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
809 T(YAFFS_TRACE_VERIFY,
810 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
811 obj->objectId,obj->parent->variantType));
814 switch(obj->variantType){
815 case YAFFS_OBJECT_TYPE_FILE:
816 yaffs_VerifyFile(obj);
818 case YAFFS_OBJECT_TYPE_SYMLINK:
819 yaffs_VerifySymlink(obj);
821 case YAFFS_OBJECT_TYPE_DIRECTORY:
822 yaffs_VerifyDirectory(obj);
824 case YAFFS_OBJECT_TYPE_HARDLINK:
825 yaffs_VerifyHardLink(obj);
827 case YAFFS_OBJECT_TYPE_SPECIAL:
828 yaffs_VerifySpecial(obj);
830 case YAFFS_OBJECT_TYPE_UNKNOWN:
832 T(YAFFS_TRACE_VERIFY,
833 (TSTR("Obj %d has illegaltype %d"TENDSTR),
834 obj->objectId,obj->variantType));
841 static void yaffs_VerifyObjects(yaffs_Device *dev)
845 struct ylist_head *lh;
847 if(yaffs_SkipVerification(dev))
850 /* Iterate through the objects in each hash entry */
852 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++){
853 ylist_for_each(lh, &dev->objectBucket[i].list) {
855 obj = ylist_entry(lh, yaffs_Object, hashLink);
856 yaffs_VerifyObject(obj);
865 * Simple hash function. Needs to have a reasonable spread
868 static Y_INLINE int yaffs_HashFunction(int n)
871 return (n % YAFFS_NOBJECT_BUCKETS);
875 * Access functions to useful fake objects.
876 * Note that root might have a presence in NAND if permissions are set.
879 yaffs_Object *yaffs_Root(yaffs_Device * dev)
884 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
886 return dev->lostNFoundDir;
891 * Erased NAND checking functions
894 int yaffs_CheckFF(__u8 * buffer, int nBytes)
896 /* Horrible, slow implementation */
905 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
909 int retval = YAFFS_OK;
910 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
911 yaffs_ExtendedTags tags;
914 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
916 if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
920 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
921 T(YAFFS_TRACE_NANDACCESS,
922 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
926 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
932 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
934 yaffs_ExtendedTags * tags,
941 yaffs_InvalidateCheckpoint(dev);
944 yaffs_BlockInfo *bi = 0;
947 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
953 /* First check this chunk is erased, if it needs
954 * checking. The checking policy (unless forced
955 * always on) is as follows:
957 * Check the first page we try to write in a block.
958 * If the check passes then we don't need to check any
959 * more. If the check fails, we check again...
960 * If the block has been erased, we don't need to check.
962 * However, if the block has been prioritised for gc,
963 * then we think there might be something odd about
964 * this block and stop using it.
966 * Rationale: We should only ever see chunks that have
967 * not been erased if there was a partially written
968 * chunk due to power loss. This checking policy should
969 * catch that case with very few checks and thus save a
970 * lot of checks that are most likely not needed.
972 if (bi->gcPrioritise) {
973 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
974 /* try another chunk */
978 /* let's give it a try */
981 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
982 bi->skipErasedCheck = 0;
984 if (!bi->skipErasedCheck) {
985 erasedOk = yaffs_CheckChunkErased(dev, chunk);
986 if (erasedOk != YAFFS_OK) {
988 (TSTR ("**>> yaffs chunk %d was not erased"
991 /* try another chunk */
994 bi->skipErasedCheck = 1;
997 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
999 if (writeOk != YAFFS_OK) {
1000 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
1001 /* try another chunk */
1005 /* Copy the data into the robustification buffer */
1006 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1008 } while (writeOk != YAFFS_OK &&
1009 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1015 T(YAFFS_TRACE_ERROR,
1016 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1019 dev->nRetriedWrites += (attempts - 1);
1026 * Block retiring for handling a broken block.
1029 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
1031 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1033 yaffs_InvalidateCheckpoint(dev);
1035 yaffs_MarkBlockBad(dev, blockInNAND);
1037 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1038 bi->gcPrioritise = 0;
1039 bi->needsRetiring = 0;
1041 dev->nRetiredBlocks++;
1045 * Functions for robustisizing TODO
1049 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
1051 const yaffs_ExtendedTags * tags)
1055 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
1056 const yaffs_ExtendedTags * tags)
1060 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1062 if(!bi->gcPrioritise){
1063 bi->gcPrioritise = 1;
1064 dev->hasPendingPrioritisedGCs = 1;
1065 bi->chunkErrorStrikes ++;
1067 if(bi->chunkErrorStrikes > 3){
1068 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1069 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1076 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
1079 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1080 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1082 yaffs_HandleChunkError(dev,bi);
1086 /* Was an actual write failure, so mark the block for retirement */
1087 bi->needsRetiring = 1;
1088 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1089 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1094 /* Delete the chunk */
1095 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1099 /*---------------- Name handling functions ------------*/
1101 static __u16 yaffs_CalcNameSum(const YCHAR * name)
1106 const YUCHAR *bname = (const YUCHAR *) name;
1108 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1110 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1111 sum += yaffs_toupper(*bname) * i;
1113 sum += (*bname) * i;
1123 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
1125 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1126 memset(obj->shortName,0,sizeof (YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1127 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
1128 yaffs_strcpy(obj->shortName, name);
1130 obj->shortName[0] = _Y('\0');
1133 obj->sum = yaffs_CalcNameSum(name);
1136 /*-------------------- TNODES -------------------
1138 * List of spare tnodes
1139 * The list is hooked together using the first pointer
1143 /* yaffs_CreateTnodes creates a bunch more tnodes and
1144 * adds them to the tnode free list.
1145 * Don't use this function directly
1148 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
1152 yaffs_Tnode *newTnodes;
1156 yaffs_TnodeList *tnl;
1161 /* Calculate the tnode size in bytes for variable width tnode support.
1162 * Must be a multiple of 32-bits */
1163 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1165 if(tnodeSize < sizeof(yaffs_Tnode))
1166 tnodeSize = sizeof(yaffs_Tnode);
1169 /* make these things */
1171 newTnodes = YMALLOC(nTnodes * tnodeSize);
1172 mem = (__u8 *)newTnodes;
1175 T(YAFFS_TRACE_ERROR,
1176 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1180 /* Hook them into the free list */
1182 for (i = 0; i < nTnodes - 1; i++) {
1183 newTnodes[i].internal[0] = &newTnodes[i + 1];
1184 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1185 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1189 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1190 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1191 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1193 dev->freeTnodes = newTnodes;
1195 /* New hookup for wide tnodes */
1196 for(i = 0; i < nTnodes -1; i++) {
1197 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1198 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1199 curr->internal[0] = next;
1202 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1203 curr->internal[0] = dev->freeTnodes;
1204 dev->freeTnodes = (yaffs_Tnode *)mem;
1209 dev->nFreeTnodes += nTnodes;
1210 dev->nTnodesCreated += nTnodes;
1212 /* Now add this bunch of tnodes to a list for freeing up.
1213 * NB If we can't add this to the management list it isn't fatal
1214 * but it just means we can't free this bunch of tnodes later.
1217 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1219 T(YAFFS_TRACE_ERROR,
1221 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1225 tnl->tnodes = newTnodes;
1226 tnl->next = dev->allocatedTnodeList;
1227 dev->allocatedTnodeList = tnl;
1230 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1235 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1237 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
1239 yaffs_Tnode *tn = NULL;
1241 /* If there are none left make more */
1242 if (!dev->freeTnodes) {
1243 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1246 if (dev->freeTnodes) {
1247 tn = dev->freeTnodes;
1248 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1249 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1250 /* Hoosterman, this thing looks like it isn't in the list */
1251 T(YAFFS_TRACE_ALWAYS,
1252 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1255 dev->freeTnodes = dev->freeTnodes->internal[0];
1259 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1264 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
1266 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1267 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1269 if(tnodeSize < sizeof(yaffs_Tnode))
1270 tnodeSize = sizeof(yaffs_Tnode);
1273 memset(tn, 0, tnodeSize);
1278 /* FreeTnode frees up a tnode and puts it back on the free list */
1279 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
1282 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1283 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1284 /* Hoosterman, this thing looks like it is already in the list */
1285 T(YAFFS_TRACE_ALWAYS,
1286 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1288 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1290 tn->internal[0] = dev->freeTnodes;
1291 dev->freeTnodes = tn;
1294 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1298 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
1300 /* Free the list of allocated tnodes */
1301 yaffs_TnodeList *tmp;
1303 while (dev->allocatedTnodeList) {
1304 tmp = dev->allocatedTnodeList->next;
1306 YFREE(dev->allocatedTnodeList->tnodes);
1307 YFREE(dev->allocatedTnodeList);
1308 dev->allocatedTnodeList = tmp;
1312 dev->freeTnodes = NULL;
1313 dev->nFreeTnodes = 0;
1316 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
1318 dev->allocatedTnodeList = NULL;
1319 dev->freeTnodes = NULL;
1320 dev->nFreeTnodes = 0;
1321 dev->nTnodesCreated = 0;
1326 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
1328 __u32 *map = (__u32 *)tn;
1334 pos &= YAFFS_TNODES_LEVEL0_MASK;
1335 val >>= dev->chunkGroupBits;
1337 bitInMap = pos * dev->tnodeWidth;
1338 wordInMap = bitInMap /32;
1339 bitInWord = bitInMap & (32 -1);
1341 mask = dev->tnodeMask << bitInWord;
1343 map[wordInMap] &= ~mask;
1344 map[wordInMap] |= (mask & (val << bitInWord));
1346 if(dev->tnodeWidth > (32-bitInWord)) {
1347 bitInWord = (32 - bitInWord);
1349 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1350 map[wordInMap] &= ~mask;
1351 map[wordInMap] |= (mask & (val >> bitInWord));
1355 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
1357 __u32 *map = (__u32 *)tn;
1363 pos &= YAFFS_TNODES_LEVEL0_MASK;
1365 bitInMap = pos * dev->tnodeWidth;
1366 wordInMap = bitInMap /32;
1367 bitInWord = bitInMap & (32 -1);
1369 val = map[wordInMap] >> bitInWord;
1371 if(dev->tnodeWidth > (32-bitInWord)) {
1372 bitInWord = (32 - bitInWord);
1374 val |= (map[wordInMap] << bitInWord);
1377 val &= dev->tnodeMask;
1378 val <<= dev->chunkGroupBits;
1383 /* ------------------- End of individual tnode manipulation -----------------*/
1385 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1386 * The look up tree is represented by the top tnode and the number of topLevel
1387 * in the tree. 0 means only the level 0 tnode is in the tree.
1390 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1391 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
1392 yaffs_FileStructure * fStruct,
1396 yaffs_Tnode *tn = fStruct->top;
1398 int requiredTallness;
1399 int level = fStruct->topLevel;
1401 /* Check sane level and chunk Id */
1402 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
1406 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1410 /* First check we're tall enough (ie enough topLevel) */
1412 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1413 requiredTallness = 0;
1415 i >>= YAFFS_TNODES_INTERNAL_BITS;
1419 if (requiredTallness > fStruct->topLevel) {
1420 /* Not tall enough, so we can't find it, return NULL. */
1424 /* Traverse down to level 0 */
1425 while (level > 0 && tn) {
1427 internal[(chunkId >>
1428 ( YAFFS_TNODES_LEVEL0_BITS +
1430 YAFFS_TNODES_INTERNAL_BITS)
1432 YAFFS_TNODES_INTERNAL_MASK];
1440 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1441 * This happens in two steps:
1442 * 1. If the tree isn't tall enough, then make it taller.
1443 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1445 * Used when modifying the tree.
1447 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1448 * be plugged into the ttree.
1451 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
1452 yaffs_FileStructure * fStruct,
1454 yaffs_Tnode *passedTn)
1457 int requiredTallness;
1465 /* Check sane level and page Id */
1466 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
1470 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1474 /* First check we're tall enough (ie enough topLevel) */
1476 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1477 requiredTallness = 0;
1479 x >>= YAFFS_TNODES_INTERNAL_BITS;
1484 if (requiredTallness > fStruct->topLevel) {
1485 /* Not tall enough,gotta make the tree taller */
1486 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1488 tn = yaffs_GetTnode(dev);
1491 tn->internal[0] = fStruct->top;
1494 T(YAFFS_TRACE_ERROR,
1495 (TSTR("yaffs: no more tnodes" TENDSTR)));
1499 fStruct->topLevel = requiredTallness;
1502 /* Traverse down to level 0, adding anything we need */
1504 l = fStruct->topLevel;
1508 while (l > 0 && tn) {
1510 ( YAFFS_TNODES_LEVEL0_BITS +
1511 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1512 YAFFS_TNODES_INTERNAL_MASK;
1515 if((l>1) && !tn->internal[x]){
1516 /* Add missing non-level-zero tnode */
1517 tn->internal[x] = yaffs_GetTnode(dev);
1520 /* Looking from level 1 at level 0 */
1522 /* If we already have one, then release it.*/
1524 yaffs_FreeTnode(dev,tn->internal[x]);
1525 tn->internal[x] = passedTn;
1527 } else if(!tn->internal[x]) {
1528 /* Don't have one, none passed in */
1529 tn->internal[x] = yaffs_GetTnode(dev);
1533 tn = tn->internal[x];
1537 /* top is level 0 */
1539 memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1540 yaffs_FreeTnode(dev,passedTn);
1547 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1548 yaffs_ExtendedTags * tags, int objectId,
1553 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1554 if (yaffs_CheckChunkBit
1555 (dev, theChunk / dev->nChunksPerBlock,
1556 theChunk % dev->nChunksPerBlock)) {
1557 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1559 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1571 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1572 * chunks and tnodes in the file
1573 * Returns 1 if the tree was deleted.
1574 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1577 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1578 int chunkOffset, int *limit)
1583 yaffs_ExtendedTags tags;
1585 yaffs_Device *dev = in->myDev;
1592 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1594 if (tn->internal[i]) {
1595 if (limit && (*limit) < 0) {
1599 yaffs_DeleteWorker(in,
1607 YAFFS_TNODES_INTERNAL_BITS)
1612 yaffs_FreeTnode(dev,
1615 tn->internal[i] = NULL;
1620 return (allDone) ? 1 : 0;
1621 } else if (level == 0) {
1624 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1626 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1631 YAFFS_TNODES_LEVEL0_BITS) + i;
1634 yaffs_FindChunkInGroup(dev,
1640 if (foundChunk > 0) {
1641 yaffs_DeleteChunk(dev,
1646 *limit = *limit - 1;
1654 yaffs_PutLevel0Tnode(dev,tn,i,0);
1658 return (i < 0) ? 1 : 0;
1668 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1671 yaffs_BlockInfo *theBlock;
1673 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1675 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1677 theBlock->softDeletions++;
1682 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1683 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1685 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1688 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1689 __u32 level, int chunkOffset)
1694 yaffs_Device *dev = in->myDev;
1699 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1701 if (tn->internal[i]) {
1703 yaffs_SoftDeleteWorker(in,
1709 YAFFS_TNODES_INTERNAL_BITS)
1712 yaffs_FreeTnode(dev,
1715 tn->internal[i] = NULL;
1717 /* Hoosterman... how could this happen? */
1721 return (allDone) ? 1 : 0;
1722 } else if (level == 0) {
1724 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1725 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1727 /* Note this does not find the real chunk, only the chunk group.
1728 * We make an assumption that a chunk group is not larger than
1731 yaffs_SoftDeleteChunk(dev, theChunk);
1732 yaffs_PutLevel0Tnode(dev,tn,i,0);
1746 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1749 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1750 if (obj->nDataChunks <= 0) {
1751 /* Empty file with no duplicate object headers, just delete it immediately */
1752 yaffs_FreeTnode(obj->myDev,
1753 obj->variant.fileVariant.top);
1754 obj->variant.fileVariant.top = NULL;
1755 T(YAFFS_TRACE_TRACING,
1756 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1758 yaffs_DoGenericObjectDeletion(obj);
1760 yaffs_SoftDeleteWorker(obj,
1761 obj->variant.fileVariant.top,
1762 obj->variant.fileVariant.
1764 obj->softDeleted = 1;
1769 /* Pruning removes any part of the file structure tree that is beyond the
1770 * bounds of the file (ie that does not point to chunks).
1772 * A file should only get pruned when its size is reduced.
1774 * Before pruning, the chunks must be pulled from the tree and the
1775 * level 0 tnode entries must be zeroed out.
1776 * Could also use this for file deletion, but that's probably better handled
1777 * by a special case.
1780 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1781 __u32 level, int del0)
1789 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1790 if (tn->internal[i] && level > 0) {
1792 yaffs_PruneWorker(dev, tn->internal[i],
1794 (i == 0) ? del0 : 1);
1797 if (tn->internal[i]) {
1802 if (hasData == 0 && del0) {
1803 /* Free and return NULL */
1805 yaffs_FreeTnode(dev, tn);
1815 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1816 yaffs_FileStructure * fStruct)
1823 if (fStruct->topLevel > 0) {
1825 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1827 /* Now we have a tree with all the non-zero branches NULL but the height
1828 * is the same as it was.
1829 * Let's see if we can trim internal tnodes to shorten the tree.
1830 * We can do this if only the 0th element in the tnode is in use
1831 * (ie all the non-zero are NULL)
1834 while (fStruct->topLevel && !done) {
1838 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1839 if (tn->internal[i]) {
1845 fStruct->top = tn->internal[0];
1846 fStruct->topLevel--;
1847 yaffs_FreeTnode(dev, tn);
1857 /*-------------------- End of File Structure functions.-------------------*/
1859 /* yaffs_CreateFreeObjects creates a bunch more objects and
1860 * adds them to the object free list.
1862 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1865 yaffs_Object *newObjects;
1866 yaffs_ObjectList *list;
1871 /* make these things */
1872 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1873 list = YMALLOC(sizeof(yaffs_ObjectList));
1875 if (!newObjects || !list) {
1880 T(YAFFS_TRACE_ALLOCATE,
1881 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1885 /* Hook them into the free list */
1886 for (i = 0; i < nObjects - 1; i++) {
1887 newObjects[i].siblings.next =
1888 (struct ylist_head *)(&newObjects[i + 1]);
1891 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1892 dev->freeObjects = newObjects;
1893 dev->nFreeObjects += nObjects;
1894 dev->nObjectsCreated += nObjects;
1896 /* Now add this bunch of Objects to a list for freeing up. */
1898 list->objects = newObjects;
1899 list->next = dev->allocatedObjectList;
1900 dev->allocatedObjectList = list;
1906 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1907 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1909 yaffs_Object *tn = NULL;
1911 #ifdef VALGRIND_TEST
1912 tn = YMALLOC(sizeof(yaffs_Object));
1914 /* If there are none left make more */
1915 if (!dev->freeObjects) {
1916 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1919 if (dev->freeObjects) {
1920 tn = dev->freeObjects;
1922 (yaffs_Object *) (dev->freeObjects->siblings.next);
1923 dev->nFreeObjects--;
1927 /* Now sweeten it up... */
1929 memset(tn, 0, sizeof(yaffs_Object));
1932 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1933 YINIT_LIST_HEAD(&(tn->hardLinks));
1934 YINIT_LIST_HEAD(&(tn->hashLink));
1935 YINIT_LIST_HEAD(&tn->siblings);
1938 /* Now make the directory sane */
1940 tn->parent = dev->rootDir;
1941 ylist_add(&(tn->siblings),&dev->rootDir->variant.directoryVariant.children);
1944 /* Add it to the lost and found directory.
1945 * NB Can't put root or lostNFound in lostNFound so
1946 * check if lostNFound exists first
1948 if (dev->lostNFoundDir) {
1949 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1953 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1958 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1963 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1965 obj->fake = 1; /* it is fake so it might have no NAND presence... */
1966 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1967 obj->unlinkAllowed = 0; /* ... or unlink it */
1970 obj->yst_mode = mode;
1972 obj->hdrChunk = 0; /* Not a valid chunk. */
1979 static void yaffs_UnhashObject(yaffs_Object * tn)
1982 yaffs_Device *dev = tn->myDev;
1984 /* If it is still linked into the bucket list, free from the list */
1985 if (!ylist_empty(&tn->hashLink)) {
1986 ylist_del_init(&tn->hashLink);
1987 bucket = yaffs_HashFunction(tn->objectId);
1988 dev->objectBucket[bucket].count--;
1993 /* FreeObject frees up a Object and puts it back on the free list */
1994 static void yaffs_FreeObject(yaffs_Object * tn)
1997 yaffs_Device *dev = tn->myDev;
2002 if(!ylist_empty(&tn->siblings))
2008 /* We're still hooked up to a cached inode.
2009 * Don't delete now, but mark for later deletion
2011 tn->deferedFree = 1;
2016 yaffs_UnhashObject(tn);
2018 #ifdef VALGRIND_TEST
2021 /* Link into the free list. */
2022 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2023 dev->freeObjects = tn;
2024 dev->nFreeObjects++;
2026 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2032 void yaffs_HandleDeferedFree(yaffs_Object * obj)
2034 if (obj->deferedFree) {
2035 yaffs_FreeObject(obj);
2041 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
2043 /* Free the list of allocated Objects */
2045 yaffs_ObjectList *tmp;
2047 while (dev->allocatedObjectList) {
2048 tmp = dev->allocatedObjectList->next;
2049 YFREE(dev->allocatedObjectList->objects);
2050 YFREE(dev->allocatedObjectList);
2052 dev->allocatedObjectList = tmp;
2055 dev->freeObjects = NULL;
2056 dev->nFreeObjects = 0;
2059 static void yaffs_InitialiseObjects(yaffs_Device * dev)
2063 dev->allocatedObjectList = NULL;
2064 dev->freeObjects = NULL;
2065 dev->nFreeObjects = 0;
2067 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2068 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2069 dev->objectBucket[i].count = 0;
2074 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
2079 int lowest = 999999;
2081 /* First let's see if we can find one that's empty. */
2083 for (i = 0; i < 10 && lowest > 0; i++) {
2085 x %= YAFFS_NOBJECT_BUCKETS;
2086 if (dev->objectBucket[x].count < lowest) {
2087 lowest = dev->objectBucket[x].count;
2093 /* If we didn't find an empty list, then try
2094 * looking a bit further for a short one
2097 for (i = 0; i < 10 && lowest > 3; i++) {
2099 x %= YAFFS_NOBJECT_BUCKETS;
2100 if (dev->objectBucket[x].count < lowest) {
2101 lowest = dev->objectBucket[x].count;
2110 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
2112 int bucket = yaffs_FindNiceObjectBucket(dev);
2114 /* Now find an object value that has not already been taken
2115 * by scanning the list.
2119 struct ylist_head *i;
2121 __u32 n = (__u32) bucket;
2123 /* yaffs_CheckObjectHashSanity(); */
2127 n += YAFFS_NOBJECT_BUCKETS;
2128 if (1 || dev->objectBucket[bucket].count > 0) {
2129 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2130 /* If there is already one in the list */
2132 && ylist_entry(i, yaffs_Object,
2133 hashLink)->objectId == n) {
2144 static void yaffs_HashObject(yaffs_Object * in)
2146 int bucket = yaffs_HashFunction(in->objectId);
2147 yaffs_Device *dev = in->myDev;
2149 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2150 dev->objectBucket[bucket].count++;
2154 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
2156 int bucket = yaffs_HashFunction(number);
2157 struct ylist_head *i;
2160 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2161 /* Look if it is in the list */
2163 in = ylist_entry(i, yaffs_Object, hashLink);
2164 if (in->objectId == number) {
2166 /* Don't tell the VFS about this one if it is defered free */
2167 if (in->deferedFree)
2179 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
2180 yaffs_ObjectType type)
2183 yaffs_Object *theObject;
2184 yaffs_Tnode *tn = NULL;
2187 number = yaffs_CreateNewObjectNumber(dev);
2190 theObject = yaffs_AllocateEmptyObject(dev);
2194 if(type == YAFFS_OBJECT_TYPE_FILE){
2195 tn = yaffs_GetTnode(dev);
2197 yaffs_FreeObject(theObject);
2205 theObject->fake = 0;
2206 theObject->renameAllowed = 1;
2207 theObject->unlinkAllowed = 1;
2208 theObject->objectId = number;
2209 yaffs_HashObject(theObject);
2210 theObject->variantType = type;
2211 #ifdef CONFIG_YAFFS_WINCE
2212 yfsd_WinFileTimeNow(theObject->win_atime);
2213 theObject->win_ctime[0] = theObject->win_mtime[0] =
2214 theObject->win_atime[0];
2215 theObject->win_ctime[1] = theObject->win_mtime[1] =
2216 theObject->win_atime[1];
2220 theObject->yst_atime = theObject->yst_mtime =
2221 theObject->yst_ctime = Y_CURRENT_TIME;
2225 theObject->sum_prev = 12345;
2226 theObject->sum_trailer = 6789;
2230 case YAFFS_OBJECT_TYPE_FILE:
2231 theObject->variant.fileVariant.fileSize = 0;
2232 theObject->variant.fileVariant.scannedFileSize = 0;
2233 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2234 theObject->variant.fileVariant.topLevel = 0;
2235 theObject->variant.fileVariant.top = tn;
2237 case YAFFS_OBJECT_TYPE_DIRECTORY:
2238 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2241 case YAFFS_OBJECT_TYPE_SYMLINK:
2242 case YAFFS_OBJECT_TYPE_HARDLINK:
2243 case YAFFS_OBJECT_TYPE_SPECIAL:
2244 /* No action required */
2246 case YAFFS_OBJECT_TYPE_UNKNOWN:
2247 /* todo this should not happen */
2255 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
2257 yaffs_ObjectType type)
2259 yaffs_Object *theObject = NULL;
2262 theObject = yaffs_FindObjectByNumber(dev, number);
2266 theObject = yaffs_CreateNewObject(dev, number, type);
2274 static YCHAR *yaffs_CloneString(const YCHAR * str)
2276 YCHAR *newStr = NULL;
2279 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2281 yaffs_strcpy(newStr, str);
2289 * Mknod (create) a new object.
2290 * equivalentObject only has meaning for a hard link;
2291 * aliasString only has meaning for a sumlink.
2292 * rdev only has meaning for devices (a subset of special objects)
2295 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2296 yaffs_Object * parent,
2301 yaffs_Object * equivalentObject,
2302 const YCHAR * aliasString, __u32 rdev)
2307 yaffs_Device *dev = parent->myDev;
2309 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2310 if (yaffs_FindObjectByName(parent, name)) {
2314 in = yaffs_CreateNewObject(dev, -1, type);
2319 if(type == YAFFS_OBJECT_TYPE_SYMLINK){
2320 str = yaffs_CloneString(aliasString);
2322 yaffs_FreeObject(in);
2332 in->variantType = type;
2334 in->yst_mode = mode;
2336 #ifdef CONFIG_YAFFS_WINCE
2337 yfsd_WinFileTimeNow(in->win_atime);
2338 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2339 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2342 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2344 in->yst_rdev = rdev;
2348 in->nDataChunks = 0;
2350 yaffs_SetObjectName(in, name);
2353 yaffs_AddObjectToDirectory(parent, in);
2355 in->myDev = parent->myDev;
2358 case YAFFS_OBJECT_TYPE_SYMLINK:
2359 in->variant.symLinkVariant.alias = str;
2361 case YAFFS_OBJECT_TYPE_HARDLINK:
2362 in->variant.hardLinkVariant.equivalentObject =
2364 in->variant.hardLinkVariant.equivalentObjectId =
2365 equivalentObject->objectId;
2366 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2368 case YAFFS_OBJECT_TYPE_FILE:
2369 case YAFFS_OBJECT_TYPE_DIRECTORY:
2370 case YAFFS_OBJECT_TYPE_SPECIAL:
2371 case YAFFS_OBJECT_TYPE_UNKNOWN:
2376 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2377 /* Could not create the object header, fail the creation */
2378 yaffs_DestroyObject(in);
2387 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
2388 __u32 mode, __u32 uid, __u32 gid)
2390 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2391 uid, gid, NULL, NULL, 0);
2394 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
2395 __u32 mode, __u32 uid, __u32 gid)
2397 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2398 mode, uid, gid, NULL, NULL, 0);
2401 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
2402 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2404 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2405 uid, gid, NULL, NULL, rdev);
2408 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
2409 __u32 mode, __u32 uid, __u32 gid,
2410 const YCHAR * alias)
2412 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2413 uid, gid, NULL, alias, 0);
2416 /* yaffs_Link returns the object id of the equivalent object.*/
2417 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
2418 yaffs_Object * equivalentObject)
2420 /* Get the real object in case we were fed a hard link as an equivalent object */
2421 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2423 if (yaffs_MknodObject
2424 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2425 equivalentObject, NULL, 0)) {
2426 return equivalentObject;
2433 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
2434 const YCHAR * newName, int force, int shadows)
2439 yaffs_Object *existingTarget;
2441 if (newDir == NULL) {
2442 newDir = obj->parent; /* use the old directory */
2445 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2446 T(YAFFS_TRACE_ALWAYS,
2448 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2453 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2454 if (obj->myDev->isYaffs2) {
2455 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2457 unlinkOp = (newDir == obj->myDev->unlinkedDir
2458 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2461 deleteOp = (newDir == obj->myDev->deletedDir);
2463 existingTarget = yaffs_FindObjectByName(newDir, newName);
2465 /* If the object is a file going into the unlinked directory,
2466 * then it is OK to just stuff it in since duplicate names are allowed.
2467 * else only proceed if the new name does not exist and if we're putting
2468 * it into a directory.
2475 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2476 yaffs_SetObjectName(obj, newName);
2479 yaffs_AddObjectToDirectory(newDir, obj);
2484 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2485 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
2492 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
2493 yaffs_Object * newDir, const YCHAR * newName)
2495 yaffs_Object *obj=NULL;
2496 yaffs_Object *existingTarget=NULL;
2500 if(!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2502 if(!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2505 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2506 /* Special case for case insemsitive systems (eg. WinCE).
2507 * While look-up is case insensitive, the name isn't.
2508 * Therefore we might want to change x.txt to X.txt
2510 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
2515 else if (yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2519 obj = yaffs_FindObjectByName(oldDir, oldName);
2521 if (obj && obj->renameAllowed) {
2523 /* Now do the handling for an existing target, if there is one */
2525 existingTarget = yaffs_FindObjectByName(newDir, newName);
2526 if (existingTarget &&
2527 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2528 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2529 /* There is a target that is a non-empty directory, so we fail */
2530 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2531 } else if (existingTarget && existingTarget != obj) {
2532 /* Nuke the target first, using shadowing,
2533 * but only if it isn't the same object
2535 yaffs_ChangeObjectName(obj, newDir, newName, force,
2536 existingTarget->objectId);
2537 yaffs_UnlinkObject(existingTarget);
2540 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2545 /*------------------------- Block Management and Page Allocation ----------------*/
2547 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
2549 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2551 dev->blockInfo = NULL;
2552 dev->chunkBits = NULL;
2554 dev->allocationBlock = -1; /* force it to get a new one */
2556 /* If the first allocation strategy fails, thry the alternate one */
2557 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2558 if(!dev->blockInfo){
2559 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2560 dev->blockInfoAlt = 1;
2563 dev->blockInfoAlt = 0;
2567 /* Set up dynamic blockinfo stuff. */
2568 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2569 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2570 if(!dev->chunkBits){
2571 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2572 dev->chunkBitsAlt = 1;
2575 dev->chunkBitsAlt = 0;
2578 if (dev->blockInfo && dev->chunkBits) {
2579 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2580 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2588 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
2590 if(dev->blockInfoAlt && dev->blockInfo)
2591 YFREE_ALT(dev->blockInfo);
2592 else if(dev->blockInfo)
2593 YFREE(dev->blockInfo);
2595 dev->blockInfoAlt = 0;
2597 dev->blockInfo = NULL;
2599 if(dev->chunkBitsAlt && dev->chunkBits)
2600 YFREE_ALT(dev->chunkBits);
2601 else if(dev->chunkBits)
2602 YFREE(dev->chunkBits);
2603 dev->chunkBitsAlt = 0;
2604 dev->chunkBits = NULL;
2607 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
2608 yaffs_BlockInfo * bi)
2615 return 1; /* disqualification only applies to yaffs2. */
2617 if (!bi->hasShrinkHeader)
2618 return 1; /* can gc */
2620 /* Find the oldest dirty sequence number if we don't know it and save it
2621 * so we don't have to keep recomputing it.
2623 if (!dev->oldestDirtySequence) {
2624 seq = dev->sequenceNumber;
2626 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2628 b = yaffs_GetBlockInfo(dev, i);
2629 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2630 (b->pagesInUse - b->softDeletions) <
2631 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2632 seq = b->sequenceNumber;
2635 dev->oldestDirtySequence = seq;
2638 /* Can't do gc of this block if there are any blocks older than this one that have
2641 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2645 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2646 * for garbage collection.
2649 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2653 int b = dev->currentDirtyChecker;
2660 yaffs_BlockInfo *bi;
2661 int pendingPrioritisedExist = 0;
2663 /* First let's see if we need to grab a prioritised block */
2664 if(dev->hasPendingPrioritisedGCs){
2665 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2667 bi = yaffs_GetBlockInfo(dev, i);
2668 //yaffs_VerifyBlock(dev,bi,i);
2670 if(bi->gcPrioritise) {
2671 pendingPrioritisedExist = 1;
2672 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2673 yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2674 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2677 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2682 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2683 dev->hasPendingPrioritisedGCs = 0;
2686 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2688 * else (we're doing a leasurely gc), then we only bother to do this if the
2689 * block has only a few pages in use.
2692 dev->nonAggressiveSkip--;
2694 if (!aggressive && (dev->nonAggressiveSkip > 0)) {
2700 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2704 dev->internalEndBlock - dev->internalStartBlock + 1;
2707 dev->internalEndBlock - dev->internalStartBlock + 1;
2708 iterations = iterations / 16;
2709 if (iterations > 200) {
2714 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2716 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2717 b = dev->internalStartBlock;
2720 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2721 T(YAFFS_TRACE_ERROR,
2722 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2726 bi = yaffs_GetBlockInfo(dev, b);
2729 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2736 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2737 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2738 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2740 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2744 dev->currentDirtyChecker = b;
2748 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2749 dev->nChunksPerBlock - pagesInUse,prioritised));
2752 dev->oldestDirtySequence = 0;
2755 dev->nonAggressiveSkip = 4;
2761 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2763 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2767 /* If the block is still healthy erase it and mark as clean.
2768 * If the block has had a data failure, then retire it.
2771 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2772 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2773 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2775 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2777 if (!bi->needsRetiring) {
2778 yaffs_InvalidateCheckpoint(dev);
2779 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2781 dev->nErasureFailures++;
2782 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2783 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2788 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2790 for (i = 0; i < dev->nChunksPerBlock; i++) {
2791 if (!yaffs_CheckChunkErased
2792 (dev, blockNo * dev->nChunksPerBlock + i)) {
2793 T(YAFFS_TRACE_ERROR,
2795 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2796 TENDSTR), blockNo, i));
2802 /* Clean it up... */
2803 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2804 dev->nErasedBlocks++;
2806 bi->softDeletions = 0;
2807 bi->hasShrinkHeader = 0;
2808 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2809 bi->gcPrioritise = 0;
2810 yaffs_ClearChunkBits(dev, blockNo);
2812 T(YAFFS_TRACE_ERASE,
2813 (TSTR("Erased block %d" TENDSTR), blockNo));
2815 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2817 yaffs_RetireBlock(dev, blockNo);
2818 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2819 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2823 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2827 yaffs_BlockInfo *bi;
2829 if (dev->nErasedBlocks < 1) {
2830 /* Hoosterman we've got a problem.
2831 * Can't get space to gc
2833 T(YAFFS_TRACE_ERROR,
2834 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2839 /* Find an empty block. */
2841 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2842 dev->allocationBlockFinder++;
2843 if (dev->allocationBlockFinder < dev->internalStartBlock
2844 || dev->allocationBlockFinder > dev->internalEndBlock) {
2845 dev->allocationBlockFinder = dev->internalStartBlock;
2848 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2850 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2851 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2852 dev->sequenceNumber++;
2853 bi->sequenceNumber = dev->sequenceNumber;
2854 dev->nErasedBlocks--;
2855 T(YAFFS_TRACE_ALLOCATE,
2856 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2857 dev->allocationBlockFinder, dev->sequenceNumber,
2858 dev->nErasedBlocks));
2859 return dev->allocationBlockFinder;
2863 T(YAFFS_TRACE_ALWAYS,
2865 ("yaffs tragedy: no more erased blocks, but there should have been %d"
2866 TENDSTR), dev->nErasedBlocks));
2873 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2875 if(!dev->nCheckpointBlocksRequired &&
2877 /* Not a valid value so recalculate */
2880 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2883 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2885 if(tnodeSize < sizeof(yaffs_Tnode))
2886 tnodeSize = sizeof(yaffs_Tnode);
2888 nBytes += sizeof(yaffs_CheckpointValidity);
2889 nBytes += sizeof(yaffs_CheckpointDevice);
2890 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2891 nBytes += devBlocks * dev->chunkBitmapStride;
2892 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2893 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2894 nBytes += sizeof(yaffs_CheckpointValidity);
2895 nBytes += sizeof(__u32); /* checksum*/
2897 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2899 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2901 dev->nCheckpointBlocksRequired = nBlocks;
2904 return dev->nCheckpointBlocksRequired;
2907 // Check if there's space to allocate...
2908 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2909 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2912 int reservedBlocks = dev->nReservedBlocks;
2913 int checkpointBlocks;
2916 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
2917 dev->blocksInCheckpoint;
2918 if(checkpointBlocks < 0)
2919 checkpointBlocks = 0;
2921 checkpointBlocks =0;
2924 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2926 return (dev->nFreeChunks > reservedChunks);
2929 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2932 yaffs_BlockInfo *bi;
2934 if (dev->allocationBlock < 0) {
2935 /* Get next block to allocate off */
2936 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2937 dev->allocationPage = 0;
2940 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2941 /* Not enough space to allocate unless we're allowed to use the reserve. */
2945 if (dev->nErasedBlocks < dev->nReservedBlocks
2946 && dev->allocationPage == 0) {
2947 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2950 /* Next page please.... */
2951 if (dev->allocationBlock >= 0) {
2952 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2954 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2955 dev->allocationPage;
2957 yaffs_SetChunkBit(dev, dev->allocationBlock,
2958 dev->allocationPage);
2960 dev->allocationPage++;
2964 /* If the block is full set the state to full */
2965 if (dev->allocationPage >= dev->nChunksPerBlock) {
2966 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2967 dev->allocationBlock = -1;
2976 T(YAFFS_TRACE_ERROR,
2977 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2982 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2986 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2988 if (dev->allocationBlock > 0) {
2989 n += (dev->nChunksPerBlock - dev->allocationPage);
2996 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
3002 int retVal = YAFFS_OK;
3005 int isCheckpointBlock;
3008 int chunksBefore = yaffs_GetErasedChunks(dev);
3011 yaffs_ExtendedTags tags;
3013 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3015 yaffs_Object *object;
3017 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3019 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3021 T(YAFFS_TRACE_TRACING,
3022 (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
3023 bi->pagesInUse, bi->hasShrinkHeader));
3025 /*yaffs_VerifyFreeChunks(dev); */
3027 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
3029 /* Take off the number of soft deleted entries because
3030 * they're going to get really deleted during GC.
3032 dev->nFreeChunks -= bi->softDeletions;
3036 if (isCheckpointBlock ||
3037 !yaffs_StillSomeChunkBits(dev, block)) {
3038 T(YAFFS_TRACE_TRACING,
3040 ("Collecting block %d that has no chunks in use" TENDSTR),
3042 yaffs_BlockBecameDirty(dev, block);
3045 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3047 yaffs_VerifyBlock(dev,bi,block);
3049 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
3050 retVal == YAFFS_OK &&
3051 chunkInBlock < dev->nChunksPerBlock
3052 && yaffs_StillSomeChunkBits(dev, block);
3053 chunkInBlock++, oldChunk++) {
3054 if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
3056 /* This page is in use and might need to be copied off */
3060 yaffs_InitialiseTags(&tags);
3062 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3066 yaffs_FindObjectByNumber(dev,
3069 T(YAFFS_TRACE_GC_DETAIL,
3071 ("Collecting page %d, %d %d %d " TENDSTR),
3072 chunkInBlock, tags.objectId, tags.chunkId,
3075 if(object && !yaffs_SkipVerification(dev)){
3076 if(tags.chunkId == 0)
3077 matchingChunk = object->hdrChunk;
3078 else if(object->softDeleted)
3079 matchingChunk = oldChunk; /* Defeat the test */
3081 matchingChunk = yaffs_FindChunkInFile(object,tags.chunkId,NULL);
3083 if(oldChunk != matchingChunk)
3084 T(YAFFS_TRACE_ERROR,
3085 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3086 oldChunk,matchingChunk,tags.objectId, tags.chunkId));
3091 T(YAFFS_TRACE_ERROR,
3093 ("page %d in gc has no object: %d %d %d "
3095 tags.objectId, tags.chunkId, tags.byteCount));
3100 object->softDeleted &&
3101 tags.chunkId != 0) {
3102 /* Data chunk in a soft deleted file, throw it away
3103 * It's a soft deleted data chunk,
3104 * No need to copy this, just forget about it and
3105 * fix up the object.
3108 object->nDataChunks--;
3110 if (object->nDataChunks <= 0) {
3111 /* remeber to clean up the object */
3112 dev->gcCleanupList[cleanups] =
3118 /* Todo object && object->deleted && object->nDataChunks == 0 */
3120 /* Deleted object header with no data chunks.
3121 * Can be discarded and the file deleted.
3123 object->hdrChunk = 0;
3124 yaffs_FreeTnode(object->myDev,
3127 object->variant.fileVariant.top = NULL;
3128 yaffs_DoGenericObjectDeletion(object);
3130 } else if (object) {
3131 /* It's either a data chunk in a live file or
3132 * an ObjectHeader, so we're interested in it.
3133 * NB Need to keep the ObjectHeaders of deleted files
3134 * until the whole file has been deleted off
3136 tags.serialNumber++;
3140 if (tags.chunkId == 0) {
3141 /* It is an object Id,
3142 * We need to nuke the shrinkheader flags first
3143 * We no longer want the shrinkHeader flag since its work is done
3144 * and if it is left in place it will mess up scanning.
3145 * Also, clear out any shadowing stuff
3148 yaffs_ObjectHeader *oh;
3149 oh = (yaffs_ObjectHeader *)buffer;
3151 /* oh->shadowsObject = oh->inbandShadowsObject = -1; */
3152 tags.extraShadows = 0;
3153 tags.extraIsShrinkHeader = 0;
3155 yaffs_VerifyObjectHeader(object,oh,&tags,1);
3159 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3162 retVal = YAFFS_FAIL;
3165 /* Ok, now fix up the Tnodes etc. */
3167 if (tags.chunkId == 0) {
3169 object->hdrChunk = newChunk;
3170 object->serial = tags.serialNumber;
3172 /* It's a data chunk */
3173 yaffs_PutChunkIntoFile
3181 if(retVal == YAFFS_OK)
3182 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3187 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3190 /* Do any required cleanups */
3191 for (i = 0; i < cleanups; i++) {
3192 /* Time to delete the file too */
3194 yaffs_FindObjectByNumber(dev,
3195 dev->gcCleanupList[i]);
3197 yaffs_FreeTnode(dev,
3198 object->variant.fileVariant.
3200 object->variant.fileVariant.top = NULL;
3203 ("yaffs: About to finally delete object %d"
3204 TENDSTR), object->objectId));
3205 yaffs_DoGenericObjectDeletion(object);
3206 object->myDev->nDeletedFiles--;
3213 yaffs_VerifyCollectedBlock(dev,bi,block);
3215 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
3218 ("gc did not increase free chunks before %d after %d"
3219 TENDSTR), chunksBefore, chunksAfter));
3227 /* New garbage collector
3228 * If we're very low on erased blocks then we do aggressive garbage collection
3229 * otherwise we do "leasurely" garbage collection.
3230 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3231 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3233 * The idea is to help clear out space in a more spread-out manner.
3234 * Dunno if it really does anything useful.
3236 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
3240 int gcOk = YAFFS_OK;
3243 int checkpointBlockAdjust;
3245 if (dev->isDoingGC) {
3246 /* Bail out so we don't get recursive gc */
3250 /* This loop should pass the first time.
3251 * We'll only see looping here if the erase of the collected block fails.
3257 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3258 if(checkpointBlockAdjust < 0)
3259 checkpointBlockAdjust = 0;
3261 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3262 /* We need a block soon...*/
3265 /* We're in no hurry */
3269 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3272 dev->garbageCollections++;
3274 dev->passiveGarbageCollections++;
3279 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3280 dev->nErasedBlocks, aggressive));
3282 gcOk = yaffs_GarbageCollectBlock(dev, block);
3285 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3288 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3289 TENDSTR), dev->nErasedBlocks, maxTries, block));
3291 } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
3294 return aggressive ? gcOk : YAFFS_OK;
3297 /*------------------------- TAGS --------------------------------*/
3299 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
3302 return (tags->chunkId == chunkInObject &&
3303 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3308 /*-------------------- Data file manipulation -----------------*/
3310 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
3311 yaffs_ExtendedTags * tags)
3313 /*Get the Tnode, then get the level 0 offset chunk offset */
3316 yaffs_ExtendedTags localTags;
3319 yaffs_Device *dev = in->myDev;
3322 /* Passed a NULL, so use our own tags space */
3326 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3329 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3332 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3338 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
3339 yaffs_ExtendedTags * tags)
3341 /* Get the Tnode, then get the level 0 offset chunk offset */
3344 yaffs_ExtendedTags localTags;
3346 yaffs_Device *dev = in->myDev;
3350 /* Passed a NULL, so use our own tags space */
3354 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3358 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3361 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3364 /* Delete the entry in the filestructure (if found) */
3366 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
3369 /*T(("No level 0 found for %d\n", chunkInInode)); */
3373 /* T(("Could not find %d to delete\n",chunkInInode)); */
3378 #ifdef YAFFS_PARANOID
3380 static int yaffs_CheckFileSanity(yaffs_Object * in)
3388 yaffs_Tags localTags;
3389 yaffs_Tags *tags = &localTags;
3393 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3394 /* T(("Object not a file\n")); */
3398 objId = in->objectId;
3399 fSize = in->variant.fileVariant.fileSize;
3401 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3403 for (chunk = 1; chunk <= nChunks; chunk++) {
3404 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3409 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
3411 if (yaffs_CheckChunkBits
3412 (dev, theChunk / dev->nChunksPerBlock,
3413 theChunk % dev->nChunksPerBlock)) {
3415 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3419 (tags, in->objectId, chunk, chunkDeleted)) {
3429 /* T(("No level 0 found for %d\n", chunk)); */
3433 return failed ? YAFFS_FAIL : YAFFS_OK;
3438 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
3439 int chunkInNAND, int inScan)
3441 /* NB inScan is zero unless scanning.
3442 * For forward scanning, inScan is > 0;
3443 * for backward scanning inScan is < 0
3447 yaffs_Device *dev = in->myDev;
3449 yaffs_ExtendedTags existingTags;
3450 yaffs_ExtendedTags newTags;
3451 unsigned existingSerial, newSerial;
3453 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3454 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3455 * If it is not during Scanning then something went wrong!
3458 T(YAFFS_TRACE_ERROR,
3460 ("yaffs tragedy:attempt to put data chunk into a non-file"
3465 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3469 tn = yaffs_AddOrFindLevel0Tnode(dev,
3470 &in->variant.fileVariant,
3477 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3480 /* If we're scanning then we need to test for duplicates
3481 * NB This does not need to be efficient since it should only ever
3482 * happen when the power fails during a write, then only one
3483 * chunk should ever be affected.
3485 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3486 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3489 if (existingChunk > 0) {
3490 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3491 * thus we have to do a FindChunkInFile to get the real chunk id.
3493 * We have a duplicate now we need to decide which one to use:
3495 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3496 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3497 * YAFFS1: Get both sets of tags and compare serial numbers.
3501 /* Only do this for forward scanning */
3502 yaffs_ReadChunkWithTagsFromNAND(dev,
3506 /* Do a proper find */
3508 yaffs_FindChunkInFile(in, chunkInInode,
3512 if (existingChunk <= 0) {
3513 /*Hoosterman - how did this happen? */
3515 T(YAFFS_TRACE_ERROR,
3517 ("yaffs tragedy: existing chunk < 0 in scan"
3522 /* NB The deleted flags should be false, otherwise the chunks will
3523 * not be loaded during a scan
3527 newSerial = newTags.serialNumber;
3528 existingSerial = existingTags.serialNumber;
3532 (in->myDev->isYaffs2 ||
3533 existingChunk <= 0 ||
3534 ((existingSerial + 1) & 3) == newSerial)) {
3535 /* Forward scanning.
3537 * Delete the old one and drop through to update the tnode
3539 yaffs_DeleteChunk(dev, existingChunk, 1,
3542 /* Backward scanning or we want to use the existing one
3544 * Delete the new one and return early so that the tnode isn't changed
3546 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3554 if (existingChunk == 0) {
3558 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
3563 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
3566 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3568 if (chunkInNAND >= 0) {
3569 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3572 T(YAFFS_TRACE_NANDACCESS,
3573 (TSTR("Chunk %d not found zero instead" TENDSTR),
3575 /* get sane (zero) data if you read a hole */
3576 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3582 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
3586 yaffs_ExtendedTags tags;
3587 yaffs_BlockInfo *bi;
3594 block = chunkId / dev->nChunksPerBlock;
3595 page = chunkId % dev->nChunksPerBlock;
3598 if(!yaffs_CheckChunkBit(dev,block,page))
3599 T(YAFFS_TRACE_VERIFY,
3600 (TSTR("Deleting invalid chunk %d"TENDSTR),
3603 bi = yaffs_GetBlockInfo(dev, block);
3605 T(YAFFS_TRACE_DELETION,
3606 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3609 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3611 yaffs_InitialiseTags(&tags);
3613 tags.chunkDeleted = 1;
3615 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3616 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3618 dev->nUnmarkedDeletions++;
3621 /* Pull out of the management area.
3622 * If the whole block became dirty, this will kick off an erasure.
3624 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3625 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3626 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3627 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3630 yaffs_ClearChunkBit(dev, block, page);
3634 if (bi->pagesInUse == 0 &&
3635 !bi->hasShrinkHeader &&
3636 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3637 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3638 yaffs_BlockBecameDirty(dev, block);
3642 /* T(("Bad news deleting chunk %d\n",chunkId)); */
3647 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
3648 const __u8 * buffer, int nBytes,
3651 /* Find old chunk Need to do this to get serial number
3652 * Write new one and patch into tree.
3653 * Invalidate old tags.
3657 yaffs_ExtendedTags prevTags;
3660 yaffs_ExtendedTags newTags;
3662 yaffs_Device *dev = in->myDev;
3664 yaffs_CheckGarbageCollection(dev);
3666 /* Get the previous chunk at this location in the file if it exists */
3667 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3669 /* Set up new tags */
3670 yaffs_InitialiseTags(&newTags);
3672 newTags.chunkId = chunkInInode;
3673 newTags.objectId = in->objectId;
3674 newTags.serialNumber =
3675 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
3676 newTags.byteCount = nBytes;
3678 if(nBytes < 1 || nBytes > dev->totalBytesPerChunk){
3679 T(YAFFS_TRACE_ERROR,
3680 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3687 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3690 if (newChunkId >= 0) {
3691 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3693 if (prevChunkId >= 0) {
3694 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3698 yaffs_CheckFileSanity(in);
3704 /* UpdateObjectHeader updates the header on NAND for an object.
3705 * If name is not NULL, then that new name is used.
3707 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
3708 int isShrink, int shadows)
3711 yaffs_BlockInfo *bi;
3713 yaffs_Device *dev = in->myDev;
3720 yaffs_ExtendedTags newTags;
3721 yaffs_ExtendedTags oldTags;
3723 __u8 *buffer = NULL;
3724 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3726 yaffs_ObjectHeader *oh = NULL;
3728 yaffs_strcpy(oldName,_Y("silly old name"));
3732 in == dev->rootDir || /* The rootDir should also be saved */
3735 yaffs_CheckGarbageCollection(dev);
3736 yaffs_CheckObjectDetailsLoaded(in);
3738 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3739 oh = (yaffs_ObjectHeader *) buffer;
3741 prevChunkId = in->hdrChunk;
3743 if (prevChunkId > 0) {
3744 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3747 yaffs_VerifyObjectHeader(in,oh,&oldTags,0);
3749 memcpy(oldName, oh->name, sizeof(oh->name));
3752 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3754 oh->type = in->variantType;
3755 oh->yst_mode = in->yst_mode;
3756 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3758 #ifdef CONFIG_YAFFS_WINCE
3759 oh->win_atime[0] = in->win_atime[0];
3760 oh->win_ctime[0] = in->win_ctime[0];
3761 oh->win_mtime[0] = in->win_mtime[0];
3762 oh->win_atime[1] = in->win_atime[1];
3763 oh->win_ctime[1] = in->win_ctime[1];
3764 oh->win_mtime[1] = in->win_mtime[1];
3766 oh->yst_uid = in->yst_uid;
3767 oh->yst_gid = in->yst_gid;
3768 oh->yst_atime = in->yst_atime;
3769 oh->yst_mtime = in->yst_mtime;
3770 oh->yst_ctime = in->yst_ctime;
3771 oh->yst_rdev = in->yst_rdev;
3774 oh->parentObjectId = in->parent->objectId;
3776 oh->parentObjectId = 0;
3779 if (name && *name) {
3780 memset(oh->name, 0, sizeof(oh->name));
3781 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3782 } else if (prevChunkId>=0) {
3783 memcpy(oh->name, oldName, sizeof(oh->name));
3785 memset(oh->name, 0, sizeof(oh->name));
3788 oh->isShrink = isShrink;
3790 switch (in->variantType) {
3791 case YAFFS_OBJECT_TYPE_UNKNOWN:
3792 /* Should not happen */
3794 case YAFFS_OBJECT_TYPE_FILE:
3796 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3797 || oh->parentObjectId ==
3798 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3799 fileVariant.fileSize;
3801 case YAFFS_OBJECT_TYPE_HARDLINK:
3802 oh->equivalentObjectId =
3803 in->variant.hardLinkVariant.equivalentObjectId;
3805 case YAFFS_OBJECT_TYPE_SPECIAL:
3808 case YAFFS_OBJECT_TYPE_DIRECTORY:
3811 case YAFFS_OBJECT_TYPE_SYMLINK:
3812 yaffs_strncpy(oh->alias,
3813 in->variant.symLinkVariant.alias,
3814 YAFFS_MAX_ALIAS_LENGTH);
3815 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3820 yaffs_InitialiseTags(&newTags);
3822 newTags.chunkId = 0;
3823 newTags.objectId = in->objectId;
3824 newTags.serialNumber = in->serial;
3826 /* Add extra info for file header */
3828 newTags.extraHeaderInfoAvailable = 1;
3829 newTags.extraParentObjectId = oh->parentObjectId;
3830 newTags.extraFileLength = oh->fileSize;
3831 newTags.extraIsShrinkHeader = oh->isShrink;
3832 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3833 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3834 newTags.extraObjectType = in->variantType;
3836 yaffs_VerifyObjectHeader(in,oh,&newTags,1);
3838 /* Create new chunk in NAND */
3840 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3841 (prevChunkId >= 0) ? 1 : 0);
3843 if (newChunkId >= 0) {
3845 in->hdrChunk = newChunkId;
3847 if (prevChunkId >= 0) {
3848 yaffs_DeleteChunk(dev, prevChunkId, 1,
3852 if(!yaffs_ObjectHasCachedWriteData(in))
3855 /* If this was a shrink, then mark the block that the chunk lives on */
3857 bi = yaffs_GetBlockInfo(in->myDev,
3858 newChunkId /in->myDev-> nChunksPerBlock);
3859 bi->hasShrinkHeader = 1;
3864 retVal = newChunkId;
3869 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3874 /*------------------------ Short Operations Cache ----------------------------------------
3875 * In many situations where there is no high level buffering (eg WinCE) a lot of
3876 * reads might be short sequential reads, and a lot of writes may be short
3877 * sequential writes. eg. scanning/writing a jpeg file.
3878 * In these cases, a short read/write cache can provide a huge perfomance benefit
3879 * with dumb-as-a-rock code.
3880 * In Linux, the page cache provides read buffering aand the short op cache provides write
3883 * There are a limited number (~10) of cache chunks per device so that we don't
3884 * need a very intelligent search.
3887 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3889 yaffs_Device *dev = obj->myDev;
3891 yaffs_ChunkCache *cache;
3892 int nCaches = obj->myDev->nShortOpCaches;
3894 for(i = 0; i < nCaches; i++){
3895 cache = &dev->srCache[i];
3896 if (cache->object == obj &&
3905 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3907 yaffs_Device *dev = obj->myDev;
3908 int lowest = -99; /* Stop compiler whining. */
3910 yaffs_ChunkCache *cache;
3911 int chunkWritten = 0;
3912 int nCaches = obj->myDev->nShortOpCaches;
3918 /* Find the dirty cache for this object with the lowest chunk id. */
3919 for (i = 0; i < nCaches; i++) {
3920 if (dev->srCache[i].object == obj &&
3921 dev->srCache[i].dirty) {
3923 || dev->srCache[i].chunkId <
3925 cache = &dev->srCache[i];
3926 lowest = cache->chunkId;
3931 if (cache && !cache->locked) {
3932 /* Write it out and free it up */
3935 yaffs_WriteChunkDataToObject(cache->object,
3941 cache->object = NULL;
3944 } while (cache && chunkWritten > 0);
3947 /* Hoosterman, disk full while writing cache out. */
3948 T(YAFFS_TRACE_ERROR,
3949 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3956 /*yaffs_FlushEntireDeviceCache(dev)
3961 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3964 int nCaches = dev->nShortOpCaches;
3967 /* Find a dirty object in the cache and flush it...
3968 * until there are no further dirty objects.
3972 for( i = 0; i < nCaches && !obj; i++) {
3973 if (dev->srCache[i].object &&
3974 dev->srCache[i].dirty)
3975 obj = dev->srCache[i].object;
3979 yaffs_FlushFilesChunkCache(obj);
3986 /* Grab us a cache chunk for use.
3987 * First look for an empty one.
3988 * Then look for the least recently used non-dirty one.
3989 * Then look for the least recently used dirty one...., flush and look again.
3991 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
3995 if (dev->nShortOpCaches > 0) {
3996 for (i = 0; i < dev->nShortOpCaches; i++) {
3997 if (!dev->srCache[i].object)
3998 return &dev->srCache[i];
4005 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
4007 yaffs_ChunkCache *cache;
4008 yaffs_Object *theObj;
4013 if (dev->nShortOpCaches > 0) {
4014 /* Try find a non-dirty one... */
4016 cache = yaffs_GrabChunkCacheWorker(dev);
4019 /* They were all dirty, find the last recently used object and flush
4020 * its cache, then find again.
4021 * NB what's here is not very accurate, we actually flush the object
4022 * the last recently used page.
4025 /* With locking we can't assume we can use entry zero */
4032 for (i = 0; i < dev->nShortOpCaches; i++) {
4033 if (dev->srCache[i].object &&
4034 !dev->srCache[i].locked &&
4035 (dev->srCache[i].lastUse < usage || !cache))
4037 usage = dev->srCache[i].lastUse;
4038 theObj = dev->srCache[i].object;
4039 cache = &dev->srCache[i];
4044 if (!cache || cache->dirty) {
4045 /* Flush and try again */
4046 yaffs_FlushFilesChunkCache(theObj);
4047 cache = yaffs_GrabChunkCacheWorker(dev);
4057 /* Find a cached chunk */
4058 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
4061 yaffs_Device *dev = obj->myDev;
4063 if (dev->nShortOpCaches > 0) {
4064 for (i = 0; i < dev->nShortOpCaches; i++) {
4065 if (dev->srCache[i].object == obj &&
4066 dev->srCache[i].chunkId == chunkId) {
4069 return &dev->srCache[i];
4076 /* Mark the chunk for the least recently used algorithym */
4077 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
4081 if (dev->nShortOpCaches > 0) {
4082 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4083 /* Reset the cache usages */
4085 for (i = 1; i < dev->nShortOpCaches; i++) {
4086 dev->srCache[i].lastUse = 0;
4093 cache->lastUse = dev->srLastUse;
4101 /* Invalidate a single cache page.
4102 * Do this when a whole page gets written,
4103 * ie the short cache for this page is no longer valid.
4105 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
4107 if (object->myDev->nShortOpCaches > 0) {
4108 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4111 cache->object = NULL;
4116 /* Invalidate all the cache pages associated with this object
4117 * Do this whenever ther file is deleted or resized.
4119 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
4122 yaffs_Device *dev = in->myDev;
4124 if (dev->nShortOpCaches > 0) {
4125 /* Invalidate it. */
4126 for (i = 0; i < dev->nShortOpCaches; i++) {
4127 if (dev->srCache[i].object == in) {
4128 dev->srCache[i].object = NULL;
4134 /*--------------------- Checkpointing --------------------*/
4137 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
4139 yaffs_CheckpointValidity cp;
4141 memset(&cp,0,sizeof(cp));
4143 cp.structType = sizeof(cp);
4144 cp.magic = YAFFS_MAGIC;
4145 cp.version = YAFFS_CHECKPOINT_VERSION;
4146 cp.head = (head) ? 1 : 0;
4148 return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
4152 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4154 yaffs_CheckpointValidity cp;
4157 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4160 ok = (cp.structType == sizeof(cp)) &&
4161 (cp.magic == YAFFS_MAGIC) &&
4162 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4163 (cp.head == ((head) ? 1 : 0));
4167 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4170 cp->nErasedBlocks = dev->nErasedBlocks;
4171 cp->allocationBlock = dev->allocationBlock;
4172 cp->allocationPage = dev->allocationPage;
4173 cp->nFreeChunks = dev->nFreeChunks;
4175 cp->nDeletedFiles = dev->nDeletedFiles;
4176 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4177 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4178 cp->sequenceNumber = dev->sequenceNumber;
4179 cp->oldestDirtySequence = dev->oldestDirtySequence;
4183 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4184 yaffs_CheckpointDevice *cp)
4186 dev->nErasedBlocks = cp->nErasedBlocks;
4187 dev->allocationBlock = cp->allocationBlock;
4188 dev->allocationPage = cp->allocationPage;
4189 dev->nFreeChunks = cp->nFreeChunks;
4191 dev->nDeletedFiles = cp->nDeletedFiles;
4192 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4193 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4194 dev->sequenceNumber = cp->sequenceNumber;
4195 dev->oldestDirtySequence = cp->oldestDirtySequence;
4199 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4201 yaffs_CheckpointDevice cp;
4203 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4207 /* Write device runtime values*/
4208 yaffs_DeviceToCheckpointDevice(&cp,dev);
4209 cp.structType = sizeof(cp);
4211 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4213 /* Write block info */
4215 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4216 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
4219 /* Write chunk bits */
4221 nBytes = nBlocks * dev->chunkBitmapStride;
4222 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
4228 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4230 yaffs_CheckpointDevice cp;
4232 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4236 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4240 if(cp.structType != sizeof(cp))
4244 yaffs_CheckpointDeviceToDevice(dev,&cp);
4246 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4248 ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
4252 nBytes = nBlocks * dev->chunkBitmapStride;
4254 ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
4259 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4263 cp->objectId = obj->objectId;
4264 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4265 cp->hdrChunk = obj->hdrChunk;
4266 cp->variantType = obj->variantType;
4267 cp->deleted = obj->deleted;
4268 cp->softDeleted = obj->softDeleted;
4269 cp->unlinked = obj->unlinked;
4270 cp->fake = obj->fake;
4271 cp->renameAllowed = obj->renameAllowed;
4272 cp->unlinkAllowed = obj->unlinkAllowed;
4273 cp->serial = obj->serial;
4274 cp->nDataChunks = obj->nDataChunks;
4276 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4277 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4278 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4279 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4282 static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
4285 yaffs_Object *parent;
4287 obj->objectId = cp->objectId;
4290 parent = yaffs_FindOrCreateObjectByNumber(
4293 YAFFS_OBJECT_TYPE_DIRECTORY);
4298 yaffs_AddObjectToDirectory(parent, obj);
4300 obj->hdrChunk = cp->hdrChunk;
4301 obj->variantType = cp->variantType;
4302 obj->deleted = cp->deleted;
4303 obj->softDeleted = cp->softDeleted;
4304 obj->unlinked = cp->unlinked;
4305 obj->fake = cp->fake;
4306 obj->renameAllowed = cp->renameAllowed;
4307 obj->unlinkAllowed = cp->unlinkAllowed;
4308 obj->serial = cp->serial;
4309 obj->nDataChunks = cp->nDataChunks;
4311 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4312 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4313 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4314 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4316 if(obj->hdrChunk > 0)
4317 obj->lazyLoaded = 1;
4322 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
4323 __u32 level, int chunkOffset)
4326 yaffs_Device *dev = in->myDev;
4328 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4330 if(tnodeSize < sizeof(yaffs_Tnode))
4331 tnodeSize = sizeof(yaffs_Tnode);
4337 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
4338 if (tn->internal[i]) {
4339 ok = yaffs_CheckpointTnodeWorker(in,
4342 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4345 } else if (level == 0) {
4346 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4347 /* printf("write tnode at %d\n",baseOffset); */
4348 ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
4350 ok = (yaffs_CheckpointWrite(dev,tn,tnodeSize) == tnodeSize);
4358 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4360 __u32 endMarker = ~0;
4363 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4364 ok = yaffs_CheckpointTnodeWorker(obj,
4365 obj->variant.fileVariant.top,
4366 obj->variant.fileVariant.topLevel,
4369 ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) ==
4376 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4380 yaffs_Device *dev = obj->myDev;
4381 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4384 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4386 if(tnodeSize < sizeof(yaffs_Tnode))
4387 tnodeSize = sizeof(yaffs_Tnode);
4389 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4391 while(ok && (~baseChunk)){
4393 /* Read level 0 tnode */
4396 /* printf("read tnode at %d\n",baseChunk); */
4397 tn = yaffs_GetTnodeRaw(dev);
4399 ok = (yaffs_CheckpointRead(dev,tn,tnodeSize) == tnodeSize);
4404 ok = yaffs_AddOrFindLevel0Tnode(dev,
4412 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4416 T(YAFFS_TRACE_CHECKPOINT,(
4417 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4418 nread,baseChunk,ok));
4424 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4427 yaffs_CheckpointObject cp;
4430 struct ylist_head *lh;
4433 /* Iterate through the objects in each hash entry,
4434 * dumping them to the checkpointing stream.
4437 for(i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++){
4438 ylist_for_each(lh, &dev->objectBucket[i].list) {
4440 obj = ylist_entry(lh, yaffs_Object, hashLink);
4441 if (!obj->deferedFree) {
4442 yaffs_ObjectToCheckpointObject(&cp,obj);
4443 cp.structType = sizeof(cp);
4445 T(YAFFS_TRACE_CHECKPOINT,(
4446 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
4447 cp.objectId,cp.parentId,cp.variantType,cp.hdrChunk,(unsigned) obj));
4449 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4451 if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4452 ok = yaffs_WriteCheckpointTnodes(obj);
4459 /* Dump end of list */
4460 memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
4461 cp.structType = sizeof(cp);
4464 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4469 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4472 yaffs_CheckpointObject cp;
4475 yaffs_Object *hardList = NULL;
4477 while(ok && !done) {
4478 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4479 if(cp.structType != sizeof(cp)) {
4480 T(YAFFS_TRACE_CHECKPOINT,(TSTR("struct size %d instead of %d ok %d"TENDSTR),
4481 cp.structType,sizeof(cp),ok));
4485 T(YAFFS_TRACE_CHECKPOINT,(TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4486 cp.objectId,cp.parentId,cp.variantType,cp.hdrChunk));
4488 if(ok && cp.objectId == ~0)
4491 obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
4493 yaffs_CheckpointObjectToObject(obj,&cp);
4494 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4495 ok = yaffs_ReadCheckpointTnodes(obj);
4496 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4497 obj->hardLinks.next =
4498 (struct ylist_head *)
4508 yaffs_HardlinkFixup(dev,hardList);
4513 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4515 __u32 checkpointSum;
4518 yaffs_GetCheckpointSum(dev,&checkpointSum);
4520 ok = (yaffs_CheckpointWrite(dev,&checkpointSum,sizeof(checkpointSum)) == sizeof(checkpointSum));
4528 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4530 __u32 checkpointSum0;
4531 __u32 checkpointSum1;
4534 yaffs_GetCheckpointSum(dev,&checkpointSum0);
4536 ok = (yaffs_CheckpointRead(dev,&checkpointSum1,sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4541 if(checkpointSum0 != checkpointSum1)
4548 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4553 if(dev->skipCheckpointWrite || !dev->isYaffs2){
4554 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint write" TENDSTR)));
4559 ok = yaffs_CheckpointOpen(dev,1);
4562 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4563 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
4566 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint device" TENDSTR)));
4567 ok = yaffs_WriteCheckpointDevice(dev);
4570 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint objects" TENDSTR)));
4571 ok = yaffs_WriteCheckpointObjects(dev);
4574 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4575 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
4579 ok = yaffs_WriteCheckpointSum(dev);
4583 if(!yaffs_CheckpointClose(dev))
4587 dev->isCheckpointed = 1;
4589 dev->isCheckpointed = 0;
4591 return dev->isCheckpointed;
4594 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4598 if(dev->skipCheckpointRead || !dev->isYaffs2){
4599 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint read" TENDSTR)));
4604 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
4607 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4608 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
4611 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint device" TENDSTR)));
4612 ok = yaffs_ReadCheckpointDevice(dev);
4615 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint objects" TENDSTR)));
4616 ok = yaffs_ReadCheckpointObjects(dev);
4619 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4620 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
4624 ok = yaffs_ReadCheckpointSum(dev);
4625 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint checksum %d" TENDSTR),ok));
4628 if(!yaffs_CheckpointClose(dev))
4632 dev->isCheckpointed = 1;
4634 dev->isCheckpointed = 0;
4640 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4642 if(dev->isCheckpointed ||
4643 dev->blocksInCheckpoint > 0){
4644 dev->isCheckpointed = 0;
4645 yaffs_CheckpointInvalidateStream(dev);
4646 if(dev->superBlock && dev->markSuperBlockDirty)
4647 dev->markSuperBlockDirty(dev->superBlock);
4652 int yaffs_CheckpointSave(yaffs_Device *dev)
4655 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4657 yaffs_VerifyObjects(dev);
4658 yaffs_VerifyBlocks(dev);
4659 yaffs_VerifyFreeChunks(dev);
4661 if(!dev->isCheckpointed) {
4662 yaffs_InvalidateCheckpoint(dev);
4663 yaffs_WriteCheckpointData(dev);
4666 T(YAFFS_TRACE_ALWAYS,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4668 return dev->isCheckpointed;
4671 int yaffs_CheckpointRestore(yaffs_Device *dev)
4674 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4676 retval = yaffs_ReadCheckpointData(dev);
4678 if(dev->isCheckpointed){
4679 yaffs_VerifyObjects(dev);
4680 yaffs_VerifyBlocks(dev);
4681 yaffs_VerifyFreeChunks(dev);
4684 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4689 /*--------------------- File read/write ------------------------
4690 * Read and write have very similar structures.
4691 * In general the read/write has three parts to it
4692 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4693 * Some complete chunks
4694 * An incomplete chunk to end off with
4696 * Curve-balls: the first chunk might also be the last chunk.
4699 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, loff_t offset,
4708 yaffs_ChunkCache *cache;
4715 //chunk = offset / dev->nDataBytesPerChunk + 1;
4716 //start = offset % dev->nDataBytesPerChunk;
4717 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4720 /* OK now check for the curveball where the start and end are in
4723 if ((start + n) < dev->nDataBytesPerChunk) {
4726 nToCopy = dev->nDataBytesPerChunk - start;
4729 cache = yaffs_FindChunkCache(in, chunk);
4731 /* If the chunk is already in the cache or it is less than a whole chunk
4732 * or we're using inband tags then use the cache (if there is caching)
4733 * else bypass the cache.
4735 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4736 if (dev->nShortOpCaches > 0) {
4738 /* If we can't find the data in the cache, then load it up. */
4741 cache = yaffs_GrabChunkCache(in->myDev);
4743 cache->chunkId = chunk;
4746 yaffs_ReadChunkDataFromObject(in, chunk,
4752 yaffs_UseChunkCache(dev, cache, 0);
4756 #ifdef CONFIG_YAFFS_WINCE
4757 yfsd_UnlockYAFFS(TRUE);
4759 memcpy(buffer, &cache->data[start], nToCopy);
4761 #ifdef CONFIG_YAFFS_WINCE
4762 yfsd_LockYAFFS(TRUE);
4766 /* Read into the local buffer then copy..*/
4769 yaffs_GetTempBuffer(dev, __LINE__);
4770 yaffs_ReadChunkDataFromObject(in, chunk,
4772 #ifdef CONFIG_YAFFS_WINCE
4773 yfsd_UnlockYAFFS(TRUE);
4775 memcpy(buffer, &localBuffer[start], nToCopy);
4777 #ifdef CONFIG_YAFFS_WINCE
4778 yfsd_LockYAFFS(TRUE);
4780 yaffs_ReleaseTempBuffer(dev, localBuffer,
4785 #ifdef CONFIG_YAFFS_WINCE
4786 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4788 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4789 * This is because we otherwise screw up WinCE's memory mapper
4791 yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
4793 #ifdef CONFIG_YAFFS_WINCE
4794 yfsd_UnlockYAFFS(TRUE);
4796 memcpy(buffer, localBuffer, dev->nDataBytesPerChunk);
4798 #ifdef CONFIG_YAFFS_WINCE
4799 yfsd_LockYAFFS(TRUE);
4800 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4804 /* A full chunk. Read directly into the supplied buffer. */
4805 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4819 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, loff_t offset,
4820 int nBytes, int writeThrough)
4829 int startOfWrite = offset;
4830 int chunkWritten = 0;
4837 while (n > 0 && chunkWritten >= 0) {
4838 //chunk = offset / dev->nDataBytesPerChunk + 1;
4839 //start = offset % dev->nDataBytesPerChunk;
4840 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4842 if(chunk * dev->nDataBytesPerChunk + start != offset ||
4843 start >= dev->nDataBytesPerChunk){
4844 T(YAFFS_TRACE_ERROR,(TSTR("AddrToChunk of offset %d gives chunk %d start %d"TENDSTR),
4845 (int)offset, chunk,start));
4849 /* OK now check for the curveball where the start and end are in
4853 if ((start + n) < dev->nDataBytesPerChunk) {
4856 /* Now folks, to calculate how many bytes to write back....
4857 * If we're overwriting and not writing to then end of file then
4858 * we need to write back as much as was there before.
4862 in->variant.fileVariant.fileSize -
4863 ((chunk - 1) * dev->nDataBytesPerChunk);
4865 if (nBytesRead > dev->nDataBytesPerChunk) {
4866 nBytesRead = dev->nDataBytesPerChunk;
4871 ((int)start + n)) ? nBytesRead : (start + n);
4874 nToCopy = dev->nDataBytesPerChunk - start;
4875 nToWriteBack = dev->nDataBytesPerChunk;
4878 if (nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4879 /* An incomplete start or end chunk (or maybe both start and end chunk),
4880 * or we're using inband tags, so we want to use the cache buffers.
4882 if (dev->nShortOpCaches > 0) {
4883 yaffs_ChunkCache *cache;
4884 /* If we can't find the data in the cache, then load the cache */
4885 cache = yaffs_FindChunkCache(in, chunk);
4888 && yaffs_CheckSpaceForAllocation(in->
4890 cache = yaffs_GrabChunkCache(in->myDev);
4892 cache->chunkId = chunk;
4895 yaffs_ReadChunkDataFromObject(in, chunk,
4901 !yaffs_CheckSpaceForAllocation(in->myDev)){
4902 /* Drop the cache if it was a read cache item and
4903 * no space check has been made for it.
4909 yaffs_UseChunkCache(dev, cache, 1);
4911 #ifdef CONFIG_YAFFS_WINCE
4912 yfsd_UnlockYAFFS(TRUE);
4915 memcpy(&cache->data[start], buffer,
4918 #ifdef CONFIG_YAFFS_WINCE
4919 yfsd_LockYAFFS(TRUE);
4922 cache->nBytes = nToWriteBack;
4926 yaffs_WriteChunkDataToObject
4929 cache->data, cache->nBytes,
4935 chunkWritten = -1; /* fail the write */
4938 /* An incomplete start or end chunk (or maybe both start and end chunk)
4939 * Read into the local buffer then copy, then copy over and write back.
4943 yaffs_GetTempBuffer(dev, __LINE__);
4945 yaffs_ReadChunkDataFromObject(in, chunk,
4948 #ifdef CONFIG_YAFFS_WINCE
4949 yfsd_UnlockYAFFS(TRUE);
4952 memcpy(&localBuffer[start], buffer, nToCopy);
4954 #ifdef CONFIG_YAFFS_WINCE
4955 yfsd_LockYAFFS(TRUE);
4958 yaffs_WriteChunkDataToObject(in, chunk,
4963 yaffs_ReleaseTempBuffer(dev, localBuffer,
4969 /* A full chunk. Write directly from the supplied buffer. */
4971 #ifdef CONFIG_YAFFS_WINCE
4972 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4973 * This is because we otherwise screw up WinCE's memory mapper
4975 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4976 #ifdef CONFIG_YAFFS_WINCE
4977 yfsd_UnlockYAFFS(TRUE);
4979 memcpy(localBuffer, buffer, dev->nDataBytesPerChunk);
4980 #ifdef CONFIG_YAFFS_WINCE
4981 yfsd_LockYAFFS(TRUE);
4984 yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
4985 dev->nDataBytesPerChunk,
4987 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4991 yaffs_WriteChunkDataToObject(in, chunk, buffer,
4992 dev->nDataBytesPerChunk,
4995 /* Since we've overwritten the cached data, we better invalidate it. */
4996 yaffs_InvalidateChunkCache(in, chunk);
4999 if (chunkWritten >= 0) {
5008 /* Update file object */
5010 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
5011 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
5020 /* ---------------------- File resizing stuff ------------------ */
5022 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
5025 yaffs_Device *dev = in->myDev;
5026 int oldFileSize = in->variant.fileVariant.fileSize;
5028 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
5030 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
5031 dev->nDataBytesPerChunk;
5035 /* Delete backwards so that we don't end up with holes if
5036 * power is lost part-way through the operation.
5038 for (i = lastDel; i >= startDel; i--) {
5039 /* NB this could be optimised somewhat,
5040 * eg. could retrieve the tags and write them without
5041 * using yaffs_DeleteChunk
5044 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5047 (dev->internalStartBlock * dev->nChunksPerBlock)
5049 ((dev->internalEndBlock +
5050 1) * dev->nChunksPerBlock)) {
5051 T(YAFFS_TRACE_ALWAYS,
5052 (TSTR("Found daft chunkId %d for %d" TENDSTR),
5056 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5063 int yaffs_ResizeFile(yaffs_Object * in, loff_t newSize)
5066 int oldFileSize = in->variant.fileVariant.fileSize;
5067 __u32 newSizeOfPartialChunk;
5070 yaffs_Device *dev = in->myDev;
5072 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5074 yaffs_FlushFilesChunkCache(in);
5075 yaffs_InvalidateWholeChunkCache(in);
5077 yaffs_CheckGarbageCollection(dev);
5079 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
5083 if (newSize == oldFileSize) {
5087 if (newSize < oldFileSize) {
5089 yaffs_PruneResizedChunks(in, newSize);
5091 if (newSizeOfPartialChunk != 0) {
5092 int lastChunk = 1 + newFullChunks;
5094 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5096 /* Got to read and rewrite the last chunk with its new size and zero pad */
5097 yaffs_ReadChunkDataFromObject(in, lastChunk,
5100 memset(localBuffer + newSizeOfPartialChunk, 0,
5101 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5103 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5104 newSizeOfPartialChunk, 1);
5106 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5109 in->variant.fileVariant.fileSize = newSize;
5111 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5113 /* newsSize > oldFileSize */
5114 in->variant.fileVariant.fileSize = newSize;
5119 /* Write a new object header.
5120 * show we've shrunk the file, if need be
5121 * Do this only if the file is not in the deleted directories.
5124 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5125 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
5126 yaffs_UpdateObjectHeader(in, NULL, 0,
5127 (newSize < oldFileSize) ? 1 : 0, 0);
5133 loff_t yaffs_GetFileSize(yaffs_Object * obj)
5135 obj = yaffs_GetEquivalentObject(obj);
5137 switch (obj->variantType) {
5138 case YAFFS_OBJECT_TYPE_FILE:
5139 return obj->variant.fileVariant.fileSize;
5140 case YAFFS_OBJECT_TYPE_SYMLINK:
5141 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5149 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
5153 yaffs_FlushFilesChunkCache(in);
5155 #ifdef CONFIG_YAFFS_WINCE
5156 yfsd_WinFileTimeNow(in->win_mtime);
5159 in->yst_mtime = Y_CURRENT_TIME;
5165 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5166 0) ? YAFFS_OK : YAFFS_FAIL;
5175 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
5178 /* First off, invalidate the file's data in the cache, without flushing. */
5179 yaffs_InvalidateWholeChunkCache(in);
5181 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5182 /* Move to the unlinked directory so we have a record that it was deleted. */
5183 yaffs_ChangeObjectName(in, in->myDev->deletedDir,_Y("deleted"), 0, 0);
5187 yaffs_RemoveObjectFromDirectory(in);
5188 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5191 yaffs_FreeObject(in);
5196 /* yaffs_DeleteFile deletes the whole file data
5197 * and the inode associated with the file.
5198 * It does not delete the links associated with the file.
5201 static int yaffs_UnlinkFile(yaffs_Object * in)
5205 int immediateDeletion = 0;
5209 immediateDeletion = 1;
5212 if (in->inUse <= 0) {
5213 immediateDeletion = 1;
5217 if (immediateDeletion) {
5219 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5220 _Y("deleted"), 0, 0);
5221 T(YAFFS_TRACE_TRACING,
5222 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5225 in->myDev->nDeletedFiles++;
5226 if (1 || in->myDev->isYaffs2) {
5227 yaffs_ResizeFile(in, 0);
5229 yaffs_SoftDeleteFile(in);
5232 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5233 _Y("unlinked"), 0, 0);
5240 int yaffs_DeleteFile(yaffs_Object * in)
5242 int retVal = YAFFS_OK;
5243 int deleted = in->deleted;
5245 yaffs_ResizeFile(in,0);
5247 if (in->nDataChunks > 0) {
5248 /* Use soft deletion if there is data in the file.
5249 * That won't be the case if it has been resized to zero.
5251 if (!in->unlinked) {
5252 retVal = yaffs_UnlinkFile(in);
5254 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5255 in->deleted = deleted = 1;
5256 in->myDev->nDeletedFiles++;
5257 yaffs_SoftDeleteFile(in);
5259 return deleted ? YAFFS_OK : YAFFS_FAIL;
5261 /* The file has no data chunks so we toss it immediately */
5262 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5263 in->variant.fileVariant.top = NULL;
5264 yaffs_DoGenericObjectDeletion(in);
5270 static int yaffs_DeleteDirectory(yaffs_Object * in)
5272 /* First check that the directory is empty. */
5273 if (ylist_empty(&in->variant.directoryVariant.children)) {
5274 return yaffs_DoGenericObjectDeletion(in);
5281 static int yaffs_DeleteSymLink(yaffs_Object * in)
5283 YFREE(in->variant.symLinkVariant.alias);
5285 return yaffs_DoGenericObjectDeletion(in);
5288 static int yaffs_DeleteHardLink(yaffs_Object * in)
5290 /* remove this hardlink from the list assocaited with the equivalent
5293 ylist_del_init(&in->hardLinks);
5294 return yaffs_DoGenericObjectDeletion(in);
5297 static void yaffs_DestroyObject(yaffs_Object * obj)
5299 switch (obj->variantType) {
5300 case YAFFS_OBJECT_TYPE_FILE:
5301 yaffs_DeleteFile(obj);
5303 case YAFFS_OBJECT_TYPE_DIRECTORY:
5304 yaffs_DeleteDirectory(obj);
5306 case YAFFS_OBJECT_TYPE_SYMLINK:
5307 yaffs_DeleteSymLink(obj);
5309 case YAFFS_OBJECT_TYPE_HARDLINK:
5310 yaffs_DeleteHardLink(obj);
5312 case YAFFS_OBJECT_TYPE_SPECIAL:
5313 yaffs_DoGenericObjectDeletion(obj);
5315 case YAFFS_OBJECT_TYPE_UNKNOWN:
5316 break; /* should not happen. */
5320 static int yaffs_UnlinkWorker(yaffs_Object * obj)
5323 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5324 return yaffs_DeleteHardLink(obj);
5325 } else if (!ylist_empty(&obj->hardLinks)) {
5326 /* Curve ball: We're unlinking an object that has a hardlink.
5328 * This problem arises because we are not strictly following
5329 * The Linux link/inode model.
5331 * We can't really delete the object.
5332 * Instead, we do the following:
5333 * - Select a hardlink.
5334 * - Unhook it from the hard links
5335 * - Unhook it from its parent directory (so that the rename can work)
5336 * - Rename the object to the hardlink's name.
5337 * - Delete the hardlink
5342 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5344 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5346 ylist_del_init(&hl->hardLinks);
5347 ylist_del_init(&hl->siblings);
5349 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5351 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
5353 if (retVal == YAFFS_OK) {
5354 retVal = yaffs_DoGenericObjectDeletion(hl);
5359 switch (obj->variantType) {
5360 case YAFFS_OBJECT_TYPE_FILE:
5361 return yaffs_UnlinkFile(obj);
5363 case YAFFS_OBJECT_TYPE_DIRECTORY:
5364 return yaffs_DeleteDirectory(obj);
5366 case YAFFS_OBJECT_TYPE_SYMLINK:
5367 return yaffs_DeleteSymLink(obj);
5369 case YAFFS_OBJECT_TYPE_SPECIAL:
5370 return yaffs_DoGenericObjectDeletion(obj);
5372 case YAFFS_OBJECT_TYPE_HARDLINK:
5373 case YAFFS_OBJECT_TYPE_UNKNOWN:
5381 static int yaffs_UnlinkObject( yaffs_Object *obj)
5384 if (obj && obj->unlinkAllowed) {
5385 return yaffs_UnlinkWorker(obj);
5391 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
5395 obj = yaffs_FindObjectByName(dir, name);
5396 return yaffs_UnlinkObject(obj);
5399 /*----------------------- Initialisation Scanning ---------------------- */
5401 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
5402 int backwardScanning)
5406 if (!backwardScanning) {
5407 /* Handle YAFFS1 forward scanning case
5408 * For YAFFS1 we always do the deletion
5412 /* Handle YAFFS2 case (backward scanning)
5413 * If the shadowed object exists then ignore.
5415 if (yaffs_FindObjectByNumber(dev, objId)) {
5420 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5421 * We put it in unlinked dir to be cleaned up after the scanning
5424 yaffs_FindOrCreateObjectByNumber(dev, objId,
5425 YAFFS_OBJECT_TYPE_FILE);
5426 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5427 obj->variant.fileVariant.shrinkSize = 0;
5428 obj->valid = 1; /* So that we don't read any other info for this file */
5438 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5445 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5447 in = yaffs_FindObjectByNumber(dev,
5448 hl->variant.hardLinkVariant.
5449 equivalentObjectId);
5452 /* Add the hardlink pointers */
5453 hl->variant.hardLinkVariant.equivalentObject = in;
5454 ylist_add(&hl->hardLinks, &in->hardLinks);
5456 /* Todo Need to report/handle this better.
5457 * Got a problem... hardlink to a non-existant object
5459 hl->variant.hardLinkVariant.equivalentObject = NULL;
5460 YINIT_LIST_HEAD(&hl->hardLinks);
5472 static int ybicmp(const void *a, const void *b){
5473 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5474 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5475 register int ablock = ((yaffs_BlockIndex *)a)->block;
5476 register int bblock = ((yaffs_BlockIndex *)b)->block;
5478 return ablock - bblock;
5485 struct yaffs_ShadowFixerStruct {
5488 struct yaffs_ShadowFixerStruct *next;
5491 static int yaffs_Scan(yaffs_Device * dev)
5493 yaffs_ExtendedTags tags;
5503 yaffs_BlockState state;
5504 yaffs_Object *hardList = NULL;
5505 yaffs_BlockInfo *bi;
5506 __u32 sequenceNumber;
5507 yaffs_ObjectHeader *oh;
5509 yaffs_Object *parent;
5511 int alloc_failed = 0;
5513 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5521 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5522 dev->internalStartBlock, dev->internalEndBlock));
5524 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5526 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5528 /* Scan all the blocks to determine their state */
5529 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5530 bi = yaffs_GetBlockInfo(dev, blk);
5531 yaffs_ClearChunkBits(dev, blk);
5533 bi->softDeletions = 0;
5535 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5537 bi->blockState = state;
5538 bi->sequenceNumber = sequenceNumber;
5540 T(YAFFS_TRACE_SCAN_DEBUG,
5541 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5542 state, sequenceNumber));
5544 if (state == YAFFS_BLOCK_STATE_DEAD) {
5545 T(YAFFS_TRACE_BAD_BLOCKS,
5546 (TSTR("block %d is bad" TENDSTR), blk));
5547 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5548 T(YAFFS_TRACE_SCAN_DEBUG,
5549 (TSTR("Block empty " TENDSTR)));
5550 dev->nErasedBlocks++;
5551 dev->nFreeChunks += dev->nChunksPerBlock;
5555 startIterator = dev->internalStartBlock;
5556 endIterator = dev->internalEndBlock;
5558 /* For each block.... */
5559 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5566 blk = blockIterator;
5568 bi = yaffs_GetBlockInfo(dev, blk);
5569 state = bi->blockState;
5573 /* For each chunk in each block that needs scanning....*/
5574 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5575 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5576 /* Read the tags and decide what to do */
5577 chunk = blk * dev->nChunksPerBlock + c;
5579 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5582 /* Let's have a good look at this chunk... */
5584 if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
5590 /*T((" %d %d deleted\n",blk,c)); */
5591 } else if (!tags.chunkUsed) {
5592 /* An unassigned chunk in the block
5593 * This means that either the block is empty or
5594 * this is the one being allocated from
5598 /* We're looking at the first chunk in the block so the block is unused */
5599 state = YAFFS_BLOCK_STATE_EMPTY;
5600 dev->nErasedBlocks++;
5602 /* this is the block being allocated from */
5605 (" Allocating from %d %d" TENDSTR),
5607 state = YAFFS_BLOCK_STATE_ALLOCATING;
5608 dev->allocationBlock = blk;
5609 dev->allocationPage = c;
5610 dev->allocationBlockFinder = blk;
5611 /* Set it to here to encourage the allocator to go forth from here. */
5615 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5616 } else if (tags.chunkId > 0) {
5617 /* chunkId > 0 so it is a data chunk... */
5618 unsigned int endpos;
5620 yaffs_SetChunkBit(dev, blk, c);
5623 in = yaffs_FindOrCreateObjectByNumber(dev,
5626 YAFFS_OBJECT_TYPE_FILE);
5627 /* PutChunkIntoFile checks for a clash (two data chunks with
5628 * the same chunkId).
5635 if(!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,1))
5640 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5643 in->variantType == YAFFS_OBJECT_TYPE_FILE
5644 && in->variant.fileVariant.scannedFileSize <
5646 in->variant.fileVariant.
5647 scannedFileSize = endpos;
5648 if (!dev->useHeaderFileSize) {
5649 in->variant.fileVariant.
5651 in->variant.fileVariant.
5656 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
5658 /* chunkId == 0, so it is an ObjectHeader.
5659 * Thus, we read in the object header and make the object
5661 yaffs_SetChunkBit(dev, blk, c);
5664 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5668 oh = (yaffs_ObjectHeader *) chunkData;
5670 in = yaffs_FindObjectByNumber(dev,
5672 if (in && in->variantType != oh->type) {
5673 /* This should not happen, but somehow
5674 * Wev'e ended up with an objectId that has been reused but not yet
5675 * deleted, and worse still it has changed type. Delete the old object.
5678 yaffs_DestroyObject(in);
5683 in = yaffs_FindOrCreateObjectByNumber(dev,
5691 if (in && oh->shadowsObject > 0) {
5693 struct yaffs_ShadowFixerStruct *fixer;
5694 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
5696 fixer-> next = shadowFixerList;
5697 shadowFixerList = fixer;
5698 fixer->objectId = tags.objectId;
5699 fixer->shadowedId = oh->shadowsObject;
5704 if (in && in->valid) {
5705 /* We have already filled this one. We have a duplicate and need to resolve it. */
5707 unsigned existingSerial = in->serial;
5708 unsigned newSerial = tags.serialNumber;
5710 if (((existingSerial + 1) & 3) == newSerial) {
5711 /* Use new one - destroy the exisiting one */
5712 yaffs_DeleteChunk(dev,
5717 /* Use existing - destroy this one. */
5718 yaffs_DeleteChunk(dev, chunk, 1,
5723 if (in && !in->valid &&
5724 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5725 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5726 /* We only load some info, don't fiddle with directory structure */
5728 in->variantType = oh->type;
5730 in->yst_mode = oh->yst_mode;
5731 #ifdef CONFIG_YAFFS_WINCE
5732 in->win_atime[0] = oh->win_atime[0];
5733 in->win_ctime[0] = oh->win_ctime[0];
5734 in->win_mtime[0] = oh->win_mtime[0];
5735 in->win_atime[1] = oh->win_atime[1];
5736 in->win_ctime[1] = oh->win_ctime[1];
5737 in->win_mtime[1] = oh->win_mtime[1];
5739 in->yst_uid = oh->yst_uid;
5740 in->yst_gid = oh->yst_gid;
5741 in->yst_atime = oh->yst_atime;
5742 in->yst_mtime = oh->yst_mtime;
5743 in->yst_ctime = oh->yst_ctime;
5744 in->yst_rdev = oh->yst_rdev;
5746 in->hdrChunk = chunk;
5747 in->serial = tags.serialNumber;
5749 } else if (in && !in->valid) {
5750 /* we need to load this info */
5753 in->variantType = oh->type;
5755 in->yst_mode = oh->yst_mode;
5756 #ifdef CONFIG_YAFFS_WINCE
5757 in->win_atime[0] = oh->win_atime[0];
5758 in->win_ctime[0] = oh->win_ctime[0];
5759 in->win_mtime[0] = oh->win_mtime[0];
5760 in->win_atime[1] = oh->win_atime[1];
5761 in->win_ctime[1] = oh->win_ctime[1];
5762 in->win_mtime[1] = oh->win_mtime[1];
5764 in->yst_uid = oh->yst_uid;
5765 in->yst_gid = oh->yst_gid;
5766 in->yst_atime = oh->yst_atime;
5767 in->yst_mtime = oh->yst_mtime;
5768 in->yst_ctime = oh->yst_ctime;
5769 in->yst_rdev = oh->yst_rdev;
5771 in->hdrChunk = chunk;
5772 in->serial = tags.serialNumber;
5774 yaffs_SetObjectName(in, oh->name);
5777 /* directory stuff...
5782 yaffs_FindOrCreateObjectByNumber
5783 (dev, oh->parentObjectId,
5784 YAFFS_OBJECT_TYPE_DIRECTORY);
5785 if (parent->variantType ==
5786 YAFFS_OBJECT_TYPE_UNKNOWN) {
5787 /* Set up as a directory */
5788 parent->variantType =
5789 YAFFS_OBJECT_TYPE_DIRECTORY;
5790 YINIT_LIST_HEAD(&parent->variant.
5793 } else if (parent->variantType !=
5794 YAFFS_OBJECT_TYPE_DIRECTORY)
5796 /* Hoosterman, another problem....
5797 * We're trying to use a non-directory as a directory
5800 T(YAFFS_TRACE_ERROR,
5802 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
5804 parent = dev->lostNFoundDir;
5807 yaffs_AddObjectToDirectory(parent, in);
5809 if (0 && (parent == dev->deletedDir ||
5810 parent == dev->unlinkedDir)) {
5811 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
5812 dev->nDeletedFiles++;
5814 /* Note re hardlinks.
5815 * Since we might scan a hardlink before its equivalent object is scanned
5816 * we put them all in a list.
5817 * After scanning is complete, we should have all the objects, so we run through this
5818 * list and fix up all the chains.
5821 switch (in->variantType) {
5822 case YAFFS_OBJECT_TYPE_UNKNOWN:
5823 /* Todo got a problem */
5825 case YAFFS_OBJECT_TYPE_FILE:
5826 if (dev->useHeaderFileSize)
5828 in->variant.fileVariant.
5833 case YAFFS_OBJECT_TYPE_HARDLINK:
5834 in->variant.hardLinkVariant.
5835 equivalentObjectId =
5836 oh->equivalentObjectId;
5837 in->hardLinks.next =
5838 (struct ylist_head *)
5842 case YAFFS_OBJECT_TYPE_DIRECTORY:
5845 case YAFFS_OBJECT_TYPE_SPECIAL:
5848 case YAFFS_OBJECT_TYPE_SYMLINK:
5849 in->variant.symLinkVariant.alias =
5850 yaffs_CloneString(oh->alias);
5851 if(!in->variant.symLinkVariant.alias)
5857 if (parent == dev->deletedDir) {
5858 yaffs_DestroyObject(in);
5859 bi->hasShrinkHeader = 1;
5866 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5867 /* If we got this far while scanning, then the block is fully allocated.*/
5868 state = YAFFS_BLOCK_STATE_FULL;
5871 bi->blockState = state;
5873 /* Now let's see if it was dirty */
5874 if (bi->pagesInUse == 0 &&
5875 !bi->hasShrinkHeader &&
5876 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5877 yaffs_BlockBecameDirty(dev, blk);
5883 /* Ok, we've done all the scanning.
5884 * Fix up the hard link chains.
5885 * We should now have scanned all the objects, now it's time to add these
5889 yaffs_HardlinkFixup(dev,hardList);
5891 /* Handle the unlinked files. Since they were left in an unlinked state we should
5895 struct ylist_head *i;
5896 struct ylist_head *n;
5899 /* Soft delete all the unlinked files */
5900 ylist_for_each_safe(i, n,
5901 &dev->unlinkedDir->variant.directoryVariant.
5904 l = ylist_entry(i, yaffs_Object, siblings);
5905 yaffs_DestroyObject(l);
5910 /* Fix up any shadowed objects */
5912 struct yaffs_ShadowFixerStruct *fixer;
5915 while(shadowFixerList){
5916 fixer = shadowFixerList;
5917 shadowFixerList = fixer->next;
5918 /* Complete the rename transaction by deleting the shadowed object
5919 * then setting the object header to unshadowed.
5921 obj = yaffs_FindObjectByNumber(dev,fixer->shadowedId);
5923 yaffs_DestroyObject(obj);
5925 obj = yaffs_FindObjectByNumber(dev,fixer->objectId);
5927 yaffs_UpdateObjectHeader(obj,NULL,1,0,0);
5934 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5940 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5946 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5949 yaffs_ObjectHeader *oh;
5951 yaffs_ExtendedTags tags;
5953 int alloc_failed = 0;
5961 T(YAFFS_TRACE_SCAN,(TSTR("details for object %d %s loaded" TENDSTR),
5963 in->lazyLoaded ? "not yet" : "already"));
5966 if(in->lazyLoaded && in->hdrChunk > 0){
5968 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5970 result = yaffs_ReadChunkWithTagsFromNAND(dev,in->hdrChunk,chunkData,&tags);
5971 oh = (yaffs_ObjectHeader *) chunkData;
5973 in->yst_mode = oh->yst_mode;
5974 #ifdef CONFIG_YAFFS_WINCE
5975 in->win_atime[0] = oh->win_atime[0];
5976 in->win_ctime[0] = oh->win_ctime[0];
5977 in->win_mtime[0] = oh->win_mtime[0];
5978 in->win_atime[1] = oh->win_atime[1];
5979 in->win_ctime[1] = oh->win_ctime[1];
5980 in->win_mtime[1] = oh->win_mtime[1];
5982 in->yst_uid = oh->yst_uid;
5983 in->yst_gid = oh->yst_gid;
5984 in->yst_atime = oh->yst_atime;
5985 in->yst_mtime = oh->yst_mtime;
5986 in->yst_ctime = oh->yst_ctime;
5987 in->yst_rdev = oh->yst_rdev;
5990 yaffs_SetObjectName(in, oh->name);
5992 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
5993 in->variant.symLinkVariant.alias =
5994 yaffs_CloneString(oh->alias);
5995 if(!in->variant.symLinkVariant.alias)
5996 alloc_failed = 1; /* Not returned to caller */
5999 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
6003 static int yaffs_ScanBackwards(yaffs_Device * dev)
6005 yaffs_ExtendedTags tags;
6010 int nBlocksToScan = 0;
6016 yaffs_BlockState state;
6017 yaffs_Object *hardList = NULL;
6018 yaffs_BlockInfo *bi;
6019 __u32 sequenceNumber;
6020 yaffs_ObjectHeader *oh;
6022 yaffs_Object *parent;
6023 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6029 int foundChunksInBlock;
6030 int equivalentObjectId;
6031 int alloc_failed = 0;
6034 yaffs_BlockIndex *blockIndex = NULL;
6035 int altBlockIndex = 0;
6037 if (!dev->isYaffs2) {
6039 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6045 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
6046 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6049 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6051 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6054 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6060 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6064 dev->blocksInCheckpoint = 0;
6066 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6068 /* Scan all the blocks to determine their state */
6069 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6070 bi = yaffs_GetBlockInfo(dev, blk);
6071 yaffs_ClearChunkBits(dev, blk);
6073 bi->softDeletions = 0;
6075 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6077 bi->blockState = state;
6078 bi->sequenceNumber = sequenceNumber;
6080 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6081 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6083 T(YAFFS_TRACE_SCAN_DEBUG,
6084 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6085 state, sequenceNumber));
6088 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
6089 dev->blocksInCheckpoint++;
6091 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6092 T(YAFFS_TRACE_BAD_BLOCKS,
6093 (TSTR("block %d is bad" TENDSTR), blk));
6094 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6095 T(YAFFS_TRACE_SCAN_DEBUG,
6096 (TSTR("Block empty " TENDSTR)));
6097 dev->nErasedBlocks++;
6098 dev->nFreeChunks += dev->nChunksPerBlock;
6099 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6101 /* Determine the highest sequence number */
6102 if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6103 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6105 blockIndex[nBlocksToScan].seq = sequenceNumber;
6106 blockIndex[nBlocksToScan].block = blk;
6110 if (sequenceNumber >= dev->sequenceNumber) {
6111 dev->sequenceNumber = sequenceNumber;
6114 /* TODO: Nasty sequence number! */
6117 ("Block scanning block %d has bad sequence number %d"
6118 TENDSTR), blk, sequenceNumber));
6125 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6131 /* Sort the blocks */
6132 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6134 /* Use qsort now. */
6135 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6139 /* Dungy old bubble sort... */
6141 yaffs_BlockIndex temp;
6145 for (i = 0; i < nBlocksToScan; i++)
6146 for (j = i + 1; j < nBlocksToScan; j++)
6147 if (blockIndex[i].seq > blockIndex[j].seq) {
6148 temp = blockIndex[j];
6149 blockIndex[j] = blockIndex[i];
6150 blockIndex[i] = temp;
6157 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6159 /* Now scan the blocks looking at the data. */
6161 endIterator = nBlocksToScan - 1;
6162 T(YAFFS_TRACE_SCAN_DEBUG,
6163 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6165 /* For each block.... backwards */
6166 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6168 /* Cooperative multitasking! This loop can run for so
6169 long that watchdog timers expire. */
6172 /* get the block to scan in the correct order */
6173 blk = blockIndex[blockIterator].block;
6175 bi = yaffs_GetBlockInfo(dev, blk);
6178 state = bi->blockState;
6182 /* For each chunk in each block that needs scanning.... */
6183 foundChunksInBlock = 0;
6184 for (c = dev->nChunksPerBlock - 1;
6185 !alloc_failed && c >= 0 &&
6186 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6187 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6188 /* Scan backwards...
6189 * Read the tags and decide what to do
6192 chunk = blk * dev->nChunksPerBlock + c;
6194 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6197 /* Let's have a good look at this chunk... */
6199 if (!tags.chunkUsed) {
6200 /* An unassigned chunk in the block.
6201 * If there are used chunks after this one, then
6202 * it is a chunk that was skipped due to failing the erased
6203 * check. Just skip it so that it can be deleted.
6204 * But, more typically, We get here when this is an unallocated
6205 * chunk and his means that either the block is empty or
6206 * this is the one being allocated from
6209 if(foundChunksInBlock)
6211 /* This is a chunk that was skipped due to failing the erased check */
6213 } else if (c == 0) {
6214 /* We're looking at the first chunk in the block so the block is unused */
6215 state = YAFFS_BLOCK_STATE_EMPTY;
6216 dev->nErasedBlocks++;
6218 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6219 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6220 if(dev->sequenceNumber == bi->sequenceNumber) {
6221 /* this is the block being allocated from */
6225 (" Allocating from %d %d"
6228 state = YAFFS_BLOCK_STATE_ALLOCATING;
6229 dev->allocationBlock = blk;
6230 dev->allocationPage = c;
6231 dev->allocationBlockFinder = blk;
6234 /* This is a partially written block that is not
6235 * the current allocation block. This block must have
6236 * had a write failure, so set up for retirement.
6239 /* bi->needsRetiring = 1; ??? TODO */
6240 bi->gcPrioritise = 1;
6242 T(YAFFS_TRACE_ALWAYS,
6243 (TSTR("Partially written block %d detected" TENDSTR),
6253 } else if (tags.chunkId > 0) {
6254 /* chunkId > 0 so it is a data chunk... */
6255 unsigned int endpos;
6257 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6259 foundChunksInBlock = 1;
6262 yaffs_SetChunkBit(dev, blk, c);
6265 in = yaffs_FindOrCreateObjectByNumber(dev,
6268 YAFFS_OBJECT_TYPE_FILE);
6275 in->variantType == YAFFS_OBJECT_TYPE_FILE
6277 in->variant.fileVariant.shrinkSize) {
6278 /* This has not been invalidated by a resize */
6279 if(!yaffs_PutChunkIntoFile(in, tags.chunkId,
6284 /* File size is calculated by looking at the data chunks if we have not
6285 * seen an object header yet. Stop this practice once we find an object header.
6289 1) * dev->nDataBytesPerChunk +
6292 if (!in->valid && /* have not got an object header yet */
6293 in->variant.fileVariant.
6294 scannedFileSize < endpos) {
6295 in->variant.fileVariant.
6296 scannedFileSize = endpos;
6297 in->variant.fileVariant.
6299 in->variant.fileVariant.
6304 /* This chunk has been invalidated by a resize, so delete */
6305 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6309 /* chunkId == 0, so it is an ObjectHeader.
6310 * Thus, we read in the object header and make the object
6312 foundChunksInBlock = 1;
6314 yaffs_SetChunkBit(dev, blk, c);
6320 if (tags.extraHeaderInfoAvailable) {
6321 in = yaffs_FindOrCreateObjectByNumber
6322 (dev, tags.objectId,
6323 tags.extraObjectType);
6327 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
6330 tags.extraShadows ||
6332 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6333 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
6336 /* If we don't have valid info then we need to read the chunk
6337 * TODO In future we can probably defer reading the chunk and
6338 * living with invalid data until needed.
6341 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6346 oh = (yaffs_ObjectHeader *) chunkData;
6348 if(dev->inbandTags){
6349 /* Fix up the header if they got corrupted by inband tags */
6350 oh->shadowsObject = oh->inbandShadowsObject;
6351 oh->isShrink = oh->inbandIsShrink;
6355 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6360 /* TODO Hoosterman we have a problem! */
6361 T(YAFFS_TRACE_ERROR,
6363 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6364 TENDSTR), tags.objectId, chunk));
6369 /* We have already filled this one.
6370 * We have a duplicate that will be discarded, but
6371 * we first have to suck out resize info if it is a file.
6374 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6376 oh-> type == YAFFS_OBJECT_TYPE_FILE)||
6377 (tags.extraHeaderInfoAvailable &&
6378 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
6381 (oh) ? oh->fileSize : tags.
6383 __u32 parentObjectId =
6385 parentObjectId : tags.
6386 extraParentObjectId;
6390 (oh) ? oh->isShrink : tags.
6391 extraIsShrinkHeader;
6393 /* If it is deleted (unlinked at start also means deleted)
6394 * we treat the file size as being zeroed at this point.
6396 if (parentObjectId ==
6397 YAFFS_OBJECTID_DELETED
6398 || parentObjectId ==
6399 YAFFS_OBJECTID_UNLINKED) {
6405 in->variant.fileVariant.
6406 shrinkSize > thisSize) {
6407 in->variant.fileVariant.
6413 bi->hasShrinkHeader = 1;
6417 /* Use existing - destroy this one. */
6418 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6423 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6425 YAFFS_OBJECTID_LOSTNFOUND)) {
6426 /* We only load some info, don't fiddle with directory structure */
6430 in->variantType = oh->type;
6432 in->yst_mode = oh->yst_mode;
6433 #ifdef CONFIG_YAFFS_WINCE
6434 in->win_atime[0] = oh->win_atime[0];
6435 in->win_ctime[0] = oh->win_ctime[0];
6436 in->win_mtime[0] = oh->win_mtime[0];
6437 in->win_atime[1] = oh->win_atime[1];
6438 in->win_ctime[1] = oh->win_ctime[1];
6439 in->win_mtime[1] = oh->win_mtime[1];
6441 in->yst_uid = oh->yst_uid;
6442 in->yst_gid = oh->yst_gid;
6443 in->yst_atime = oh->yst_atime;
6444 in->yst_mtime = oh->yst_mtime;
6445 in->yst_ctime = oh->yst_ctime;
6446 in->yst_rdev = oh->yst_rdev;
6450 in->variantType = tags.extraObjectType;
6454 in->hdrChunk = chunk;
6456 } else if (!in->valid) {
6457 /* we need to load this info */
6460 in->hdrChunk = chunk;
6463 in->variantType = oh->type;
6465 in->yst_mode = oh->yst_mode;
6466 #ifdef CONFIG_YAFFS_WINCE
6467 in->win_atime[0] = oh->win_atime[0];
6468 in->win_ctime[0] = oh->win_ctime[0];
6469 in->win_mtime[0] = oh->win_mtime[0];
6470 in->win_atime[1] = oh->win_atime[1];
6471 in->win_ctime[1] = oh->win_ctime[1];
6472 in->win_mtime[1] = oh->win_mtime[1];
6474 in->yst_uid = oh->yst_uid;
6475 in->yst_gid = oh->yst_gid;
6476 in->yst_atime = oh->yst_atime;
6477 in->yst_mtime = oh->yst_mtime;
6478 in->yst_ctime = oh->yst_ctime;
6479 in->yst_rdev = oh->yst_rdev;
6482 if (oh->shadowsObject > 0)
6483 yaffs_HandleShadowedObject(dev,
6489 yaffs_SetObjectName(in, oh->name);
6491 yaffs_FindOrCreateObjectByNumber
6492 (dev, oh->parentObjectId,
6493 YAFFS_OBJECT_TYPE_DIRECTORY);
6495 fileSize = oh->fileSize;
6496 isShrink = oh->isShrink;
6497 equivalentObjectId = oh->equivalentObjectId;
6501 in->variantType = tags.extraObjectType;
6503 yaffs_FindOrCreateObjectByNumber
6504 (dev, tags.extraParentObjectId,
6505 YAFFS_OBJECT_TYPE_DIRECTORY);
6506 fileSize = tags.extraFileLength;
6507 isShrink = tags.extraIsShrinkHeader;
6508 equivalentObjectId = tags.extraEquivalentObjectId;
6514 /* directory stuff...
6518 if (parent->variantType ==
6519 YAFFS_OBJECT_TYPE_UNKNOWN) {
6520 /* Set up as a directory */
6521 parent->variantType =
6522 YAFFS_OBJECT_TYPE_DIRECTORY;
6523 YINIT_LIST_HEAD(&parent->variant.
6526 } else if (parent->variantType !=
6527 YAFFS_OBJECT_TYPE_DIRECTORY)
6529 /* Hoosterman, another problem....
6530 * We're trying to use a non-directory as a directory
6533 T(YAFFS_TRACE_ERROR,
6535 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6537 parent = dev->lostNFoundDir;
6540 yaffs_AddObjectToDirectory(parent, in);
6542 itsUnlinked = (parent == dev->deletedDir) ||
6543 (parent == dev->unlinkedDir);
6546 /* Mark the block as having a shrinkHeader */
6547 bi->hasShrinkHeader = 1;
6550 /* Note re hardlinks.
6551 * Since we might scan a hardlink before its equivalent object is scanned
6552 * we put them all in a list.
6553 * After scanning is complete, we should have all the objects, so we run
6554 * through this list and fix up all the chains.
6557 switch (in->variantType) {
6558 case YAFFS_OBJECT_TYPE_UNKNOWN:
6559 /* Todo got a problem */
6561 case YAFFS_OBJECT_TYPE_FILE:
6563 if (in->variant.fileVariant.
6564 scannedFileSize < fileSize) {
6565 /* This covers the case where the file size is greater
6566 * than where the data is
6567 * This will happen if the file is resized to be larger
6568 * than its current data extents.
6570 in->variant.fileVariant.fileSize = fileSize;
6571 in->variant.fileVariant.scannedFileSize =
6572 in->variant.fileVariant.fileSize;
6576 in->variant.fileVariant.shrinkSize > fileSize) {
6577 in->variant.fileVariant.shrinkSize = fileSize;
6581 case YAFFS_OBJECT_TYPE_HARDLINK:
6583 in->variant.hardLinkVariant.equivalentObjectId =
6585 in->hardLinks.next =
6586 (struct ylist_head *) hardList;
6590 case YAFFS_OBJECT_TYPE_DIRECTORY:
6593 case YAFFS_OBJECT_TYPE_SPECIAL:
6596 case YAFFS_OBJECT_TYPE_SYMLINK:
6598 in->variant.symLinkVariant.alias =
6599 yaffs_CloneString(oh->
6601 if(!in->variant.symLinkVariant.alias)
6611 } /* End of scanning for each chunk */
6613 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6614 /* If we got this far while scanning, then the block is fully allocated. */
6615 state = YAFFS_BLOCK_STATE_FULL;
6618 bi->blockState = state;
6620 /* Now let's see if it was dirty */
6621 if (bi->pagesInUse == 0 &&
6622 !bi->hasShrinkHeader &&
6623 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6624 yaffs_BlockBecameDirty(dev, blk);
6630 YFREE_ALT(blockIndex);
6634 /* Ok, we've done all the scanning.
6635 * Fix up the hard link chains.
6636 * We should now have scanned all the objects, now it's time to add these
6639 yaffs_HardlinkFixup(dev,hardList);
6643 * Sort out state of unlinked and deleted objects.
6646 struct ylist_head *i;
6647 struct ylist_head *n;
6651 /* Soft delete all the unlinked files */
6652 ylist_for_each_safe(i, n,
6653 &dev->unlinkedDir->variant.directoryVariant.
6656 l = ylist_entry(i, yaffs_Object, siblings);
6657 yaffs_DestroyObject(l);
6661 /* Soft delete all the deletedDir files */
6662 ylist_for_each_safe(i, n,
6663 &dev->deletedDir->variant.directoryVariant.
6666 l = ylist_entry(i, yaffs_Object, siblings);
6667 yaffs_DestroyObject(l);
6673 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6679 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6684 /*------------------------------ Directory Functions ----------------------------- */
6686 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
6688 struct ylist_head *lh;
6689 yaffs_Object *listObj;
6696 if(yaffs_SkipVerification(obj->myDev))
6702 if(obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
6705 /* Iterate through the objects in each hash entry */
6707 ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
6709 listObj = ylist_entry(lh, yaffs_Object, siblings);
6710 yaffs_VerifyObject(listObj);
6722 static void yaffs_VerifyDirectory(yaffs_Object *directory)
6725 struct ylist_head *lh;
6726 yaffs_Object *listObj;
6731 if(yaffs_SkipVerification(directory->myDev))
6735 if(directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
6738 /* Iterate through the objects in each hash entry */
6740 ylist_for_each(lh, &directory->variant.directoryVariant.children) {
6742 listObj = ylist_entry(lh, yaffs_Object, siblings);
6743 if(listObj->parent != directory)
6745 yaffs_VerifyObjectInDirectory(listObj);
6752 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
6754 yaffs_Device *dev = obj->myDev;
6755 yaffs_Object *parent;
6757 yaffs_VerifyObjectInDirectory(obj);
6758 parent = obj->parent;
6760 yaffs_VerifyDirectory(parent);
6762 if(dev && dev->removeObjectCallback)
6763 dev->removeObjectCallback(obj);
6766 ylist_del_init(&obj->siblings);
6769 yaffs_VerifyDirectory(parent);
6774 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
6779 T(YAFFS_TRACE_ALWAYS,
6781 ("tragedy: Trying to add an object to a null pointer directory"
6785 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6786 T(YAFFS_TRACE_ALWAYS,
6788 ("tragedy: Trying to add an object to a non-directory"
6793 if (obj->siblings.prev == NULL) {
6794 /* Not initialised */
6797 } else if (ylist_empty(&obj->siblings)) {
6802 yaffs_VerifyDirectory(directory);
6804 yaffs_RemoveObjectFromDirectory(obj);
6808 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
6809 obj->parent = directory;
6811 if (directory == obj->myDev->unlinkedDir
6812 || directory == obj->myDev->deletedDir) {
6814 obj->myDev->nUnlinkedFiles++;
6815 obj->renameAllowed = 0;
6818 yaffs_VerifyDirectory(directory);
6819 yaffs_VerifyObjectInDirectory(obj);
6824 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
6829 struct ylist_head *i;
6830 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
6839 T(YAFFS_TRACE_ALWAYS,
6841 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6845 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6846 T(YAFFS_TRACE_ALWAYS,
6848 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6852 sum = yaffs_CalcNameSum(name);
6854 ylist_for_each(i, &directory->variant.directoryVariant.children) {
6856 l = ylist_entry(i, yaffs_Object, siblings);
6858 if(l->parent != directory)
6861 yaffs_CheckObjectDetailsLoaded(l);
6863 /* Special case for lost-n-found */
6864 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6865 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
6868 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0){
6869 /* LostnFound chunk called Objxxx
6872 yaffs_GetObjectName(l, buffer,
6873 YAFFS_MAX_NAME_LENGTH);
6874 if (yaffs_strncmp(name, buffer,YAFFS_MAX_NAME_LENGTH) == 0) {
6887 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
6888 int (*fn) (yaffs_Object *))
6890 struct ylist_head *i;
6894 T(YAFFS_TRACE_ALWAYS,
6896 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6900 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6901 T(YAFFS_TRACE_ALWAYS,
6903 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6907 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
6909 l = ylist_entry(i, yaffs_Object, siblings);
6921 /* GetEquivalentObject dereferences any hard links to get to the
6925 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
6927 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
6928 /* We want the object id of the equivalent object, not this one */
6929 obj = obj->variant.hardLinkVariant.equivalentObject;
6930 yaffs_CheckObjectDetailsLoaded(obj);
6936 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
6938 memset(name, 0, buffSize * sizeof(YCHAR));
6940 yaffs_CheckObjectDetailsLoaded(obj);
6942 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6943 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
6944 } else if (obj->hdrChunk <= 0) {
6946 YCHAR numString[20];
6947 YCHAR *x = &numString[19];
6948 unsigned v = obj->objectId;
6952 *x = '0' + (v % 10);
6955 /* make up a name */
6956 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
6957 yaffs_strcat(locName,x);
6958 yaffs_strncpy(name, locName, buffSize - 1);
6961 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
6962 else if (obj->shortName[0]) {
6963 yaffs_strcpy(name, obj->shortName);
6968 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
6970 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
6972 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
6974 if (obj->hdrChunk > 0) {
6975 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
6976 obj->hdrChunk, buffer,
6979 yaffs_strncpy(name, oh->name, buffSize - 1);
6981 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
6984 return yaffs_strlen(name);
6987 int yaffs_GetObjectFileLength(yaffs_Object * obj)
6990 /* Dereference any hard linking */
6991 obj = yaffs_GetEquivalentObject(obj);
6993 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
6994 return obj->variant.fileVariant.fileSize;
6996 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6997 return yaffs_strlen(obj->variant.symLinkVariant.alias);
6999 /* Only a directory should drop through to here */
7000 return obj->myDev->nDataBytesPerChunk;
7004 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
7007 struct ylist_head *i;
7009 if (!obj->unlinked) {
7010 count++; /* the object itself */
7012 ylist_for_each(i, &obj->hardLinks) {
7013 count++; /* add the hard links; */
7019 int yaffs_GetObjectInode(yaffs_Object * obj)
7021 obj = yaffs_GetEquivalentObject(obj);
7023 return obj->objectId;
7026 unsigned yaffs_GetObjectType(yaffs_Object * obj)
7028 obj = yaffs_GetEquivalentObject(obj);
7030 switch (obj->variantType) {
7031 case YAFFS_OBJECT_TYPE_FILE:
7034 case YAFFS_OBJECT_TYPE_DIRECTORY:
7037 case YAFFS_OBJECT_TYPE_SYMLINK:
7040 case YAFFS_OBJECT_TYPE_HARDLINK:
7043 case YAFFS_OBJECT_TYPE_SPECIAL:
7044 if (S_ISFIFO(obj->yst_mode))
7046 if (S_ISCHR(obj->yst_mode))
7048 if (S_ISBLK(obj->yst_mode))
7050 if (S_ISSOCK(obj->yst_mode))
7058 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
7060 obj = yaffs_GetEquivalentObject(obj);
7061 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
7062 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7064 return yaffs_CloneString(_Y(""));
7068 #ifndef CONFIG_YAFFS_WINCE
7070 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
7072 unsigned int valid = attr->ia_valid;
7074 if (valid & ATTR_MODE)
7075 obj->yst_mode = attr->ia_mode;
7076 if (valid & ATTR_UID)
7077 obj->yst_uid = attr->ia_uid;
7078 if (valid & ATTR_GID)
7079 obj->yst_gid = attr->ia_gid;
7081 if (valid & ATTR_ATIME)
7082 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7083 if (valid & ATTR_CTIME)
7084 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7085 if (valid & ATTR_MTIME)
7086 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7088 if (valid & ATTR_SIZE)
7089 yaffs_ResizeFile(obj, attr->ia_size);
7091 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7096 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
7098 unsigned int valid = 0;
7100 attr->ia_mode = obj->yst_mode;
7102 attr->ia_uid = obj->yst_uid;
7104 attr->ia_gid = obj->yst_gid;
7107 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7108 valid |= ATTR_ATIME;
7109 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7110 valid |= ATTR_CTIME;
7111 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7112 valid |= ATTR_MTIME;
7114 attr->ia_size = yaffs_GetFileSize(obj);
7117 attr->ia_valid = valid;
7126 int yaffs_DumpObject(yaffs_Object * obj)
7130 yaffs_GetObjectName(obj, name, 256);
7132 T(YAFFS_TRACE_ALWAYS,
7134 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7135 " chunk %d type %d size %d\n"
7136 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7137 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7138 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7144 /*---------------------------- Initialisation code -------------------------------------- */
7146 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
7149 /* Common functions, gotta have */
7150 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
7153 #ifdef CONFIG_YAFFS_YAFFS2
7155 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7156 if (dev->writeChunkWithTagsToNAND &&
7157 dev->readChunkWithTagsFromNAND &&
7158 !dev->writeChunkToNAND &&
7159 !dev->readChunkFromNAND &&
7160 dev->markNANDBlockBad && dev->queryNANDBlock)
7164 /* Can use the "spare" style interface for yaffs1 */
7165 if (!dev->isYaffs2 &&
7166 !dev->writeChunkWithTagsToNAND &&
7167 !dev->readChunkWithTagsFromNAND &&
7168 dev->writeChunkToNAND &&
7169 dev->readChunkFromNAND &&
7170 !dev->markNANDBlockBad && !dev->queryNANDBlock)
7177 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7179 /* Initialise the unlinked, deleted, root and lost and found directories */
7181 dev->lostNFoundDir = dev->rootDir = NULL;
7182 dev->unlinkedDir = dev->deletedDir = NULL;
7185 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7188 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7191 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7192 YAFFS_ROOT_MODE | S_IFDIR);
7193 dev->lostNFoundDir =
7194 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7195 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7197 if(dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir){
7198 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7205 int yaffs_GutsInitialise(yaffs_Device * dev)
7207 int init_failed = 0;
7211 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7213 /* Check stuff that must be set */
7216 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7220 dev->internalStartBlock = dev->startBlock;
7221 dev->internalEndBlock = dev->endBlock;
7222 dev->blockOffset = 0;
7223 dev->chunkOffset = 0;
7224 dev->nFreeChunks = 0;
7226 if (dev->startBlock == 0) {
7227 dev->internalStartBlock = dev->startBlock + 1;
7228 dev->internalEndBlock = dev->endBlock + 1;
7229 dev->blockOffset = 1;
7230 dev->chunkOffset = dev->nChunksPerBlock;
7233 /* Check geometry parameters. */
7235 if ((!dev->inbandTags && dev->isYaffs2 && dev->totalBytesPerChunk < 1024) ||
7236 (!dev->isYaffs2 && dev->totalBytesPerChunk < 512) ||
7237 (dev->inbandTags && !dev->isYaffs2 ) ||
7238 dev->nChunksPerBlock < 2 ||
7239 dev->nReservedBlocks < 2 ||
7240 dev->internalStartBlock <= 0 ||
7241 dev->internalEndBlock <= 0 ||
7242 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
7244 T(YAFFS_TRACE_ALWAYS,
7246 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7247 TENDSTR), dev->totalBytesPerChunk, dev->isYaffs2 ? "2" : "", dev->inbandTags));
7251 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7252 T(YAFFS_TRACE_ALWAYS,
7253 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7257 /* Sort out space for inband tags, if required */
7259 dev->nDataBytesPerChunk = dev->totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7261 dev->nDataBytesPerChunk = dev->totalBytesPerChunk;
7263 /* Got the right mix of functions? */
7264 if (!yaffs_CheckDevFunctions(dev)) {
7265 /* Function missing */
7266 T(YAFFS_TRACE_ALWAYS,
7268 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7273 /* This is really a compilation check. */
7274 if (!yaffs_CheckStructures()) {
7275 T(YAFFS_TRACE_ALWAYS,
7276 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7280 if (dev->isMounted) {
7281 T(YAFFS_TRACE_ALWAYS,
7282 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7286 /* Finished with most checks. One or two more checks happen later on too. */
7290 /* OK now calculate a few things for the device */
7293 * Calculate all the chunk size manipulation numbers:
7295 x = dev->nDataBytesPerChunk;
7296 /* We always use dev->chunkShift and dev->chunkDiv */
7297 dev->chunkShift = Shifts(x);
7298 x >>= dev->chunkShift;
7300 /* We only use chunk mask if chunkDiv is 1 */
7301 dev->chunkMask = (1<<dev->chunkShift) - 1;
7304 * Calculate chunkGroupBits.
7305 * We need to find the next power of 2 > than internalEndBlock
7308 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7312 /* Set up tnode width if wide tnodes are enabled. */
7313 if(!dev->wideTnodesDisabled){
7314 /* bits must be even so that we end up with 32-bit words */
7318 dev->tnodeWidth = 16;
7320 dev->tnodeWidth = bits;
7323 dev->tnodeWidth = 16;
7325 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7327 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7328 * so if the bitwidth of the
7329 * chunk range we're using is greater than 16 we need
7330 * to figure out chunk shift and chunkGroupSize
7333 if (bits <= dev->tnodeWidth)
7334 dev->chunkGroupBits = 0;
7336 dev->chunkGroupBits = bits - dev->tnodeWidth;
7339 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7341 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7342 /* We have a problem because the soft delete won't work if
7343 * the chunk group size > chunks per block.
7344 * This can be remedied by using larger "virtual blocks".
7346 T(YAFFS_TRACE_ALWAYS,
7347 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7352 /* OK, we've finished verifying the device, lets continue with initialisation */
7354 /* More device initialisation */
7355 dev->garbageCollections = 0;
7356 dev->passiveGarbageCollections = 0;
7357 dev->currentDirtyChecker = 0;
7358 dev->bufferedBlock = -1;
7359 dev->doingBufferedBlockRewrite = 0;
7360 dev->nDeletedFiles = 0;
7361 dev->nBackgroundDeletions = 0;
7362 dev->nUnlinkedFiles = 0;
7364 dev->eccUnfixed = 0;
7365 dev->tagsEccFixed = 0;
7366 dev->tagsEccUnfixed = 0;
7367 dev->nErasureFailures = 0;
7368 dev->nErasedBlocks = 0;
7370 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7372 /* Initialise temporary buffers and caches. */
7373 if(!yaffs_InitialiseTempBuffers(dev))
7376 dev->srCache = NULL;
7377 dev->gcCleanupList = NULL;
7381 dev->nShortOpCaches > 0) {
7384 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7386 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
7387 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7390 dev->srCache = YMALLOC(srCacheBytes);
7392 buf = (__u8 *) dev->srCache;
7395 memset(dev->srCache,0,srCacheBytes);
7397 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7398 dev->srCache[i].object = NULL;
7399 dev->srCache[i].lastUse = 0;
7400 dev->srCache[i].dirty = 0;
7401 dev->srCache[i].data = buf = YMALLOC_DMA(dev->totalBytesPerChunk);
7412 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7413 if(!dev->gcCleanupList)
7417 if (dev->isYaffs2) {
7418 dev->useHeaderFileSize = 1;
7420 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7423 yaffs_InitialiseTnodes(dev);
7424 yaffs_InitialiseObjects(dev);
7426 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7431 /* Now scan the flash. */
7432 if (dev->isYaffs2) {
7433 if(yaffs_CheckpointRestore(dev)) {
7434 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7435 T(YAFFS_TRACE_ALWAYS,
7436 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7439 /* Clean up the mess caused by an aborted checkpoint load
7440 * and scan backwards.
7442 yaffs_DeinitialiseBlocks(dev);
7443 yaffs_DeinitialiseTnodes(dev);
7444 yaffs_DeinitialiseObjects(dev);
7447 dev->nErasedBlocks = 0;
7448 dev->nFreeChunks = 0;
7449 dev->allocationBlock = -1;
7450 dev->allocationPage = -1;
7451 dev->nDeletedFiles = 0;
7452 dev->nUnlinkedFiles = 0;
7453 dev->nBackgroundDeletions = 0;
7454 dev->oldestDirtySequence = 0;
7456 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7459 yaffs_InitialiseTnodes(dev);
7460 yaffs_InitialiseObjects(dev);
7462 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7465 if(!init_failed && !yaffs_ScanBackwards(dev))
7469 if(!yaffs_Scan(dev))
7474 /* Clean up the mess */
7475 T(YAFFS_TRACE_TRACING,
7476 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7478 yaffs_Deinitialise(dev);
7482 /* Zero out stats */
7483 dev->nPageReads = 0;
7484 dev->nPageWrites = 0;
7485 dev->nBlockErasures = 0;
7487 dev->nRetriedWrites = 0;
7489 dev->nRetiredBlocks = 0;
7491 yaffs_VerifyFreeChunks(dev);
7492 yaffs_VerifyBlocks(dev);
7495 T(YAFFS_TRACE_TRACING,
7496 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7501 void yaffs_Deinitialise(yaffs_Device * dev)
7503 if (dev->isMounted) {
7506 yaffs_DeinitialiseBlocks(dev);
7507 yaffs_DeinitialiseTnodes(dev);
7508 yaffs_DeinitialiseObjects(dev);
7509 if (dev->nShortOpCaches > 0 &&
7512 for (i = 0; i < dev->nShortOpCaches; i++) {
7513 if(dev->srCache[i].data)
7514 YFREE(dev->srCache[i].data);
7515 dev->srCache[i].data = NULL;
7518 YFREE(dev->srCache);
7519 dev->srCache = NULL;
7522 YFREE(dev->gcCleanupList);
7524 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
7525 YFREE(dev->tempBuffer[i].buffer);
7531 if(dev->deinitialiseNAND)
7532 dev->deinitialiseNAND(dev);
7537 static int yaffs_CountFreeChunks(yaffs_Device * dev)
7542 yaffs_BlockInfo *blk;
7544 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7546 blk = yaffs_GetBlockInfo(dev, b);
7548 switch (blk->blockState) {
7549 case YAFFS_BLOCK_STATE_EMPTY:
7550 case YAFFS_BLOCK_STATE_ALLOCATING:
7551 case YAFFS_BLOCK_STATE_COLLECTING:
7552 case YAFFS_BLOCK_STATE_FULL:
7554 (dev->nChunksPerBlock - blk->pagesInUse +
7555 blk->softDeletions);
7566 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
7568 /* This is what we report to the outside world */
7571 int nDirtyCacheChunks;
7572 int blocksForCheckpoint;
7575 nFree = dev->nFreeChunks;
7577 nFree = yaffs_CountFreeChunks(dev);
7580 nFree += dev->nDeletedFiles;
7582 /* Now count the number of dirty chunks in the cache and subtract those */
7586 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7587 if (dev->srCache[i].dirty)
7588 nDirtyCacheChunks++;
7592 nFree -= nDirtyCacheChunks;
7594 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7596 /* Now we figure out how much to reserve for the checkpoint and report that... */
7597 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7598 if(blocksForCheckpoint < 0)
7599 blocksForCheckpoint = 0;
7601 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7610 static int yaffs_freeVerificationFailures;
7612 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
7617 if(yaffs_SkipVerification(dev))
7620 counted = yaffs_CountFreeChunks(dev);
7622 difference = dev->nFreeChunks - counted;
7625 T(YAFFS_TRACE_ALWAYS,
7626 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7627 dev->nFreeChunks, counted, difference));
7628 yaffs_freeVerificationFailures++;
7632 /*---------------------------------------- YAFFS test code ----------------------*/
7634 #define yaffs_CheckStruct(structure,syze, name) \
7636 if(sizeof(structure) != syze) \
7638 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
7639 name,syze,sizeof(structure))); \
7640 return YAFFS_FAIL; \
7644 static int yaffs_CheckStructures(void)
7646 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
7647 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
7648 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
7649 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7650 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode");
7652 #ifndef CONFIG_YAFFS_WINCE
7653 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");