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.70 2009-01-09 02:52:28 charles Exp $";
19 #include "yaffsinterface.h"
20 #include "yaffs_guts.h"
21 #include "yaffs_tagsvalidity.h"
22 #include "yaffs_getblockinfo.h"
24 #include "yaffs_tagscompat.h"
25 #ifndef CONFIG_YAFFS_USE_OWN_SORT
26 #include "yaffs_qsort.h"
28 #include "yaffs_nand.h"
30 #include "yaffs_checkptrw.h"
32 #include "yaffs_nand.h"
33 #include "yaffs_packedtags2.h"
36 #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));
409 static int yaffs_SkipFullVerification(yaffs_Device *dev)
411 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
414 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
416 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
419 static const char * blockStateName[] = {
432 static void yaffs_VerifyBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
437 if(yaffs_SkipVerification(dev))
440 /* Report illegal runtime states */
441 if(bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
442 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has undefined state %d"TENDSTR),n,bi->blockState));
444 switch(bi->blockState){
445 case YAFFS_BLOCK_STATE_UNKNOWN:
446 case YAFFS_BLOCK_STATE_SCANNING:
447 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
448 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has bad run-state %s"TENDSTR),
449 n,blockStateName[bi->blockState]));
452 /* Check pages in use and soft deletions are legal */
454 actuallyUsed = bi->pagesInUse - bi->softDeletions;
456 if(bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
457 bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
458 actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock)
459 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
460 n,bi->pagesInUse,bi->softDeletions));
463 /* Check chunk bitmap legal */
464 inUse = yaffs_CountChunkBits(dev,n);
465 if(inUse != bi->pagesInUse)
466 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
467 n,bi->pagesInUse,inUse));
469 /* Check that the sequence number is valid.
470 * Ten million is legal, but is very unlikely
473 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
474 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000 ))
475 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has suspect sequence number of %d"TENDSTR),
476 n,bi->sequenceNumber));
480 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
482 yaffs_VerifyBlock(dev,bi,n);
484 /* After collection the block should be in the erased state */
485 /* This will need to change if we do partial gc */
487 if(bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
488 bi->blockState != YAFFS_BLOCK_STATE_EMPTY){
489 T(YAFFS_TRACE_ERROR,(TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
494 static void yaffs_VerifyBlocks(yaffs_Device *dev)
497 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
498 int nIllegalBlockStates = 0;
501 if(yaffs_SkipVerification(dev))
504 memset(nBlocksPerState,0,sizeof(nBlocksPerState));
507 for(i = dev->internalStartBlock; i <= dev->internalEndBlock; i++){
508 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
509 yaffs_VerifyBlock(dev,bi,i);
511 if(bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
512 nBlocksPerState[bi->blockState]++;
514 nIllegalBlockStates++;
518 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
519 T(YAFFS_TRACE_VERIFY,(TSTR("Block summary"TENDSTR)));
521 T(YAFFS_TRACE_VERIFY,(TSTR("%d blocks have illegal states"TENDSTR),nIllegalBlockStates));
522 if(nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
523 T(YAFFS_TRACE_VERIFY,(TSTR("Too many allocating blocks"TENDSTR)));
525 for(i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
526 T(YAFFS_TRACE_VERIFY,
527 (TSTR("%s %d blocks"TENDSTR),
528 blockStateName[i],nBlocksPerState[i]));
530 if(dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
531 T(YAFFS_TRACE_VERIFY,
532 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
533 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
535 if(dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
536 T(YAFFS_TRACE_VERIFY,
537 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
538 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
540 if(nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
541 T(YAFFS_TRACE_VERIFY,
542 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
543 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
545 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
550 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
551 * case those tests will not be performed.
553 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
555 if(obj && yaffs_SkipVerification(obj->myDev))
558 if(!(tags && obj && oh)){
559 T(YAFFS_TRACE_VERIFY,
560 (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR),
561 (__u32)tags,(__u32)obj,(__u32)oh));
565 if(oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
566 oh->type > YAFFS_OBJECT_TYPE_MAX)
567 T(YAFFS_TRACE_VERIFY,
568 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
569 tags->objectId, oh->type));
571 if(tags->objectId != obj->objectId)
572 T(YAFFS_TRACE_VERIFY,
573 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
574 tags->objectId, obj->objectId));
578 * Check that the object's parent ids match if parentCheck requested.
580 * Tests do not apply to the root object.
583 if(parentCheck && tags->objectId > 1 && !obj->parent)
584 T(YAFFS_TRACE_VERIFY,
585 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
586 tags->objectId, oh->parentObjectId));
589 if(parentCheck && obj->parent &&
590 oh->parentObjectId != obj->parent->objectId &&
591 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
592 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
593 T(YAFFS_TRACE_VERIFY,
594 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
595 tags->objectId, oh->parentObjectId, obj->parent->objectId));
598 if(tags->objectId > 1 && oh->name[0] == 0) /* Null name */
599 T(YAFFS_TRACE_VERIFY,
600 (TSTR("Obj %d header name is NULL"TENDSTR),
603 if(tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
604 T(YAFFS_TRACE_VERIFY,
605 (TSTR("Obj %d header name is 0xFF"TENDSTR),
611 static int yaffs_VerifyTnodeWorker(yaffs_Object * obj, yaffs_Tnode * tn,
612 __u32 level, int chunkOffset)
615 yaffs_Device *dev = obj->myDev;
621 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
622 if (tn->internal[i]) {
623 ok = yaffs_VerifyTnodeWorker(obj,
626 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
629 } else if (level == 0) {
630 yaffs_ExtendedTags tags;
631 __u32 objectId = obj->objectId;
633 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
635 for(i = 0; i < YAFFS_NTNODES_LEVEL0; i++){
636 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
639 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
640 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
641 if(tags.objectId != objectId || tags.chunkId != chunkOffset){
642 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
643 objectId, chunkOffset, theChunk,
644 tags.objectId, tags.chunkId));
657 static void yaffs_VerifyFile(yaffs_Object *obj)
659 int requiredTallness;
665 yaffs_ExtendedTags tags;
672 if(yaffs_SkipVerification(obj->myDev))
676 objectId = obj->objectId;
678 /* Check file size is consistent with tnode depth */
679 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
680 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
681 requiredTallness = 0;
683 x >>= YAFFS_TNODES_INTERNAL_BITS;
687 actualTallness = obj->variant.fileVariant.topLevel;
689 if(requiredTallness > actualTallness )
690 T(YAFFS_TRACE_VERIFY,
691 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
692 obj->objectId,actualTallness, requiredTallness));
695 /* Check that the chunks in the tnode tree are all correct.
696 * We do this by scanning through the tnode tree and
697 * checking the tags for every chunk match.
700 if(yaffs_SkipNANDVerification(dev))
703 for(i = 1; i <= lastChunk; i++){
704 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant,i);
707 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
709 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
710 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
711 if(tags.objectId != objectId || tags.chunkId != i){
712 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
713 objectId, i, theChunk,
714 tags.objectId, tags.chunkId));
724 static void yaffs_VerifyHardLink(yaffs_Object *obj)
726 if(obj && yaffs_SkipVerification(obj->myDev))
729 /* Verify sane equivalent object */
732 static void yaffs_VerifySymlink(yaffs_Object *obj)
734 if(obj && yaffs_SkipVerification(obj->myDev))
737 /* Verify symlink string */
740 static void yaffs_VerifySpecial(yaffs_Object *obj)
742 if(obj && yaffs_SkipVerification(obj->myDev))
746 static void yaffs_VerifyObject(yaffs_Object *obj)
761 if(yaffs_SkipVerification(dev))
764 /* Check sane object header chunk */
766 chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
767 chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
769 chunkIdOk = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
770 chunkIsLive = chunkIdOk &&
771 yaffs_CheckChunkBit(dev,
772 obj->hdrChunk / dev->nChunksPerBlock,
773 obj->hdrChunk % dev->nChunksPerBlock);
775 (!chunkIdOk || !chunkIsLive)) {
776 T(YAFFS_TRACE_VERIFY,
777 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
778 obj->objectId,obj->hdrChunk,
779 chunkIdOk ? "" : ",out of range",
780 chunkIsLive || !chunkIdOk ? "" : ",marked as deleted"));
783 if(chunkIdOk && chunkIsLive &&!yaffs_SkipNANDVerification(dev)) {
784 yaffs_ExtendedTags tags;
785 yaffs_ObjectHeader *oh;
786 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
788 oh = (yaffs_ObjectHeader *)buffer;
790 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk,buffer, &tags);
792 yaffs_VerifyObjectHeader(obj,oh,&tags,1);
794 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
797 /* Verify it has a parent */
798 if(obj && !obj->fake &&
799 (!obj->parent || obj->parent->myDev != dev)){
800 T(YAFFS_TRACE_VERIFY,
801 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
802 obj->objectId,obj->parent));
805 /* Verify parent is a directory */
806 if(obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
807 T(YAFFS_TRACE_VERIFY,
808 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
809 obj->objectId,obj->parent->variantType));
812 switch(obj->variantType){
813 case YAFFS_OBJECT_TYPE_FILE:
814 yaffs_VerifyFile(obj);
816 case YAFFS_OBJECT_TYPE_SYMLINK:
817 yaffs_VerifySymlink(obj);
819 case YAFFS_OBJECT_TYPE_DIRECTORY:
820 yaffs_VerifyDirectory(obj);
822 case YAFFS_OBJECT_TYPE_HARDLINK:
823 yaffs_VerifyHardLink(obj);
825 case YAFFS_OBJECT_TYPE_SPECIAL:
826 yaffs_VerifySpecial(obj);
828 case YAFFS_OBJECT_TYPE_UNKNOWN:
830 T(YAFFS_TRACE_VERIFY,
831 (TSTR("Obj %d has illegaltype %d"TENDSTR),
832 obj->objectId,obj->variantType));
839 static void yaffs_VerifyObjects(yaffs_Device *dev)
843 struct ylist_head *lh;
845 if(yaffs_SkipVerification(dev))
848 /* Iterate through the objects in each hash entry */
850 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++){
851 ylist_for_each(lh, &dev->objectBucket[i].list) {
853 obj = ylist_entry(lh, yaffs_Object, hashLink);
854 yaffs_VerifyObject(obj);
863 * Simple hash function. Needs to have a reasonable spread
866 static Y_INLINE int yaffs_HashFunction(int n)
869 return (n % YAFFS_NOBJECT_BUCKETS);
873 * Access functions to useful fake objects.
874 * Note that root might have a presence in NAND if permissions are set.
877 yaffs_Object *yaffs_Root(yaffs_Device * dev)
882 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
884 return dev->lostNFoundDir;
889 * Erased NAND checking functions
892 int yaffs_CheckFF(__u8 * buffer, int nBytes)
894 /* Horrible, slow implementation */
903 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
907 int retval = YAFFS_OK;
908 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
909 yaffs_ExtendedTags tags;
912 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
914 if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
918 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
919 T(YAFFS_TRACE_NANDACCESS,
920 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
924 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
930 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
932 yaffs_ExtendedTags * tags,
939 yaffs_InvalidateCheckpoint(dev);
942 yaffs_BlockInfo *bi = 0;
945 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
951 /* First check this chunk is erased, if it needs
952 * checking. The checking policy (unless forced
953 * always on) is as follows:
955 * Check the first page we try to write in a block.
956 * If the check passes then we don't need to check any
957 * more. If the check fails, we check again...
958 * If the block has been erased, we don't need to check.
960 * However, if the block has been prioritised for gc,
961 * then we think there might be something odd about
962 * this block and stop using it.
964 * Rationale: We should only ever see chunks that have
965 * not been erased if there was a partially written
966 * chunk due to power loss. This checking policy should
967 * catch that case with very few checks and thus save a
968 * lot of checks that are most likely not needed.
970 if (bi->gcPrioritise) {
971 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
972 /* try another chunk */
976 /* let's give it a try */
979 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
980 bi->skipErasedCheck = 0;
982 if (!bi->skipErasedCheck) {
983 erasedOk = yaffs_CheckChunkErased(dev, chunk);
984 if (erasedOk != YAFFS_OK) {
986 (TSTR ("**>> yaffs chunk %d was not erased"
989 /* try another chunk */
992 bi->skipErasedCheck = 1;
995 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
997 if (writeOk != YAFFS_OK) {
998 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
999 /* try another chunk */
1003 /* Copy the data into the robustification buffer */
1004 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1006 } while (writeOk != YAFFS_OK &&
1007 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1013 T(YAFFS_TRACE_ERROR,
1014 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1017 dev->nRetriedWrites += (attempts - 1);
1024 * Block retiring for handling a broken block.
1027 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
1029 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1031 yaffs_InvalidateCheckpoint(dev);
1033 yaffs_MarkBlockBad(dev, blockInNAND);
1035 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1036 bi->gcPrioritise = 0;
1037 bi->needsRetiring = 0;
1039 dev->nRetiredBlocks++;
1043 * Functions for robustisizing TODO
1047 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
1049 const yaffs_ExtendedTags * tags)
1053 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
1054 const yaffs_ExtendedTags * tags)
1058 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1060 if(!bi->gcPrioritise){
1061 bi->gcPrioritise = 1;
1062 dev->hasPendingPrioritisedGCs = 1;
1063 bi->chunkErrorStrikes ++;
1065 if(bi->chunkErrorStrikes > 3){
1066 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1067 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1074 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
1077 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1078 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1080 yaffs_HandleChunkError(dev,bi);
1084 /* Was an actual write failure, so mark the block for retirement */
1085 bi->needsRetiring = 1;
1086 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1087 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1092 /* Delete the chunk */
1093 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1097 /*---------------- Name handling functions ------------*/
1099 static __u16 yaffs_CalcNameSum(const YCHAR * name)
1104 const YUCHAR *bname = (const YUCHAR *) name;
1106 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1108 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1109 sum += yaffs_toupper(*bname) * i;
1111 sum += (*bname) * i;
1121 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
1123 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1124 memset(obj->shortName,0,sizeof (YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1125 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
1126 yaffs_strcpy(obj->shortName, name);
1128 obj->shortName[0] = _Y('\0');
1131 obj->sum = yaffs_CalcNameSum(name);
1134 /*-------------------- TNODES -------------------
1136 * List of spare tnodes
1137 * The list is hooked together using the first pointer
1141 /* yaffs_CreateTnodes creates a bunch more tnodes and
1142 * adds them to the tnode free list.
1143 * Don't use this function directly
1146 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
1150 yaffs_Tnode *newTnodes;
1154 yaffs_TnodeList *tnl;
1159 /* Calculate the tnode size in bytes for variable width tnode support.
1160 * Must be a multiple of 32-bits */
1161 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1163 if(tnodeSize < sizeof(yaffs_Tnode))
1164 tnodeSize = sizeof(yaffs_Tnode);
1167 /* make these things */
1169 newTnodes = YMALLOC(nTnodes * tnodeSize);
1170 mem = (__u8 *)newTnodes;
1173 T(YAFFS_TRACE_ERROR,
1174 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1178 /* Hook them into the free list */
1180 for (i = 0; i < nTnodes - 1; i++) {
1181 newTnodes[i].internal[0] = &newTnodes[i + 1];
1182 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1183 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1187 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1188 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1189 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1191 dev->freeTnodes = newTnodes;
1193 /* New hookup for wide tnodes */
1194 for(i = 0; i < nTnodes -1; i++) {
1195 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1196 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1197 curr->internal[0] = next;
1200 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1201 curr->internal[0] = dev->freeTnodes;
1202 dev->freeTnodes = (yaffs_Tnode *)mem;
1207 dev->nFreeTnodes += nTnodes;
1208 dev->nTnodesCreated += nTnodes;
1210 /* Now add this bunch of tnodes to a list for freeing up.
1211 * NB If we can't add this to the management list it isn't fatal
1212 * but it just means we can't free this bunch of tnodes later.
1215 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1217 T(YAFFS_TRACE_ERROR,
1219 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1223 tnl->tnodes = newTnodes;
1224 tnl->next = dev->allocatedTnodeList;
1225 dev->allocatedTnodeList = tnl;
1228 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1233 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1235 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
1237 yaffs_Tnode *tn = NULL;
1239 /* If there are none left make more */
1240 if (!dev->freeTnodes) {
1241 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1244 if (dev->freeTnodes) {
1245 tn = dev->freeTnodes;
1246 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1247 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1248 /* Hoosterman, this thing looks like it isn't in the list */
1249 T(YAFFS_TRACE_ALWAYS,
1250 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1253 dev->freeTnodes = dev->freeTnodes->internal[0];
1257 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1262 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
1264 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1265 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1267 if(tnodeSize < sizeof(yaffs_Tnode))
1268 tnodeSize = sizeof(yaffs_Tnode);
1271 memset(tn, 0, tnodeSize);
1276 /* FreeTnode frees up a tnode and puts it back on the free list */
1277 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
1280 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1281 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1282 /* Hoosterman, this thing looks like it is already in the list */
1283 T(YAFFS_TRACE_ALWAYS,
1284 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1286 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1288 tn->internal[0] = dev->freeTnodes;
1289 dev->freeTnodes = tn;
1292 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1296 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
1298 /* Free the list of allocated tnodes */
1299 yaffs_TnodeList *tmp;
1301 while (dev->allocatedTnodeList) {
1302 tmp = dev->allocatedTnodeList->next;
1304 YFREE(dev->allocatedTnodeList->tnodes);
1305 YFREE(dev->allocatedTnodeList);
1306 dev->allocatedTnodeList = tmp;
1310 dev->freeTnodes = NULL;
1311 dev->nFreeTnodes = 0;
1314 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
1316 dev->allocatedTnodeList = NULL;
1317 dev->freeTnodes = NULL;
1318 dev->nFreeTnodes = 0;
1319 dev->nTnodesCreated = 0;
1324 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
1326 __u32 *map = (__u32 *)tn;
1332 pos &= YAFFS_TNODES_LEVEL0_MASK;
1333 val >>= dev->chunkGroupBits;
1335 bitInMap = pos * dev->tnodeWidth;
1336 wordInMap = bitInMap /32;
1337 bitInWord = bitInMap & (32 -1);
1339 mask = dev->tnodeMask << bitInWord;
1341 map[wordInMap] &= ~mask;
1342 map[wordInMap] |= (mask & (val << bitInWord));
1344 if(dev->tnodeWidth > (32-bitInWord)) {
1345 bitInWord = (32 - bitInWord);
1347 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1348 map[wordInMap] &= ~mask;
1349 map[wordInMap] |= (mask & (val >> bitInWord));
1353 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
1355 __u32 *map = (__u32 *)tn;
1361 pos &= YAFFS_TNODES_LEVEL0_MASK;
1363 bitInMap = pos * dev->tnodeWidth;
1364 wordInMap = bitInMap /32;
1365 bitInWord = bitInMap & (32 -1);
1367 val = map[wordInMap] >> bitInWord;
1369 if(dev->tnodeWidth > (32-bitInWord)) {
1370 bitInWord = (32 - bitInWord);
1372 val |= (map[wordInMap] << bitInWord);
1375 val &= dev->tnodeMask;
1376 val <<= dev->chunkGroupBits;
1381 /* ------------------- End of individual tnode manipulation -----------------*/
1383 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1384 * The look up tree is represented by the top tnode and the number of topLevel
1385 * in the tree. 0 means only the level 0 tnode is in the tree.
1388 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1389 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
1390 yaffs_FileStructure * fStruct,
1394 yaffs_Tnode *tn = fStruct->top;
1396 int requiredTallness;
1397 int level = fStruct->topLevel;
1399 /* Check sane level and chunk Id */
1400 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
1404 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1408 /* First check we're tall enough (ie enough topLevel) */
1410 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1411 requiredTallness = 0;
1413 i >>= YAFFS_TNODES_INTERNAL_BITS;
1417 if (requiredTallness > fStruct->topLevel) {
1418 /* Not tall enough, so we can't find it, return NULL. */
1422 /* Traverse down to level 0 */
1423 while (level > 0 && tn) {
1425 internal[(chunkId >>
1426 ( YAFFS_TNODES_LEVEL0_BITS +
1428 YAFFS_TNODES_INTERNAL_BITS)
1430 YAFFS_TNODES_INTERNAL_MASK];
1438 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1439 * This happens in two steps:
1440 * 1. If the tree isn't tall enough, then make it taller.
1441 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1443 * Used when modifying the tree.
1445 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1446 * be plugged into the ttree.
1449 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
1450 yaffs_FileStructure * fStruct,
1452 yaffs_Tnode *passedTn)
1455 int requiredTallness;
1463 /* Check sane level and page Id */
1464 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
1468 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1472 /* First check we're tall enough (ie enough topLevel) */
1474 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1475 requiredTallness = 0;
1477 x >>= YAFFS_TNODES_INTERNAL_BITS;
1482 if (requiredTallness > fStruct->topLevel) {
1483 /* Not tall enough,gotta make the tree taller */
1484 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1486 tn = yaffs_GetTnode(dev);
1489 tn->internal[0] = fStruct->top;
1492 T(YAFFS_TRACE_ERROR,
1493 (TSTR("yaffs: no more tnodes" TENDSTR)));
1497 fStruct->topLevel = requiredTallness;
1500 /* Traverse down to level 0, adding anything we need */
1502 l = fStruct->topLevel;
1506 while (l > 0 && tn) {
1508 ( YAFFS_TNODES_LEVEL0_BITS +
1509 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1510 YAFFS_TNODES_INTERNAL_MASK;
1513 if((l>1) && !tn->internal[x]){
1514 /* Add missing non-level-zero tnode */
1515 tn->internal[x] = yaffs_GetTnode(dev);
1518 /* Looking from level 1 at level 0 */
1520 /* If we already have one, then release it.*/
1522 yaffs_FreeTnode(dev,tn->internal[x]);
1523 tn->internal[x] = passedTn;
1525 } else if(!tn->internal[x]) {
1526 /* Don't have one, none passed in */
1527 tn->internal[x] = yaffs_GetTnode(dev);
1531 tn = tn->internal[x];
1535 /* top is level 0 */
1537 memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1538 yaffs_FreeTnode(dev,passedTn);
1545 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1546 yaffs_ExtendedTags * tags, int objectId,
1551 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1552 if (yaffs_CheckChunkBit
1553 (dev, theChunk / dev->nChunksPerBlock,
1554 theChunk % dev->nChunksPerBlock)) {
1555 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1557 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1569 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1570 * chunks and tnodes in the file
1571 * Returns 1 if the tree was deleted.
1572 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1575 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1576 int chunkOffset, int *limit)
1581 yaffs_ExtendedTags tags;
1583 yaffs_Device *dev = in->myDev;
1590 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1592 if (tn->internal[i]) {
1593 if (limit && (*limit) < 0) {
1597 yaffs_DeleteWorker(in,
1605 YAFFS_TNODES_INTERNAL_BITS)
1610 yaffs_FreeTnode(dev,
1613 tn->internal[i] = NULL;
1618 return (allDone) ? 1 : 0;
1619 } else if (level == 0) {
1622 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1624 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1629 YAFFS_TNODES_LEVEL0_BITS) + i;
1632 yaffs_FindChunkInGroup(dev,
1638 if (foundChunk > 0) {
1639 yaffs_DeleteChunk(dev,
1644 *limit = *limit - 1;
1652 yaffs_PutLevel0Tnode(dev,tn,i,0);
1656 return (i < 0) ? 1 : 0;
1666 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1669 yaffs_BlockInfo *theBlock;
1671 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1673 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1675 theBlock->softDeletions++;
1680 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1681 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1683 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1686 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1687 __u32 level, int chunkOffset)
1692 yaffs_Device *dev = in->myDev;
1697 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1699 if (tn->internal[i]) {
1701 yaffs_SoftDeleteWorker(in,
1707 YAFFS_TNODES_INTERNAL_BITS)
1710 yaffs_FreeTnode(dev,
1713 tn->internal[i] = NULL;
1715 /* Hoosterman... how could this happen? */
1719 return (allDone) ? 1 : 0;
1720 } else if (level == 0) {
1722 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1723 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1725 /* Note this does not find the real chunk, only the chunk group.
1726 * We make an assumption that a chunk group is not larger than
1729 yaffs_SoftDeleteChunk(dev, theChunk);
1730 yaffs_PutLevel0Tnode(dev,tn,i,0);
1744 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1747 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1748 if (obj->nDataChunks <= 0) {
1749 /* Empty file with no duplicate object headers, just delete it immediately */
1750 yaffs_FreeTnode(obj->myDev,
1751 obj->variant.fileVariant.top);
1752 obj->variant.fileVariant.top = NULL;
1753 T(YAFFS_TRACE_TRACING,
1754 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1756 yaffs_DoGenericObjectDeletion(obj);
1758 yaffs_SoftDeleteWorker(obj,
1759 obj->variant.fileVariant.top,
1760 obj->variant.fileVariant.
1762 obj->softDeleted = 1;
1767 /* Pruning removes any part of the file structure tree that is beyond the
1768 * bounds of the file (ie that does not point to chunks).
1770 * A file should only get pruned when its size is reduced.
1772 * Before pruning, the chunks must be pulled from the tree and the
1773 * level 0 tnode entries must be zeroed out.
1774 * Could also use this for file deletion, but that's probably better handled
1775 * by a special case.
1778 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1779 __u32 level, int del0)
1787 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1788 if (tn->internal[i] && level > 0) {
1790 yaffs_PruneWorker(dev, tn->internal[i],
1792 (i == 0) ? del0 : 1);
1795 if (tn->internal[i]) {
1800 if (hasData == 0 && del0) {
1801 /* Free and return NULL */
1803 yaffs_FreeTnode(dev, tn);
1813 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1814 yaffs_FileStructure * fStruct)
1821 if (fStruct->topLevel > 0) {
1823 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1825 /* Now we have a tree with all the non-zero branches NULL but the height
1826 * is the same as it was.
1827 * Let's see if we can trim internal tnodes to shorten the tree.
1828 * We can do this if only the 0th element in the tnode is in use
1829 * (ie all the non-zero are NULL)
1832 while (fStruct->topLevel && !done) {
1836 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1837 if (tn->internal[i]) {
1843 fStruct->top = tn->internal[0];
1844 fStruct->topLevel--;
1845 yaffs_FreeTnode(dev, tn);
1855 /*-------------------- End of File Structure functions.-------------------*/
1857 /* yaffs_CreateFreeObjects creates a bunch more objects and
1858 * adds them to the object free list.
1860 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1863 yaffs_Object *newObjects;
1864 yaffs_ObjectList *list;
1869 /* make these things */
1870 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1871 list = YMALLOC(sizeof(yaffs_ObjectList));
1873 if (!newObjects || !list) {
1878 T(YAFFS_TRACE_ALLOCATE,
1879 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1883 /* Hook them into the free list */
1884 for (i = 0; i < nObjects - 1; i++) {
1885 newObjects[i].siblings.next =
1886 (struct ylist_head *)(&newObjects[i + 1]);
1889 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1890 dev->freeObjects = newObjects;
1891 dev->nFreeObjects += nObjects;
1892 dev->nObjectsCreated += nObjects;
1894 /* Now add this bunch of Objects to a list for freeing up. */
1896 list->objects = newObjects;
1897 list->next = dev->allocatedObjectList;
1898 dev->allocatedObjectList = list;
1904 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1905 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1907 yaffs_Object *tn = NULL;
1909 #ifdef VALGRIND_TEST
1910 tn = YMALLOC(sizeof(yaffs_Object));
1912 /* If there are none left make more */
1913 if (!dev->freeObjects) {
1914 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1917 if (dev->freeObjects) {
1918 tn = dev->freeObjects;
1920 (yaffs_Object *) (dev->freeObjects->siblings.next);
1921 dev->nFreeObjects--;
1925 /* Now sweeten it up... */
1927 memset(tn, 0, sizeof(yaffs_Object));
1930 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1931 YINIT_LIST_HEAD(&(tn->hardLinks));
1932 YINIT_LIST_HEAD(&(tn->hashLink));
1933 YINIT_LIST_HEAD(&tn->siblings);
1936 /* Now make the directory sane */
1938 tn->parent = dev->rootDir;
1939 ylist_add(&(tn->siblings),&dev->rootDir->variant.directoryVariant.children);
1942 /* Add it to the lost and found directory.
1943 * NB Can't put root or lostNFound in lostNFound so
1944 * check if lostNFound exists first
1946 if (dev->lostNFoundDir) {
1947 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1951 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1956 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1961 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1963 obj->fake = 1; /* it is fake so it might have no NAND presence... */
1964 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1965 obj->unlinkAllowed = 0; /* ... or unlink it */
1968 obj->yst_mode = mode;
1970 obj->hdrChunk = 0; /* Not a valid chunk. */
1977 static void yaffs_UnhashObject(yaffs_Object * tn)
1980 yaffs_Device *dev = tn->myDev;
1982 /* If it is still linked into the bucket list, free from the list */
1983 if (!ylist_empty(&tn->hashLink)) {
1984 ylist_del_init(&tn->hashLink);
1985 bucket = yaffs_HashFunction(tn->objectId);
1986 dev->objectBucket[bucket].count--;
1991 /* FreeObject frees up a Object and puts it back on the free list */
1992 static void yaffs_FreeObject(yaffs_Object * tn)
1995 yaffs_Device *dev = tn->myDev;
2000 if(!ylist_empty(&tn->siblings))
2006 /* We're still hooked up to a cached inode.
2007 * Don't delete now, but mark for later deletion
2009 tn->deferedFree = 1;
2014 yaffs_UnhashObject(tn);
2016 #ifdef VALGRIND_TEST
2019 /* Link into the free list. */
2020 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2021 dev->freeObjects = tn;
2022 dev->nFreeObjects++;
2024 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2030 void yaffs_HandleDeferedFree(yaffs_Object * obj)
2032 if (obj->deferedFree) {
2033 yaffs_FreeObject(obj);
2039 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
2041 /* Free the list of allocated Objects */
2043 yaffs_ObjectList *tmp;
2045 while (dev->allocatedObjectList) {
2046 tmp = dev->allocatedObjectList->next;
2047 YFREE(dev->allocatedObjectList->objects);
2048 YFREE(dev->allocatedObjectList);
2050 dev->allocatedObjectList = tmp;
2053 dev->freeObjects = NULL;
2054 dev->nFreeObjects = 0;
2057 static void yaffs_InitialiseObjects(yaffs_Device * dev)
2061 dev->allocatedObjectList = NULL;
2062 dev->freeObjects = NULL;
2063 dev->nFreeObjects = 0;
2065 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2066 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2067 dev->objectBucket[i].count = 0;
2072 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
2077 int lowest = 999999;
2079 /* First let's see if we can find one that's empty. */
2081 for (i = 0; i < 10 && lowest > 0; i++) {
2083 x %= YAFFS_NOBJECT_BUCKETS;
2084 if (dev->objectBucket[x].count < lowest) {
2085 lowest = dev->objectBucket[x].count;
2091 /* If we didn't find an empty list, then try
2092 * looking a bit further for a short one
2095 for (i = 0; i < 10 && lowest > 3; i++) {
2097 x %= YAFFS_NOBJECT_BUCKETS;
2098 if (dev->objectBucket[x].count < lowest) {
2099 lowest = dev->objectBucket[x].count;
2108 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
2110 int bucket = yaffs_FindNiceObjectBucket(dev);
2112 /* Now find an object value that has not already been taken
2113 * by scanning the list.
2117 struct ylist_head *i;
2119 __u32 n = (__u32) bucket;
2121 /* yaffs_CheckObjectHashSanity(); */
2125 n += YAFFS_NOBJECT_BUCKETS;
2126 if (1 || dev->objectBucket[bucket].count > 0) {
2127 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2128 /* If there is already one in the list */
2130 && ylist_entry(i, yaffs_Object,
2131 hashLink)->objectId == n) {
2142 static void yaffs_HashObject(yaffs_Object * in)
2144 int bucket = yaffs_HashFunction(in->objectId);
2145 yaffs_Device *dev = in->myDev;
2147 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2148 dev->objectBucket[bucket].count++;
2152 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
2154 int bucket = yaffs_HashFunction(number);
2155 struct ylist_head *i;
2158 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2159 /* Look if it is in the list */
2161 in = ylist_entry(i, yaffs_Object, hashLink);
2162 if (in->objectId == number) {
2164 /* Don't tell the VFS about this one if it is defered free */
2165 if (in->deferedFree)
2177 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
2178 yaffs_ObjectType type)
2181 yaffs_Object *theObject;
2182 yaffs_Tnode *tn = NULL;
2185 number = yaffs_CreateNewObjectNumber(dev);
2188 theObject = yaffs_AllocateEmptyObject(dev);
2192 if(type == YAFFS_OBJECT_TYPE_FILE){
2193 tn = yaffs_GetTnode(dev);
2195 yaffs_FreeObject(theObject);
2203 theObject->fake = 0;
2204 theObject->renameAllowed = 1;
2205 theObject->unlinkAllowed = 1;
2206 theObject->objectId = number;
2207 yaffs_HashObject(theObject);
2208 theObject->variantType = type;
2209 #ifdef CONFIG_YAFFS_WINCE
2210 yfsd_WinFileTimeNow(theObject->win_atime);
2211 theObject->win_ctime[0] = theObject->win_mtime[0] =
2212 theObject->win_atime[0];
2213 theObject->win_ctime[1] = theObject->win_mtime[1] =
2214 theObject->win_atime[1];
2218 theObject->yst_atime = theObject->yst_mtime =
2219 theObject->yst_ctime = Y_CURRENT_TIME;
2223 theObject->sum_prev = 12345;
2224 theObject->sum_trailer = 6789;
2228 case YAFFS_OBJECT_TYPE_FILE:
2229 theObject->variant.fileVariant.fileSize = 0;
2230 theObject->variant.fileVariant.scannedFileSize = 0;
2231 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2232 theObject->variant.fileVariant.topLevel = 0;
2233 theObject->variant.fileVariant.top = tn;
2235 case YAFFS_OBJECT_TYPE_DIRECTORY:
2236 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2239 case YAFFS_OBJECT_TYPE_SYMLINK:
2240 case YAFFS_OBJECT_TYPE_HARDLINK:
2241 case YAFFS_OBJECT_TYPE_SPECIAL:
2242 /* No action required */
2244 case YAFFS_OBJECT_TYPE_UNKNOWN:
2245 /* todo this should not happen */
2253 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
2255 yaffs_ObjectType type)
2257 yaffs_Object *theObject = NULL;
2260 theObject = yaffs_FindObjectByNumber(dev, number);
2264 theObject = yaffs_CreateNewObject(dev, number, type);
2272 static YCHAR *yaffs_CloneString(const YCHAR * str)
2274 YCHAR *newStr = NULL;
2277 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2279 yaffs_strcpy(newStr, str);
2287 * Mknod (create) a new object.
2288 * equivalentObject only has meaning for a hard link;
2289 * aliasString only has meaning for a sumlink.
2290 * rdev only has meaning for devices (a subset of special objects)
2293 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2294 yaffs_Object * parent,
2299 yaffs_Object * equivalentObject,
2300 const YCHAR * aliasString, __u32 rdev)
2305 yaffs_Device *dev = parent->myDev;
2307 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2308 if (yaffs_FindObjectByName(parent, name)) {
2312 in = yaffs_CreateNewObject(dev, -1, type);
2317 if(type == YAFFS_OBJECT_TYPE_SYMLINK){
2318 str = yaffs_CloneString(aliasString);
2320 yaffs_FreeObject(in);
2330 in->variantType = type;
2332 in->yst_mode = mode;
2334 #ifdef CONFIG_YAFFS_WINCE
2335 yfsd_WinFileTimeNow(in->win_atime);
2336 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2337 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2340 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2342 in->yst_rdev = rdev;
2346 in->nDataChunks = 0;
2348 yaffs_SetObjectName(in, name);
2351 yaffs_AddObjectToDirectory(parent, in);
2353 in->myDev = parent->myDev;
2356 case YAFFS_OBJECT_TYPE_SYMLINK:
2357 in->variant.symLinkVariant.alias = str;
2359 case YAFFS_OBJECT_TYPE_HARDLINK:
2360 in->variant.hardLinkVariant.equivalentObject =
2362 in->variant.hardLinkVariant.equivalentObjectId =
2363 equivalentObject->objectId;
2364 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2366 case YAFFS_OBJECT_TYPE_FILE:
2367 case YAFFS_OBJECT_TYPE_DIRECTORY:
2368 case YAFFS_OBJECT_TYPE_SPECIAL:
2369 case YAFFS_OBJECT_TYPE_UNKNOWN:
2374 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2375 /* Could not create the object header, fail the creation */
2376 yaffs_DestroyObject(in);
2385 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
2386 __u32 mode, __u32 uid, __u32 gid)
2388 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2389 uid, gid, NULL, NULL, 0);
2392 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
2393 __u32 mode, __u32 uid, __u32 gid)
2395 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2396 mode, uid, gid, NULL, NULL, 0);
2399 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
2400 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2402 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2403 uid, gid, NULL, NULL, rdev);
2406 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
2407 __u32 mode, __u32 uid, __u32 gid,
2408 const YCHAR * alias)
2410 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2411 uid, gid, NULL, alias, 0);
2414 /* yaffs_Link returns the object id of the equivalent object.*/
2415 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
2416 yaffs_Object * equivalentObject)
2418 /* Get the real object in case we were fed a hard link as an equivalent object */
2419 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2421 if (yaffs_MknodObject
2422 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2423 equivalentObject, NULL, 0)) {
2424 return equivalentObject;
2431 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
2432 const YCHAR * newName, int force, int shadows)
2437 yaffs_Object *existingTarget;
2439 if (newDir == NULL) {
2440 newDir = obj->parent; /* use the old directory */
2443 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2444 T(YAFFS_TRACE_ALWAYS,
2446 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2451 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2452 if (obj->myDev->isYaffs2) {
2453 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2455 unlinkOp = (newDir == obj->myDev->unlinkedDir
2456 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2459 deleteOp = (newDir == obj->myDev->deletedDir);
2461 existingTarget = yaffs_FindObjectByName(newDir, newName);
2463 /* If the object is a file going into the unlinked directory,
2464 * then it is OK to just stuff it in since duplicate names are allowed.
2465 * else only proceed if the new name does not exist and if we're putting
2466 * it into a directory.
2473 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2474 yaffs_SetObjectName(obj, newName);
2477 yaffs_AddObjectToDirectory(newDir, obj);
2482 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2483 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
2490 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
2491 yaffs_Object * newDir, const YCHAR * newName)
2493 yaffs_Object *obj=NULL;
2494 yaffs_Object *existingTarget=NULL;
2498 if(!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2500 if(!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2503 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2504 /* Special case for case insemsitive systems (eg. WinCE).
2505 * While look-up is case insensitive, the name isn't.
2506 * Therefore we might want to change x.txt to X.txt
2508 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
2513 else if (yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2517 obj = yaffs_FindObjectByName(oldDir, oldName);
2519 if (obj && obj->renameAllowed) {
2521 /* Now do the handling for an existing target, if there is one */
2523 existingTarget = yaffs_FindObjectByName(newDir, newName);
2524 if (existingTarget &&
2525 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2526 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2527 /* There is a target that is a non-empty directory, so we fail */
2528 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2529 } else if (existingTarget && existingTarget != obj) {
2530 /* Nuke the target first, using shadowing,
2531 * but only if it isn't the same object
2533 yaffs_ChangeObjectName(obj, newDir, newName, force,
2534 existingTarget->objectId);
2535 yaffs_UnlinkObject(existingTarget);
2538 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2543 /*------------------------- Block Management and Page Allocation ----------------*/
2545 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
2547 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2549 dev->blockInfo = NULL;
2550 dev->chunkBits = NULL;
2552 dev->allocationBlock = -1; /* force it to get a new one */
2554 /* If the first allocation strategy fails, thry the alternate one */
2555 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2556 if(!dev->blockInfo){
2557 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2558 dev->blockInfoAlt = 1;
2561 dev->blockInfoAlt = 0;
2565 /* Set up dynamic blockinfo stuff. */
2566 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2567 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2568 if(!dev->chunkBits){
2569 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2570 dev->chunkBitsAlt = 1;
2573 dev->chunkBitsAlt = 0;
2576 if (dev->blockInfo && dev->chunkBits) {
2577 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2578 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2586 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
2588 if(dev->blockInfoAlt && dev->blockInfo)
2589 YFREE_ALT(dev->blockInfo);
2590 else if(dev->blockInfo)
2591 YFREE(dev->blockInfo);
2593 dev->blockInfoAlt = 0;
2595 dev->blockInfo = NULL;
2597 if(dev->chunkBitsAlt && dev->chunkBits)
2598 YFREE_ALT(dev->chunkBits);
2599 else if(dev->chunkBits)
2600 YFREE(dev->chunkBits);
2601 dev->chunkBitsAlt = 0;
2602 dev->chunkBits = NULL;
2605 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
2606 yaffs_BlockInfo * bi)
2613 return 1; /* disqualification only applies to yaffs2. */
2615 if (!bi->hasShrinkHeader)
2616 return 1; /* can gc */
2618 /* Find the oldest dirty sequence number if we don't know it and save it
2619 * so we don't have to keep recomputing it.
2621 if (!dev->oldestDirtySequence) {
2622 seq = dev->sequenceNumber;
2624 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2626 b = yaffs_GetBlockInfo(dev, i);
2627 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2628 (b->pagesInUse - b->softDeletions) <
2629 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2630 seq = b->sequenceNumber;
2633 dev->oldestDirtySequence = seq;
2636 /* Can't do gc of this block if there are any blocks older than this one that have
2639 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2643 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2644 * for garbage collection.
2647 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2651 int b = dev->currentDirtyChecker;
2658 yaffs_BlockInfo *bi;
2659 int pendingPrioritisedExist = 0;
2661 /* First let's see if we need to grab a prioritised block */
2662 if(dev->hasPendingPrioritisedGCs){
2663 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2665 bi = yaffs_GetBlockInfo(dev, i);
2666 //yaffs_VerifyBlock(dev,bi,i);
2668 if(bi->gcPrioritise) {
2669 pendingPrioritisedExist = 1;
2670 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2671 yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2672 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2675 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2680 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2681 dev->hasPendingPrioritisedGCs = 0;
2684 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2686 * else (we're doing a leasurely gc), then we only bother to do this if the
2687 * block has only a few pages in use.
2690 dev->nonAggressiveSkip--;
2692 if (!aggressive && (dev->nonAggressiveSkip > 0)) {
2698 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2702 dev->internalEndBlock - dev->internalStartBlock + 1;
2705 dev->internalEndBlock - dev->internalStartBlock + 1;
2706 iterations = iterations / 16;
2707 if (iterations > 200) {
2712 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2714 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2715 b = dev->internalStartBlock;
2718 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2719 T(YAFFS_TRACE_ERROR,
2720 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2724 bi = yaffs_GetBlockInfo(dev, b);
2727 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2734 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2735 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2736 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2738 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2742 dev->currentDirtyChecker = b;
2746 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2747 dev->nChunksPerBlock - pagesInUse,prioritised));
2750 dev->oldestDirtySequence = 0;
2753 dev->nonAggressiveSkip = 4;
2759 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2761 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2765 /* If the block is still healthy erase it and mark as clean.
2766 * If the block has had a data failure, then retire it.
2769 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2770 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2771 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2773 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2775 if (!bi->needsRetiring) {
2776 yaffs_InvalidateCheckpoint(dev);
2777 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2779 dev->nErasureFailures++;
2780 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2781 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2786 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2788 for (i = 0; i < dev->nChunksPerBlock; i++) {
2789 if (!yaffs_CheckChunkErased
2790 (dev, blockNo * dev->nChunksPerBlock + i)) {
2791 T(YAFFS_TRACE_ERROR,
2793 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2794 TENDSTR), blockNo, i));
2800 /* Clean it up... */
2801 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2802 dev->nErasedBlocks++;
2804 bi->softDeletions = 0;
2805 bi->hasShrinkHeader = 0;
2806 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2807 bi->gcPrioritise = 0;
2808 yaffs_ClearChunkBits(dev, blockNo);
2810 T(YAFFS_TRACE_ERASE,
2811 (TSTR("Erased block %d" TENDSTR), blockNo));
2813 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2815 yaffs_RetireBlock(dev, blockNo);
2816 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2817 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2821 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2825 yaffs_BlockInfo *bi;
2827 if (dev->nErasedBlocks < 1) {
2828 /* Hoosterman we've got a problem.
2829 * Can't get space to gc
2831 T(YAFFS_TRACE_ERROR,
2832 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2837 /* Find an empty block. */
2839 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2840 dev->allocationBlockFinder++;
2841 if (dev->allocationBlockFinder < dev->internalStartBlock
2842 || dev->allocationBlockFinder > dev->internalEndBlock) {
2843 dev->allocationBlockFinder = dev->internalStartBlock;
2846 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2848 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2849 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2850 dev->sequenceNumber++;
2851 bi->sequenceNumber = dev->sequenceNumber;
2852 dev->nErasedBlocks--;
2853 T(YAFFS_TRACE_ALLOCATE,
2854 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2855 dev->allocationBlockFinder, dev->sequenceNumber,
2856 dev->nErasedBlocks));
2857 return dev->allocationBlockFinder;
2861 T(YAFFS_TRACE_ALWAYS,
2863 ("yaffs tragedy: no more erased blocks, but there should have been %d"
2864 TENDSTR), dev->nErasedBlocks));
2871 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2873 if(!dev->nCheckpointBlocksRequired &&
2875 /* Not a valid value so recalculate */
2878 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2881 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2883 if(tnodeSize < sizeof(yaffs_Tnode))
2884 tnodeSize = sizeof(yaffs_Tnode);
2886 nBytes += sizeof(yaffs_CheckpointValidity);
2887 nBytes += sizeof(yaffs_CheckpointDevice);
2888 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2889 nBytes += devBlocks * dev->chunkBitmapStride;
2890 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2891 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2892 nBytes += sizeof(yaffs_CheckpointValidity);
2893 nBytes += sizeof(__u32); /* checksum*/
2895 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2897 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2899 dev->nCheckpointBlocksRequired = nBlocks;
2902 return dev->nCheckpointBlocksRequired;
2905 // Check if there's space to allocate...
2906 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2907 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2910 int reservedBlocks = dev->nReservedBlocks;
2911 int checkpointBlocks;
2914 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
2915 dev->blocksInCheckpoint;
2916 if(checkpointBlocks < 0)
2917 checkpointBlocks = 0;
2919 checkpointBlocks =0;
2922 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2924 return (dev->nFreeChunks > reservedChunks);
2927 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2930 yaffs_BlockInfo *bi;
2932 if (dev->allocationBlock < 0) {
2933 /* Get next block to allocate off */
2934 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2935 dev->allocationPage = 0;
2938 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2939 /* Not enough space to allocate unless we're allowed to use the reserve. */
2943 if (dev->nErasedBlocks < dev->nReservedBlocks
2944 && dev->allocationPage == 0) {
2945 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2948 /* Next page please.... */
2949 if (dev->allocationBlock >= 0) {
2950 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2952 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2953 dev->allocationPage;
2955 yaffs_SetChunkBit(dev, dev->allocationBlock,
2956 dev->allocationPage);
2958 dev->allocationPage++;
2962 /* If the block is full set the state to full */
2963 if (dev->allocationPage >= dev->nChunksPerBlock) {
2964 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2965 dev->allocationBlock = -1;
2974 T(YAFFS_TRACE_ERROR,
2975 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2980 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2984 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2986 if (dev->allocationBlock > 0) {
2987 n += (dev->nChunksPerBlock - dev->allocationPage);
2994 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block, int wholeBlock)
2999 int retVal = YAFFS_OK;
3002 int isCheckpointBlock;
3006 int chunksBefore = yaffs_GetErasedChunks(dev);
3009 yaffs_ExtendedTags tags;
3011 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3013 yaffs_Object *object;
3015 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3017 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3019 T(YAFFS_TRACE_TRACING,
3020 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3023 bi->hasShrinkHeader,
3026 /*yaffs_VerifyFreeChunks(dev); */
3028 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
3030 /* Take off the number of soft deleted entries because
3031 * they're going to get really deleted during GC.
3033 dev->nFreeChunks -= bi->softDeletions;
3037 if (isCheckpointBlock ||
3038 !yaffs_StillSomeChunkBits(dev, block)) {
3039 T(YAFFS_TRACE_TRACING,
3041 ("Collecting block %d that has no chunks in use" TENDSTR),
3043 yaffs_BlockBecameDirty(dev, block);
3046 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3048 yaffs_VerifyBlock(dev,bi,block);
3050 maxCopies = (wholeBlock) ? dev->nChunksPerBlock : 10;
3051 oldChunk = block * dev->nChunksPerBlock + dev->gcChunk;
3053 for ( /* init already done */;
3054 retVal == YAFFS_OK &&
3055 dev->gcChunk < dev->nChunksPerBlock &&
3056 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING)&&
3058 dev->gcChunk++, oldChunk++) {
3059 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3061 /* This page is in use and might need to be copied off */
3067 yaffs_InitialiseTags(&tags);
3069 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3073 yaffs_FindObjectByNumber(dev,
3076 T(YAFFS_TRACE_GC_DETAIL,
3078 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3079 dev->gcChunk, tags.objectId, tags.chunkId,
3082 if(object && !yaffs_SkipVerification(dev)){
3083 if(tags.chunkId == 0)
3084 matchingChunk = object->hdrChunk;
3085 else if(object->softDeleted)
3086 matchingChunk = oldChunk; /* Defeat the test */
3088 matchingChunk = yaffs_FindChunkInFile(object,tags.chunkId,NULL);
3090 if(oldChunk != matchingChunk)
3091 T(YAFFS_TRACE_ERROR,
3092 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3093 oldChunk,matchingChunk,tags.objectId, tags.chunkId));
3098 T(YAFFS_TRACE_ERROR,
3100 ("page %d in gc has no object: %d %d %d "
3102 tags.objectId, tags.chunkId, tags.byteCount));
3107 object->softDeleted &&
3108 tags.chunkId != 0) {
3109 /* Data chunk in a soft deleted file, throw it away
3110 * It's a soft deleted data chunk,
3111 * No need to copy this, just forget about it and
3112 * fix up the object.
3115 object->nDataChunks--;
3117 if (object->nDataChunks <= 0) {
3118 /* remeber to clean up the object */
3119 dev->gcCleanupList[cleanups] =
3125 /* Todo object && object->deleted && object->nDataChunks == 0 */
3127 /* Deleted object header with no data chunks.
3128 * Can be discarded and the file deleted.
3130 object->hdrChunk = 0;
3131 yaffs_FreeTnode(object->myDev,
3134 object->variant.fileVariant.top = NULL;
3135 yaffs_DoGenericObjectDeletion(object);
3137 } else if (object) {
3138 /* It's either a data chunk in a live file or
3139 * an ObjectHeader, so we're interested in it.
3140 * NB Need to keep the ObjectHeaders of deleted files
3141 * until the whole file has been deleted off
3143 tags.serialNumber++;
3147 if (tags.chunkId == 0) {
3148 /* It is an object Id,
3149 * We need to nuke the shrinkheader flags first
3150 * We no longer want the shrinkHeader flag since its work is done
3151 * and if it is left in place it will mess up scanning.
3152 * Also, clear out any shadowing stuff
3155 yaffs_ObjectHeader *oh;
3156 oh = (yaffs_ObjectHeader *)buffer;
3158 tags.extraShadows = 0;
3159 tags.extraIsShrinkHeader = 0;
3161 yaffs_VerifyObjectHeader(object,oh,&tags,1);
3165 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3168 retVal = YAFFS_FAIL;
3171 /* Ok, now fix up the Tnodes etc. */
3173 if (tags.chunkId == 0) {
3175 object->hdrChunk = newChunk;
3176 object->serial = tags.serialNumber;
3178 /* It's a data chunk */
3179 yaffs_PutChunkIntoFile
3187 if(retVal == YAFFS_OK)
3188 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3193 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3197 /* Do any required cleanups */
3198 for (i = 0; i < cleanups; i++) {
3199 /* Time to delete the file too */
3201 yaffs_FindObjectByNumber(dev,
3202 dev->gcCleanupList[i]);
3204 yaffs_FreeTnode(dev,
3205 object->variant.fileVariant.
3207 object->variant.fileVariant.top = NULL;
3210 ("yaffs: About to finally delete object %d"
3211 TENDSTR), object->objectId));
3212 yaffs_DoGenericObjectDeletion(object);
3213 object->myDev->nDeletedFiles--;
3220 yaffs_VerifyCollectedBlock(dev,bi,block);
3222 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
3225 ("gc did not increase free chunks before %d after %d"
3226 TENDSTR), chunksBefore, chunksAfter));
3229 /* If the gc completed then clear the current gcBlock so that we find another. */
3230 if(bi->blockState != YAFFS_BLOCK_STATE_COLLECTING){
3240 /* New garbage collector
3241 * If we're very low on erased blocks then we do aggressive garbage collection
3242 * otherwise we do "leasurely" garbage collection.
3243 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3244 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3246 * The idea is to help clear out space in a more spread-out manner.
3247 * Dunno if it really does anything useful.
3249 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
3253 int gcOk = YAFFS_OK;
3256 int checkpointBlockAdjust;
3258 if (dev->isDoingGC) {
3259 /* Bail out so we don't get recursive gc */
3263 /* This loop should pass the first time.
3264 * We'll only see looping here if the erase of the collected block fails.
3270 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3271 if(checkpointBlockAdjust < 0)
3272 checkpointBlockAdjust = 0;
3274 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3275 /* We need a block soon...*/
3278 /* We're in no hurry */
3282 if(dev->gcBlock <= 0){
3283 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3287 block = dev->gcBlock;
3290 dev->garbageCollections++;
3292 dev->passiveGarbageCollections++;
3297 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3298 dev->nErasedBlocks, aggressive));
3300 gcOk = yaffs_GarbageCollectBlock(dev,block,aggressive);
3303 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3306 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3307 TENDSTR), dev->nErasedBlocks, maxTries, block));
3309 } while ((dev->nErasedBlocks < dev->nReservedBlocks) &&
3313 return aggressive ? gcOk : YAFFS_OK;
3316 /*------------------------- TAGS --------------------------------*/
3318 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
3321 return (tags->chunkId == chunkInObject &&
3322 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3327 /*-------------------- Data file manipulation -----------------*/
3329 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
3330 yaffs_ExtendedTags * tags)
3332 /*Get the Tnode, then get the level 0 offset chunk offset */
3335 yaffs_ExtendedTags localTags;
3338 yaffs_Device *dev = in->myDev;
3341 /* Passed a NULL, so use our own tags space */
3345 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3348 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3351 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3357 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
3358 yaffs_ExtendedTags * tags)
3360 /* Get the Tnode, then get the level 0 offset chunk offset */
3363 yaffs_ExtendedTags localTags;
3365 yaffs_Device *dev = in->myDev;
3369 /* Passed a NULL, so use our own tags space */
3373 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3377 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3380 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3383 /* Delete the entry in the filestructure (if found) */
3385 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
3388 /*T(("No level 0 found for %d\n", chunkInInode)); */
3392 /* T(("Could not find %d to delete\n",chunkInInode)); */
3397 #ifdef YAFFS_PARANOID
3399 static int yaffs_CheckFileSanity(yaffs_Object * in)
3407 yaffs_Tags localTags;
3408 yaffs_Tags *tags = &localTags;
3412 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3413 /* T(("Object not a file\n")); */
3417 objId = in->objectId;
3418 fSize = in->variant.fileVariant.fileSize;
3420 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3422 for (chunk = 1; chunk <= nChunks; chunk++) {
3423 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3428 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
3430 if (yaffs_CheckChunkBits
3431 (dev, theChunk / dev->nChunksPerBlock,
3432 theChunk % dev->nChunksPerBlock)) {
3434 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3438 (tags, in->objectId, chunk, chunkDeleted)) {
3448 /* T(("No level 0 found for %d\n", chunk)); */
3452 return failed ? YAFFS_FAIL : YAFFS_OK;
3457 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
3458 int chunkInNAND, int inScan)
3460 /* NB inScan is zero unless scanning.
3461 * For forward scanning, inScan is > 0;
3462 * for backward scanning inScan is < 0
3466 yaffs_Device *dev = in->myDev;
3468 yaffs_ExtendedTags existingTags;
3469 yaffs_ExtendedTags newTags;
3470 unsigned existingSerial, newSerial;
3472 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3473 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3474 * If it is not during Scanning then something went wrong!
3477 T(YAFFS_TRACE_ERROR,
3479 ("yaffs tragedy:attempt to put data chunk into a non-file"
3484 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3488 tn = yaffs_AddOrFindLevel0Tnode(dev,
3489 &in->variant.fileVariant,
3496 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3499 /* If we're scanning then we need to test for duplicates
3500 * NB This does not need to be efficient since it should only ever
3501 * happen when the power fails during a write, then only one
3502 * chunk should ever be affected.
3504 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3505 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3508 if (existingChunk > 0) {
3509 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3510 * thus we have to do a FindChunkInFile to get the real chunk id.
3512 * We have a duplicate now we need to decide which one to use:
3514 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3515 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3516 * YAFFS1: Get both sets of tags and compare serial numbers.
3520 /* Only do this for forward scanning */
3521 yaffs_ReadChunkWithTagsFromNAND(dev,
3525 /* Do a proper find */
3527 yaffs_FindChunkInFile(in, chunkInInode,
3531 if (existingChunk <= 0) {
3532 /*Hoosterman - how did this happen? */
3534 T(YAFFS_TRACE_ERROR,
3536 ("yaffs tragedy: existing chunk < 0 in scan"
3541 /* NB The deleted flags should be false, otherwise the chunks will
3542 * not be loaded during a scan
3546 newSerial = newTags.serialNumber;
3547 existingSerial = existingTags.serialNumber;
3551 (in->myDev->isYaffs2 ||
3552 existingChunk <= 0 ||
3553 ((existingSerial + 1) & 3) == newSerial)) {
3554 /* Forward scanning.
3556 * Delete the old one and drop through to update the tnode
3558 yaffs_DeleteChunk(dev, existingChunk, 1,
3561 /* Backward scanning or we want to use the existing one
3563 * Delete the new one and return early so that the tnode isn't changed
3565 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3573 if (existingChunk == 0) {
3577 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
3582 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
3585 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3587 if (chunkInNAND >= 0) {
3588 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3591 T(YAFFS_TRACE_NANDACCESS,
3592 (TSTR("Chunk %d not found zero instead" TENDSTR),
3594 /* get sane (zero) data if you read a hole */
3595 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3601 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
3605 yaffs_ExtendedTags tags;
3606 yaffs_BlockInfo *bi;
3613 block = chunkId / dev->nChunksPerBlock;
3614 page = chunkId % dev->nChunksPerBlock;
3617 if(!yaffs_CheckChunkBit(dev,block,page))
3618 T(YAFFS_TRACE_VERIFY,
3619 (TSTR("Deleting invalid chunk %d"TENDSTR),
3622 bi = yaffs_GetBlockInfo(dev, block);
3624 T(YAFFS_TRACE_DELETION,
3625 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3628 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3630 yaffs_InitialiseTags(&tags);
3632 tags.chunkDeleted = 1;
3634 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3635 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3637 dev->nUnmarkedDeletions++;
3640 /* Pull out of the management area.
3641 * If the whole block became dirty, this will kick off an erasure.
3643 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3644 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3645 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3646 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3649 yaffs_ClearChunkBit(dev, block, page);
3653 if (bi->pagesInUse == 0 &&
3654 !bi->hasShrinkHeader &&
3655 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3656 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3657 yaffs_BlockBecameDirty(dev, block);
3661 /* T(("Bad news deleting chunk %d\n",chunkId)); */
3666 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
3667 const __u8 * buffer, int nBytes,
3670 /* Find old chunk Need to do this to get serial number
3671 * Write new one and patch into tree.
3672 * Invalidate old tags.
3676 yaffs_ExtendedTags prevTags;
3679 yaffs_ExtendedTags newTags;
3681 yaffs_Device *dev = in->myDev;
3683 yaffs_CheckGarbageCollection(dev);
3685 /* Get the previous chunk at this location in the file if it exists */
3686 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3688 /* Set up new tags */
3689 yaffs_InitialiseTags(&newTags);
3691 newTags.chunkId = chunkInInode;
3692 newTags.objectId = in->objectId;
3693 newTags.serialNumber =
3694 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
3695 newTags.byteCount = nBytes;
3697 if(nBytes < 1 || nBytes > dev->totalBytesPerChunk){
3698 T(YAFFS_TRACE_ERROR,
3699 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3706 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3709 if (newChunkId >= 0) {
3710 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3712 if (prevChunkId >= 0) {
3713 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3717 yaffs_CheckFileSanity(in);
3723 /* UpdateObjectHeader updates the header on NAND for an object.
3724 * If name is not NULL, then that new name is used.
3726 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
3727 int isShrink, int shadows)
3730 yaffs_BlockInfo *bi;
3732 yaffs_Device *dev = in->myDev;
3739 yaffs_ExtendedTags newTags;
3740 yaffs_ExtendedTags oldTags;
3742 __u8 *buffer = NULL;
3743 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3745 yaffs_ObjectHeader *oh = NULL;
3747 yaffs_strcpy(oldName,_Y("silly old name"));
3751 in == dev->rootDir || /* The rootDir should also be saved */
3754 yaffs_CheckGarbageCollection(dev);
3755 yaffs_CheckObjectDetailsLoaded(in);
3757 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3758 oh = (yaffs_ObjectHeader *) buffer;
3760 prevChunkId = in->hdrChunk;
3762 if (prevChunkId > 0) {
3763 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3766 yaffs_VerifyObjectHeader(in,oh,&oldTags,0);
3768 memcpy(oldName, oh->name, sizeof(oh->name));
3771 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3773 oh->type = in->variantType;
3774 oh->yst_mode = in->yst_mode;
3775 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3777 #ifdef CONFIG_YAFFS_WINCE
3778 oh->win_atime[0] = in->win_atime[0];
3779 oh->win_ctime[0] = in->win_ctime[0];
3780 oh->win_mtime[0] = in->win_mtime[0];
3781 oh->win_atime[1] = in->win_atime[1];
3782 oh->win_ctime[1] = in->win_ctime[1];
3783 oh->win_mtime[1] = in->win_mtime[1];
3785 oh->yst_uid = in->yst_uid;
3786 oh->yst_gid = in->yst_gid;
3787 oh->yst_atime = in->yst_atime;
3788 oh->yst_mtime = in->yst_mtime;
3789 oh->yst_ctime = in->yst_ctime;
3790 oh->yst_rdev = in->yst_rdev;
3793 oh->parentObjectId = in->parent->objectId;
3795 oh->parentObjectId = 0;
3798 if (name && *name) {
3799 memset(oh->name, 0, sizeof(oh->name));
3800 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3801 } else if (prevChunkId>=0) {
3802 memcpy(oh->name, oldName, sizeof(oh->name));
3804 memset(oh->name, 0, sizeof(oh->name));
3807 oh->isShrink = isShrink;
3809 switch (in->variantType) {
3810 case YAFFS_OBJECT_TYPE_UNKNOWN:
3811 /* Should not happen */
3813 case YAFFS_OBJECT_TYPE_FILE:
3815 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3816 || oh->parentObjectId ==
3817 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3818 fileVariant.fileSize;
3820 case YAFFS_OBJECT_TYPE_HARDLINK:
3821 oh->equivalentObjectId =
3822 in->variant.hardLinkVariant.equivalentObjectId;
3824 case YAFFS_OBJECT_TYPE_SPECIAL:
3827 case YAFFS_OBJECT_TYPE_DIRECTORY:
3830 case YAFFS_OBJECT_TYPE_SYMLINK:
3831 yaffs_strncpy(oh->alias,
3832 in->variant.symLinkVariant.alias,
3833 YAFFS_MAX_ALIAS_LENGTH);
3834 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3839 yaffs_InitialiseTags(&newTags);
3841 newTags.chunkId = 0;
3842 newTags.objectId = in->objectId;
3843 newTags.serialNumber = in->serial;
3845 /* Add extra info for file header */
3847 newTags.extraHeaderInfoAvailable = 1;
3848 newTags.extraParentObjectId = oh->parentObjectId;
3849 newTags.extraFileLength = oh->fileSize;
3850 newTags.extraIsShrinkHeader = oh->isShrink;
3851 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3852 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3853 newTags.extraObjectType = in->variantType;
3855 yaffs_VerifyObjectHeader(in,oh,&newTags,1);
3857 /* Create new chunk in NAND */
3859 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3860 (prevChunkId >= 0) ? 1 : 0);
3862 if (newChunkId >= 0) {
3864 in->hdrChunk = newChunkId;
3866 if (prevChunkId >= 0) {
3867 yaffs_DeleteChunk(dev, prevChunkId, 1,
3871 if(!yaffs_ObjectHasCachedWriteData(in))
3874 /* If this was a shrink, then mark the block that the chunk lives on */
3876 bi = yaffs_GetBlockInfo(in->myDev,
3877 newChunkId /in->myDev-> nChunksPerBlock);
3878 bi->hasShrinkHeader = 1;
3883 retVal = newChunkId;
3888 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3893 /*------------------------ Short Operations Cache ----------------------------------------
3894 * In many situations where there is no high level buffering (eg WinCE) a lot of
3895 * reads might be short sequential reads, and a lot of writes may be short
3896 * sequential writes. eg. scanning/writing a jpeg file.
3897 * In these cases, a short read/write cache can provide a huge perfomance benefit
3898 * with dumb-as-a-rock code.
3899 * In Linux, the page cache provides read buffering aand the short op cache provides write
3902 * There are a limited number (~10) of cache chunks per device so that we don't
3903 * need a very intelligent search.
3906 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3908 yaffs_Device *dev = obj->myDev;
3910 yaffs_ChunkCache *cache;
3911 int nCaches = obj->myDev->nShortOpCaches;
3913 for(i = 0; i < nCaches; i++){
3914 cache = &dev->srCache[i];
3915 if (cache->object == obj &&
3924 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3926 yaffs_Device *dev = obj->myDev;
3927 int lowest = -99; /* Stop compiler whining. */
3929 yaffs_ChunkCache *cache;
3930 int chunkWritten = 0;
3931 int nCaches = obj->myDev->nShortOpCaches;
3937 /* Find the dirty cache for this object with the lowest chunk id. */
3938 for (i = 0; i < nCaches; i++) {
3939 if (dev->srCache[i].object == obj &&
3940 dev->srCache[i].dirty) {
3942 || dev->srCache[i].chunkId <
3944 cache = &dev->srCache[i];
3945 lowest = cache->chunkId;
3950 if (cache && !cache->locked) {
3951 /* Write it out and free it up */
3954 yaffs_WriteChunkDataToObject(cache->object,
3960 cache->object = NULL;
3963 } while (cache && chunkWritten > 0);
3966 /* Hoosterman, disk full while writing cache out. */
3967 T(YAFFS_TRACE_ERROR,
3968 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3975 /*yaffs_FlushEntireDeviceCache(dev)
3980 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3983 int nCaches = dev->nShortOpCaches;
3986 /* Find a dirty object in the cache and flush it...
3987 * until there are no further dirty objects.
3991 for( i = 0; i < nCaches && !obj; i++) {
3992 if (dev->srCache[i].object &&
3993 dev->srCache[i].dirty)
3994 obj = dev->srCache[i].object;
3998 yaffs_FlushFilesChunkCache(obj);
4005 /* Grab us a cache chunk for use.
4006 * First look for an empty one.
4007 * Then look for the least recently used non-dirty one.
4008 * Then look for the least recently used dirty one...., flush and look again.
4010 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
4014 if (dev->nShortOpCaches > 0) {
4015 for (i = 0; i < dev->nShortOpCaches; i++) {
4016 if (!dev->srCache[i].object)
4017 return &dev->srCache[i];
4024 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
4026 yaffs_ChunkCache *cache;
4027 yaffs_Object *theObj;
4032 if (dev->nShortOpCaches > 0) {
4033 /* Try find a non-dirty one... */
4035 cache = yaffs_GrabChunkCacheWorker(dev);
4038 /* They were all dirty, find the last recently used object and flush
4039 * its cache, then find again.
4040 * NB what's here is not very accurate, we actually flush the object
4041 * the last recently used page.
4044 /* With locking we can't assume we can use entry zero */
4051 for (i = 0; i < dev->nShortOpCaches; i++) {
4052 if (dev->srCache[i].object &&
4053 !dev->srCache[i].locked &&
4054 (dev->srCache[i].lastUse < usage || !cache))
4056 usage = dev->srCache[i].lastUse;
4057 theObj = dev->srCache[i].object;
4058 cache = &dev->srCache[i];
4063 if (!cache || cache->dirty) {
4064 /* Flush and try again */
4065 yaffs_FlushFilesChunkCache(theObj);
4066 cache = yaffs_GrabChunkCacheWorker(dev);
4076 /* Find a cached chunk */
4077 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
4080 yaffs_Device *dev = obj->myDev;
4082 if (dev->nShortOpCaches > 0) {
4083 for (i = 0; i < dev->nShortOpCaches; i++) {
4084 if (dev->srCache[i].object == obj &&
4085 dev->srCache[i].chunkId == chunkId) {
4088 return &dev->srCache[i];
4095 /* Mark the chunk for the least recently used algorithym */
4096 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
4100 if (dev->nShortOpCaches > 0) {
4101 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4102 /* Reset the cache usages */
4104 for (i = 1; i < dev->nShortOpCaches; i++) {
4105 dev->srCache[i].lastUse = 0;
4112 cache->lastUse = dev->srLastUse;
4120 /* Invalidate a single cache page.
4121 * Do this when a whole page gets written,
4122 * ie the short cache for this page is no longer valid.
4124 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
4126 if (object->myDev->nShortOpCaches > 0) {
4127 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4130 cache->object = NULL;
4135 /* Invalidate all the cache pages associated with this object
4136 * Do this whenever ther file is deleted or resized.
4138 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
4141 yaffs_Device *dev = in->myDev;
4143 if (dev->nShortOpCaches > 0) {
4144 /* Invalidate it. */
4145 for (i = 0; i < dev->nShortOpCaches; i++) {
4146 if (dev->srCache[i].object == in) {
4147 dev->srCache[i].object = NULL;
4153 /*--------------------- Checkpointing --------------------*/
4156 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
4158 yaffs_CheckpointValidity cp;
4160 memset(&cp,0,sizeof(cp));
4162 cp.structType = sizeof(cp);
4163 cp.magic = YAFFS_MAGIC;
4164 cp.version = YAFFS_CHECKPOINT_VERSION;
4165 cp.head = (head) ? 1 : 0;
4167 return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
4171 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4173 yaffs_CheckpointValidity cp;
4176 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4179 ok = (cp.structType == sizeof(cp)) &&
4180 (cp.magic == YAFFS_MAGIC) &&
4181 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4182 (cp.head == ((head) ? 1 : 0));
4186 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4189 cp->nErasedBlocks = dev->nErasedBlocks;
4190 cp->allocationBlock = dev->allocationBlock;
4191 cp->allocationPage = dev->allocationPage;
4192 cp->nFreeChunks = dev->nFreeChunks;
4194 cp->nDeletedFiles = dev->nDeletedFiles;
4195 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4196 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4197 cp->sequenceNumber = dev->sequenceNumber;
4198 cp->oldestDirtySequence = dev->oldestDirtySequence;
4202 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4203 yaffs_CheckpointDevice *cp)
4205 dev->nErasedBlocks = cp->nErasedBlocks;
4206 dev->allocationBlock = cp->allocationBlock;
4207 dev->allocationPage = cp->allocationPage;
4208 dev->nFreeChunks = cp->nFreeChunks;
4210 dev->nDeletedFiles = cp->nDeletedFiles;
4211 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4212 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4213 dev->sequenceNumber = cp->sequenceNumber;
4214 dev->oldestDirtySequence = cp->oldestDirtySequence;
4218 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4220 yaffs_CheckpointDevice cp;
4222 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4226 /* Write device runtime values*/
4227 yaffs_DeviceToCheckpointDevice(&cp,dev);
4228 cp.structType = sizeof(cp);
4230 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4232 /* Write block info */
4234 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4235 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
4238 /* Write chunk bits */
4240 nBytes = nBlocks * dev->chunkBitmapStride;
4241 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
4247 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4249 yaffs_CheckpointDevice cp;
4251 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4255 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4259 if(cp.structType != sizeof(cp))
4263 yaffs_CheckpointDeviceToDevice(dev,&cp);
4265 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4267 ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
4271 nBytes = nBlocks * dev->chunkBitmapStride;
4273 ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
4278 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4282 cp->objectId = obj->objectId;
4283 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4284 cp->hdrChunk = obj->hdrChunk;
4285 cp->variantType = obj->variantType;
4286 cp->deleted = obj->deleted;
4287 cp->softDeleted = obj->softDeleted;
4288 cp->unlinked = obj->unlinked;
4289 cp->fake = obj->fake;
4290 cp->renameAllowed = obj->renameAllowed;
4291 cp->unlinkAllowed = obj->unlinkAllowed;
4292 cp->serial = obj->serial;
4293 cp->nDataChunks = obj->nDataChunks;
4295 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4296 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4297 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4298 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4301 static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
4304 yaffs_Object *parent;
4306 obj->objectId = cp->objectId;
4309 parent = yaffs_FindOrCreateObjectByNumber(
4312 YAFFS_OBJECT_TYPE_DIRECTORY);
4317 yaffs_AddObjectToDirectory(parent, obj);
4319 obj->hdrChunk = cp->hdrChunk;
4320 obj->variantType = cp->variantType;
4321 obj->deleted = cp->deleted;
4322 obj->softDeleted = cp->softDeleted;
4323 obj->unlinked = cp->unlinked;
4324 obj->fake = cp->fake;
4325 obj->renameAllowed = cp->renameAllowed;
4326 obj->unlinkAllowed = cp->unlinkAllowed;
4327 obj->serial = cp->serial;
4328 obj->nDataChunks = cp->nDataChunks;
4330 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4331 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4332 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4333 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4335 if(obj->hdrChunk > 0)
4336 obj->lazyLoaded = 1;
4341 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
4342 __u32 level, int chunkOffset)
4345 yaffs_Device *dev = in->myDev;
4347 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4349 if(tnodeSize < sizeof(yaffs_Tnode))
4350 tnodeSize = sizeof(yaffs_Tnode);
4356 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
4357 if (tn->internal[i]) {
4358 ok = yaffs_CheckpointTnodeWorker(in,
4361 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4364 } else if (level == 0) {
4365 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4366 /* printf("write tnode at %d\n",baseOffset); */
4367 ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
4369 ok = (yaffs_CheckpointWrite(dev,tn,tnodeSize) == tnodeSize);
4377 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4379 __u32 endMarker = ~0;
4382 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4383 ok = yaffs_CheckpointTnodeWorker(obj,
4384 obj->variant.fileVariant.top,
4385 obj->variant.fileVariant.topLevel,
4388 ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) ==
4395 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4399 yaffs_Device *dev = obj->myDev;
4400 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4403 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4405 if(tnodeSize < sizeof(yaffs_Tnode))
4406 tnodeSize = sizeof(yaffs_Tnode);
4408 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4410 while(ok && (~baseChunk)){
4412 /* Read level 0 tnode */
4415 /* printf("read tnode at %d\n",baseChunk); */
4416 tn = yaffs_GetTnodeRaw(dev);
4418 ok = (yaffs_CheckpointRead(dev,tn,tnodeSize) == tnodeSize);
4423 ok = yaffs_AddOrFindLevel0Tnode(dev,
4431 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4435 T(YAFFS_TRACE_CHECKPOINT,(
4436 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4437 nread,baseChunk,ok));
4443 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4446 yaffs_CheckpointObject cp;
4449 struct ylist_head *lh;
4452 /* Iterate through the objects in each hash entry,
4453 * dumping them to the checkpointing stream.
4456 for(i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++){
4457 ylist_for_each(lh, &dev->objectBucket[i].list) {
4459 obj = ylist_entry(lh, yaffs_Object, hashLink);
4460 if (!obj->deferedFree) {
4461 yaffs_ObjectToCheckpointObject(&cp,obj);
4462 cp.structType = sizeof(cp);
4464 T(YAFFS_TRACE_CHECKPOINT,(
4465 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
4466 cp.objectId,cp.parentId,cp.variantType,cp.hdrChunk,(unsigned) obj));
4468 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4470 if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4471 ok = yaffs_WriteCheckpointTnodes(obj);
4478 /* Dump end of list */
4479 memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
4480 cp.structType = sizeof(cp);
4483 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4488 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4491 yaffs_CheckpointObject cp;
4494 yaffs_Object *hardList = NULL;
4496 while(ok && !done) {
4497 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4498 if(cp.structType != sizeof(cp)) {
4499 T(YAFFS_TRACE_CHECKPOINT,(TSTR("struct size %d instead of %d ok %d"TENDSTR),
4500 cp.structType,sizeof(cp),ok));
4504 T(YAFFS_TRACE_CHECKPOINT,(TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4505 cp.objectId,cp.parentId,cp.variantType,cp.hdrChunk));
4507 if(ok && cp.objectId == ~0)
4510 obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
4512 yaffs_CheckpointObjectToObject(obj,&cp);
4513 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4514 ok = yaffs_ReadCheckpointTnodes(obj);
4515 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4516 obj->hardLinks.next =
4517 (struct ylist_head *)
4527 yaffs_HardlinkFixup(dev,hardList);
4532 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4534 __u32 checkpointSum;
4537 yaffs_GetCheckpointSum(dev,&checkpointSum);
4539 ok = (yaffs_CheckpointWrite(dev,&checkpointSum,sizeof(checkpointSum)) == sizeof(checkpointSum));
4547 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4549 __u32 checkpointSum0;
4550 __u32 checkpointSum1;
4553 yaffs_GetCheckpointSum(dev,&checkpointSum0);
4555 ok = (yaffs_CheckpointRead(dev,&checkpointSum1,sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4560 if(checkpointSum0 != checkpointSum1)
4567 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4572 if(dev->skipCheckpointWrite || !dev->isYaffs2){
4573 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint write" TENDSTR)));
4578 ok = yaffs_CheckpointOpen(dev,1);
4581 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4582 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
4585 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint device" TENDSTR)));
4586 ok = yaffs_WriteCheckpointDevice(dev);
4589 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint objects" TENDSTR)));
4590 ok = yaffs_WriteCheckpointObjects(dev);
4593 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4594 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
4598 ok = yaffs_WriteCheckpointSum(dev);
4602 if(!yaffs_CheckpointClose(dev))
4606 dev->isCheckpointed = 1;
4608 dev->isCheckpointed = 0;
4610 return dev->isCheckpointed;
4613 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4617 if(dev->skipCheckpointRead || !dev->isYaffs2){
4618 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint read" TENDSTR)));
4623 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
4626 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4627 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
4630 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint device" TENDSTR)));
4631 ok = yaffs_ReadCheckpointDevice(dev);
4634 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint objects" TENDSTR)));
4635 ok = yaffs_ReadCheckpointObjects(dev);
4638 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4639 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
4643 ok = yaffs_ReadCheckpointSum(dev);
4644 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint checksum %d" TENDSTR),ok));
4647 if(!yaffs_CheckpointClose(dev))
4651 dev->isCheckpointed = 1;
4653 dev->isCheckpointed = 0;
4659 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4661 if(dev->isCheckpointed ||
4662 dev->blocksInCheckpoint > 0){
4663 dev->isCheckpointed = 0;
4664 yaffs_CheckpointInvalidateStream(dev);
4665 if(dev->superBlock && dev->markSuperBlockDirty)
4666 dev->markSuperBlockDirty(dev->superBlock);
4671 int yaffs_CheckpointSave(yaffs_Device *dev)
4674 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4676 yaffs_VerifyObjects(dev);
4677 yaffs_VerifyBlocks(dev);
4678 yaffs_VerifyFreeChunks(dev);
4680 if(!dev->isCheckpointed) {
4681 yaffs_InvalidateCheckpoint(dev);
4682 yaffs_WriteCheckpointData(dev);
4685 T(YAFFS_TRACE_ALWAYS,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4687 return dev->isCheckpointed;
4690 int yaffs_CheckpointRestore(yaffs_Device *dev)
4693 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4695 retval = yaffs_ReadCheckpointData(dev);
4697 if(dev->isCheckpointed){
4698 yaffs_VerifyObjects(dev);
4699 yaffs_VerifyBlocks(dev);
4700 yaffs_VerifyFreeChunks(dev);
4703 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4708 /*--------------------- File read/write ------------------------
4709 * Read and write have very similar structures.
4710 * In general the read/write has three parts to it
4711 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4712 * Some complete chunks
4713 * An incomplete chunk to end off with
4715 * Curve-balls: the first chunk might also be the last chunk.
4718 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, loff_t offset,
4727 yaffs_ChunkCache *cache;
4734 //chunk = offset / dev->nDataBytesPerChunk + 1;
4735 //start = offset % dev->nDataBytesPerChunk;
4736 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4739 /* OK now check for the curveball where the start and end are in
4742 if ((start + n) < dev->nDataBytesPerChunk) {
4745 nToCopy = dev->nDataBytesPerChunk - start;
4748 cache = yaffs_FindChunkCache(in, chunk);
4750 /* If the chunk is already in the cache or it is less than a whole chunk
4751 * or we're using inband tags then use the cache (if there is caching)
4752 * else bypass the cache.
4754 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4755 if (dev->nShortOpCaches > 0) {
4757 /* If we can't find the data in the cache, then load it up. */
4760 cache = yaffs_GrabChunkCache(in->myDev);
4762 cache->chunkId = chunk;
4765 yaffs_ReadChunkDataFromObject(in, chunk,
4771 yaffs_UseChunkCache(dev, cache, 0);
4775 #ifdef CONFIG_YAFFS_WINCE
4776 yfsd_UnlockYAFFS(TRUE);
4778 memcpy(buffer, &cache->data[start], nToCopy);
4780 #ifdef CONFIG_YAFFS_WINCE
4781 yfsd_LockYAFFS(TRUE);
4785 /* Read into the local buffer then copy..*/
4788 yaffs_GetTempBuffer(dev, __LINE__);
4789 yaffs_ReadChunkDataFromObject(in, chunk,
4791 #ifdef CONFIG_YAFFS_WINCE
4792 yfsd_UnlockYAFFS(TRUE);
4794 memcpy(buffer, &localBuffer[start], nToCopy);
4796 #ifdef CONFIG_YAFFS_WINCE
4797 yfsd_LockYAFFS(TRUE);
4799 yaffs_ReleaseTempBuffer(dev, localBuffer,
4804 #ifdef CONFIG_YAFFS_WINCE
4805 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4807 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4808 * This is because we otherwise screw up WinCE's memory mapper
4810 yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
4812 #ifdef CONFIG_YAFFS_WINCE
4813 yfsd_UnlockYAFFS(TRUE);
4815 memcpy(buffer, localBuffer, dev->nDataBytesPerChunk);
4817 #ifdef CONFIG_YAFFS_WINCE
4818 yfsd_LockYAFFS(TRUE);
4819 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4823 /* A full chunk. Read directly into the supplied buffer. */
4824 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4838 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, loff_t offset,
4839 int nBytes, int writeThrough)
4848 int startOfWrite = offset;
4849 int chunkWritten = 0;
4857 while (n > 0 && chunkWritten >= 0) {
4858 //chunk = offset / dev->nDataBytesPerChunk + 1;
4859 //start = offset % dev->nDataBytesPerChunk;
4860 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4862 if(chunk * dev->nDataBytesPerChunk + start != offset ||
4863 start >= dev->nDataBytesPerChunk){
4864 T(YAFFS_TRACE_ERROR,(TSTR("AddrToChunk of offset %d gives chunk %d start %d"TENDSTR),
4865 (int)offset, chunk,start));
4869 /* OK now check for the curveball where the start and end are in
4873 if ((start + n) < dev->nDataBytesPerChunk) {
4876 /* Now folks, to calculate how many bytes to write back....
4877 * If we're overwriting and not writing to then end of file then
4878 * we need to write back as much as was there before.
4881 chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
4883 if(chunkStart > in->variant.fileVariant.fileSize)
4884 nBytesRead = 0; /* Past end of file */
4886 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
4888 if (nBytesRead > dev->nDataBytesPerChunk) {
4889 nBytesRead = dev->nDataBytesPerChunk;
4894 (start + n)) ? nBytesRead : (start + n);
4896 if(nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
4900 nToCopy = dev->nDataBytesPerChunk - start;
4901 nToWriteBack = dev->nDataBytesPerChunk;
4904 if (nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4905 /* An incomplete start or end chunk (or maybe both start and end chunk),
4906 * or we're using inband tags, so we want to use the cache buffers.
4908 if (dev->nShortOpCaches > 0) {
4909 yaffs_ChunkCache *cache;
4910 /* If we can't find the data in the cache, then load the cache */
4911 cache = yaffs_FindChunkCache(in, chunk);
4914 && yaffs_CheckSpaceForAllocation(in->
4916 cache = yaffs_GrabChunkCache(in->myDev);
4918 cache->chunkId = chunk;
4921 yaffs_ReadChunkDataFromObject(in, chunk,
4927 !yaffs_CheckSpaceForAllocation(in->myDev)){
4928 /* Drop the cache if it was a read cache item and
4929 * no space check has been made for it.
4935 yaffs_UseChunkCache(dev, cache, 1);
4937 #ifdef CONFIG_YAFFS_WINCE
4938 yfsd_UnlockYAFFS(TRUE);
4941 memcpy(&cache->data[start], buffer,
4944 #ifdef CONFIG_YAFFS_WINCE
4945 yfsd_LockYAFFS(TRUE);
4948 cache->nBytes = nToWriteBack;
4952 yaffs_WriteChunkDataToObject
4955 cache->data, cache->nBytes,
4961 chunkWritten = -1; /* fail the write */
4964 /* An incomplete start or end chunk (or maybe both start and end chunk)
4965 * Read into the local buffer then copy, then copy over and write back.
4969 yaffs_GetTempBuffer(dev, __LINE__);
4971 yaffs_ReadChunkDataFromObject(in, chunk,
4974 #ifdef CONFIG_YAFFS_WINCE
4975 yfsd_UnlockYAFFS(TRUE);
4978 memcpy(&localBuffer[start], buffer, nToCopy);
4980 #ifdef CONFIG_YAFFS_WINCE
4981 yfsd_LockYAFFS(TRUE);
4984 yaffs_WriteChunkDataToObject(in, chunk,
4989 yaffs_ReleaseTempBuffer(dev, localBuffer,
4995 /* A full chunk. Write directly from the supplied buffer. */
4997 #ifdef CONFIG_YAFFS_WINCE
4998 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4999 * This is because we otherwise screw up WinCE's memory mapper
5001 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5002 #ifdef CONFIG_YAFFS_WINCE
5003 yfsd_UnlockYAFFS(TRUE);
5005 memcpy(localBuffer, buffer, dev->nDataBytesPerChunk);
5006 #ifdef CONFIG_YAFFS_WINCE
5007 yfsd_LockYAFFS(TRUE);
5010 yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
5011 dev->nDataBytesPerChunk,
5013 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5017 yaffs_WriteChunkDataToObject(in, chunk, buffer,
5018 dev->nDataBytesPerChunk,
5021 /* Since we've overwritten the cached data, we better invalidate it. */
5022 yaffs_InvalidateChunkCache(in, chunk);
5025 if (chunkWritten >= 0) {
5034 /* Update file object */
5036 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
5037 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
5046 /* ---------------------- File resizing stuff ------------------ */
5048 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
5051 yaffs_Device *dev = in->myDev;
5052 int oldFileSize = in->variant.fileVariant.fileSize;
5054 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
5056 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
5057 dev->nDataBytesPerChunk;
5061 /* Delete backwards so that we don't end up with holes if
5062 * power is lost part-way through the operation.
5064 for (i = lastDel; i >= startDel; i--) {
5065 /* NB this could be optimised somewhat,
5066 * eg. could retrieve the tags and write them without
5067 * using yaffs_DeleteChunk
5070 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5073 (dev->internalStartBlock * dev->nChunksPerBlock)
5075 ((dev->internalEndBlock +
5076 1) * dev->nChunksPerBlock)) {
5077 T(YAFFS_TRACE_ALWAYS,
5078 (TSTR("Found daft chunkId %d for %d" TENDSTR),
5082 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5089 int yaffs_ResizeFile(yaffs_Object * in, loff_t newSize)
5092 int oldFileSize = in->variant.fileVariant.fileSize;
5093 __u32 newSizeOfPartialChunk;
5096 yaffs_Device *dev = in->myDev;
5098 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5100 yaffs_FlushFilesChunkCache(in);
5101 yaffs_InvalidateWholeChunkCache(in);
5103 yaffs_CheckGarbageCollection(dev);
5105 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
5109 if (newSize == oldFileSize) {
5113 if (newSize < oldFileSize) {
5115 yaffs_PruneResizedChunks(in, newSize);
5117 if (newSizeOfPartialChunk != 0) {
5118 int lastChunk = 1 + newFullChunks;
5120 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5122 /* Got to read and rewrite the last chunk with its new size and zero pad */
5123 yaffs_ReadChunkDataFromObject(in, lastChunk,
5126 memset(localBuffer + newSizeOfPartialChunk, 0,
5127 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5129 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5130 newSizeOfPartialChunk, 1);
5132 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5135 in->variant.fileVariant.fileSize = newSize;
5137 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5139 /* newsSize > oldFileSize */
5140 in->variant.fileVariant.fileSize = newSize;
5145 /* Write a new object header.
5146 * show we've shrunk the file, if need be
5147 * Do this only if the file is not in the deleted directories.
5150 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5151 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
5152 yaffs_UpdateObjectHeader(in, NULL, 0,
5153 (newSize < oldFileSize) ? 1 : 0, 0);
5159 loff_t yaffs_GetFileSize(yaffs_Object * obj)
5161 obj = yaffs_GetEquivalentObject(obj);
5163 switch (obj->variantType) {
5164 case YAFFS_OBJECT_TYPE_FILE:
5165 return obj->variant.fileVariant.fileSize;
5166 case YAFFS_OBJECT_TYPE_SYMLINK:
5167 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5175 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
5179 yaffs_FlushFilesChunkCache(in);
5181 #ifdef CONFIG_YAFFS_WINCE
5182 yfsd_WinFileTimeNow(in->win_mtime);
5185 in->yst_mtime = Y_CURRENT_TIME;
5191 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5192 0) ? YAFFS_OK : YAFFS_FAIL;
5201 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
5204 /* First off, invalidate the file's data in the cache, without flushing. */
5205 yaffs_InvalidateWholeChunkCache(in);
5207 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5208 /* Move to the unlinked directory so we have a record that it was deleted. */
5209 yaffs_ChangeObjectName(in, in->myDev->deletedDir,_Y("deleted"), 0, 0);
5213 yaffs_RemoveObjectFromDirectory(in);
5214 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5217 yaffs_FreeObject(in);
5222 /* yaffs_DeleteFile deletes the whole file data
5223 * and the inode associated with the file.
5224 * It does not delete the links associated with the file.
5227 static int yaffs_UnlinkFile(yaffs_Object * in)
5231 int immediateDeletion = 0;
5235 immediateDeletion = 1;
5238 if (in->inUse <= 0) {
5239 immediateDeletion = 1;
5243 if (immediateDeletion) {
5245 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5246 _Y("deleted"), 0, 0);
5247 T(YAFFS_TRACE_TRACING,
5248 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5251 in->myDev->nDeletedFiles++;
5252 if (1 || in->myDev->isYaffs2) {
5253 yaffs_ResizeFile(in, 0);
5255 yaffs_SoftDeleteFile(in);
5258 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5259 _Y("unlinked"), 0, 0);
5266 int yaffs_DeleteFile(yaffs_Object * in)
5268 int retVal = YAFFS_OK;
5269 int deleted = in->deleted;
5271 yaffs_ResizeFile(in,0);
5273 if (in->nDataChunks > 0) {
5274 /* Use soft deletion if there is data in the file.
5275 * That won't be the case if it has been resized to zero.
5277 if (!in->unlinked) {
5278 retVal = yaffs_UnlinkFile(in);
5280 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5281 in->deleted = deleted = 1;
5282 in->myDev->nDeletedFiles++;
5283 yaffs_SoftDeleteFile(in);
5285 return deleted ? YAFFS_OK : YAFFS_FAIL;
5287 /* The file has no data chunks so we toss it immediately */
5288 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5289 in->variant.fileVariant.top = NULL;
5290 yaffs_DoGenericObjectDeletion(in);
5296 static int yaffs_DeleteDirectory(yaffs_Object * in)
5298 /* First check that the directory is empty. */
5299 if (ylist_empty(&in->variant.directoryVariant.children)) {
5300 return yaffs_DoGenericObjectDeletion(in);
5307 static int yaffs_DeleteSymLink(yaffs_Object * in)
5309 YFREE(in->variant.symLinkVariant.alias);
5311 return yaffs_DoGenericObjectDeletion(in);
5314 static int yaffs_DeleteHardLink(yaffs_Object * in)
5316 /* remove this hardlink from the list assocaited with the equivalent
5319 ylist_del_init(&in->hardLinks);
5320 return yaffs_DoGenericObjectDeletion(in);
5323 static void yaffs_DestroyObject(yaffs_Object * obj)
5325 switch (obj->variantType) {
5326 case YAFFS_OBJECT_TYPE_FILE:
5327 yaffs_DeleteFile(obj);
5329 case YAFFS_OBJECT_TYPE_DIRECTORY:
5330 yaffs_DeleteDirectory(obj);
5332 case YAFFS_OBJECT_TYPE_SYMLINK:
5333 yaffs_DeleteSymLink(obj);
5335 case YAFFS_OBJECT_TYPE_HARDLINK:
5336 yaffs_DeleteHardLink(obj);
5338 case YAFFS_OBJECT_TYPE_SPECIAL:
5339 yaffs_DoGenericObjectDeletion(obj);
5341 case YAFFS_OBJECT_TYPE_UNKNOWN:
5342 break; /* should not happen. */
5346 static int yaffs_UnlinkWorker(yaffs_Object * obj)
5349 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5350 return yaffs_DeleteHardLink(obj);
5351 } else if (!ylist_empty(&obj->hardLinks)) {
5352 /* Curve ball: We're unlinking an object that has a hardlink.
5354 * This problem arises because we are not strictly following
5355 * The Linux link/inode model.
5357 * We can't really delete the object.
5358 * Instead, we do the following:
5359 * - Select a hardlink.
5360 * - Unhook it from the hard links
5361 * - Unhook it from its parent directory (so that the rename can work)
5362 * - Rename the object to the hardlink's name.
5363 * - Delete the hardlink
5368 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5370 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5372 ylist_del_init(&hl->hardLinks);
5373 ylist_del_init(&hl->siblings);
5375 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5377 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
5379 if (retVal == YAFFS_OK) {
5380 retVal = yaffs_DoGenericObjectDeletion(hl);
5385 switch (obj->variantType) {
5386 case YAFFS_OBJECT_TYPE_FILE:
5387 return yaffs_UnlinkFile(obj);
5389 case YAFFS_OBJECT_TYPE_DIRECTORY:
5390 return yaffs_DeleteDirectory(obj);
5392 case YAFFS_OBJECT_TYPE_SYMLINK:
5393 return yaffs_DeleteSymLink(obj);
5395 case YAFFS_OBJECT_TYPE_SPECIAL:
5396 return yaffs_DoGenericObjectDeletion(obj);
5398 case YAFFS_OBJECT_TYPE_HARDLINK:
5399 case YAFFS_OBJECT_TYPE_UNKNOWN:
5407 static int yaffs_UnlinkObject( yaffs_Object *obj)
5410 if (obj && obj->unlinkAllowed) {
5411 return yaffs_UnlinkWorker(obj);
5417 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
5421 obj = yaffs_FindObjectByName(dir, name);
5422 return yaffs_UnlinkObject(obj);
5425 /*----------------------- Initialisation Scanning ---------------------- */
5427 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
5428 int backwardScanning)
5432 if (!backwardScanning) {
5433 /* Handle YAFFS1 forward scanning case
5434 * For YAFFS1 we always do the deletion
5438 /* Handle YAFFS2 case (backward scanning)
5439 * If the shadowed object exists then ignore.
5441 if (yaffs_FindObjectByNumber(dev, objId)) {
5446 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5447 * We put it in unlinked dir to be cleaned up after the scanning
5450 yaffs_FindOrCreateObjectByNumber(dev, objId,
5451 YAFFS_OBJECT_TYPE_FILE);
5452 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5453 obj->variant.fileVariant.shrinkSize = 0;
5454 obj->valid = 1; /* So that we don't read any other info for this file */
5464 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5471 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5473 in = yaffs_FindObjectByNumber(dev,
5474 hl->variant.hardLinkVariant.
5475 equivalentObjectId);
5478 /* Add the hardlink pointers */
5479 hl->variant.hardLinkVariant.equivalentObject = in;
5480 ylist_add(&hl->hardLinks, &in->hardLinks);
5482 /* Todo Need to report/handle this better.
5483 * Got a problem... hardlink to a non-existant object
5485 hl->variant.hardLinkVariant.equivalentObject = NULL;
5486 YINIT_LIST_HEAD(&hl->hardLinks);
5498 static int ybicmp(const void *a, const void *b){
5499 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5500 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5501 register int ablock = ((yaffs_BlockIndex *)a)->block;
5502 register int bblock = ((yaffs_BlockIndex *)b)->block;
5504 return ablock - bblock;
5511 struct yaffs_ShadowFixerStruct {
5514 struct yaffs_ShadowFixerStruct *next;
5517 static int yaffs_Scan(yaffs_Device * dev)
5519 yaffs_ExtendedTags tags;
5529 yaffs_BlockState state;
5530 yaffs_Object *hardList = NULL;
5531 yaffs_BlockInfo *bi;
5532 __u32 sequenceNumber;
5533 yaffs_ObjectHeader *oh;
5535 yaffs_Object *parent;
5537 int alloc_failed = 0;
5539 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5547 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5548 dev->internalStartBlock, dev->internalEndBlock));
5550 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5552 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5554 /* Scan all the blocks to determine their state */
5555 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5556 bi = yaffs_GetBlockInfo(dev, blk);
5557 yaffs_ClearChunkBits(dev, blk);
5559 bi->softDeletions = 0;
5561 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5563 bi->blockState = state;
5564 bi->sequenceNumber = sequenceNumber;
5566 T(YAFFS_TRACE_SCAN_DEBUG,
5567 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5568 state, sequenceNumber));
5570 if (state == YAFFS_BLOCK_STATE_DEAD) {
5571 T(YAFFS_TRACE_BAD_BLOCKS,
5572 (TSTR("block %d is bad" TENDSTR), blk));
5573 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5574 T(YAFFS_TRACE_SCAN_DEBUG,
5575 (TSTR("Block empty " TENDSTR)));
5576 dev->nErasedBlocks++;
5577 dev->nFreeChunks += dev->nChunksPerBlock;
5581 startIterator = dev->internalStartBlock;
5582 endIterator = dev->internalEndBlock;
5584 /* For each block.... */
5585 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5592 blk = blockIterator;
5594 bi = yaffs_GetBlockInfo(dev, blk);
5595 state = bi->blockState;
5599 /* For each chunk in each block that needs scanning....*/
5600 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5601 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5602 /* Read the tags and decide what to do */
5603 chunk = blk * dev->nChunksPerBlock + c;
5605 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5608 /* Let's have a good look at this chunk... */
5610 if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
5616 /*T((" %d %d deleted\n",blk,c)); */
5617 } else if (!tags.chunkUsed) {
5618 /* An unassigned chunk in the block
5619 * This means that either the block is empty or
5620 * this is the one being allocated from
5624 /* We're looking at the first chunk in the block so the block is unused */
5625 state = YAFFS_BLOCK_STATE_EMPTY;
5626 dev->nErasedBlocks++;
5628 /* this is the block being allocated from */
5631 (" Allocating from %d %d" TENDSTR),
5633 state = YAFFS_BLOCK_STATE_ALLOCATING;
5634 dev->allocationBlock = blk;
5635 dev->allocationPage = c;
5636 dev->allocationBlockFinder = blk;
5637 /* Set it to here to encourage the allocator to go forth from here. */
5641 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5642 } else if (tags.chunkId > 0) {
5643 /* chunkId > 0 so it is a data chunk... */
5644 unsigned int endpos;
5646 yaffs_SetChunkBit(dev, blk, c);
5649 in = yaffs_FindOrCreateObjectByNumber(dev,
5652 YAFFS_OBJECT_TYPE_FILE);
5653 /* PutChunkIntoFile checks for a clash (two data chunks with
5654 * the same chunkId).
5661 if(!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,1))
5666 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5669 in->variantType == YAFFS_OBJECT_TYPE_FILE
5670 && in->variant.fileVariant.scannedFileSize <
5672 in->variant.fileVariant.
5673 scannedFileSize = endpos;
5674 if (!dev->useHeaderFileSize) {
5675 in->variant.fileVariant.
5677 in->variant.fileVariant.
5682 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
5684 /* chunkId == 0, so it is an ObjectHeader.
5685 * Thus, we read in the object header and make the object
5687 yaffs_SetChunkBit(dev, blk, c);
5690 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5694 oh = (yaffs_ObjectHeader *) chunkData;
5696 in = yaffs_FindObjectByNumber(dev,
5698 if (in && in->variantType != oh->type) {
5699 /* This should not happen, but somehow
5700 * Wev'e ended up with an objectId that has been reused but not yet
5701 * deleted, and worse still it has changed type. Delete the old object.
5704 yaffs_DestroyObject(in);
5709 in = yaffs_FindOrCreateObjectByNumber(dev,
5717 if (in && oh->shadowsObject > 0) {
5719 struct yaffs_ShadowFixerStruct *fixer;
5720 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
5722 fixer-> next = shadowFixerList;
5723 shadowFixerList = fixer;
5724 fixer->objectId = tags.objectId;
5725 fixer->shadowedId = oh->shadowsObject;
5730 if (in && in->valid) {
5731 /* We have already filled this one. We have a duplicate and need to resolve it. */
5733 unsigned existingSerial = in->serial;
5734 unsigned newSerial = tags.serialNumber;
5736 if (((existingSerial + 1) & 3) == newSerial) {
5737 /* Use new one - destroy the exisiting one */
5738 yaffs_DeleteChunk(dev,
5743 /* Use existing - destroy this one. */
5744 yaffs_DeleteChunk(dev, chunk, 1,
5749 if (in && !in->valid &&
5750 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5751 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5752 /* We only load some info, don't fiddle with directory structure */
5754 in->variantType = oh->type;
5756 in->yst_mode = oh->yst_mode;
5757 #ifdef CONFIG_YAFFS_WINCE
5758 in->win_atime[0] = oh->win_atime[0];
5759 in->win_ctime[0] = oh->win_ctime[0];
5760 in->win_mtime[0] = oh->win_mtime[0];
5761 in->win_atime[1] = oh->win_atime[1];
5762 in->win_ctime[1] = oh->win_ctime[1];
5763 in->win_mtime[1] = oh->win_mtime[1];
5765 in->yst_uid = oh->yst_uid;
5766 in->yst_gid = oh->yst_gid;
5767 in->yst_atime = oh->yst_atime;
5768 in->yst_mtime = oh->yst_mtime;
5769 in->yst_ctime = oh->yst_ctime;
5770 in->yst_rdev = oh->yst_rdev;
5772 in->hdrChunk = chunk;
5773 in->serial = tags.serialNumber;
5775 } else if (in && !in->valid) {
5776 /* we need to load this info */
5779 in->variantType = oh->type;
5781 in->yst_mode = oh->yst_mode;
5782 #ifdef CONFIG_YAFFS_WINCE
5783 in->win_atime[0] = oh->win_atime[0];
5784 in->win_ctime[0] = oh->win_ctime[0];
5785 in->win_mtime[0] = oh->win_mtime[0];
5786 in->win_atime[1] = oh->win_atime[1];
5787 in->win_ctime[1] = oh->win_ctime[1];
5788 in->win_mtime[1] = oh->win_mtime[1];
5790 in->yst_uid = oh->yst_uid;
5791 in->yst_gid = oh->yst_gid;
5792 in->yst_atime = oh->yst_atime;
5793 in->yst_mtime = oh->yst_mtime;
5794 in->yst_ctime = oh->yst_ctime;
5795 in->yst_rdev = oh->yst_rdev;
5797 in->hdrChunk = chunk;
5798 in->serial = tags.serialNumber;
5800 yaffs_SetObjectName(in, oh->name);
5803 /* directory stuff...
5808 yaffs_FindOrCreateObjectByNumber
5809 (dev, oh->parentObjectId,
5810 YAFFS_OBJECT_TYPE_DIRECTORY);
5811 if (parent->variantType ==
5812 YAFFS_OBJECT_TYPE_UNKNOWN) {
5813 /* Set up as a directory */
5814 parent->variantType =
5815 YAFFS_OBJECT_TYPE_DIRECTORY;
5816 YINIT_LIST_HEAD(&parent->variant.
5819 } else if (parent->variantType !=
5820 YAFFS_OBJECT_TYPE_DIRECTORY)
5822 /* Hoosterman, another problem....
5823 * We're trying to use a non-directory as a directory
5826 T(YAFFS_TRACE_ERROR,
5828 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
5830 parent = dev->lostNFoundDir;
5833 yaffs_AddObjectToDirectory(parent, in);
5835 if (0 && (parent == dev->deletedDir ||
5836 parent == dev->unlinkedDir)) {
5837 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
5838 dev->nDeletedFiles++;
5840 /* Note re hardlinks.
5841 * Since we might scan a hardlink before its equivalent object is scanned
5842 * we put them all in a list.
5843 * After scanning is complete, we should have all the objects, so we run through this
5844 * list and fix up all the chains.
5847 switch (in->variantType) {
5848 case YAFFS_OBJECT_TYPE_UNKNOWN:
5849 /* Todo got a problem */
5851 case YAFFS_OBJECT_TYPE_FILE:
5852 if (dev->useHeaderFileSize)
5854 in->variant.fileVariant.
5859 case YAFFS_OBJECT_TYPE_HARDLINK:
5860 in->variant.hardLinkVariant.
5861 equivalentObjectId =
5862 oh->equivalentObjectId;
5863 in->hardLinks.next =
5864 (struct ylist_head *)
5868 case YAFFS_OBJECT_TYPE_DIRECTORY:
5871 case YAFFS_OBJECT_TYPE_SPECIAL:
5874 case YAFFS_OBJECT_TYPE_SYMLINK:
5875 in->variant.symLinkVariant.alias =
5876 yaffs_CloneString(oh->alias);
5877 if(!in->variant.symLinkVariant.alias)
5883 if (parent == dev->deletedDir) {
5884 yaffs_DestroyObject(in);
5885 bi->hasShrinkHeader = 1;
5892 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5893 /* If we got this far while scanning, then the block is fully allocated.*/
5894 state = YAFFS_BLOCK_STATE_FULL;
5897 bi->blockState = state;
5899 /* Now let's see if it was dirty */
5900 if (bi->pagesInUse == 0 &&
5901 !bi->hasShrinkHeader &&
5902 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5903 yaffs_BlockBecameDirty(dev, blk);
5909 /* Ok, we've done all the scanning.
5910 * Fix up the hard link chains.
5911 * We should now have scanned all the objects, now it's time to add these
5915 yaffs_HardlinkFixup(dev,hardList);
5917 /* Handle the unlinked files. Since they were left in an unlinked state we should
5921 struct ylist_head *i;
5922 struct ylist_head *n;
5925 /* Soft delete all the unlinked files */
5926 ylist_for_each_safe(i, n,
5927 &dev->unlinkedDir->variant.directoryVariant.
5930 l = ylist_entry(i, yaffs_Object, siblings);
5931 yaffs_DestroyObject(l);
5936 /* Fix up any shadowed objects */
5938 struct yaffs_ShadowFixerStruct *fixer;
5941 while(shadowFixerList){
5942 fixer = shadowFixerList;
5943 shadowFixerList = fixer->next;
5944 /* Complete the rename transaction by deleting the shadowed object
5945 * then setting the object header to unshadowed.
5947 obj = yaffs_FindObjectByNumber(dev,fixer->shadowedId);
5949 yaffs_DestroyObject(obj);
5951 obj = yaffs_FindObjectByNumber(dev,fixer->objectId);
5953 yaffs_UpdateObjectHeader(obj,NULL,1,0,0);
5960 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5966 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5972 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5975 yaffs_ObjectHeader *oh;
5977 yaffs_ExtendedTags tags;
5979 int alloc_failed = 0;
5987 T(YAFFS_TRACE_SCAN,(TSTR("details for object %d %s loaded" TENDSTR),
5989 in->lazyLoaded ? "not yet" : "already"));
5992 if(in->lazyLoaded && in->hdrChunk > 0){
5994 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5996 result = yaffs_ReadChunkWithTagsFromNAND(dev,in->hdrChunk,chunkData,&tags);
5997 oh = (yaffs_ObjectHeader *) chunkData;
5999 in->yst_mode = oh->yst_mode;
6000 #ifdef CONFIG_YAFFS_WINCE
6001 in->win_atime[0] = oh->win_atime[0];
6002 in->win_ctime[0] = oh->win_ctime[0];
6003 in->win_mtime[0] = oh->win_mtime[0];
6004 in->win_atime[1] = oh->win_atime[1];
6005 in->win_ctime[1] = oh->win_ctime[1];
6006 in->win_mtime[1] = oh->win_mtime[1];
6008 in->yst_uid = oh->yst_uid;
6009 in->yst_gid = oh->yst_gid;
6010 in->yst_atime = oh->yst_atime;
6011 in->yst_mtime = oh->yst_mtime;
6012 in->yst_ctime = oh->yst_ctime;
6013 in->yst_rdev = oh->yst_rdev;
6016 yaffs_SetObjectName(in, oh->name);
6018 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
6019 in->variant.symLinkVariant.alias =
6020 yaffs_CloneString(oh->alias);
6021 if(!in->variant.symLinkVariant.alias)
6022 alloc_failed = 1; /* Not returned to caller */
6025 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
6029 static int yaffs_ScanBackwards(yaffs_Device * dev)
6031 yaffs_ExtendedTags tags;
6036 int nBlocksToScan = 0;
6042 yaffs_BlockState state;
6043 yaffs_Object *hardList = NULL;
6044 yaffs_BlockInfo *bi;
6045 __u32 sequenceNumber;
6046 yaffs_ObjectHeader *oh;
6048 yaffs_Object *parent;
6049 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6055 int foundChunksInBlock;
6056 int equivalentObjectId;
6057 int alloc_failed = 0;
6060 yaffs_BlockIndex *blockIndex = NULL;
6061 int altBlockIndex = 0;
6063 if (!dev->isYaffs2) {
6065 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6071 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
6072 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6075 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6077 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6080 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6086 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6090 dev->blocksInCheckpoint = 0;
6092 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6094 /* Scan all the blocks to determine their state */
6095 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6096 bi = yaffs_GetBlockInfo(dev, blk);
6097 yaffs_ClearChunkBits(dev, blk);
6099 bi->softDeletions = 0;
6101 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6103 bi->blockState = state;
6104 bi->sequenceNumber = sequenceNumber;
6106 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6107 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6109 T(YAFFS_TRACE_SCAN_DEBUG,
6110 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6111 state, sequenceNumber));
6114 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
6115 dev->blocksInCheckpoint++;
6117 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6118 T(YAFFS_TRACE_BAD_BLOCKS,
6119 (TSTR("block %d is bad" TENDSTR), blk));
6120 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6121 T(YAFFS_TRACE_SCAN_DEBUG,
6122 (TSTR("Block empty " TENDSTR)));
6123 dev->nErasedBlocks++;
6124 dev->nFreeChunks += dev->nChunksPerBlock;
6125 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6127 /* Determine the highest sequence number */
6128 if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6129 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6131 blockIndex[nBlocksToScan].seq = sequenceNumber;
6132 blockIndex[nBlocksToScan].block = blk;
6136 if (sequenceNumber >= dev->sequenceNumber) {
6137 dev->sequenceNumber = sequenceNumber;
6140 /* TODO: Nasty sequence number! */
6143 ("Block scanning block %d has bad sequence number %d"
6144 TENDSTR), blk, sequenceNumber));
6151 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6157 /* Sort the blocks */
6158 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6160 /* Use qsort now. */
6161 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6165 /* Dungy old bubble sort... */
6167 yaffs_BlockIndex temp;
6171 for (i = 0; i < nBlocksToScan; i++)
6172 for (j = i + 1; j < nBlocksToScan; j++)
6173 if (blockIndex[i].seq > blockIndex[j].seq) {
6174 temp = blockIndex[j];
6175 blockIndex[j] = blockIndex[i];
6176 blockIndex[i] = temp;
6183 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6185 /* Now scan the blocks looking at the data. */
6187 endIterator = nBlocksToScan - 1;
6188 T(YAFFS_TRACE_SCAN_DEBUG,
6189 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6191 /* For each block.... backwards */
6192 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6194 /* Cooperative multitasking! This loop can run for so
6195 long that watchdog timers expire. */
6198 /* get the block to scan in the correct order */
6199 blk = blockIndex[blockIterator].block;
6201 bi = yaffs_GetBlockInfo(dev, blk);
6204 state = bi->blockState;
6208 /* For each chunk in each block that needs scanning.... */
6209 foundChunksInBlock = 0;
6210 for (c = dev->nChunksPerBlock - 1;
6211 !alloc_failed && c >= 0 &&
6212 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6213 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6214 /* Scan backwards...
6215 * Read the tags and decide what to do
6218 chunk = blk * dev->nChunksPerBlock + c;
6220 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6223 /* Let's have a good look at this chunk... */
6225 if (!tags.chunkUsed) {
6226 /* An unassigned chunk in the block.
6227 * If there are used chunks after this one, then
6228 * it is a chunk that was skipped due to failing the erased
6229 * check. Just skip it so that it can be deleted.
6230 * But, more typically, We get here when this is an unallocated
6231 * chunk and his means that either the block is empty or
6232 * this is the one being allocated from
6235 if(foundChunksInBlock)
6237 /* This is a chunk that was skipped due to failing the erased check */
6239 } else if (c == 0) {
6240 /* We're looking at the first chunk in the block so the block is unused */
6241 state = YAFFS_BLOCK_STATE_EMPTY;
6242 dev->nErasedBlocks++;
6244 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6245 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6246 if(dev->sequenceNumber == bi->sequenceNumber) {
6247 /* this is the block being allocated from */
6251 (" Allocating from %d %d"
6254 state = YAFFS_BLOCK_STATE_ALLOCATING;
6255 dev->allocationBlock = blk;
6256 dev->allocationPage = c;
6257 dev->allocationBlockFinder = blk;
6260 /* This is a partially written block that is not
6261 * the current allocation block. This block must have
6262 * had a write failure, so set up for retirement.
6265 /* bi->needsRetiring = 1; ??? TODO */
6266 bi->gcPrioritise = 1;
6268 T(YAFFS_TRACE_ALWAYS,
6269 (TSTR("Partially written block %d detected" TENDSTR),
6279 } else if (tags.chunkId > 0) {
6280 /* chunkId > 0 so it is a data chunk... */
6281 unsigned int endpos;
6283 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6285 foundChunksInBlock = 1;
6288 yaffs_SetChunkBit(dev, blk, c);
6291 in = yaffs_FindOrCreateObjectByNumber(dev,
6294 YAFFS_OBJECT_TYPE_FILE);
6301 in->variantType == YAFFS_OBJECT_TYPE_FILE
6303 in->variant.fileVariant.shrinkSize) {
6304 /* This has not been invalidated by a resize */
6305 if(!yaffs_PutChunkIntoFile(in, tags.chunkId,
6310 /* File size is calculated by looking at the data chunks if we have not
6311 * seen an object header yet. Stop this practice once we find an object header.
6315 1) * dev->nDataBytesPerChunk +
6318 if (!in->valid && /* have not got an object header yet */
6319 in->variant.fileVariant.
6320 scannedFileSize < endpos) {
6321 in->variant.fileVariant.
6322 scannedFileSize = endpos;
6323 in->variant.fileVariant.
6325 in->variant.fileVariant.
6330 /* This chunk has been invalidated by a resize, so delete */
6331 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6335 /* chunkId == 0, so it is an ObjectHeader.
6336 * Thus, we read in the object header and make the object
6338 foundChunksInBlock = 1;
6340 yaffs_SetChunkBit(dev, blk, c);
6346 if (tags.extraHeaderInfoAvailable) {
6347 in = yaffs_FindOrCreateObjectByNumber
6348 (dev, tags.objectId,
6349 tags.extraObjectType);
6353 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
6356 tags.extraShadows ||
6358 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6359 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
6362 /* If we don't have valid info then we need to read the chunk
6363 * TODO In future we can probably defer reading the chunk and
6364 * living with invalid data until needed.
6367 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6372 oh = (yaffs_ObjectHeader *) chunkData;
6374 if(dev->inbandTags){
6375 /* Fix up the header if they got corrupted by inband tags */
6376 oh->shadowsObject = oh->inbandShadowsObject;
6377 oh->isShrink = oh->inbandIsShrink;
6381 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6386 /* TODO Hoosterman we have a problem! */
6387 T(YAFFS_TRACE_ERROR,
6389 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6390 TENDSTR), tags.objectId, chunk));
6395 /* We have already filled this one.
6396 * We have a duplicate that will be discarded, but
6397 * we first have to suck out resize info if it is a file.
6400 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6402 oh-> type == YAFFS_OBJECT_TYPE_FILE)||
6403 (tags.extraHeaderInfoAvailable &&
6404 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
6407 (oh) ? oh->fileSize : tags.
6409 __u32 parentObjectId =
6411 parentObjectId : tags.
6412 extraParentObjectId;
6416 (oh) ? oh->isShrink : tags.
6417 extraIsShrinkHeader;
6419 /* If it is deleted (unlinked at start also means deleted)
6420 * we treat the file size as being zeroed at this point.
6422 if (parentObjectId ==
6423 YAFFS_OBJECTID_DELETED
6424 || parentObjectId ==
6425 YAFFS_OBJECTID_UNLINKED) {
6431 in->variant.fileVariant.
6432 shrinkSize > thisSize) {
6433 in->variant.fileVariant.
6439 bi->hasShrinkHeader = 1;
6443 /* Use existing - destroy this one. */
6444 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6449 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6451 YAFFS_OBJECTID_LOSTNFOUND)) {
6452 /* We only load some info, don't fiddle with directory structure */
6456 in->variantType = oh->type;
6458 in->yst_mode = oh->yst_mode;
6459 #ifdef CONFIG_YAFFS_WINCE
6460 in->win_atime[0] = oh->win_atime[0];
6461 in->win_ctime[0] = oh->win_ctime[0];
6462 in->win_mtime[0] = oh->win_mtime[0];
6463 in->win_atime[1] = oh->win_atime[1];
6464 in->win_ctime[1] = oh->win_ctime[1];
6465 in->win_mtime[1] = oh->win_mtime[1];
6467 in->yst_uid = oh->yst_uid;
6468 in->yst_gid = oh->yst_gid;
6469 in->yst_atime = oh->yst_atime;
6470 in->yst_mtime = oh->yst_mtime;
6471 in->yst_ctime = oh->yst_ctime;
6472 in->yst_rdev = oh->yst_rdev;
6476 in->variantType = tags.extraObjectType;
6480 in->hdrChunk = chunk;
6482 } else if (!in->valid) {
6483 /* we need to load this info */
6486 in->hdrChunk = chunk;
6489 in->variantType = oh->type;
6491 in->yst_mode = oh->yst_mode;
6492 #ifdef CONFIG_YAFFS_WINCE
6493 in->win_atime[0] = oh->win_atime[0];
6494 in->win_ctime[0] = oh->win_ctime[0];
6495 in->win_mtime[0] = oh->win_mtime[0];
6496 in->win_atime[1] = oh->win_atime[1];
6497 in->win_ctime[1] = oh->win_ctime[1];
6498 in->win_mtime[1] = oh->win_mtime[1];
6500 in->yst_uid = oh->yst_uid;
6501 in->yst_gid = oh->yst_gid;
6502 in->yst_atime = oh->yst_atime;
6503 in->yst_mtime = oh->yst_mtime;
6504 in->yst_ctime = oh->yst_ctime;
6505 in->yst_rdev = oh->yst_rdev;
6508 if (oh->shadowsObject > 0)
6509 yaffs_HandleShadowedObject(dev,
6515 yaffs_SetObjectName(in, oh->name);
6517 yaffs_FindOrCreateObjectByNumber
6518 (dev, oh->parentObjectId,
6519 YAFFS_OBJECT_TYPE_DIRECTORY);
6521 fileSize = oh->fileSize;
6522 isShrink = oh->isShrink;
6523 equivalentObjectId = oh->equivalentObjectId;
6527 in->variantType = tags.extraObjectType;
6529 yaffs_FindOrCreateObjectByNumber
6530 (dev, tags.extraParentObjectId,
6531 YAFFS_OBJECT_TYPE_DIRECTORY);
6532 fileSize = tags.extraFileLength;
6533 isShrink = tags.extraIsShrinkHeader;
6534 equivalentObjectId = tags.extraEquivalentObjectId;
6540 /* directory stuff...
6544 if (parent->variantType ==
6545 YAFFS_OBJECT_TYPE_UNKNOWN) {
6546 /* Set up as a directory */
6547 parent->variantType =
6548 YAFFS_OBJECT_TYPE_DIRECTORY;
6549 YINIT_LIST_HEAD(&parent->variant.
6552 } else if (parent->variantType !=
6553 YAFFS_OBJECT_TYPE_DIRECTORY)
6555 /* Hoosterman, another problem....
6556 * We're trying to use a non-directory as a directory
6559 T(YAFFS_TRACE_ERROR,
6561 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6563 parent = dev->lostNFoundDir;
6566 yaffs_AddObjectToDirectory(parent, in);
6568 itsUnlinked = (parent == dev->deletedDir) ||
6569 (parent == dev->unlinkedDir);
6572 /* Mark the block as having a shrinkHeader */
6573 bi->hasShrinkHeader = 1;
6576 /* Note re hardlinks.
6577 * Since we might scan a hardlink before its equivalent object is scanned
6578 * we put them all in a list.
6579 * After scanning is complete, we should have all the objects, so we run
6580 * through this list and fix up all the chains.
6583 switch (in->variantType) {
6584 case YAFFS_OBJECT_TYPE_UNKNOWN:
6585 /* Todo got a problem */
6587 case YAFFS_OBJECT_TYPE_FILE:
6589 if (in->variant.fileVariant.
6590 scannedFileSize < fileSize) {
6591 /* This covers the case where the file size is greater
6592 * than where the data is
6593 * This will happen if the file is resized to be larger
6594 * than its current data extents.
6596 in->variant.fileVariant.fileSize = fileSize;
6597 in->variant.fileVariant.scannedFileSize =
6598 in->variant.fileVariant.fileSize;
6602 in->variant.fileVariant.shrinkSize > fileSize) {
6603 in->variant.fileVariant.shrinkSize = fileSize;
6607 case YAFFS_OBJECT_TYPE_HARDLINK:
6609 in->variant.hardLinkVariant.equivalentObjectId =
6611 in->hardLinks.next =
6612 (struct ylist_head *) hardList;
6616 case YAFFS_OBJECT_TYPE_DIRECTORY:
6619 case YAFFS_OBJECT_TYPE_SPECIAL:
6622 case YAFFS_OBJECT_TYPE_SYMLINK:
6624 in->variant.symLinkVariant.alias =
6625 yaffs_CloneString(oh->
6627 if(!in->variant.symLinkVariant.alias)
6637 } /* End of scanning for each chunk */
6639 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6640 /* If we got this far while scanning, then the block is fully allocated. */
6641 state = YAFFS_BLOCK_STATE_FULL;
6644 bi->blockState = state;
6646 /* Now let's see if it was dirty */
6647 if (bi->pagesInUse == 0 &&
6648 !bi->hasShrinkHeader &&
6649 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6650 yaffs_BlockBecameDirty(dev, blk);
6656 YFREE_ALT(blockIndex);
6660 /* Ok, we've done all the scanning.
6661 * Fix up the hard link chains.
6662 * We should now have scanned all the objects, now it's time to add these
6665 yaffs_HardlinkFixup(dev,hardList);
6669 * Sort out state of unlinked and deleted objects.
6672 struct ylist_head *i;
6673 struct ylist_head *n;
6677 /* Soft delete all the unlinked files */
6678 ylist_for_each_safe(i, n,
6679 &dev->unlinkedDir->variant.directoryVariant.
6682 l = ylist_entry(i, yaffs_Object, siblings);
6683 yaffs_DestroyObject(l);
6687 /* Soft delete all the deletedDir files */
6688 ylist_for_each_safe(i, n,
6689 &dev->deletedDir->variant.directoryVariant.
6692 l = ylist_entry(i, yaffs_Object, siblings);
6693 yaffs_DestroyObject(l);
6699 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6705 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6710 /*------------------------------ Directory Functions ----------------------------- */
6712 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
6714 struct ylist_head *lh;
6715 yaffs_Object *listObj;
6720 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
6724 if(yaffs_SkipVerification(obj->myDev))
6728 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
6732 if(obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
6733 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
6737 /* Iterate through the objects in each hash entry */
6739 ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
6741 listObj = ylist_entry(lh, yaffs_Object, siblings);
6742 yaffs_VerifyObject(listObj);
6749 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR),count));
6755 static void yaffs_VerifyDirectory(yaffs_Object *directory)
6758 struct ylist_head *lh;
6759 yaffs_Object *listObj;
6764 if(yaffs_SkipFullVerification(directory->myDev))
6768 if(directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
6769 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR),directory->variantType));
6773 /* Iterate through the objects in each hash entry */
6775 ylist_for_each(lh, &directory->variant.directoryVariant.children) {
6777 listObj = ylist_entry(lh, yaffs_Object, siblings);
6778 if(listObj->parent != directory){
6779 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR),listObj->parent));
6782 yaffs_VerifyObjectInDirectory(listObj);
6789 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
6791 yaffs_Device *dev = obj->myDev;
6792 yaffs_Object *parent;
6794 yaffs_VerifyObjectInDirectory(obj);
6795 parent = obj->parent;
6797 yaffs_VerifyDirectory(parent);
6799 if(dev && dev->removeObjectCallback)
6800 dev->removeObjectCallback(obj);
6803 ylist_del_init(&obj->siblings);
6806 yaffs_VerifyDirectory(parent);
6811 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
6816 T(YAFFS_TRACE_ALWAYS,
6818 ("tragedy: Trying to add an object to a null pointer directory"
6822 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6823 T(YAFFS_TRACE_ALWAYS,
6825 ("tragedy: Trying to add an object to a non-directory"
6830 if (obj->siblings.prev == NULL) {
6831 /* Not initialised */
6834 } else if (ylist_empty(&obj->siblings)) {
6839 yaffs_VerifyDirectory(directory);
6841 yaffs_RemoveObjectFromDirectory(obj);
6845 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
6846 obj->parent = directory;
6848 if (directory == obj->myDev->unlinkedDir
6849 || directory == obj->myDev->deletedDir) {
6851 obj->myDev->nUnlinkedFiles++;
6852 obj->renameAllowed = 0;
6855 yaffs_VerifyDirectory(directory);
6856 yaffs_VerifyObjectInDirectory(obj);
6861 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
6866 struct ylist_head *i;
6867 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
6876 T(YAFFS_TRACE_ALWAYS,
6878 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6882 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6883 T(YAFFS_TRACE_ALWAYS,
6885 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6889 sum = yaffs_CalcNameSum(name);
6891 ylist_for_each(i, &directory->variant.directoryVariant.children) {
6893 l = ylist_entry(i, yaffs_Object, siblings);
6895 if(l->parent != directory)
6898 yaffs_CheckObjectDetailsLoaded(l);
6900 /* Special case for lost-n-found */
6901 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6902 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
6905 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0){
6906 /* LostnFound chunk called Objxxx
6909 yaffs_GetObjectName(l, buffer,
6910 YAFFS_MAX_NAME_LENGTH);
6911 if (yaffs_strncmp(name, buffer,YAFFS_MAX_NAME_LENGTH) == 0) {
6924 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
6925 int (*fn) (yaffs_Object *))
6927 struct ylist_head *i;
6931 T(YAFFS_TRACE_ALWAYS,
6933 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6937 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6938 T(YAFFS_TRACE_ALWAYS,
6940 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6944 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
6946 l = ylist_entry(i, yaffs_Object, siblings);
6958 /* GetEquivalentObject dereferences any hard links to get to the
6962 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
6964 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
6965 /* We want the object id of the equivalent object, not this one */
6966 obj = obj->variant.hardLinkVariant.equivalentObject;
6967 yaffs_CheckObjectDetailsLoaded(obj);
6973 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
6975 memset(name, 0, buffSize * sizeof(YCHAR));
6977 yaffs_CheckObjectDetailsLoaded(obj);
6979 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6980 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
6981 } else if (obj->hdrChunk <= 0) {
6983 YCHAR numString[20];
6984 YCHAR *x = &numString[19];
6985 unsigned v = obj->objectId;
6989 *x = '0' + (v % 10);
6992 /* make up a name */
6993 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
6994 yaffs_strcat(locName,x);
6995 yaffs_strncpy(name, locName, buffSize - 1);
6998 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
6999 else if (obj->shortName[0]) {
7000 yaffs_strcpy(name, obj->shortName);
7005 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
7007 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
7009 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
7011 if (obj->hdrChunk > 0) {
7012 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
7013 obj->hdrChunk, buffer,
7016 yaffs_strncpy(name, oh->name, buffSize - 1);
7018 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
7021 return yaffs_strlen(name);
7024 int yaffs_GetObjectFileLength(yaffs_Object * obj)
7027 /* Dereference any hard linking */
7028 obj = yaffs_GetEquivalentObject(obj);
7030 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
7031 return obj->variant.fileVariant.fileSize;
7033 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
7034 return yaffs_strlen(obj->variant.symLinkVariant.alias);
7036 /* Only a directory should drop through to here */
7037 return obj->myDev->nDataBytesPerChunk;
7041 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
7044 struct ylist_head *i;
7046 if (!obj->unlinked) {
7047 count++; /* the object itself */
7049 ylist_for_each(i, &obj->hardLinks) {
7050 count++; /* add the hard links; */
7056 int yaffs_GetObjectInode(yaffs_Object * obj)
7058 obj = yaffs_GetEquivalentObject(obj);
7060 return obj->objectId;
7063 unsigned yaffs_GetObjectType(yaffs_Object * obj)
7065 obj = yaffs_GetEquivalentObject(obj);
7067 switch (obj->variantType) {
7068 case YAFFS_OBJECT_TYPE_FILE:
7071 case YAFFS_OBJECT_TYPE_DIRECTORY:
7074 case YAFFS_OBJECT_TYPE_SYMLINK:
7077 case YAFFS_OBJECT_TYPE_HARDLINK:
7080 case YAFFS_OBJECT_TYPE_SPECIAL:
7081 if (S_ISFIFO(obj->yst_mode))
7083 if (S_ISCHR(obj->yst_mode))
7085 if (S_ISBLK(obj->yst_mode))
7087 if (S_ISSOCK(obj->yst_mode))
7095 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
7097 obj = yaffs_GetEquivalentObject(obj);
7098 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
7099 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7101 return yaffs_CloneString(_Y(""));
7105 #ifndef CONFIG_YAFFS_WINCE
7107 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
7109 unsigned int valid = attr->ia_valid;
7111 if (valid & ATTR_MODE)
7112 obj->yst_mode = attr->ia_mode;
7113 if (valid & ATTR_UID)
7114 obj->yst_uid = attr->ia_uid;
7115 if (valid & ATTR_GID)
7116 obj->yst_gid = attr->ia_gid;
7118 if (valid & ATTR_ATIME)
7119 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7120 if (valid & ATTR_CTIME)
7121 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7122 if (valid & ATTR_MTIME)
7123 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7125 if (valid & ATTR_SIZE)
7126 yaffs_ResizeFile(obj, attr->ia_size);
7128 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7133 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
7135 unsigned int valid = 0;
7137 attr->ia_mode = obj->yst_mode;
7139 attr->ia_uid = obj->yst_uid;
7141 attr->ia_gid = obj->yst_gid;
7144 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7145 valid |= ATTR_ATIME;
7146 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7147 valid |= ATTR_CTIME;
7148 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7149 valid |= ATTR_MTIME;
7151 attr->ia_size = yaffs_GetFileSize(obj);
7154 attr->ia_valid = valid;
7163 int yaffs_DumpObject(yaffs_Object * obj)
7167 yaffs_GetObjectName(obj, name, 256);
7169 T(YAFFS_TRACE_ALWAYS,
7171 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7172 " chunk %d type %d size %d\n"
7173 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7174 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7175 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7181 /*---------------------------- Initialisation code -------------------------------------- */
7183 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
7186 /* Common functions, gotta have */
7187 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
7190 #ifdef CONFIG_YAFFS_YAFFS2
7192 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7193 if (dev->writeChunkWithTagsToNAND &&
7194 dev->readChunkWithTagsFromNAND &&
7195 !dev->writeChunkToNAND &&
7196 !dev->readChunkFromNAND &&
7197 dev->markNANDBlockBad && dev->queryNANDBlock)
7201 /* Can use the "spare" style interface for yaffs1 */
7202 if (!dev->isYaffs2 &&
7203 !dev->writeChunkWithTagsToNAND &&
7204 !dev->readChunkWithTagsFromNAND &&
7205 dev->writeChunkToNAND &&
7206 dev->readChunkFromNAND &&
7207 !dev->markNANDBlockBad && !dev->queryNANDBlock)
7214 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7216 /* Initialise the unlinked, deleted, root and lost and found directories */
7218 dev->lostNFoundDir = dev->rootDir = NULL;
7219 dev->unlinkedDir = dev->deletedDir = NULL;
7222 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7225 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7228 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7229 YAFFS_ROOT_MODE | S_IFDIR);
7230 dev->lostNFoundDir =
7231 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7232 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7234 if(dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir){
7235 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7242 int yaffs_GutsInitialise(yaffs_Device * dev)
7244 int init_failed = 0;
7248 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7250 /* Check stuff that must be set */
7253 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7257 dev->internalStartBlock = dev->startBlock;
7258 dev->internalEndBlock = dev->endBlock;
7259 dev->blockOffset = 0;
7260 dev->chunkOffset = 0;
7261 dev->nFreeChunks = 0;
7265 if (dev->startBlock == 0) {
7266 dev->internalStartBlock = dev->startBlock + 1;
7267 dev->internalEndBlock = dev->endBlock + 1;
7268 dev->blockOffset = 1;
7269 dev->chunkOffset = dev->nChunksPerBlock;
7272 /* Check geometry parameters. */
7274 if ((!dev->inbandTags && dev->isYaffs2 && dev->totalBytesPerChunk < 1024) ||
7275 (!dev->isYaffs2 && dev->totalBytesPerChunk < 512) ||
7276 (dev->inbandTags && !dev->isYaffs2 ) ||
7277 dev->nChunksPerBlock < 2 ||
7278 dev->nReservedBlocks < 2 ||
7279 dev->internalStartBlock <= 0 ||
7280 dev->internalEndBlock <= 0 ||
7281 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
7283 T(YAFFS_TRACE_ALWAYS,
7285 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7286 TENDSTR), dev->totalBytesPerChunk, dev->isYaffs2 ? "2" : "", dev->inbandTags));
7290 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7291 T(YAFFS_TRACE_ALWAYS,
7292 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7296 /* Sort out space for inband tags, if required */
7298 dev->nDataBytesPerChunk = dev->totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7300 dev->nDataBytesPerChunk = dev->totalBytesPerChunk;
7302 /* Got the right mix of functions? */
7303 if (!yaffs_CheckDevFunctions(dev)) {
7304 /* Function missing */
7305 T(YAFFS_TRACE_ALWAYS,
7307 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7312 /* This is really a compilation check. */
7313 if (!yaffs_CheckStructures()) {
7314 T(YAFFS_TRACE_ALWAYS,
7315 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7319 if (dev->isMounted) {
7320 T(YAFFS_TRACE_ALWAYS,
7321 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7325 /* Finished with most checks. One or two more checks happen later on too. */
7329 /* OK now calculate a few things for the device */
7332 * Calculate all the chunk size manipulation numbers:
7334 x = dev->nDataBytesPerChunk;
7335 /* We always use dev->chunkShift and dev->chunkDiv */
7336 dev->chunkShift = Shifts(x);
7337 x >>= dev->chunkShift;
7339 /* We only use chunk mask if chunkDiv is 1 */
7340 dev->chunkMask = (1<<dev->chunkShift) - 1;
7343 * Calculate chunkGroupBits.
7344 * We need to find the next power of 2 > than internalEndBlock
7347 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7351 /* Set up tnode width if wide tnodes are enabled. */
7352 if(!dev->wideTnodesDisabled){
7353 /* bits must be even so that we end up with 32-bit words */
7357 dev->tnodeWidth = 16;
7359 dev->tnodeWidth = bits;
7362 dev->tnodeWidth = 16;
7364 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7366 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7367 * so if the bitwidth of the
7368 * chunk range we're using is greater than 16 we need
7369 * to figure out chunk shift and chunkGroupSize
7372 if (bits <= dev->tnodeWidth)
7373 dev->chunkGroupBits = 0;
7375 dev->chunkGroupBits = bits - dev->tnodeWidth;
7378 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7380 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7381 /* We have a problem because the soft delete won't work if
7382 * the chunk group size > chunks per block.
7383 * This can be remedied by using larger "virtual blocks".
7385 T(YAFFS_TRACE_ALWAYS,
7386 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7391 /* OK, we've finished verifying the device, lets continue with initialisation */
7393 /* More device initialisation */
7394 dev->garbageCollections = 0;
7395 dev->passiveGarbageCollections = 0;
7396 dev->currentDirtyChecker = 0;
7397 dev->bufferedBlock = -1;
7398 dev->doingBufferedBlockRewrite = 0;
7399 dev->nDeletedFiles = 0;
7400 dev->nBackgroundDeletions = 0;
7401 dev->nUnlinkedFiles = 0;
7403 dev->eccUnfixed = 0;
7404 dev->tagsEccFixed = 0;
7405 dev->tagsEccUnfixed = 0;
7406 dev->nErasureFailures = 0;
7407 dev->nErasedBlocks = 0;
7409 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7411 /* Initialise temporary buffers and caches. */
7412 if(!yaffs_InitialiseTempBuffers(dev))
7415 dev->srCache = NULL;
7416 dev->gcCleanupList = NULL;
7420 dev->nShortOpCaches > 0) {
7423 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7425 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
7426 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7429 dev->srCache = YMALLOC(srCacheBytes);
7431 buf = (__u8 *) dev->srCache;
7434 memset(dev->srCache,0,srCacheBytes);
7436 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7437 dev->srCache[i].object = NULL;
7438 dev->srCache[i].lastUse = 0;
7439 dev->srCache[i].dirty = 0;
7440 dev->srCache[i].data = buf = YMALLOC_DMA(dev->totalBytesPerChunk);
7451 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7452 if(!dev->gcCleanupList)
7456 if (dev->isYaffs2) {
7457 dev->useHeaderFileSize = 1;
7459 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7462 yaffs_InitialiseTnodes(dev);
7463 yaffs_InitialiseObjects(dev);
7465 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7470 /* Now scan the flash. */
7471 if (dev->isYaffs2) {
7472 if(yaffs_CheckpointRestore(dev)) {
7473 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7474 T(YAFFS_TRACE_ALWAYS,
7475 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7478 /* Clean up the mess caused by an aborted checkpoint load
7479 * and scan backwards.
7481 yaffs_DeinitialiseBlocks(dev);
7482 yaffs_DeinitialiseTnodes(dev);
7483 yaffs_DeinitialiseObjects(dev);
7486 dev->nErasedBlocks = 0;
7487 dev->nFreeChunks = 0;
7488 dev->allocationBlock = -1;
7489 dev->allocationPage = -1;
7490 dev->nDeletedFiles = 0;
7491 dev->nUnlinkedFiles = 0;
7492 dev->nBackgroundDeletions = 0;
7493 dev->oldestDirtySequence = 0;
7495 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7498 yaffs_InitialiseTnodes(dev);
7499 yaffs_InitialiseObjects(dev);
7501 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7504 if(!init_failed && !yaffs_ScanBackwards(dev))
7508 if(!yaffs_Scan(dev))
7513 /* Clean up the mess */
7514 T(YAFFS_TRACE_TRACING,
7515 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7517 yaffs_Deinitialise(dev);
7521 /* Zero out stats */
7522 dev->nPageReads = 0;
7523 dev->nPageWrites = 0;
7524 dev->nBlockErasures = 0;
7526 dev->nRetriedWrites = 0;
7528 dev->nRetiredBlocks = 0;
7530 yaffs_VerifyFreeChunks(dev);
7531 yaffs_VerifyBlocks(dev);
7534 T(YAFFS_TRACE_TRACING,
7535 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7540 void yaffs_Deinitialise(yaffs_Device * dev)
7542 if (dev->isMounted) {
7545 yaffs_DeinitialiseBlocks(dev);
7546 yaffs_DeinitialiseTnodes(dev);
7547 yaffs_DeinitialiseObjects(dev);
7548 if (dev->nShortOpCaches > 0 &&
7551 for (i = 0; i < dev->nShortOpCaches; i++) {
7552 if(dev->srCache[i].data)
7553 YFREE(dev->srCache[i].data);
7554 dev->srCache[i].data = NULL;
7557 YFREE(dev->srCache);
7558 dev->srCache = NULL;
7561 YFREE(dev->gcCleanupList);
7563 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
7564 YFREE(dev->tempBuffer[i].buffer);
7570 if(dev->deinitialiseNAND)
7571 dev->deinitialiseNAND(dev);
7576 static int yaffs_CountFreeChunks(yaffs_Device * dev)
7581 yaffs_BlockInfo *blk;
7583 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7585 blk = yaffs_GetBlockInfo(dev, b);
7587 switch (blk->blockState) {
7588 case YAFFS_BLOCK_STATE_EMPTY:
7589 case YAFFS_BLOCK_STATE_ALLOCATING:
7590 case YAFFS_BLOCK_STATE_COLLECTING:
7591 case YAFFS_BLOCK_STATE_FULL:
7593 (dev->nChunksPerBlock - blk->pagesInUse +
7594 blk->softDeletions);
7605 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
7607 /* This is what we report to the outside world */
7610 int nDirtyCacheChunks;
7611 int blocksForCheckpoint;
7614 nFree = dev->nFreeChunks;
7616 nFree = yaffs_CountFreeChunks(dev);
7619 nFree += dev->nDeletedFiles;
7621 /* Now count the number of dirty chunks in the cache and subtract those */
7625 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7626 if (dev->srCache[i].dirty)
7627 nDirtyCacheChunks++;
7631 nFree -= nDirtyCacheChunks;
7633 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7635 /* Now we figure out how much to reserve for the checkpoint and report that... */
7636 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7637 if(blocksForCheckpoint < 0)
7638 blocksForCheckpoint = 0;
7640 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7649 static int yaffs_freeVerificationFailures;
7651 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
7656 if(yaffs_SkipVerification(dev))
7659 counted = yaffs_CountFreeChunks(dev);
7661 difference = dev->nFreeChunks - counted;
7664 T(YAFFS_TRACE_ALWAYS,
7665 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7666 dev->nFreeChunks, counted, difference));
7667 yaffs_freeVerificationFailures++;
7671 /*---------------------------------------- YAFFS test code ----------------------*/
7673 #define yaffs_CheckStruct(structure,syze, name) \
7675 if(sizeof(structure) != syze) \
7677 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
7678 name,syze,sizeof(structure))); \
7679 return YAFFS_FAIL; \
7683 static int yaffs_CheckStructures(void)
7685 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
7686 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
7687 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
7688 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7689 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode");
7691 #ifndef CONFIG_YAFFS_WINCE
7692 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");