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.68 2008-11-27 20:32:52 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 /* TODO: This will need to change if we do partial gc */
487 if(bi->blockState != YAFFS_BLOCK_STATE_EMPTY){
488 T(YAFFS_TRACE_ERROR,(TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
493 static void yaffs_VerifyBlocks(yaffs_Device *dev)
496 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
497 int nIllegalBlockStates = 0;
500 if(yaffs_SkipVerification(dev))
503 memset(nBlocksPerState,0,sizeof(nBlocksPerState));
506 for(i = dev->internalStartBlock; i <= dev->internalEndBlock; i++){
507 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
508 yaffs_VerifyBlock(dev,bi,i);
510 if(bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
511 nBlocksPerState[bi->blockState]++;
513 nIllegalBlockStates++;
517 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
518 T(YAFFS_TRACE_VERIFY,(TSTR("Block summary"TENDSTR)));
520 T(YAFFS_TRACE_VERIFY,(TSTR("%d blocks have illegal states"TENDSTR),nIllegalBlockStates));
521 if(nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
522 T(YAFFS_TRACE_VERIFY,(TSTR("Too many allocating blocks"TENDSTR)));
524 for(i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
525 T(YAFFS_TRACE_VERIFY,
526 (TSTR("%s %d blocks"TENDSTR),
527 blockStateName[i],nBlocksPerState[i]));
529 if(dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
530 T(YAFFS_TRACE_VERIFY,
531 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
532 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
534 if(dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
535 T(YAFFS_TRACE_VERIFY,
536 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
537 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
539 if(nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
540 T(YAFFS_TRACE_VERIFY,
541 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
542 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
544 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
549 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
550 * case those tests will not be performed.
552 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
554 if(obj && yaffs_SkipVerification(obj->myDev))
557 if(!(tags && obj && oh)){
558 T(YAFFS_TRACE_VERIFY,
559 (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR),
560 (__u32)tags,(__u32)obj,(__u32)oh));
564 if(oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
565 oh->type > YAFFS_OBJECT_TYPE_MAX)
566 T(YAFFS_TRACE_VERIFY,
567 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
568 tags->objectId, oh->type));
570 if(tags->objectId != obj->objectId)
571 T(YAFFS_TRACE_VERIFY,
572 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
573 tags->objectId, obj->objectId));
577 * Check that the object's parent ids match if parentCheck requested.
579 * Tests do not apply to the root object.
582 if(parentCheck && tags->objectId > 1 && !obj->parent)
583 T(YAFFS_TRACE_VERIFY,
584 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
585 tags->objectId, oh->parentObjectId));
588 if(parentCheck && obj->parent &&
589 oh->parentObjectId != obj->parent->objectId &&
590 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
591 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
592 T(YAFFS_TRACE_VERIFY,
593 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
594 tags->objectId, oh->parentObjectId, obj->parent->objectId));
597 if(tags->objectId > 1 && oh->name[0] == 0) /* Null name */
598 T(YAFFS_TRACE_VERIFY,
599 (TSTR("Obj %d header name is NULL"TENDSTR),
602 if(tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
603 T(YAFFS_TRACE_VERIFY,
604 (TSTR("Obj %d header name is 0xFF"TENDSTR),
610 static int yaffs_VerifyTnodeWorker(yaffs_Object * obj, yaffs_Tnode * tn,
611 __u32 level, int chunkOffset)
614 yaffs_Device *dev = obj->myDev;
620 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
621 if (tn->internal[i]) {
622 ok = yaffs_VerifyTnodeWorker(obj,
625 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
628 } else if (level == 0) {
629 yaffs_ExtendedTags tags;
630 __u32 objectId = obj->objectId;
632 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
634 for(i = 0; i < YAFFS_NTNODES_LEVEL0; i++){
635 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
638 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
639 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
640 if(tags.objectId != objectId || tags.chunkId != chunkOffset){
641 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
642 objectId, chunkOffset, theChunk,
643 tags.objectId, tags.chunkId));
656 static void yaffs_VerifyFile(yaffs_Object *obj)
658 int requiredTallness;
664 yaffs_ExtendedTags tags;
671 if(yaffs_SkipVerification(obj->myDev))
675 objectId = obj->objectId;
677 /* Check file size is consistent with tnode depth */
678 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
679 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
680 requiredTallness = 0;
682 x >>= YAFFS_TNODES_INTERNAL_BITS;
686 actualTallness = obj->variant.fileVariant.topLevel;
688 if(requiredTallness > actualTallness )
689 T(YAFFS_TRACE_VERIFY,
690 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
691 obj->objectId,actualTallness, requiredTallness));
694 /* Check that the chunks in the tnode tree are all correct.
695 * We do this by scanning through the tnode tree and
696 * checking the tags for every chunk match.
699 if(yaffs_SkipNANDVerification(dev))
702 for(i = 1; i <= lastChunk; i++){
703 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant,i);
706 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
708 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
709 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
710 if(tags.objectId != objectId || tags.chunkId != i){
711 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
712 objectId, i, theChunk,
713 tags.objectId, tags.chunkId));
723 static void yaffs_VerifyHardLink(yaffs_Object *obj)
725 if(obj && yaffs_SkipVerification(obj->myDev))
728 /* Verify sane equivalent object */
731 static void yaffs_VerifySymlink(yaffs_Object *obj)
733 if(obj && yaffs_SkipVerification(obj->myDev))
736 /* Verify symlink string */
739 static void yaffs_VerifySpecial(yaffs_Object *obj)
741 if(obj && yaffs_SkipVerification(obj->myDev))
745 static void yaffs_VerifyObject(yaffs_Object *obj)
760 if(yaffs_SkipVerification(dev))
763 /* Check sane object header chunk */
765 chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
766 chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
768 chunkIdOk = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
769 chunkIsLive = chunkIdOk &&
770 yaffs_CheckChunkBit(dev,
771 obj->hdrChunk / dev->nChunksPerBlock,
772 obj->hdrChunk % dev->nChunksPerBlock);
774 (!chunkIdOk || !chunkIsLive)) {
775 T(YAFFS_TRACE_VERIFY,
776 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
777 obj->objectId,obj->hdrChunk,
778 chunkIdOk ? "" : ",out of range",
779 chunkIsLive || !chunkIdOk ? "" : ",marked as deleted"));
782 if(chunkIdOk && chunkIsLive &&!yaffs_SkipNANDVerification(dev)) {
783 yaffs_ExtendedTags tags;
784 yaffs_ObjectHeader *oh;
785 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
787 oh = (yaffs_ObjectHeader *)buffer;
789 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk,buffer, &tags);
791 yaffs_VerifyObjectHeader(obj,oh,&tags,1);
793 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
796 /* Verify it has a parent */
797 if(obj && !obj->fake &&
798 (!obj->parent || obj->parent->myDev != dev)){
799 T(YAFFS_TRACE_VERIFY,
800 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
801 obj->objectId,obj->parent));
804 /* Verify parent is a directory */
805 if(obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
806 T(YAFFS_TRACE_VERIFY,
807 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
808 obj->objectId,obj->parent->variantType));
811 switch(obj->variantType){
812 case YAFFS_OBJECT_TYPE_FILE:
813 yaffs_VerifyFile(obj);
815 case YAFFS_OBJECT_TYPE_SYMLINK:
816 yaffs_VerifySymlink(obj);
818 case YAFFS_OBJECT_TYPE_DIRECTORY:
819 yaffs_VerifyDirectory(obj);
821 case YAFFS_OBJECT_TYPE_HARDLINK:
822 yaffs_VerifyHardLink(obj);
824 case YAFFS_OBJECT_TYPE_SPECIAL:
825 yaffs_VerifySpecial(obj);
827 case YAFFS_OBJECT_TYPE_UNKNOWN:
829 T(YAFFS_TRACE_VERIFY,
830 (TSTR("Obj %d has illegaltype %d"TENDSTR),
831 obj->objectId,obj->variantType));
838 static void yaffs_VerifyObjects(yaffs_Device *dev)
842 struct ylist_head *lh;
844 if(yaffs_SkipVerification(dev))
847 /* Iterate through the objects in each hash entry */
849 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++){
850 ylist_for_each(lh, &dev->objectBucket[i].list) {
852 obj = ylist_entry(lh, yaffs_Object, hashLink);
853 yaffs_VerifyObject(obj);
862 * Simple hash function. Needs to have a reasonable spread
865 static Y_INLINE int yaffs_HashFunction(int n)
868 return (n % YAFFS_NOBJECT_BUCKETS);
872 * Access functions to useful fake objects.
873 * Note that root might have a presence in NAND if permissions are set.
876 yaffs_Object *yaffs_Root(yaffs_Device * dev)
881 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
883 return dev->lostNFoundDir;
888 * Erased NAND checking functions
891 int yaffs_CheckFF(__u8 * buffer, int nBytes)
893 /* Horrible, slow implementation */
902 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
906 int retval = YAFFS_OK;
907 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
908 yaffs_ExtendedTags tags;
911 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
913 if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
917 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
918 T(YAFFS_TRACE_NANDACCESS,
919 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
923 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
929 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
931 yaffs_ExtendedTags * tags,
938 yaffs_InvalidateCheckpoint(dev);
941 yaffs_BlockInfo *bi = 0;
944 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
950 /* First check this chunk is erased, if it needs
951 * checking. The checking policy (unless forced
952 * always on) is as follows:
954 * Check the first page we try to write in a block.
955 * If the check passes then we don't need to check any
956 * more. If the check fails, we check again...
957 * If the block has been erased, we don't need to check.
959 * However, if the block has been prioritised for gc,
960 * then we think there might be something odd about
961 * this block and stop using it.
963 * Rationale: We should only ever see chunks that have
964 * not been erased if there was a partially written
965 * chunk due to power loss. This checking policy should
966 * catch that case with very few checks and thus save a
967 * lot of checks that are most likely not needed.
969 if (bi->gcPrioritise) {
970 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
971 /* try another chunk */
975 /* let's give it a try */
978 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
979 bi->skipErasedCheck = 0;
981 if (!bi->skipErasedCheck) {
982 erasedOk = yaffs_CheckChunkErased(dev, chunk);
983 if (erasedOk != YAFFS_OK) {
985 (TSTR ("**>> yaffs chunk %d was not erased"
988 /* try another chunk */
991 bi->skipErasedCheck = 1;
994 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
996 if (writeOk != YAFFS_OK) {
997 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
998 /* try another chunk */
1002 /* Copy the data into the robustification buffer */
1003 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1005 } while (writeOk != YAFFS_OK &&
1006 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1012 T(YAFFS_TRACE_ERROR,
1013 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1016 dev->nRetriedWrites += (attempts - 1);
1023 * Block retiring for handling a broken block.
1026 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
1028 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1030 yaffs_InvalidateCheckpoint(dev);
1032 yaffs_MarkBlockBad(dev, blockInNAND);
1034 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1035 bi->gcPrioritise = 0;
1036 bi->needsRetiring = 0;
1038 dev->nRetiredBlocks++;
1042 * Functions for robustisizing TODO
1046 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
1048 const yaffs_ExtendedTags * tags)
1052 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
1053 const yaffs_ExtendedTags * tags)
1057 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1059 if(!bi->gcPrioritise){
1060 bi->gcPrioritise = 1;
1061 dev->hasPendingPrioritisedGCs = 1;
1062 bi->chunkErrorStrikes ++;
1064 if(bi->chunkErrorStrikes > 3){
1065 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1066 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1073 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
1076 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1077 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1079 yaffs_HandleChunkError(dev,bi);
1083 /* Was an actual write failure, so mark the block for retirement */
1084 bi->needsRetiring = 1;
1085 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1086 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1091 /* Delete the chunk */
1092 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1096 /*---------------- Name handling functions ------------*/
1098 static __u16 yaffs_CalcNameSum(const YCHAR * name)
1103 const YUCHAR *bname = (const YUCHAR *) name;
1105 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1107 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1108 sum += yaffs_toupper(*bname) * i;
1110 sum += (*bname) * i;
1120 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
1122 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1123 memset(obj->shortName,0,sizeof (YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1124 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
1125 yaffs_strcpy(obj->shortName, name);
1127 obj->shortName[0] = _Y('\0');
1130 obj->sum = yaffs_CalcNameSum(name);
1133 /*-------------------- TNODES -------------------
1135 * List of spare tnodes
1136 * The list is hooked together using the first pointer
1140 /* yaffs_CreateTnodes creates a bunch more tnodes and
1141 * adds them to the tnode free list.
1142 * Don't use this function directly
1145 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
1149 yaffs_Tnode *newTnodes;
1153 yaffs_TnodeList *tnl;
1158 /* Calculate the tnode size in bytes for variable width tnode support.
1159 * Must be a multiple of 32-bits */
1160 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1162 if(tnodeSize < sizeof(yaffs_Tnode))
1163 tnodeSize = sizeof(yaffs_Tnode);
1166 /* make these things */
1168 newTnodes = YMALLOC(nTnodes * tnodeSize);
1169 mem = (__u8 *)newTnodes;
1172 T(YAFFS_TRACE_ERROR,
1173 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1177 /* Hook them into the free list */
1179 for (i = 0; i < nTnodes - 1; i++) {
1180 newTnodes[i].internal[0] = &newTnodes[i + 1];
1181 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1182 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1186 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1187 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1188 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1190 dev->freeTnodes = newTnodes;
1192 /* New hookup for wide tnodes */
1193 for(i = 0; i < nTnodes -1; i++) {
1194 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1195 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1196 curr->internal[0] = next;
1199 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1200 curr->internal[0] = dev->freeTnodes;
1201 dev->freeTnodes = (yaffs_Tnode *)mem;
1206 dev->nFreeTnodes += nTnodes;
1207 dev->nTnodesCreated += nTnodes;
1209 /* Now add this bunch of tnodes to a list for freeing up.
1210 * NB If we can't add this to the management list it isn't fatal
1211 * but it just means we can't free this bunch of tnodes later.
1214 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1216 T(YAFFS_TRACE_ERROR,
1218 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1222 tnl->tnodes = newTnodes;
1223 tnl->next = dev->allocatedTnodeList;
1224 dev->allocatedTnodeList = tnl;
1227 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1232 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1234 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
1236 yaffs_Tnode *tn = NULL;
1238 /* If there are none left make more */
1239 if (!dev->freeTnodes) {
1240 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1243 if (dev->freeTnodes) {
1244 tn = dev->freeTnodes;
1245 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1246 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1247 /* Hoosterman, this thing looks like it isn't in the list */
1248 T(YAFFS_TRACE_ALWAYS,
1249 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1252 dev->freeTnodes = dev->freeTnodes->internal[0];
1256 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1261 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
1263 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1264 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1266 if(tnodeSize < sizeof(yaffs_Tnode))
1267 tnodeSize = sizeof(yaffs_Tnode);
1270 memset(tn, 0, tnodeSize);
1275 /* FreeTnode frees up a tnode and puts it back on the free list */
1276 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
1279 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1280 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1281 /* Hoosterman, this thing looks like it is already in the list */
1282 T(YAFFS_TRACE_ALWAYS,
1283 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1285 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1287 tn->internal[0] = dev->freeTnodes;
1288 dev->freeTnodes = tn;
1291 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1295 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
1297 /* Free the list of allocated tnodes */
1298 yaffs_TnodeList *tmp;
1300 while (dev->allocatedTnodeList) {
1301 tmp = dev->allocatedTnodeList->next;
1303 YFREE(dev->allocatedTnodeList->tnodes);
1304 YFREE(dev->allocatedTnodeList);
1305 dev->allocatedTnodeList = tmp;
1309 dev->freeTnodes = NULL;
1310 dev->nFreeTnodes = 0;
1313 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
1315 dev->allocatedTnodeList = NULL;
1316 dev->freeTnodes = NULL;
1317 dev->nFreeTnodes = 0;
1318 dev->nTnodesCreated = 0;
1323 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
1325 __u32 *map = (__u32 *)tn;
1331 pos &= YAFFS_TNODES_LEVEL0_MASK;
1332 val >>= dev->chunkGroupBits;
1334 bitInMap = pos * dev->tnodeWidth;
1335 wordInMap = bitInMap /32;
1336 bitInWord = bitInMap & (32 -1);
1338 mask = dev->tnodeMask << bitInWord;
1340 map[wordInMap] &= ~mask;
1341 map[wordInMap] |= (mask & (val << bitInWord));
1343 if(dev->tnodeWidth > (32-bitInWord)) {
1344 bitInWord = (32 - bitInWord);
1346 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1347 map[wordInMap] &= ~mask;
1348 map[wordInMap] |= (mask & (val >> bitInWord));
1352 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
1354 __u32 *map = (__u32 *)tn;
1360 pos &= YAFFS_TNODES_LEVEL0_MASK;
1362 bitInMap = pos * dev->tnodeWidth;
1363 wordInMap = bitInMap /32;
1364 bitInWord = bitInMap & (32 -1);
1366 val = map[wordInMap] >> bitInWord;
1368 if(dev->tnodeWidth > (32-bitInWord)) {
1369 bitInWord = (32 - bitInWord);
1371 val |= (map[wordInMap] << bitInWord);
1374 val &= dev->tnodeMask;
1375 val <<= dev->chunkGroupBits;
1380 /* ------------------- End of individual tnode manipulation -----------------*/
1382 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1383 * The look up tree is represented by the top tnode and the number of topLevel
1384 * in the tree. 0 means only the level 0 tnode is in the tree.
1387 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1388 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
1389 yaffs_FileStructure * fStruct,
1393 yaffs_Tnode *tn = fStruct->top;
1395 int requiredTallness;
1396 int level = fStruct->topLevel;
1398 /* Check sane level and chunk Id */
1399 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
1403 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1407 /* First check we're tall enough (ie enough topLevel) */
1409 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1410 requiredTallness = 0;
1412 i >>= YAFFS_TNODES_INTERNAL_BITS;
1416 if (requiredTallness > fStruct->topLevel) {
1417 /* Not tall enough, so we can't find it, return NULL. */
1421 /* Traverse down to level 0 */
1422 while (level > 0 && tn) {
1424 internal[(chunkId >>
1425 ( YAFFS_TNODES_LEVEL0_BITS +
1427 YAFFS_TNODES_INTERNAL_BITS)
1429 YAFFS_TNODES_INTERNAL_MASK];
1437 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1438 * This happens in two steps:
1439 * 1. If the tree isn't tall enough, then make it taller.
1440 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1442 * Used when modifying the tree.
1444 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1445 * be plugged into the ttree.
1448 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
1449 yaffs_FileStructure * fStruct,
1451 yaffs_Tnode *passedTn)
1454 int requiredTallness;
1462 /* Check sane level and page Id */
1463 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
1467 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1471 /* First check we're tall enough (ie enough topLevel) */
1473 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1474 requiredTallness = 0;
1476 x >>= YAFFS_TNODES_INTERNAL_BITS;
1481 if (requiredTallness > fStruct->topLevel) {
1482 /* Not tall enough,gotta make the tree taller */
1483 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1485 tn = yaffs_GetTnode(dev);
1488 tn->internal[0] = fStruct->top;
1491 T(YAFFS_TRACE_ERROR,
1492 (TSTR("yaffs: no more tnodes" TENDSTR)));
1496 fStruct->topLevel = requiredTallness;
1499 /* Traverse down to level 0, adding anything we need */
1501 l = fStruct->topLevel;
1505 while (l > 0 && tn) {
1507 ( YAFFS_TNODES_LEVEL0_BITS +
1508 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1509 YAFFS_TNODES_INTERNAL_MASK;
1512 if((l>1) && !tn->internal[x]){
1513 /* Add missing non-level-zero tnode */
1514 tn->internal[x] = yaffs_GetTnode(dev);
1517 /* Looking from level 1 at level 0 */
1519 /* If we already have one, then release it.*/
1521 yaffs_FreeTnode(dev,tn->internal[x]);
1522 tn->internal[x] = passedTn;
1524 } else if(!tn->internal[x]) {
1525 /* Don't have one, none passed in */
1526 tn->internal[x] = yaffs_GetTnode(dev);
1530 tn = tn->internal[x];
1534 /* top is level 0 */
1536 memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1537 yaffs_FreeTnode(dev,passedTn);
1544 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1545 yaffs_ExtendedTags * tags, int objectId,
1550 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1551 if (yaffs_CheckChunkBit
1552 (dev, theChunk / dev->nChunksPerBlock,
1553 theChunk % dev->nChunksPerBlock)) {
1554 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1556 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1568 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1569 * chunks and tnodes in the file
1570 * Returns 1 if the tree was deleted.
1571 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1574 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1575 int chunkOffset, int *limit)
1580 yaffs_ExtendedTags tags;
1582 yaffs_Device *dev = in->myDev;
1589 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1591 if (tn->internal[i]) {
1592 if (limit && (*limit) < 0) {
1596 yaffs_DeleteWorker(in,
1604 YAFFS_TNODES_INTERNAL_BITS)
1609 yaffs_FreeTnode(dev,
1612 tn->internal[i] = NULL;
1617 return (allDone) ? 1 : 0;
1618 } else if (level == 0) {
1621 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1623 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1628 YAFFS_TNODES_LEVEL0_BITS) + i;
1631 yaffs_FindChunkInGroup(dev,
1637 if (foundChunk > 0) {
1638 yaffs_DeleteChunk(dev,
1643 *limit = *limit - 1;
1651 yaffs_PutLevel0Tnode(dev,tn,i,0);
1655 return (i < 0) ? 1 : 0;
1665 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1668 yaffs_BlockInfo *theBlock;
1670 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1672 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1674 theBlock->softDeletions++;
1679 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1680 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1682 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1685 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1686 __u32 level, int chunkOffset)
1691 yaffs_Device *dev = in->myDev;
1696 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1698 if (tn->internal[i]) {
1700 yaffs_SoftDeleteWorker(in,
1706 YAFFS_TNODES_INTERNAL_BITS)
1709 yaffs_FreeTnode(dev,
1712 tn->internal[i] = NULL;
1714 /* Hoosterman... how could this happen? */
1718 return (allDone) ? 1 : 0;
1719 } else if (level == 0) {
1721 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1722 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1724 /* Note this does not find the real chunk, only the chunk group.
1725 * We make an assumption that a chunk group is not larger than
1728 yaffs_SoftDeleteChunk(dev, theChunk);
1729 yaffs_PutLevel0Tnode(dev,tn,i,0);
1743 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1746 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1747 if (obj->nDataChunks <= 0) {
1748 /* Empty file with no duplicate object headers, just delete it immediately */
1749 yaffs_FreeTnode(obj->myDev,
1750 obj->variant.fileVariant.top);
1751 obj->variant.fileVariant.top = NULL;
1752 T(YAFFS_TRACE_TRACING,
1753 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1755 yaffs_DoGenericObjectDeletion(obj);
1757 yaffs_SoftDeleteWorker(obj,
1758 obj->variant.fileVariant.top,
1759 obj->variant.fileVariant.
1761 obj->softDeleted = 1;
1766 /* Pruning removes any part of the file structure tree that is beyond the
1767 * bounds of the file (ie that does not point to chunks).
1769 * A file should only get pruned when its size is reduced.
1771 * Before pruning, the chunks must be pulled from the tree and the
1772 * level 0 tnode entries must be zeroed out.
1773 * Could also use this for file deletion, but that's probably better handled
1774 * by a special case.
1777 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1778 __u32 level, int del0)
1786 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1787 if (tn->internal[i] && level > 0) {
1789 yaffs_PruneWorker(dev, tn->internal[i],
1791 (i == 0) ? del0 : 1);
1794 if (tn->internal[i]) {
1799 if (hasData == 0 && del0) {
1800 /* Free and return NULL */
1802 yaffs_FreeTnode(dev, tn);
1812 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1813 yaffs_FileStructure * fStruct)
1820 if (fStruct->topLevel > 0) {
1822 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1824 /* Now we have a tree with all the non-zero branches NULL but the height
1825 * is the same as it was.
1826 * Let's see if we can trim internal tnodes to shorten the tree.
1827 * We can do this if only the 0th element in the tnode is in use
1828 * (ie all the non-zero are NULL)
1831 while (fStruct->topLevel && !done) {
1835 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1836 if (tn->internal[i]) {
1842 fStruct->top = tn->internal[0];
1843 fStruct->topLevel--;
1844 yaffs_FreeTnode(dev, tn);
1854 /*-------------------- End of File Structure functions.-------------------*/
1856 /* yaffs_CreateFreeObjects creates a bunch more objects and
1857 * adds them to the object free list.
1859 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1862 yaffs_Object *newObjects;
1863 yaffs_ObjectList *list;
1868 /* make these things */
1869 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1870 list = YMALLOC(sizeof(yaffs_ObjectList));
1872 if (!newObjects || !list) {
1877 T(YAFFS_TRACE_ALLOCATE,
1878 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1882 /* Hook them into the free list */
1883 for (i = 0; i < nObjects - 1; i++) {
1884 newObjects[i].siblings.next =
1885 (struct ylist_head *)(&newObjects[i + 1]);
1888 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1889 dev->freeObjects = newObjects;
1890 dev->nFreeObjects += nObjects;
1891 dev->nObjectsCreated += nObjects;
1893 /* Now add this bunch of Objects to a list for freeing up. */
1895 list->objects = newObjects;
1896 list->next = dev->allocatedObjectList;
1897 dev->allocatedObjectList = list;
1903 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1904 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1906 yaffs_Object *tn = NULL;
1908 #ifdef VALGRIND_TEST
1909 tn = YMALLOC(sizeof(yaffs_Object));
1911 /* If there are none left make more */
1912 if (!dev->freeObjects) {
1913 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1916 if (dev->freeObjects) {
1917 tn = dev->freeObjects;
1919 (yaffs_Object *) (dev->freeObjects->siblings.next);
1920 dev->nFreeObjects--;
1924 /* Now sweeten it up... */
1926 memset(tn, 0, sizeof(yaffs_Object));
1929 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1930 YINIT_LIST_HEAD(&(tn->hardLinks));
1931 YINIT_LIST_HEAD(&(tn->hashLink));
1932 YINIT_LIST_HEAD(&tn->siblings);
1935 /* Now make the directory sane */
1937 tn->parent = dev->rootDir;
1938 ylist_add(&(tn->siblings),&dev->rootDir->variant.directoryVariant.children);
1941 /* Add it to the lost and found directory.
1942 * NB Can't put root or lostNFound in lostNFound so
1943 * check if lostNFound exists first
1945 if (dev->lostNFoundDir) {
1946 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1950 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1955 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1960 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1962 obj->fake = 1; /* it is fake so it might have no NAND presence... */
1963 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1964 obj->unlinkAllowed = 0; /* ... or unlink it */
1967 obj->yst_mode = mode;
1969 obj->hdrChunk = 0; /* Not a valid chunk. */
1976 static void yaffs_UnhashObject(yaffs_Object * tn)
1979 yaffs_Device *dev = tn->myDev;
1981 /* If it is still linked into the bucket list, free from the list */
1982 if (!ylist_empty(&tn->hashLink)) {
1983 ylist_del_init(&tn->hashLink);
1984 bucket = yaffs_HashFunction(tn->objectId);
1985 dev->objectBucket[bucket].count--;
1990 /* FreeObject frees up a Object and puts it back on the free list */
1991 static void yaffs_FreeObject(yaffs_Object * tn)
1994 yaffs_Device *dev = tn->myDev;
1999 if(!ylist_empty(&tn->siblings))
2005 /* We're still hooked up to a cached inode.
2006 * Don't delete now, but mark for later deletion
2008 tn->deferedFree = 1;
2013 yaffs_UnhashObject(tn);
2015 #ifdef VALGRIND_TEST
2018 /* Link into the free list. */
2019 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2020 dev->freeObjects = tn;
2021 dev->nFreeObjects++;
2023 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2029 void yaffs_HandleDeferedFree(yaffs_Object * obj)
2031 if (obj->deferedFree) {
2032 yaffs_FreeObject(obj);
2038 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
2040 /* Free the list of allocated Objects */
2042 yaffs_ObjectList *tmp;
2044 while (dev->allocatedObjectList) {
2045 tmp = dev->allocatedObjectList->next;
2046 YFREE(dev->allocatedObjectList->objects);
2047 YFREE(dev->allocatedObjectList);
2049 dev->allocatedObjectList = tmp;
2052 dev->freeObjects = NULL;
2053 dev->nFreeObjects = 0;
2056 static void yaffs_InitialiseObjects(yaffs_Device * dev)
2060 dev->allocatedObjectList = NULL;
2061 dev->freeObjects = NULL;
2062 dev->nFreeObjects = 0;
2064 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2065 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2066 dev->objectBucket[i].count = 0;
2071 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
2076 int lowest = 999999;
2078 /* First let's see if we can find one that's empty. */
2080 for (i = 0; i < 10 && lowest > 0; i++) {
2082 x %= YAFFS_NOBJECT_BUCKETS;
2083 if (dev->objectBucket[x].count < lowest) {
2084 lowest = dev->objectBucket[x].count;
2090 /* If we didn't find an empty list, then try
2091 * looking a bit further for a short one
2094 for (i = 0; i < 10 && lowest > 3; i++) {
2096 x %= YAFFS_NOBJECT_BUCKETS;
2097 if (dev->objectBucket[x].count < lowest) {
2098 lowest = dev->objectBucket[x].count;
2107 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
2109 int bucket = yaffs_FindNiceObjectBucket(dev);
2111 /* Now find an object value that has not already been taken
2112 * by scanning the list.
2116 struct ylist_head *i;
2118 __u32 n = (__u32) bucket;
2120 /* yaffs_CheckObjectHashSanity(); */
2124 n += YAFFS_NOBJECT_BUCKETS;
2125 if (1 || dev->objectBucket[bucket].count > 0) {
2126 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2127 /* If there is already one in the list */
2129 && ylist_entry(i, yaffs_Object,
2130 hashLink)->objectId == n) {
2141 static void yaffs_HashObject(yaffs_Object * in)
2143 int bucket = yaffs_HashFunction(in->objectId);
2144 yaffs_Device *dev = in->myDev;
2146 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2147 dev->objectBucket[bucket].count++;
2151 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
2153 int bucket = yaffs_HashFunction(number);
2154 struct ylist_head *i;
2157 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2158 /* Look if it is in the list */
2160 in = ylist_entry(i, yaffs_Object, hashLink);
2161 if (in->objectId == number) {
2163 /* Don't tell the VFS about this one if it is defered free */
2164 if (in->deferedFree)
2176 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
2177 yaffs_ObjectType type)
2180 yaffs_Object *theObject;
2181 yaffs_Tnode *tn = NULL;
2184 number = yaffs_CreateNewObjectNumber(dev);
2187 theObject = yaffs_AllocateEmptyObject(dev);
2191 if(type == YAFFS_OBJECT_TYPE_FILE){
2192 tn = yaffs_GetTnode(dev);
2194 yaffs_FreeObject(theObject);
2202 theObject->fake = 0;
2203 theObject->renameAllowed = 1;
2204 theObject->unlinkAllowed = 1;
2205 theObject->objectId = number;
2206 yaffs_HashObject(theObject);
2207 theObject->variantType = type;
2208 #ifdef CONFIG_YAFFS_WINCE
2209 yfsd_WinFileTimeNow(theObject->win_atime);
2210 theObject->win_ctime[0] = theObject->win_mtime[0] =
2211 theObject->win_atime[0];
2212 theObject->win_ctime[1] = theObject->win_mtime[1] =
2213 theObject->win_atime[1];
2217 theObject->yst_atime = theObject->yst_mtime =
2218 theObject->yst_ctime = Y_CURRENT_TIME;
2222 theObject->sum_prev = 12345;
2223 theObject->sum_trailer = 6789;
2227 case YAFFS_OBJECT_TYPE_FILE:
2228 theObject->variant.fileVariant.fileSize = 0;
2229 theObject->variant.fileVariant.scannedFileSize = 0;
2230 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2231 theObject->variant.fileVariant.topLevel = 0;
2232 theObject->variant.fileVariant.top = tn;
2234 case YAFFS_OBJECT_TYPE_DIRECTORY:
2235 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2238 case YAFFS_OBJECT_TYPE_SYMLINK:
2239 case YAFFS_OBJECT_TYPE_HARDLINK:
2240 case YAFFS_OBJECT_TYPE_SPECIAL:
2241 /* No action required */
2243 case YAFFS_OBJECT_TYPE_UNKNOWN:
2244 /* todo this should not happen */
2252 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
2254 yaffs_ObjectType type)
2256 yaffs_Object *theObject = NULL;
2259 theObject = yaffs_FindObjectByNumber(dev, number);
2263 theObject = yaffs_CreateNewObject(dev, number, type);
2271 static YCHAR *yaffs_CloneString(const YCHAR * str)
2273 YCHAR *newStr = NULL;
2276 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2278 yaffs_strcpy(newStr, str);
2286 * Mknod (create) a new object.
2287 * equivalentObject only has meaning for a hard link;
2288 * aliasString only has meaning for a sumlink.
2289 * rdev only has meaning for devices (a subset of special objects)
2292 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2293 yaffs_Object * parent,
2298 yaffs_Object * equivalentObject,
2299 const YCHAR * aliasString, __u32 rdev)
2304 yaffs_Device *dev = parent->myDev;
2306 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2307 if (yaffs_FindObjectByName(parent, name)) {
2311 in = yaffs_CreateNewObject(dev, -1, type);
2316 if(type == YAFFS_OBJECT_TYPE_SYMLINK){
2317 str = yaffs_CloneString(aliasString);
2319 yaffs_FreeObject(in);
2329 in->variantType = type;
2331 in->yst_mode = mode;
2333 #ifdef CONFIG_YAFFS_WINCE
2334 yfsd_WinFileTimeNow(in->win_atime);
2335 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2336 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2339 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2341 in->yst_rdev = rdev;
2345 in->nDataChunks = 0;
2347 yaffs_SetObjectName(in, name);
2350 yaffs_AddObjectToDirectory(parent, in);
2352 in->myDev = parent->myDev;
2355 case YAFFS_OBJECT_TYPE_SYMLINK:
2356 in->variant.symLinkVariant.alias = str;
2358 case YAFFS_OBJECT_TYPE_HARDLINK:
2359 in->variant.hardLinkVariant.equivalentObject =
2361 in->variant.hardLinkVariant.equivalentObjectId =
2362 equivalentObject->objectId;
2363 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2365 case YAFFS_OBJECT_TYPE_FILE:
2366 case YAFFS_OBJECT_TYPE_DIRECTORY:
2367 case YAFFS_OBJECT_TYPE_SPECIAL:
2368 case YAFFS_OBJECT_TYPE_UNKNOWN:
2373 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2374 /* Could not create the object header, fail the creation */
2375 yaffs_DestroyObject(in);
2384 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
2385 __u32 mode, __u32 uid, __u32 gid)
2387 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2388 uid, gid, NULL, NULL, 0);
2391 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
2392 __u32 mode, __u32 uid, __u32 gid)
2394 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2395 mode, uid, gid, NULL, NULL, 0);
2398 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
2399 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2401 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2402 uid, gid, NULL, NULL, rdev);
2405 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
2406 __u32 mode, __u32 uid, __u32 gid,
2407 const YCHAR * alias)
2409 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2410 uid, gid, NULL, alias, 0);
2413 /* yaffs_Link returns the object id of the equivalent object.*/
2414 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
2415 yaffs_Object * equivalentObject)
2417 /* Get the real object in case we were fed a hard link as an equivalent object */
2418 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2420 if (yaffs_MknodObject
2421 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2422 equivalentObject, NULL, 0)) {
2423 return equivalentObject;
2430 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
2431 const YCHAR * newName, int force, int shadows)
2436 yaffs_Object *existingTarget;
2438 if (newDir == NULL) {
2439 newDir = obj->parent; /* use the old directory */
2442 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2443 T(YAFFS_TRACE_ALWAYS,
2445 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2450 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2451 if (obj->myDev->isYaffs2) {
2452 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2454 unlinkOp = (newDir == obj->myDev->unlinkedDir
2455 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2458 deleteOp = (newDir == obj->myDev->deletedDir);
2460 existingTarget = yaffs_FindObjectByName(newDir, newName);
2462 /* If the object is a file going into the unlinked directory,
2463 * then it is OK to just stuff it in since duplicate names are allowed.
2464 * else only proceed if the new name does not exist and if we're putting
2465 * it into a directory.
2472 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2473 yaffs_SetObjectName(obj, newName);
2476 yaffs_AddObjectToDirectory(newDir, obj);
2481 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2482 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
2489 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
2490 yaffs_Object * newDir, const YCHAR * newName)
2492 yaffs_Object *obj=NULL;
2493 yaffs_Object *existingTarget=NULL;
2497 if(!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2499 if(!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2502 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2503 /* Special case for case insemsitive systems (eg. WinCE).
2504 * While look-up is case insensitive, the name isn't.
2505 * Therefore we might want to change x.txt to X.txt
2507 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
2512 else if (yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2516 obj = yaffs_FindObjectByName(oldDir, oldName);
2518 if (obj && obj->renameAllowed) {
2520 /* Now do the handling for an existing target, if there is one */
2522 existingTarget = yaffs_FindObjectByName(newDir, newName);
2523 if (existingTarget &&
2524 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2525 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2526 /* There is a target that is a non-empty directory, so we fail */
2527 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2528 } else if (existingTarget && existingTarget != obj) {
2529 /* Nuke the target first, using shadowing,
2530 * but only if it isn't the same object
2532 yaffs_ChangeObjectName(obj, newDir, newName, force,
2533 existingTarget->objectId);
2534 yaffs_UnlinkObject(existingTarget);
2537 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2542 /*------------------------- Block Management and Page Allocation ----------------*/
2544 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
2546 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2548 dev->blockInfo = NULL;
2549 dev->chunkBits = NULL;
2551 dev->allocationBlock = -1; /* force it to get a new one */
2553 /* If the first allocation strategy fails, thry the alternate one */
2554 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2555 if(!dev->blockInfo){
2556 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2557 dev->blockInfoAlt = 1;
2560 dev->blockInfoAlt = 0;
2564 /* Set up dynamic blockinfo stuff. */
2565 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2566 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2567 if(!dev->chunkBits){
2568 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2569 dev->chunkBitsAlt = 1;
2572 dev->chunkBitsAlt = 0;
2575 if (dev->blockInfo && dev->chunkBits) {
2576 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2577 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2585 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
2587 if(dev->blockInfoAlt && dev->blockInfo)
2588 YFREE_ALT(dev->blockInfo);
2589 else if(dev->blockInfo)
2590 YFREE(dev->blockInfo);
2592 dev->blockInfoAlt = 0;
2594 dev->blockInfo = NULL;
2596 if(dev->chunkBitsAlt && dev->chunkBits)
2597 YFREE_ALT(dev->chunkBits);
2598 else if(dev->chunkBits)
2599 YFREE(dev->chunkBits);
2600 dev->chunkBitsAlt = 0;
2601 dev->chunkBits = NULL;
2604 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
2605 yaffs_BlockInfo * bi)
2612 return 1; /* disqualification only applies to yaffs2. */
2614 if (!bi->hasShrinkHeader)
2615 return 1; /* can gc */
2617 /* Find the oldest dirty sequence number if we don't know it and save it
2618 * so we don't have to keep recomputing it.
2620 if (!dev->oldestDirtySequence) {
2621 seq = dev->sequenceNumber;
2623 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2625 b = yaffs_GetBlockInfo(dev, i);
2626 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2627 (b->pagesInUse - b->softDeletions) <
2628 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2629 seq = b->sequenceNumber;
2632 dev->oldestDirtySequence = seq;
2635 /* Can't do gc of this block if there are any blocks older than this one that have
2638 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2642 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2643 * for garbage collection.
2646 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2650 int b = dev->currentDirtyChecker;
2657 yaffs_BlockInfo *bi;
2658 int pendingPrioritisedExist = 0;
2660 /* First let's see if we need to grab a prioritised block */
2661 if(dev->hasPendingPrioritisedGCs){
2662 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2664 bi = yaffs_GetBlockInfo(dev, i);
2665 //yaffs_VerifyBlock(dev,bi,i);
2667 if(bi->gcPrioritise) {
2668 pendingPrioritisedExist = 1;
2669 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2670 yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2671 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2674 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2679 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2680 dev->hasPendingPrioritisedGCs = 0;
2683 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2685 * else (we're doing a leasurely gc), then we only bother to do this if the
2686 * block has only a few pages in use.
2689 dev->nonAggressiveSkip--;
2691 if (!aggressive && (dev->nonAggressiveSkip > 0)) {
2697 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2701 dev->internalEndBlock - dev->internalStartBlock + 1;
2704 dev->internalEndBlock - dev->internalStartBlock + 1;
2705 iterations = iterations / 16;
2706 if (iterations > 200) {
2711 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2713 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2714 b = dev->internalStartBlock;
2717 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2718 T(YAFFS_TRACE_ERROR,
2719 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2723 bi = yaffs_GetBlockInfo(dev, b);
2726 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2733 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2734 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2735 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2737 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2741 dev->currentDirtyChecker = b;
2745 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2746 dev->nChunksPerBlock - pagesInUse,prioritised));
2749 dev->oldestDirtySequence = 0;
2752 dev->nonAggressiveSkip = 4;
2758 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2760 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2764 /* If the block is still healthy erase it and mark as clean.
2765 * If the block has had a data failure, then retire it.
2768 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2769 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2770 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2772 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2774 if (!bi->needsRetiring) {
2775 yaffs_InvalidateCheckpoint(dev);
2776 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2778 dev->nErasureFailures++;
2779 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2780 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2785 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2787 for (i = 0; i < dev->nChunksPerBlock; i++) {
2788 if (!yaffs_CheckChunkErased
2789 (dev, blockNo * dev->nChunksPerBlock + i)) {
2790 T(YAFFS_TRACE_ERROR,
2792 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2793 TENDSTR), blockNo, i));
2799 /* Clean it up... */
2800 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2801 dev->nErasedBlocks++;
2803 bi->softDeletions = 0;
2804 bi->hasShrinkHeader = 0;
2805 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2806 bi->gcPrioritise = 0;
2807 yaffs_ClearChunkBits(dev, blockNo);
2809 T(YAFFS_TRACE_ERASE,
2810 (TSTR("Erased block %d" TENDSTR), blockNo));
2812 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2814 yaffs_RetireBlock(dev, blockNo);
2815 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2816 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2820 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2824 yaffs_BlockInfo *bi;
2826 if (dev->nErasedBlocks < 1) {
2827 /* Hoosterman we've got a problem.
2828 * Can't get space to gc
2830 T(YAFFS_TRACE_ERROR,
2831 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2836 /* Find an empty block. */
2838 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2839 dev->allocationBlockFinder++;
2840 if (dev->allocationBlockFinder < dev->internalStartBlock
2841 || dev->allocationBlockFinder > dev->internalEndBlock) {
2842 dev->allocationBlockFinder = dev->internalStartBlock;
2845 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2847 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2848 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2849 dev->sequenceNumber++;
2850 bi->sequenceNumber = dev->sequenceNumber;
2851 dev->nErasedBlocks--;
2852 T(YAFFS_TRACE_ALLOCATE,
2853 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2854 dev->allocationBlockFinder, dev->sequenceNumber,
2855 dev->nErasedBlocks));
2856 return dev->allocationBlockFinder;
2860 T(YAFFS_TRACE_ALWAYS,
2862 ("yaffs tragedy: no more erased blocks, but there should have been %d"
2863 TENDSTR), dev->nErasedBlocks));
2870 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2872 if(!dev->nCheckpointBlocksRequired &&
2874 /* Not a valid value so recalculate */
2877 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2880 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2882 if(tnodeSize < sizeof(yaffs_Tnode))
2883 tnodeSize = sizeof(yaffs_Tnode);
2885 nBytes += sizeof(yaffs_CheckpointValidity);
2886 nBytes += sizeof(yaffs_CheckpointDevice);
2887 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2888 nBytes += devBlocks * dev->chunkBitmapStride;
2889 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2890 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2891 nBytes += sizeof(yaffs_CheckpointValidity);
2892 nBytes += sizeof(__u32); /* checksum*/
2894 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2896 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2898 dev->nCheckpointBlocksRequired = nBlocks;
2901 return dev->nCheckpointBlocksRequired;
2904 // Check if there's space to allocate...
2905 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2906 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2909 int reservedBlocks = dev->nReservedBlocks;
2910 int checkpointBlocks;
2913 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
2914 dev->blocksInCheckpoint;
2915 if(checkpointBlocks < 0)
2916 checkpointBlocks = 0;
2918 checkpointBlocks =0;
2921 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2923 return (dev->nFreeChunks > reservedChunks);
2926 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2929 yaffs_BlockInfo *bi;
2931 if (dev->allocationBlock < 0) {
2932 /* Get next block to allocate off */
2933 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2934 dev->allocationPage = 0;
2937 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2938 /* Not enough space to allocate unless we're allowed to use the reserve. */
2942 if (dev->nErasedBlocks < dev->nReservedBlocks
2943 && dev->allocationPage == 0) {
2944 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2947 /* Next page please.... */
2948 if (dev->allocationBlock >= 0) {
2949 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2951 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2952 dev->allocationPage;
2954 yaffs_SetChunkBit(dev, dev->allocationBlock,
2955 dev->allocationPage);
2957 dev->allocationPage++;
2961 /* If the block is full set the state to full */
2962 if (dev->allocationPage >= dev->nChunksPerBlock) {
2963 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2964 dev->allocationBlock = -1;
2973 T(YAFFS_TRACE_ERROR,
2974 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2979 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2983 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2985 if (dev->allocationBlock > 0) {
2986 n += (dev->nChunksPerBlock - dev->allocationPage);
2993 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block, int wholeBlock)
2998 int retVal = YAFFS_OK;
3001 int isCheckpointBlock;
3005 int chunksBefore = yaffs_GetErasedChunks(dev);
3008 yaffs_ExtendedTags tags;
3010 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3012 yaffs_Object *object;
3014 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3016 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3018 T(YAFFS_TRACE_TRACING,
3019 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3022 bi->hasShrinkHeader,
3025 /*yaffs_VerifyFreeChunks(dev); */
3027 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
3029 /* Take off the number of soft deleted entries because
3030 * they're going to get really deleted during GC.
3032 dev->nFreeChunks -= bi->softDeletions;
3036 if (isCheckpointBlock ||
3037 !yaffs_StillSomeChunkBits(dev, block)) {
3038 T(YAFFS_TRACE_TRACING,
3040 ("Collecting block %d that has no chunks in use" TENDSTR),
3042 yaffs_BlockBecameDirty(dev, block);
3045 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3047 yaffs_VerifyBlock(dev,bi,block);
3049 maxCopies = (wholeBlock) ? dev->nChunksPerBlock : 10;
3050 oldChunk = block * dev->nChunksPerBlock + dev->gcChunk;
3052 for ( /* init already done */;
3053 retVal == YAFFS_OK &&
3054 dev->gcChunk < dev->nChunksPerBlock &&
3055 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING)&&
3057 dev->gcChunk++, oldChunk++) {
3058 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3060 /* This page is in use and might need to be copied off */
3066 yaffs_InitialiseTags(&tags);
3068 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3072 yaffs_FindObjectByNumber(dev,
3075 T(YAFFS_TRACE_GC_DETAIL,
3077 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3078 dev->gcChunk, tags.objectId, tags.chunkId,
3081 if(object && !yaffs_SkipVerification(dev)){
3082 if(tags.chunkId == 0)
3083 matchingChunk = object->hdrChunk;
3084 else if(object->softDeleted)
3085 matchingChunk = oldChunk; /* Defeat the test */
3087 matchingChunk = yaffs_FindChunkInFile(object,tags.chunkId,NULL);
3089 if(oldChunk != matchingChunk)
3090 T(YAFFS_TRACE_ERROR,
3091 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3092 oldChunk,matchingChunk,tags.objectId, tags.chunkId));
3097 T(YAFFS_TRACE_ERROR,
3099 ("page %d in gc has no object: %d %d %d "
3101 tags.objectId, tags.chunkId, tags.byteCount));
3106 object->softDeleted &&
3107 tags.chunkId != 0) {
3108 /* Data chunk in a soft deleted file, throw it away
3109 * It's a soft deleted data chunk,
3110 * No need to copy this, just forget about it and
3111 * fix up the object.
3114 object->nDataChunks--;
3116 if (object->nDataChunks <= 0) {
3117 /* remeber to clean up the object */
3118 dev->gcCleanupList[cleanups] =
3124 /* Todo object && object->deleted && object->nDataChunks == 0 */
3126 /* Deleted object header with no data chunks.
3127 * Can be discarded and the file deleted.
3129 object->hdrChunk = 0;
3130 yaffs_FreeTnode(object->myDev,
3133 object->variant.fileVariant.top = NULL;
3134 yaffs_DoGenericObjectDeletion(object);
3136 } else if (object) {
3137 /* It's either a data chunk in a live file or
3138 * an ObjectHeader, so we're interested in it.
3139 * NB Need to keep the ObjectHeaders of deleted files
3140 * until the whole file has been deleted off
3142 tags.serialNumber++;
3146 if (tags.chunkId == 0) {
3147 /* It is an object Id,
3148 * We need to nuke the shrinkheader flags first
3149 * We no longer want the shrinkHeader flag since its work is done
3150 * and if it is left in place it will mess up scanning.
3151 * Also, clear out any shadowing stuff
3154 yaffs_ObjectHeader *oh;
3155 oh = (yaffs_ObjectHeader *)buffer;
3157 tags.extraShadows = 0;
3158 tags.extraIsShrinkHeader = 0;
3160 yaffs_VerifyObjectHeader(object,oh,&tags,1);
3164 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3167 retVal = YAFFS_FAIL;
3170 /* Ok, now fix up the Tnodes etc. */
3172 if (tags.chunkId == 0) {
3174 object->hdrChunk = newChunk;
3175 object->serial = tags.serialNumber;
3177 /* It's a data chunk */
3178 yaffs_PutChunkIntoFile
3186 if(retVal == YAFFS_OK)
3187 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3192 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3196 /* Do any required cleanups */
3197 for (i = 0; i < cleanups; i++) {
3198 /* Time to delete the file too */
3200 yaffs_FindObjectByNumber(dev,
3201 dev->gcCleanupList[i]);
3203 yaffs_FreeTnode(dev,
3204 object->variant.fileVariant.
3206 object->variant.fileVariant.top = NULL;
3209 ("yaffs: About to finally delete object %d"
3210 TENDSTR), object->objectId));
3211 yaffs_DoGenericObjectDeletion(object);
3212 object->myDev->nDeletedFiles--;
3219 yaffs_VerifyCollectedBlock(dev,bi,block);
3221 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
3224 ("gc did not increase free chunks before %d after %d"
3225 TENDSTR), chunksBefore, chunksAfter));
3228 /* If the gc completed then clear the current gcBlock so that we find another. */
3229 if(bi->blockState != YAFFS_BLOCK_STATE_COLLECTING){
3239 /* New garbage collector
3240 * If we're very low on erased blocks then we do aggressive garbage collection
3241 * otherwise we do "leasurely" garbage collection.
3242 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3243 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3245 * The idea is to help clear out space in a more spread-out manner.
3246 * Dunno if it really does anything useful.
3248 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
3252 int gcOk = YAFFS_OK;
3255 int checkpointBlockAdjust;
3257 if (dev->isDoingGC) {
3258 /* Bail out so we don't get recursive gc */
3262 /* This loop should pass the first time.
3263 * We'll only see looping here if the erase of the collected block fails.
3269 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3270 if(checkpointBlockAdjust < 0)
3271 checkpointBlockAdjust = 0;
3273 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3274 /* We need a block soon...*/
3277 /* We're in no hurry */
3281 if(dev->gcBlock <= 0){
3282 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3286 block = dev->gcBlock;
3289 dev->garbageCollections++;
3291 dev->passiveGarbageCollections++;
3296 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3297 dev->nErasedBlocks, aggressive));
3299 gcOk = yaffs_GarbageCollectBlock(dev,block,aggressive);
3302 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3305 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3306 TENDSTR), dev->nErasedBlocks, maxTries, block));
3308 } while ((dev->nErasedBlocks < dev->nReservedBlocks) &&
3312 return aggressive ? gcOk : YAFFS_OK;
3315 /*------------------------- TAGS --------------------------------*/
3317 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
3320 return (tags->chunkId == chunkInObject &&
3321 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3326 /*-------------------- Data file manipulation -----------------*/
3328 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
3329 yaffs_ExtendedTags * tags)
3331 /*Get the Tnode, then get the level 0 offset chunk offset */
3334 yaffs_ExtendedTags localTags;
3337 yaffs_Device *dev = in->myDev;
3340 /* Passed a NULL, so use our own tags space */
3344 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3347 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3350 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3356 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
3357 yaffs_ExtendedTags * tags)
3359 /* Get the Tnode, then get the level 0 offset chunk offset */
3362 yaffs_ExtendedTags localTags;
3364 yaffs_Device *dev = in->myDev;
3368 /* Passed a NULL, so use our own tags space */
3372 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3376 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3379 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3382 /* Delete the entry in the filestructure (if found) */
3384 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
3387 /*T(("No level 0 found for %d\n", chunkInInode)); */
3391 /* T(("Could not find %d to delete\n",chunkInInode)); */
3396 #ifdef YAFFS_PARANOID
3398 static int yaffs_CheckFileSanity(yaffs_Object * in)
3406 yaffs_Tags localTags;
3407 yaffs_Tags *tags = &localTags;
3411 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3412 /* T(("Object not a file\n")); */
3416 objId = in->objectId;
3417 fSize = in->variant.fileVariant.fileSize;
3419 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3421 for (chunk = 1; chunk <= nChunks; chunk++) {
3422 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3427 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
3429 if (yaffs_CheckChunkBits
3430 (dev, theChunk / dev->nChunksPerBlock,
3431 theChunk % dev->nChunksPerBlock)) {
3433 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3437 (tags, in->objectId, chunk, chunkDeleted)) {
3447 /* T(("No level 0 found for %d\n", chunk)); */
3451 return failed ? YAFFS_FAIL : YAFFS_OK;
3456 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
3457 int chunkInNAND, int inScan)
3459 /* NB inScan is zero unless scanning.
3460 * For forward scanning, inScan is > 0;
3461 * for backward scanning inScan is < 0
3465 yaffs_Device *dev = in->myDev;
3467 yaffs_ExtendedTags existingTags;
3468 yaffs_ExtendedTags newTags;
3469 unsigned existingSerial, newSerial;
3471 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3472 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3473 * If it is not during Scanning then something went wrong!
3476 T(YAFFS_TRACE_ERROR,
3478 ("yaffs tragedy:attempt to put data chunk into a non-file"
3483 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3487 tn = yaffs_AddOrFindLevel0Tnode(dev,
3488 &in->variant.fileVariant,
3495 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3498 /* If we're scanning then we need to test for duplicates
3499 * NB This does not need to be efficient since it should only ever
3500 * happen when the power fails during a write, then only one
3501 * chunk should ever be affected.
3503 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3504 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3507 if (existingChunk > 0) {
3508 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3509 * thus we have to do a FindChunkInFile to get the real chunk id.
3511 * We have a duplicate now we need to decide which one to use:
3513 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3514 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3515 * YAFFS1: Get both sets of tags and compare serial numbers.
3519 /* Only do this for forward scanning */
3520 yaffs_ReadChunkWithTagsFromNAND(dev,
3524 /* Do a proper find */
3526 yaffs_FindChunkInFile(in, chunkInInode,
3530 if (existingChunk <= 0) {
3531 /*Hoosterman - how did this happen? */
3533 T(YAFFS_TRACE_ERROR,
3535 ("yaffs tragedy: existing chunk < 0 in scan"
3540 /* NB The deleted flags should be false, otherwise the chunks will
3541 * not be loaded during a scan
3545 newSerial = newTags.serialNumber;
3546 existingSerial = existingTags.serialNumber;
3550 (in->myDev->isYaffs2 ||
3551 existingChunk <= 0 ||
3552 ((existingSerial + 1) & 3) == newSerial)) {
3553 /* Forward scanning.
3555 * Delete the old one and drop through to update the tnode
3557 yaffs_DeleteChunk(dev, existingChunk, 1,
3560 /* Backward scanning or we want to use the existing one
3562 * Delete the new one and return early so that the tnode isn't changed
3564 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3572 if (existingChunk == 0) {
3576 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
3581 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
3584 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3586 if (chunkInNAND >= 0) {
3587 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3590 T(YAFFS_TRACE_NANDACCESS,
3591 (TSTR("Chunk %d not found zero instead" TENDSTR),
3593 /* get sane (zero) data if you read a hole */
3594 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3600 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
3604 yaffs_ExtendedTags tags;
3605 yaffs_BlockInfo *bi;
3612 block = chunkId / dev->nChunksPerBlock;
3613 page = chunkId % dev->nChunksPerBlock;
3616 if(!yaffs_CheckChunkBit(dev,block,page))
3617 T(YAFFS_TRACE_VERIFY,
3618 (TSTR("Deleting invalid chunk %d"TENDSTR),
3621 bi = yaffs_GetBlockInfo(dev, block);
3623 T(YAFFS_TRACE_DELETION,
3624 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3627 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3629 yaffs_InitialiseTags(&tags);
3631 tags.chunkDeleted = 1;
3633 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3634 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3636 dev->nUnmarkedDeletions++;
3639 /* Pull out of the management area.
3640 * If the whole block became dirty, this will kick off an erasure.
3642 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3643 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3644 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3645 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3648 yaffs_ClearChunkBit(dev, block, page);
3652 if (bi->pagesInUse == 0 &&
3653 !bi->hasShrinkHeader &&
3654 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3655 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3656 yaffs_BlockBecameDirty(dev, block);
3660 /* T(("Bad news deleting chunk %d\n",chunkId)); */
3665 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
3666 const __u8 * buffer, int nBytes,
3669 /* Find old chunk Need to do this to get serial number
3670 * Write new one and patch into tree.
3671 * Invalidate old tags.
3675 yaffs_ExtendedTags prevTags;
3678 yaffs_ExtendedTags newTags;
3680 yaffs_Device *dev = in->myDev;
3682 yaffs_CheckGarbageCollection(dev);
3684 /* Get the previous chunk at this location in the file if it exists */
3685 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3687 /* Set up new tags */
3688 yaffs_InitialiseTags(&newTags);
3690 newTags.chunkId = chunkInInode;
3691 newTags.objectId = in->objectId;
3692 newTags.serialNumber =
3693 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
3694 newTags.byteCount = nBytes;
3696 if(nBytes < 1 || nBytes > dev->totalBytesPerChunk){
3697 T(YAFFS_TRACE_ERROR,
3698 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3705 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3708 if (newChunkId >= 0) {
3709 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3711 if (prevChunkId >= 0) {
3712 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3716 yaffs_CheckFileSanity(in);
3722 /* UpdateObjectHeader updates the header on NAND for an object.
3723 * If name is not NULL, then that new name is used.
3725 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
3726 int isShrink, int shadows)
3729 yaffs_BlockInfo *bi;
3731 yaffs_Device *dev = in->myDev;
3738 yaffs_ExtendedTags newTags;
3739 yaffs_ExtendedTags oldTags;
3741 __u8 *buffer = NULL;
3742 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3744 yaffs_ObjectHeader *oh = NULL;
3746 yaffs_strcpy(oldName,_Y("silly old name"));
3750 in == dev->rootDir || /* The rootDir should also be saved */
3753 yaffs_CheckGarbageCollection(dev);
3754 yaffs_CheckObjectDetailsLoaded(in);
3756 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3757 oh = (yaffs_ObjectHeader *) buffer;
3759 prevChunkId = in->hdrChunk;
3761 if (prevChunkId > 0) {
3762 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3765 yaffs_VerifyObjectHeader(in,oh,&oldTags,0);
3767 memcpy(oldName, oh->name, sizeof(oh->name));
3770 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3772 oh->type = in->variantType;
3773 oh->yst_mode = in->yst_mode;
3774 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3776 #ifdef CONFIG_YAFFS_WINCE
3777 oh->win_atime[0] = in->win_atime[0];
3778 oh->win_ctime[0] = in->win_ctime[0];
3779 oh->win_mtime[0] = in->win_mtime[0];
3780 oh->win_atime[1] = in->win_atime[1];
3781 oh->win_ctime[1] = in->win_ctime[1];
3782 oh->win_mtime[1] = in->win_mtime[1];
3784 oh->yst_uid = in->yst_uid;
3785 oh->yst_gid = in->yst_gid;
3786 oh->yst_atime = in->yst_atime;
3787 oh->yst_mtime = in->yst_mtime;
3788 oh->yst_ctime = in->yst_ctime;
3789 oh->yst_rdev = in->yst_rdev;
3792 oh->parentObjectId = in->parent->objectId;
3794 oh->parentObjectId = 0;
3797 if (name && *name) {
3798 memset(oh->name, 0, sizeof(oh->name));
3799 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3800 } else if (prevChunkId>=0) {
3801 memcpy(oh->name, oldName, sizeof(oh->name));
3803 memset(oh->name, 0, sizeof(oh->name));
3806 oh->isShrink = isShrink;
3808 switch (in->variantType) {
3809 case YAFFS_OBJECT_TYPE_UNKNOWN:
3810 /* Should not happen */
3812 case YAFFS_OBJECT_TYPE_FILE:
3814 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3815 || oh->parentObjectId ==
3816 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3817 fileVariant.fileSize;
3819 case YAFFS_OBJECT_TYPE_HARDLINK:
3820 oh->equivalentObjectId =
3821 in->variant.hardLinkVariant.equivalentObjectId;
3823 case YAFFS_OBJECT_TYPE_SPECIAL:
3826 case YAFFS_OBJECT_TYPE_DIRECTORY:
3829 case YAFFS_OBJECT_TYPE_SYMLINK:
3830 yaffs_strncpy(oh->alias,
3831 in->variant.symLinkVariant.alias,
3832 YAFFS_MAX_ALIAS_LENGTH);
3833 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3838 yaffs_InitialiseTags(&newTags);
3840 newTags.chunkId = 0;
3841 newTags.objectId = in->objectId;
3842 newTags.serialNumber = in->serial;
3844 /* Add extra info for file header */
3846 newTags.extraHeaderInfoAvailable = 1;
3847 newTags.extraParentObjectId = oh->parentObjectId;
3848 newTags.extraFileLength = oh->fileSize;
3849 newTags.extraIsShrinkHeader = oh->isShrink;
3850 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3851 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3852 newTags.extraObjectType = in->variantType;
3854 yaffs_VerifyObjectHeader(in,oh,&newTags,1);
3856 /* Create new chunk in NAND */
3858 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3859 (prevChunkId >= 0) ? 1 : 0);
3861 if (newChunkId >= 0) {
3863 in->hdrChunk = newChunkId;
3865 if (prevChunkId >= 0) {
3866 yaffs_DeleteChunk(dev, prevChunkId, 1,
3870 if(!yaffs_ObjectHasCachedWriteData(in))
3873 /* If this was a shrink, then mark the block that the chunk lives on */
3875 bi = yaffs_GetBlockInfo(in->myDev,
3876 newChunkId /in->myDev-> nChunksPerBlock);
3877 bi->hasShrinkHeader = 1;
3882 retVal = newChunkId;
3887 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3892 /*------------------------ Short Operations Cache ----------------------------------------
3893 * In many situations where there is no high level buffering (eg WinCE) a lot of
3894 * reads might be short sequential reads, and a lot of writes may be short
3895 * sequential writes. eg. scanning/writing a jpeg file.
3896 * In these cases, a short read/write cache can provide a huge perfomance benefit
3897 * with dumb-as-a-rock code.
3898 * In Linux, the page cache provides read buffering aand the short op cache provides write
3901 * There are a limited number (~10) of cache chunks per device so that we don't
3902 * need a very intelligent search.
3905 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3907 yaffs_Device *dev = obj->myDev;
3909 yaffs_ChunkCache *cache;
3910 int nCaches = obj->myDev->nShortOpCaches;
3912 for(i = 0; i < nCaches; i++){
3913 cache = &dev->srCache[i];
3914 if (cache->object == obj &&
3923 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3925 yaffs_Device *dev = obj->myDev;
3926 int lowest = -99; /* Stop compiler whining. */
3928 yaffs_ChunkCache *cache;
3929 int chunkWritten = 0;
3930 int nCaches = obj->myDev->nShortOpCaches;
3936 /* Find the dirty cache for this object with the lowest chunk id. */
3937 for (i = 0; i < nCaches; i++) {
3938 if (dev->srCache[i].object == obj &&
3939 dev->srCache[i].dirty) {
3941 || dev->srCache[i].chunkId <
3943 cache = &dev->srCache[i];
3944 lowest = cache->chunkId;
3949 if (cache && !cache->locked) {
3950 /* Write it out and free it up */
3953 yaffs_WriteChunkDataToObject(cache->object,
3959 cache->object = NULL;
3962 } while (cache && chunkWritten > 0);
3965 /* Hoosterman, disk full while writing cache out. */
3966 T(YAFFS_TRACE_ERROR,
3967 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3974 /*yaffs_FlushEntireDeviceCache(dev)
3979 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3982 int nCaches = dev->nShortOpCaches;
3985 /* Find a dirty object in the cache and flush it...
3986 * until there are no further dirty objects.
3990 for( i = 0; i < nCaches && !obj; i++) {
3991 if (dev->srCache[i].object &&
3992 dev->srCache[i].dirty)
3993 obj = dev->srCache[i].object;
3997 yaffs_FlushFilesChunkCache(obj);
4004 /* Grab us a cache chunk for use.
4005 * First look for an empty one.
4006 * Then look for the least recently used non-dirty one.
4007 * Then look for the least recently used dirty one...., flush and look again.
4009 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
4013 if (dev->nShortOpCaches > 0) {
4014 for (i = 0; i < dev->nShortOpCaches; i++) {
4015 if (!dev->srCache[i].object)
4016 return &dev->srCache[i];
4023 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
4025 yaffs_ChunkCache *cache;
4026 yaffs_Object *theObj;
4031 if (dev->nShortOpCaches > 0) {
4032 /* Try find a non-dirty one... */
4034 cache = yaffs_GrabChunkCacheWorker(dev);
4037 /* They were all dirty, find the last recently used object and flush
4038 * its cache, then find again.
4039 * NB what's here is not very accurate, we actually flush the object
4040 * the last recently used page.
4043 /* With locking we can't assume we can use entry zero */
4050 for (i = 0; i < dev->nShortOpCaches; i++) {
4051 if (dev->srCache[i].object &&
4052 !dev->srCache[i].locked &&
4053 (dev->srCache[i].lastUse < usage || !cache))
4055 usage = dev->srCache[i].lastUse;
4056 theObj = dev->srCache[i].object;
4057 cache = &dev->srCache[i];
4062 if (!cache || cache->dirty) {
4063 /* Flush and try again */
4064 yaffs_FlushFilesChunkCache(theObj);
4065 cache = yaffs_GrabChunkCacheWorker(dev);
4075 /* Find a cached chunk */
4076 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
4079 yaffs_Device *dev = obj->myDev;
4081 if (dev->nShortOpCaches > 0) {
4082 for (i = 0; i < dev->nShortOpCaches; i++) {
4083 if (dev->srCache[i].object == obj &&
4084 dev->srCache[i].chunkId == chunkId) {
4087 return &dev->srCache[i];
4094 /* Mark the chunk for the least recently used algorithym */
4095 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
4099 if (dev->nShortOpCaches > 0) {
4100 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4101 /* Reset the cache usages */
4103 for (i = 1; i < dev->nShortOpCaches; i++) {
4104 dev->srCache[i].lastUse = 0;
4111 cache->lastUse = dev->srLastUse;
4119 /* Invalidate a single cache page.
4120 * Do this when a whole page gets written,
4121 * ie the short cache for this page is no longer valid.
4123 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
4125 if (object->myDev->nShortOpCaches > 0) {
4126 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4129 cache->object = NULL;
4134 /* Invalidate all the cache pages associated with this object
4135 * Do this whenever ther file is deleted or resized.
4137 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
4140 yaffs_Device *dev = in->myDev;
4142 if (dev->nShortOpCaches > 0) {
4143 /* Invalidate it. */
4144 for (i = 0; i < dev->nShortOpCaches; i++) {
4145 if (dev->srCache[i].object == in) {
4146 dev->srCache[i].object = NULL;
4152 /*--------------------- Checkpointing --------------------*/
4155 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
4157 yaffs_CheckpointValidity cp;
4159 memset(&cp,0,sizeof(cp));
4161 cp.structType = sizeof(cp);
4162 cp.magic = YAFFS_MAGIC;
4163 cp.version = YAFFS_CHECKPOINT_VERSION;
4164 cp.head = (head) ? 1 : 0;
4166 return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
4170 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4172 yaffs_CheckpointValidity cp;
4175 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4178 ok = (cp.structType == sizeof(cp)) &&
4179 (cp.magic == YAFFS_MAGIC) &&
4180 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4181 (cp.head == ((head) ? 1 : 0));
4185 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4188 cp->nErasedBlocks = dev->nErasedBlocks;
4189 cp->allocationBlock = dev->allocationBlock;
4190 cp->allocationPage = dev->allocationPage;
4191 cp->nFreeChunks = dev->nFreeChunks;
4193 cp->nDeletedFiles = dev->nDeletedFiles;
4194 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4195 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4196 cp->sequenceNumber = dev->sequenceNumber;
4197 cp->oldestDirtySequence = dev->oldestDirtySequence;
4201 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4202 yaffs_CheckpointDevice *cp)
4204 dev->nErasedBlocks = cp->nErasedBlocks;
4205 dev->allocationBlock = cp->allocationBlock;
4206 dev->allocationPage = cp->allocationPage;
4207 dev->nFreeChunks = cp->nFreeChunks;
4209 dev->nDeletedFiles = cp->nDeletedFiles;
4210 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4211 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4212 dev->sequenceNumber = cp->sequenceNumber;
4213 dev->oldestDirtySequence = cp->oldestDirtySequence;
4217 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4219 yaffs_CheckpointDevice cp;
4221 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4225 /* Write device runtime values*/
4226 yaffs_DeviceToCheckpointDevice(&cp,dev);
4227 cp.structType = sizeof(cp);
4229 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4231 /* Write block info */
4233 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4234 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
4237 /* Write chunk bits */
4239 nBytes = nBlocks * dev->chunkBitmapStride;
4240 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
4246 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4248 yaffs_CheckpointDevice cp;
4250 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4254 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4258 if(cp.structType != sizeof(cp))
4262 yaffs_CheckpointDeviceToDevice(dev,&cp);
4264 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4266 ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
4270 nBytes = nBlocks * dev->chunkBitmapStride;
4272 ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
4277 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4281 cp->objectId = obj->objectId;
4282 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4283 cp->hdrChunk = obj->hdrChunk;
4284 cp->variantType = obj->variantType;
4285 cp->deleted = obj->deleted;
4286 cp->softDeleted = obj->softDeleted;
4287 cp->unlinked = obj->unlinked;
4288 cp->fake = obj->fake;
4289 cp->renameAllowed = obj->renameAllowed;
4290 cp->unlinkAllowed = obj->unlinkAllowed;
4291 cp->serial = obj->serial;
4292 cp->nDataChunks = obj->nDataChunks;
4294 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4295 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4296 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4297 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4300 static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
4303 yaffs_Object *parent;
4305 obj->objectId = cp->objectId;
4308 parent = yaffs_FindOrCreateObjectByNumber(
4311 YAFFS_OBJECT_TYPE_DIRECTORY);
4316 yaffs_AddObjectToDirectory(parent, obj);
4318 obj->hdrChunk = cp->hdrChunk;
4319 obj->variantType = cp->variantType;
4320 obj->deleted = cp->deleted;
4321 obj->softDeleted = cp->softDeleted;
4322 obj->unlinked = cp->unlinked;
4323 obj->fake = cp->fake;
4324 obj->renameAllowed = cp->renameAllowed;
4325 obj->unlinkAllowed = cp->unlinkAllowed;
4326 obj->serial = cp->serial;
4327 obj->nDataChunks = cp->nDataChunks;
4329 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4330 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4331 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4332 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4334 if(obj->hdrChunk > 0)
4335 obj->lazyLoaded = 1;
4340 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
4341 __u32 level, int chunkOffset)
4344 yaffs_Device *dev = in->myDev;
4346 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4348 if(tnodeSize < sizeof(yaffs_Tnode))
4349 tnodeSize = sizeof(yaffs_Tnode);
4355 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
4356 if (tn->internal[i]) {
4357 ok = yaffs_CheckpointTnodeWorker(in,
4360 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4363 } else if (level == 0) {
4364 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4365 /* printf("write tnode at %d\n",baseOffset); */
4366 ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
4368 ok = (yaffs_CheckpointWrite(dev,tn,tnodeSize) == tnodeSize);
4376 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4378 __u32 endMarker = ~0;
4381 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4382 ok = yaffs_CheckpointTnodeWorker(obj,
4383 obj->variant.fileVariant.top,
4384 obj->variant.fileVariant.topLevel,
4387 ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) ==
4394 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4398 yaffs_Device *dev = obj->myDev;
4399 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4402 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4404 if(tnodeSize < sizeof(yaffs_Tnode))
4405 tnodeSize = sizeof(yaffs_Tnode);
4407 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4409 while(ok && (~baseChunk)){
4411 /* Read level 0 tnode */
4414 /* printf("read tnode at %d\n",baseChunk); */
4415 tn = yaffs_GetTnodeRaw(dev);
4417 ok = (yaffs_CheckpointRead(dev,tn,tnodeSize) == tnodeSize);
4422 ok = yaffs_AddOrFindLevel0Tnode(dev,
4430 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4434 T(YAFFS_TRACE_CHECKPOINT,(
4435 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4436 nread,baseChunk,ok));
4442 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4445 yaffs_CheckpointObject cp;
4448 struct ylist_head *lh;
4451 /* Iterate through the objects in each hash entry,
4452 * dumping them to the checkpointing stream.
4455 for(i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++){
4456 ylist_for_each(lh, &dev->objectBucket[i].list) {
4458 obj = ylist_entry(lh, yaffs_Object, hashLink);
4459 if (!obj->deferedFree) {
4460 yaffs_ObjectToCheckpointObject(&cp,obj);
4461 cp.structType = sizeof(cp);
4463 T(YAFFS_TRACE_CHECKPOINT,(
4464 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
4465 cp.objectId,cp.parentId,cp.variantType,cp.hdrChunk,(unsigned) obj));
4467 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4469 if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4470 ok = yaffs_WriteCheckpointTnodes(obj);
4477 /* Dump end of list */
4478 memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
4479 cp.structType = sizeof(cp);
4482 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4487 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4490 yaffs_CheckpointObject cp;
4493 yaffs_Object *hardList = NULL;
4495 while(ok && !done) {
4496 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4497 if(cp.structType != sizeof(cp)) {
4498 T(YAFFS_TRACE_CHECKPOINT,(TSTR("struct size %d instead of %d ok %d"TENDSTR),
4499 cp.structType,sizeof(cp),ok));
4503 T(YAFFS_TRACE_CHECKPOINT,(TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4504 cp.objectId,cp.parentId,cp.variantType,cp.hdrChunk));
4506 if(ok && cp.objectId == ~0)
4509 obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
4511 yaffs_CheckpointObjectToObject(obj,&cp);
4512 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4513 ok = yaffs_ReadCheckpointTnodes(obj);
4514 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4515 obj->hardLinks.next =
4516 (struct ylist_head *)
4526 yaffs_HardlinkFixup(dev,hardList);
4531 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4533 __u32 checkpointSum;
4536 yaffs_GetCheckpointSum(dev,&checkpointSum);
4538 ok = (yaffs_CheckpointWrite(dev,&checkpointSum,sizeof(checkpointSum)) == sizeof(checkpointSum));
4546 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4548 __u32 checkpointSum0;
4549 __u32 checkpointSum1;
4552 yaffs_GetCheckpointSum(dev,&checkpointSum0);
4554 ok = (yaffs_CheckpointRead(dev,&checkpointSum1,sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4559 if(checkpointSum0 != checkpointSum1)
4566 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4571 if(dev->skipCheckpointWrite || !dev->isYaffs2){
4572 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint write" TENDSTR)));
4577 ok = yaffs_CheckpointOpen(dev,1);
4580 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4581 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
4584 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint device" TENDSTR)));
4585 ok = yaffs_WriteCheckpointDevice(dev);
4588 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint objects" TENDSTR)));
4589 ok = yaffs_WriteCheckpointObjects(dev);
4592 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4593 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
4597 ok = yaffs_WriteCheckpointSum(dev);
4601 if(!yaffs_CheckpointClose(dev))
4605 dev->isCheckpointed = 1;
4607 dev->isCheckpointed = 0;
4609 return dev->isCheckpointed;
4612 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4616 if(dev->skipCheckpointRead || !dev->isYaffs2){
4617 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint read" TENDSTR)));
4622 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
4625 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4626 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
4629 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint device" TENDSTR)));
4630 ok = yaffs_ReadCheckpointDevice(dev);
4633 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint objects" TENDSTR)));
4634 ok = yaffs_ReadCheckpointObjects(dev);
4637 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4638 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
4642 ok = yaffs_ReadCheckpointSum(dev);
4643 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint checksum %d" TENDSTR),ok));
4646 if(!yaffs_CheckpointClose(dev))
4650 dev->isCheckpointed = 1;
4652 dev->isCheckpointed = 0;
4658 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4660 if(dev->isCheckpointed ||
4661 dev->blocksInCheckpoint > 0){
4662 dev->isCheckpointed = 0;
4663 yaffs_CheckpointInvalidateStream(dev);
4664 if(dev->superBlock && dev->markSuperBlockDirty)
4665 dev->markSuperBlockDirty(dev->superBlock);
4670 int yaffs_CheckpointSave(yaffs_Device *dev)
4673 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4675 yaffs_VerifyObjects(dev);
4676 yaffs_VerifyBlocks(dev);
4677 yaffs_VerifyFreeChunks(dev);
4679 if(!dev->isCheckpointed) {
4680 yaffs_InvalidateCheckpoint(dev);
4681 yaffs_WriteCheckpointData(dev);
4684 T(YAFFS_TRACE_ALWAYS,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4686 return dev->isCheckpointed;
4689 int yaffs_CheckpointRestore(yaffs_Device *dev)
4692 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4694 retval = yaffs_ReadCheckpointData(dev);
4696 if(dev->isCheckpointed){
4697 yaffs_VerifyObjects(dev);
4698 yaffs_VerifyBlocks(dev);
4699 yaffs_VerifyFreeChunks(dev);
4702 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4707 /*--------------------- File read/write ------------------------
4708 * Read and write have very similar structures.
4709 * In general the read/write has three parts to it
4710 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4711 * Some complete chunks
4712 * An incomplete chunk to end off with
4714 * Curve-balls: the first chunk might also be the last chunk.
4717 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, loff_t offset,
4726 yaffs_ChunkCache *cache;
4733 //chunk = offset / dev->nDataBytesPerChunk + 1;
4734 //start = offset % dev->nDataBytesPerChunk;
4735 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4738 /* OK now check for the curveball where the start and end are in
4741 if ((start + n) < dev->nDataBytesPerChunk) {
4744 nToCopy = dev->nDataBytesPerChunk - start;
4747 cache = yaffs_FindChunkCache(in, chunk);
4749 /* If the chunk is already in the cache or it is less than a whole chunk
4750 * or we're using inband tags then use the cache (if there is caching)
4751 * else bypass the cache.
4753 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4754 if (dev->nShortOpCaches > 0) {
4756 /* If we can't find the data in the cache, then load it up. */
4759 cache = yaffs_GrabChunkCache(in->myDev);
4761 cache->chunkId = chunk;
4764 yaffs_ReadChunkDataFromObject(in, chunk,
4770 yaffs_UseChunkCache(dev, cache, 0);
4774 #ifdef CONFIG_YAFFS_WINCE
4775 yfsd_UnlockYAFFS(TRUE);
4777 memcpy(buffer, &cache->data[start], nToCopy);
4779 #ifdef CONFIG_YAFFS_WINCE
4780 yfsd_LockYAFFS(TRUE);
4784 /* Read into the local buffer then copy..*/
4787 yaffs_GetTempBuffer(dev, __LINE__);
4788 yaffs_ReadChunkDataFromObject(in, chunk,
4790 #ifdef CONFIG_YAFFS_WINCE
4791 yfsd_UnlockYAFFS(TRUE);
4793 memcpy(buffer, &localBuffer[start], nToCopy);
4795 #ifdef CONFIG_YAFFS_WINCE
4796 yfsd_LockYAFFS(TRUE);
4798 yaffs_ReleaseTempBuffer(dev, localBuffer,
4803 #ifdef CONFIG_YAFFS_WINCE
4804 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4806 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4807 * This is because we otherwise screw up WinCE's memory mapper
4809 yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
4811 #ifdef CONFIG_YAFFS_WINCE
4812 yfsd_UnlockYAFFS(TRUE);
4814 memcpy(buffer, localBuffer, dev->nDataBytesPerChunk);
4816 #ifdef CONFIG_YAFFS_WINCE
4817 yfsd_LockYAFFS(TRUE);
4818 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4822 /* A full chunk. Read directly into the supplied buffer. */
4823 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4837 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, loff_t offset,
4838 int nBytes, int writeThrough)
4847 int startOfWrite = offset;
4848 int chunkWritten = 0;
4855 while (n > 0 && chunkWritten >= 0) {
4856 //chunk = offset / dev->nDataBytesPerChunk + 1;
4857 //start = offset % dev->nDataBytesPerChunk;
4858 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4860 if(chunk * dev->nDataBytesPerChunk + start != offset ||
4861 start >= dev->nDataBytesPerChunk){
4862 T(YAFFS_TRACE_ERROR,(TSTR("AddrToChunk of offset %d gives chunk %d start %d"TENDSTR),
4863 (int)offset, chunk,start));
4867 /* OK now check for the curveball where the start and end are in
4871 if ((start + n) < dev->nDataBytesPerChunk) {
4874 /* Now folks, to calculate how many bytes to write back....
4875 * If we're overwriting and not writing to then end of file then
4876 * we need to write back as much as was there before.
4880 in->variant.fileVariant.fileSize -
4881 ((chunk - 1) * dev->nDataBytesPerChunk);
4883 if (nBytesRead > dev->nDataBytesPerChunk) {
4884 nBytesRead = dev->nDataBytesPerChunk;
4889 ((int)start + n)) ? nBytesRead : (start + n);
4892 nToCopy = dev->nDataBytesPerChunk - start;
4893 nToWriteBack = dev->nDataBytesPerChunk;
4896 if (nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4897 /* An incomplete start or end chunk (or maybe both start and end chunk),
4898 * or we're using inband tags, so we want to use the cache buffers.
4900 if (dev->nShortOpCaches > 0) {
4901 yaffs_ChunkCache *cache;
4902 /* If we can't find the data in the cache, then load the cache */
4903 cache = yaffs_FindChunkCache(in, chunk);
4906 && yaffs_CheckSpaceForAllocation(in->
4908 cache = yaffs_GrabChunkCache(in->myDev);
4910 cache->chunkId = chunk;
4913 yaffs_ReadChunkDataFromObject(in, chunk,
4919 !yaffs_CheckSpaceForAllocation(in->myDev)){
4920 /* Drop the cache if it was a read cache item and
4921 * no space check has been made for it.
4927 yaffs_UseChunkCache(dev, cache, 1);
4929 #ifdef CONFIG_YAFFS_WINCE
4930 yfsd_UnlockYAFFS(TRUE);
4933 memcpy(&cache->data[start], buffer,
4936 #ifdef CONFIG_YAFFS_WINCE
4937 yfsd_LockYAFFS(TRUE);
4940 cache->nBytes = nToWriteBack;
4944 yaffs_WriteChunkDataToObject
4947 cache->data, cache->nBytes,
4953 chunkWritten = -1; /* fail the write */
4956 /* An incomplete start or end chunk (or maybe both start and end chunk)
4957 * Read into the local buffer then copy, then copy over and write back.
4961 yaffs_GetTempBuffer(dev, __LINE__);
4963 yaffs_ReadChunkDataFromObject(in, chunk,
4966 #ifdef CONFIG_YAFFS_WINCE
4967 yfsd_UnlockYAFFS(TRUE);
4970 memcpy(&localBuffer[start], buffer, nToCopy);
4972 #ifdef CONFIG_YAFFS_WINCE
4973 yfsd_LockYAFFS(TRUE);
4976 yaffs_WriteChunkDataToObject(in, chunk,
4981 yaffs_ReleaseTempBuffer(dev, localBuffer,
4987 /* A full chunk. Write directly from the supplied buffer. */
4989 #ifdef CONFIG_YAFFS_WINCE
4990 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4991 * This is because we otherwise screw up WinCE's memory mapper
4993 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4994 #ifdef CONFIG_YAFFS_WINCE
4995 yfsd_UnlockYAFFS(TRUE);
4997 memcpy(localBuffer, buffer, dev->nDataBytesPerChunk);
4998 #ifdef CONFIG_YAFFS_WINCE
4999 yfsd_LockYAFFS(TRUE);
5002 yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
5003 dev->nDataBytesPerChunk,
5005 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5009 yaffs_WriteChunkDataToObject(in, chunk, buffer,
5010 dev->nDataBytesPerChunk,
5013 /* Since we've overwritten the cached data, we better invalidate it. */
5014 yaffs_InvalidateChunkCache(in, chunk);
5017 if (chunkWritten >= 0) {
5026 /* Update file object */
5028 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
5029 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
5038 /* ---------------------- File resizing stuff ------------------ */
5040 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
5043 yaffs_Device *dev = in->myDev;
5044 int oldFileSize = in->variant.fileVariant.fileSize;
5046 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
5048 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
5049 dev->nDataBytesPerChunk;
5053 /* Delete backwards so that we don't end up with holes if
5054 * power is lost part-way through the operation.
5056 for (i = lastDel; i >= startDel; i--) {
5057 /* NB this could be optimised somewhat,
5058 * eg. could retrieve the tags and write them without
5059 * using yaffs_DeleteChunk
5062 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5065 (dev->internalStartBlock * dev->nChunksPerBlock)
5067 ((dev->internalEndBlock +
5068 1) * dev->nChunksPerBlock)) {
5069 T(YAFFS_TRACE_ALWAYS,
5070 (TSTR("Found daft chunkId %d for %d" TENDSTR),
5074 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5081 int yaffs_ResizeFile(yaffs_Object * in, loff_t newSize)
5084 int oldFileSize = in->variant.fileVariant.fileSize;
5085 __u32 newSizeOfPartialChunk;
5088 yaffs_Device *dev = in->myDev;
5090 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5092 yaffs_FlushFilesChunkCache(in);
5093 yaffs_InvalidateWholeChunkCache(in);
5095 yaffs_CheckGarbageCollection(dev);
5097 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
5101 if (newSize == oldFileSize) {
5105 if (newSize < oldFileSize) {
5107 yaffs_PruneResizedChunks(in, newSize);
5109 if (newSizeOfPartialChunk != 0) {
5110 int lastChunk = 1 + newFullChunks;
5112 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5114 /* Got to read and rewrite the last chunk with its new size and zero pad */
5115 yaffs_ReadChunkDataFromObject(in, lastChunk,
5118 memset(localBuffer + newSizeOfPartialChunk, 0,
5119 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5121 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5122 newSizeOfPartialChunk, 1);
5124 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5127 in->variant.fileVariant.fileSize = newSize;
5129 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5131 /* newsSize > oldFileSize */
5132 in->variant.fileVariant.fileSize = newSize;
5137 /* Write a new object header.
5138 * show we've shrunk the file, if need be
5139 * Do this only if the file is not in the deleted directories.
5142 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5143 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
5144 yaffs_UpdateObjectHeader(in, NULL, 0,
5145 (newSize < oldFileSize) ? 1 : 0, 0);
5151 loff_t yaffs_GetFileSize(yaffs_Object * obj)
5153 obj = yaffs_GetEquivalentObject(obj);
5155 switch (obj->variantType) {
5156 case YAFFS_OBJECT_TYPE_FILE:
5157 return obj->variant.fileVariant.fileSize;
5158 case YAFFS_OBJECT_TYPE_SYMLINK:
5159 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5167 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
5171 yaffs_FlushFilesChunkCache(in);
5173 #ifdef CONFIG_YAFFS_WINCE
5174 yfsd_WinFileTimeNow(in->win_mtime);
5177 in->yst_mtime = Y_CURRENT_TIME;
5183 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5184 0) ? YAFFS_OK : YAFFS_FAIL;
5193 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
5196 /* First off, invalidate the file's data in the cache, without flushing. */
5197 yaffs_InvalidateWholeChunkCache(in);
5199 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5200 /* Move to the unlinked directory so we have a record that it was deleted. */
5201 yaffs_ChangeObjectName(in, in->myDev->deletedDir,_Y("deleted"), 0, 0);
5205 yaffs_RemoveObjectFromDirectory(in);
5206 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5209 yaffs_FreeObject(in);
5214 /* yaffs_DeleteFile deletes the whole file data
5215 * and the inode associated with the file.
5216 * It does not delete the links associated with the file.
5219 static int yaffs_UnlinkFile(yaffs_Object * in)
5223 int immediateDeletion = 0;
5227 immediateDeletion = 1;
5230 if (in->inUse <= 0) {
5231 immediateDeletion = 1;
5235 if (immediateDeletion) {
5237 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5238 _Y("deleted"), 0, 0);
5239 T(YAFFS_TRACE_TRACING,
5240 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5243 in->myDev->nDeletedFiles++;
5244 if (1 || in->myDev->isYaffs2) {
5245 yaffs_ResizeFile(in, 0);
5247 yaffs_SoftDeleteFile(in);
5250 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5251 _Y("unlinked"), 0, 0);
5258 int yaffs_DeleteFile(yaffs_Object * in)
5260 int retVal = YAFFS_OK;
5261 int deleted = in->deleted;
5263 yaffs_ResizeFile(in,0);
5265 if (in->nDataChunks > 0) {
5266 /* Use soft deletion if there is data in the file.
5267 * That won't be the case if it has been resized to zero.
5269 if (!in->unlinked) {
5270 retVal = yaffs_UnlinkFile(in);
5272 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5273 in->deleted = deleted = 1;
5274 in->myDev->nDeletedFiles++;
5275 yaffs_SoftDeleteFile(in);
5277 return deleted ? YAFFS_OK : YAFFS_FAIL;
5279 /* The file has no data chunks so we toss it immediately */
5280 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5281 in->variant.fileVariant.top = NULL;
5282 yaffs_DoGenericObjectDeletion(in);
5288 static int yaffs_DeleteDirectory(yaffs_Object * in)
5290 /* First check that the directory is empty. */
5291 if (ylist_empty(&in->variant.directoryVariant.children)) {
5292 return yaffs_DoGenericObjectDeletion(in);
5299 static int yaffs_DeleteSymLink(yaffs_Object * in)
5301 YFREE(in->variant.symLinkVariant.alias);
5303 return yaffs_DoGenericObjectDeletion(in);
5306 static int yaffs_DeleteHardLink(yaffs_Object * in)
5308 /* remove this hardlink from the list assocaited with the equivalent
5311 ylist_del_init(&in->hardLinks);
5312 return yaffs_DoGenericObjectDeletion(in);
5315 static void yaffs_DestroyObject(yaffs_Object * obj)
5317 switch (obj->variantType) {
5318 case YAFFS_OBJECT_TYPE_FILE:
5319 yaffs_DeleteFile(obj);
5321 case YAFFS_OBJECT_TYPE_DIRECTORY:
5322 yaffs_DeleteDirectory(obj);
5324 case YAFFS_OBJECT_TYPE_SYMLINK:
5325 yaffs_DeleteSymLink(obj);
5327 case YAFFS_OBJECT_TYPE_HARDLINK:
5328 yaffs_DeleteHardLink(obj);
5330 case YAFFS_OBJECT_TYPE_SPECIAL:
5331 yaffs_DoGenericObjectDeletion(obj);
5333 case YAFFS_OBJECT_TYPE_UNKNOWN:
5334 break; /* should not happen. */
5338 static int yaffs_UnlinkWorker(yaffs_Object * obj)
5341 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5342 return yaffs_DeleteHardLink(obj);
5343 } else if (!ylist_empty(&obj->hardLinks)) {
5344 /* Curve ball: We're unlinking an object that has a hardlink.
5346 * This problem arises because we are not strictly following
5347 * The Linux link/inode model.
5349 * We can't really delete the object.
5350 * Instead, we do the following:
5351 * - Select a hardlink.
5352 * - Unhook it from the hard links
5353 * - Unhook it from its parent directory (so that the rename can work)
5354 * - Rename the object to the hardlink's name.
5355 * - Delete the hardlink
5360 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5362 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5364 ylist_del_init(&hl->hardLinks);
5365 ylist_del_init(&hl->siblings);
5367 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5369 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
5371 if (retVal == YAFFS_OK) {
5372 retVal = yaffs_DoGenericObjectDeletion(hl);
5377 switch (obj->variantType) {
5378 case YAFFS_OBJECT_TYPE_FILE:
5379 return yaffs_UnlinkFile(obj);
5381 case YAFFS_OBJECT_TYPE_DIRECTORY:
5382 return yaffs_DeleteDirectory(obj);
5384 case YAFFS_OBJECT_TYPE_SYMLINK:
5385 return yaffs_DeleteSymLink(obj);
5387 case YAFFS_OBJECT_TYPE_SPECIAL:
5388 return yaffs_DoGenericObjectDeletion(obj);
5390 case YAFFS_OBJECT_TYPE_HARDLINK:
5391 case YAFFS_OBJECT_TYPE_UNKNOWN:
5399 static int yaffs_UnlinkObject( yaffs_Object *obj)
5402 if (obj && obj->unlinkAllowed) {
5403 return yaffs_UnlinkWorker(obj);
5409 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
5413 obj = yaffs_FindObjectByName(dir, name);
5414 return yaffs_UnlinkObject(obj);
5417 /*----------------------- Initialisation Scanning ---------------------- */
5419 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
5420 int backwardScanning)
5424 if (!backwardScanning) {
5425 /* Handle YAFFS1 forward scanning case
5426 * For YAFFS1 we always do the deletion
5430 /* Handle YAFFS2 case (backward scanning)
5431 * If the shadowed object exists then ignore.
5433 if (yaffs_FindObjectByNumber(dev, objId)) {
5438 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5439 * We put it in unlinked dir to be cleaned up after the scanning
5442 yaffs_FindOrCreateObjectByNumber(dev, objId,
5443 YAFFS_OBJECT_TYPE_FILE);
5444 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5445 obj->variant.fileVariant.shrinkSize = 0;
5446 obj->valid = 1; /* So that we don't read any other info for this file */
5456 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5463 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5465 in = yaffs_FindObjectByNumber(dev,
5466 hl->variant.hardLinkVariant.
5467 equivalentObjectId);
5470 /* Add the hardlink pointers */
5471 hl->variant.hardLinkVariant.equivalentObject = in;
5472 ylist_add(&hl->hardLinks, &in->hardLinks);
5474 /* Todo Need to report/handle this better.
5475 * Got a problem... hardlink to a non-existant object
5477 hl->variant.hardLinkVariant.equivalentObject = NULL;
5478 YINIT_LIST_HEAD(&hl->hardLinks);
5490 static int ybicmp(const void *a, const void *b){
5491 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5492 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5493 register int ablock = ((yaffs_BlockIndex *)a)->block;
5494 register int bblock = ((yaffs_BlockIndex *)b)->block;
5496 return ablock - bblock;
5503 struct yaffs_ShadowFixerStruct {
5506 struct yaffs_ShadowFixerStruct *next;
5509 static int yaffs_Scan(yaffs_Device * dev)
5511 yaffs_ExtendedTags tags;
5521 yaffs_BlockState state;
5522 yaffs_Object *hardList = NULL;
5523 yaffs_BlockInfo *bi;
5524 __u32 sequenceNumber;
5525 yaffs_ObjectHeader *oh;
5527 yaffs_Object *parent;
5529 int alloc_failed = 0;
5531 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5539 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5540 dev->internalStartBlock, dev->internalEndBlock));
5542 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5544 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5546 /* Scan all the blocks to determine their state */
5547 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5548 bi = yaffs_GetBlockInfo(dev, blk);
5549 yaffs_ClearChunkBits(dev, blk);
5551 bi->softDeletions = 0;
5553 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5555 bi->blockState = state;
5556 bi->sequenceNumber = sequenceNumber;
5558 T(YAFFS_TRACE_SCAN_DEBUG,
5559 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5560 state, sequenceNumber));
5562 if (state == YAFFS_BLOCK_STATE_DEAD) {
5563 T(YAFFS_TRACE_BAD_BLOCKS,
5564 (TSTR("block %d is bad" TENDSTR), blk));
5565 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5566 T(YAFFS_TRACE_SCAN_DEBUG,
5567 (TSTR("Block empty " TENDSTR)));
5568 dev->nErasedBlocks++;
5569 dev->nFreeChunks += dev->nChunksPerBlock;
5573 startIterator = dev->internalStartBlock;
5574 endIterator = dev->internalEndBlock;
5576 /* For each block.... */
5577 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5584 blk = blockIterator;
5586 bi = yaffs_GetBlockInfo(dev, blk);
5587 state = bi->blockState;
5591 /* For each chunk in each block that needs scanning....*/
5592 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5593 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5594 /* Read the tags and decide what to do */
5595 chunk = blk * dev->nChunksPerBlock + c;
5597 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5600 /* Let's have a good look at this chunk... */
5602 if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
5608 /*T((" %d %d deleted\n",blk,c)); */
5609 } else if (!tags.chunkUsed) {
5610 /* An unassigned chunk in the block
5611 * This means that either the block is empty or
5612 * this is the one being allocated from
5616 /* We're looking at the first chunk in the block so the block is unused */
5617 state = YAFFS_BLOCK_STATE_EMPTY;
5618 dev->nErasedBlocks++;
5620 /* this is the block being allocated from */
5623 (" Allocating from %d %d" TENDSTR),
5625 state = YAFFS_BLOCK_STATE_ALLOCATING;
5626 dev->allocationBlock = blk;
5627 dev->allocationPage = c;
5628 dev->allocationBlockFinder = blk;
5629 /* Set it to here to encourage the allocator to go forth from here. */
5633 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5634 } else if (tags.chunkId > 0) {
5635 /* chunkId > 0 so it is a data chunk... */
5636 unsigned int endpos;
5638 yaffs_SetChunkBit(dev, blk, c);
5641 in = yaffs_FindOrCreateObjectByNumber(dev,
5644 YAFFS_OBJECT_TYPE_FILE);
5645 /* PutChunkIntoFile checks for a clash (two data chunks with
5646 * the same chunkId).
5653 if(!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,1))
5658 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5661 in->variantType == YAFFS_OBJECT_TYPE_FILE
5662 && in->variant.fileVariant.scannedFileSize <
5664 in->variant.fileVariant.
5665 scannedFileSize = endpos;
5666 if (!dev->useHeaderFileSize) {
5667 in->variant.fileVariant.
5669 in->variant.fileVariant.
5674 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
5676 /* chunkId == 0, so it is an ObjectHeader.
5677 * Thus, we read in the object header and make the object
5679 yaffs_SetChunkBit(dev, blk, c);
5682 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5686 oh = (yaffs_ObjectHeader *) chunkData;
5688 in = yaffs_FindObjectByNumber(dev,
5690 if (in && in->variantType != oh->type) {
5691 /* This should not happen, but somehow
5692 * Wev'e ended up with an objectId that has been reused but not yet
5693 * deleted, and worse still it has changed type. Delete the old object.
5696 yaffs_DestroyObject(in);
5701 in = yaffs_FindOrCreateObjectByNumber(dev,
5709 if (in && oh->shadowsObject > 0) {
5711 struct yaffs_ShadowFixerStruct *fixer;
5712 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
5714 fixer-> next = shadowFixerList;
5715 shadowFixerList = fixer;
5716 fixer->objectId = tags.objectId;
5717 fixer->shadowedId = oh->shadowsObject;
5722 if (in && in->valid) {
5723 /* We have already filled this one. We have a duplicate and need to resolve it. */
5725 unsigned existingSerial = in->serial;
5726 unsigned newSerial = tags.serialNumber;
5728 if (((existingSerial + 1) & 3) == newSerial) {
5729 /* Use new one - destroy the exisiting one */
5730 yaffs_DeleteChunk(dev,
5735 /* Use existing - destroy this one. */
5736 yaffs_DeleteChunk(dev, chunk, 1,
5741 if (in && !in->valid &&
5742 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5743 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5744 /* We only load some info, don't fiddle with directory structure */
5746 in->variantType = oh->type;
5748 in->yst_mode = oh->yst_mode;
5749 #ifdef CONFIG_YAFFS_WINCE
5750 in->win_atime[0] = oh->win_atime[0];
5751 in->win_ctime[0] = oh->win_ctime[0];
5752 in->win_mtime[0] = oh->win_mtime[0];
5753 in->win_atime[1] = oh->win_atime[1];
5754 in->win_ctime[1] = oh->win_ctime[1];
5755 in->win_mtime[1] = oh->win_mtime[1];
5757 in->yst_uid = oh->yst_uid;
5758 in->yst_gid = oh->yst_gid;
5759 in->yst_atime = oh->yst_atime;
5760 in->yst_mtime = oh->yst_mtime;
5761 in->yst_ctime = oh->yst_ctime;
5762 in->yst_rdev = oh->yst_rdev;
5764 in->hdrChunk = chunk;
5765 in->serial = tags.serialNumber;
5767 } else if (in && !in->valid) {
5768 /* we need to load this info */
5771 in->variantType = oh->type;
5773 in->yst_mode = oh->yst_mode;
5774 #ifdef CONFIG_YAFFS_WINCE
5775 in->win_atime[0] = oh->win_atime[0];
5776 in->win_ctime[0] = oh->win_ctime[0];
5777 in->win_mtime[0] = oh->win_mtime[0];
5778 in->win_atime[1] = oh->win_atime[1];
5779 in->win_ctime[1] = oh->win_ctime[1];
5780 in->win_mtime[1] = oh->win_mtime[1];
5782 in->yst_uid = oh->yst_uid;
5783 in->yst_gid = oh->yst_gid;
5784 in->yst_atime = oh->yst_atime;
5785 in->yst_mtime = oh->yst_mtime;
5786 in->yst_ctime = oh->yst_ctime;
5787 in->yst_rdev = oh->yst_rdev;
5789 in->hdrChunk = chunk;
5790 in->serial = tags.serialNumber;
5792 yaffs_SetObjectName(in, oh->name);
5795 /* directory stuff...
5800 yaffs_FindOrCreateObjectByNumber
5801 (dev, oh->parentObjectId,
5802 YAFFS_OBJECT_TYPE_DIRECTORY);
5803 if (parent->variantType ==
5804 YAFFS_OBJECT_TYPE_UNKNOWN) {
5805 /* Set up as a directory */
5806 parent->variantType =
5807 YAFFS_OBJECT_TYPE_DIRECTORY;
5808 YINIT_LIST_HEAD(&parent->variant.
5811 } else if (parent->variantType !=
5812 YAFFS_OBJECT_TYPE_DIRECTORY)
5814 /* Hoosterman, another problem....
5815 * We're trying to use a non-directory as a directory
5818 T(YAFFS_TRACE_ERROR,
5820 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
5822 parent = dev->lostNFoundDir;
5825 yaffs_AddObjectToDirectory(parent, in);
5827 if (0 && (parent == dev->deletedDir ||
5828 parent == dev->unlinkedDir)) {
5829 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
5830 dev->nDeletedFiles++;
5832 /* Note re hardlinks.
5833 * Since we might scan a hardlink before its equivalent object is scanned
5834 * we put them all in a list.
5835 * After scanning is complete, we should have all the objects, so we run through this
5836 * list and fix up all the chains.
5839 switch (in->variantType) {
5840 case YAFFS_OBJECT_TYPE_UNKNOWN:
5841 /* Todo got a problem */
5843 case YAFFS_OBJECT_TYPE_FILE:
5844 if (dev->useHeaderFileSize)
5846 in->variant.fileVariant.
5851 case YAFFS_OBJECT_TYPE_HARDLINK:
5852 in->variant.hardLinkVariant.
5853 equivalentObjectId =
5854 oh->equivalentObjectId;
5855 in->hardLinks.next =
5856 (struct ylist_head *)
5860 case YAFFS_OBJECT_TYPE_DIRECTORY:
5863 case YAFFS_OBJECT_TYPE_SPECIAL:
5866 case YAFFS_OBJECT_TYPE_SYMLINK:
5867 in->variant.symLinkVariant.alias =
5868 yaffs_CloneString(oh->alias);
5869 if(!in->variant.symLinkVariant.alias)
5875 if (parent == dev->deletedDir) {
5876 yaffs_DestroyObject(in);
5877 bi->hasShrinkHeader = 1;
5884 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5885 /* If we got this far while scanning, then the block is fully allocated.*/
5886 state = YAFFS_BLOCK_STATE_FULL;
5889 bi->blockState = state;
5891 /* Now let's see if it was dirty */
5892 if (bi->pagesInUse == 0 &&
5893 !bi->hasShrinkHeader &&
5894 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5895 yaffs_BlockBecameDirty(dev, blk);
5901 /* Ok, we've done all the scanning.
5902 * Fix up the hard link chains.
5903 * We should now have scanned all the objects, now it's time to add these
5907 yaffs_HardlinkFixup(dev,hardList);
5909 /* Handle the unlinked files. Since they were left in an unlinked state we should
5913 struct ylist_head *i;
5914 struct ylist_head *n;
5917 /* Soft delete all the unlinked files */
5918 ylist_for_each_safe(i, n,
5919 &dev->unlinkedDir->variant.directoryVariant.
5922 l = ylist_entry(i, yaffs_Object, siblings);
5923 yaffs_DestroyObject(l);
5928 /* Fix up any shadowed objects */
5930 struct yaffs_ShadowFixerStruct *fixer;
5933 while(shadowFixerList){
5934 fixer = shadowFixerList;
5935 shadowFixerList = fixer->next;
5936 /* Complete the rename transaction by deleting the shadowed object
5937 * then setting the object header to unshadowed.
5939 obj = yaffs_FindObjectByNumber(dev,fixer->shadowedId);
5941 yaffs_DestroyObject(obj);
5943 obj = yaffs_FindObjectByNumber(dev,fixer->objectId);
5945 yaffs_UpdateObjectHeader(obj,NULL,1,0,0);
5952 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5958 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5964 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5967 yaffs_ObjectHeader *oh;
5969 yaffs_ExtendedTags tags;
5971 int alloc_failed = 0;
5979 T(YAFFS_TRACE_SCAN,(TSTR("details for object %d %s loaded" TENDSTR),
5981 in->lazyLoaded ? "not yet" : "already"));
5984 if(in->lazyLoaded && in->hdrChunk > 0){
5986 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5988 result = yaffs_ReadChunkWithTagsFromNAND(dev,in->hdrChunk,chunkData,&tags);
5989 oh = (yaffs_ObjectHeader *) chunkData;
5991 in->yst_mode = oh->yst_mode;
5992 #ifdef CONFIG_YAFFS_WINCE
5993 in->win_atime[0] = oh->win_atime[0];
5994 in->win_ctime[0] = oh->win_ctime[0];
5995 in->win_mtime[0] = oh->win_mtime[0];
5996 in->win_atime[1] = oh->win_atime[1];
5997 in->win_ctime[1] = oh->win_ctime[1];
5998 in->win_mtime[1] = oh->win_mtime[1];
6000 in->yst_uid = oh->yst_uid;
6001 in->yst_gid = oh->yst_gid;
6002 in->yst_atime = oh->yst_atime;
6003 in->yst_mtime = oh->yst_mtime;
6004 in->yst_ctime = oh->yst_ctime;
6005 in->yst_rdev = oh->yst_rdev;
6008 yaffs_SetObjectName(in, oh->name);
6010 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
6011 in->variant.symLinkVariant.alias =
6012 yaffs_CloneString(oh->alias);
6013 if(!in->variant.symLinkVariant.alias)
6014 alloc_failed = 1; /* Not returned to caller */
6017 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
6021 static int yaffs_ScanBackwards(yaffs_Device * dev)
6023 yaffs_ExtendedTags tags;
6028 int nBlocksToScan = 0;
6034 yaffs_BlockState state;
6035 yaffs_Object *hardList = NULL;
6036 yaffs_BlockInfo *bi;
6037 __u32 sequenceNumber;
6038 yaffs_ObjectHeader *oh;
6040 yaffs_Object *parent;
6041 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6047 int foundChunksInBlock;
6048 int equivalentObjectId;
6049 int alloc_failed = 0;
6052 yaffs_BlockIndex *blockIndex = NULL;
6053 int altBlockIndex = 0;
6055 if (!dev->isYaffs2) {
6057 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6063 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
6064 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6067 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6069 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6072 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6078 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6082 dev->blocksInCheckpoint = 0;
6084 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6086 /* Scan all the blocks to determine their state */
6087 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6088 bi = yaffs_GetBlockInfo(dev, blk);
6089 yaffs_ClearChunkBits(dev, blk);
6091 bi->softDeletions = 0;
6093 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6095 bi->blockState = state;
6096 bi->sequenceNumber = sequenceNumber;
6098 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6099 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6101 T(YAFFS_TRACE_SCAN_DEBUG,
6102 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6103 state, sequenceNumber));
6106 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
6107 dev->blocksInCheckpoint++;
6109 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6110 T(YAFFS_TRACE_BAD_BLOCKS,
6111 (TSTR("block %d is bad" TENDSTR), blk));
6112 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6113 T(YAFFS_TRACE_SCAN_DEBUG,
6114 (TSTR("Block empty " TENDSTR)));
6115 dev->nErasedBlocks++;
6116 dev->nFreeChunks += dev->nChunksPerBlock;
6117 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6119 /* Determine the highest sequence number */
6120 if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6121 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6123 blockIndex[nBlocksToScan].seq = sequenceNumber;
6124 blockIndex[nBlocksToScan].block = blk;
6128 if (sequenceNumber >= dev->sequenceNumber) {
6129 dev->sequenceNumber = sequenceNumber;
6132 /* TODO: Nasty sequence number! */
6135 ("Block scanning block %d has bad sequence number %d"
6136 TENDSTR), blk, sequenceNumber));
6143 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6149 /* Sort the blocks */
6150 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6152 /* Use qsort now. */
6153 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6157 /* Dungy old bubble sort... */
6159 yaffs_BlockIndex temp;
6163 for (i = 0; i < nBlocksToScan; i++)
6164 for (j = i + 1; j < nBlocksToScan; j++)
6165 if (blockIndex[i].seq > blockIndex[j].seq) {
6166 temp = blockIndex[j];
6167 blockIndex[j] = blockIndex[i];
6168 blockIndex[i] = temp;
6175 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6177 /* Now scan the blocks looking at the data. */
6179 endIterator = nBlocksToScan - 1;
6180 T(YAFFS_TRACE_SCAN_DEBUG,
6181 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6183 /* For each block.... backwards */
6184 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6186 /* Cooperative multitasking! This loop can run for so
6187 long that watchdog timers expire. */
6190 /* get the block to scan in the correct order */
6191 blk = blockIndex[blockIterator].block;
6193 bi = yaffs_GetBlockInfo(dev, blk);
6196 state = bi->blockState;
6200 /* For each chunk in each block that needs scanning.... */
6201 foundChunksInBlock = 0;
6202 for (c = dev->nChunksPerBlock - 1;
6203 !alloc_failed && c >= 0 &&
6204 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6205 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6206 /* Scan backwards...
6207 * Read the tags and decide what to do
6210 chunk = blk * dev->nChunksPerBlock + c;
6212 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6215 /* Let's have a good look at this chunk... */
6217 if (!tags.chunkUsed) {
6218 /* An unassigned chunk in the block.
6219 * If there are used chunks after this one, then
6220 * it is a chunk that was skipped due to failing the erased
6221 * check. Just skip it so that it can be deleted.
6222 * But, more typically, We get here when this is an unallocated
6223 * chunk and his means that either the block is empty or
6224 * this is the one being allocated from
6227 if(foundChunksInBlock)
6229 /* This is a chunk that was skipped due to failing the erased check */
6231 } else if (c == 0) {
6232 /* We're looking at the first chunk in the block so the block is unused */
6233 state = YAFFS_BLOCK_STATE_EMPTY;
6234 dev->nErasedBlocks++;
6236 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6237 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6238 if(dev->sequenceNumber == bi->sequenceNumber) {
6239 /* this is the block being allocated from */
6243 (" Allocating from %d %d"
6246 state = YAFFS_BLOCK_STATE_ALLOCATING;
6247 dev->allocationBlock = blk;
6248 dev->allocationPage = c;
6249 dev->allocationBlockFinder = blk;
6252 /* This is a partially written block that is not
6253 * the current allocation block. This block must have
6254 * had a write failure, so set up for retirement.
6257 /* bi->needsRetiring = 1; ??? TODO */
6258 bi->gcPrioritise = 1;
6260 T(YAFFS_TRACE_ALWAYS,
6261 (TSTR("Partially written block %d detected" TENDSTR),
6271 } else if (tags.chunkId > 0) {
6272 /* chunkId > 0 so it is a data chunk... */
6273 unsigned int endpos;
6275 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6277 foundChunksInBlock = 1;
6280 yaffs_SetChunkBit(dev, blk, c);
6283 in = yaffs_FindOrCreateObjectByNumber(dev,
6286 YAFFS_OBJECT_TYPE_FILE);
6293 in->variantType == YAFFS_OBJECT_TYPE_FILE
6295 in->variant.fileVariant.shrinkSize) {
6296 /* This has not been invalidated by a resize */
6297 if(!yaffs_PutChunkIntoFile(in, tags.chunkId,
6302 /* File size is calculated by looking at the data chunks if we have not
6303 * seen an object header yet. Stop this practice once we find an object header.
6307 1) * dev->nDataBytesPerChunk +
6310 if (!in->valid && /* have not got an object header yet */
6311 in->variant.fileVariant.
6312 scannedFileSize < endpos) {
6313 in->variant.fileVariant.
6314 scannedFileSize = endpos;
6315 in->variant.fileVariant.
6317 in->variant.fileVariant.
6322 /* This chunk has been invalidated by a resize, so delete */
6323 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6327 /* chunkId == 0, so it is an ObjectHeader.
6328 * Thus, we read in the object header and make the object
6330 foundChunksInBlock = 1;
6332 yaffs_SetChunkBit(dev, blk, c);
6338 if (tags.extraHeaderInfoAvailable) {
6339 in = yaffs_FindOrCreateObjectByNumber
6340 (dev, tags.objectId,
6341 tags.extraObjectType);
6345 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
6348 tags.extraShadows ||
6350 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6351 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
6354 /* If we don't have valid info then we need to read the chunk
6355 * TODO In future we can probably defer reading the chunk and
6356 * living with invalid data until needed.
6359 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6364 oh = (yaffs_ObjectHeader *) chunkData;
6366 if(dev->inbandTags){
6367 /* Fix up the header if they got corrupted by inband tags */
6368 oh->shadowsObject = oh->inbandShadowsObject;
6369 oh->isShrink = oh->inbandIsShrink;
6373 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6378 /* TODO Hoosterman we have a problem! */
6379 T(YAFFS_TRACE_ERROR,
6381 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6382 TENDSTR), tags.objectId, chunk));
6387 /* We have already filled this one.
6388 * We have a duplicate that will be discarded, but
6389 * we first have to suck out resize info if it is a file.
6392 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6394 oh-> type == YAFFS_OBJECT_TYPE_FILE)||
6395 (tags.extraHeaderInfoAvailable &&
6396 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
6399 (oh) ? oh->fileSize : tags.
6401 __u32 parentObjectId =
6403 parentObjectId : tags.
6404 extraParentObjectId;
6408 (oh) ? oh->isShrink : tags.
6409 extraIsShrinkHeader;
6411 /* If it is deleted (unlinked at start also means deleted)
6412 * we treat the file size as being zeroed at this point.
6414 if (parentObjectId ==
6415 YAFFS_OBJECTID_DELETED
6416 || parentObjectId ==
6417 YAFFS_OBJECTID_UNLINKED) {
6423 in->variant.fileVariant.
6424 shrinkSize > thisSize) {
6425 in->variant.fileVariant.
6431 bi->hasShrinkHeader = 1;
6435 /* Use existing - destroy this one. */
6436 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6441 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6443 YAFFS_OBJECTID_LOSTNFOUND)) {
6444 /* We only load some info, don't fiddle with directory structure */
6448 in->variantType = oh->type;
6450 in->yst_mode = oh->yst_mode;
6451 #ifdef CONFIG_YAFFS_WINCE
6452 in->win_atime[0] = oh->win_atime[0];
6453 in->win_ctime[0] = oh->win_ctime[0];
6454 in->win_mtime[0] = oh->win_mtime[0];
6455 in->win_atime[1] = oh->win_atime[1];
6456 in->win_ctime[1] = oh->win_ctime[1];
6457 in->win_mtime[1] = oh->win_mtime[1];
6459 in->yst_uid = oh->yst_uid;
6460 in->yst_gid = oh->yst_gid;
6461 in->yst_atime = oh->yst_atime;
6462 in->yst_mtime = oh->yst_mtime;
6463 in->yst_ctime = oh->yst_ctime;
6464 in->yst_rdev = oh->yst_rdev;
6468 in->variantType = tags.extraObjectType;
6472 in->hdrChunk = chunk;
6474 } else if (!in->valid) {
6475 /* we need to load this info */
6478 in->hdrChunk = chunk;
6481 in->variantType = oh->type;
6483 in->yst_mode = oh->yst_mode;
6484 #ifdef CONFIG_YAFFS_WINCE
6485 in->win_atime[0] = oh->win_atime[0];
6486 in->win_ctime[0] = oh->win_ctime[0];
6487 in->win_mtime[0] = oh->win_mtime[0];
6488 in->win_atime[1] = oh->win_atime[1];
6489 in->win_ctime[1] = oh->win_ctime[1];
6490 in->win_mtime[1] = oh->win_mtime[1];
6492 in->yst_uid = oh->yst_uid;
6493 in->yst_gid = oh->yst_gid;
6494 in->yst_atime = oh->yst_atime;
6495 in->yst_mtime = oh->yst_mtime;
6496 in->yst_ctime = oh->yst_ctime;
6497 in->yst_rdev = oh->yst_rdev;
6500 if (oh->shadowsObject > 0)
6501 yaffs_HandleShadowedObject(dev,
6507 yaffs_SetObjectName(in, oh->name);
6509 yaffs_FindOrCreateObjectByNumber
6510 (dev, oh->parentObjectId,
6511 YAFFS_OBJECT_TYPE_DIRECTORY);
6513 fileSize = oh->fileSize;
6514 isShrink = oh->isShrink;
6515 equivalentObjectId = oh->equivalentObjectId;
6519 in->variantType = tags.extraObjectType;
6521 yaffs_FindOrCreateObjectByNumber
6522 (dev, tags.extraParentObjectId,
6523 YAFFS_OBJECT_TYPE_DIRECTORY);
6524 fileSize = tags.extraFileLength;
6525 isShrink = tags.extraIsShrinkHeader;
6526 equivalentObjectId = tags.extraEquivalentObjectId;
6532 /* directory stuff...
6536 if (parent->variantType ==
6537 YAFFS_OBJECT_TYPE_UNKNOWN) {
6538 /* Set up as a directory */
6539 parent->variantType =
6540 YAFFS_OBJECT_TYPE_DIRECTORY;
6541 YINIT_LIST_HEAD(&parent->variant.
6544 } else if (parent->variantType !=
6545 YAFFS_OBJECT_TYPE_DIRECTORY)
6547 /* Hoosterman, another problem....
6548 * We're trying to use a non-directory as a directory
6551 T(YAFFS_TRACE_ERROR,
6553 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6555 parent = dev->lostNFoundDir;
6558 yaffs_AddObjectToDirectory(parent, in);
6560 itsUnlinked = (parent == dev->deletedDir) ||
6561 (parent == dev->unlinkedDir);
6564 /* Mark the block as having a shrinkHeader */
6565 bi->hasShrinkHeader = 1;
6568 /* Note re hardlinks.
6569 * Since we might scan a hardlink before its equivalent object is scanned
6570 * we put them all in a list.
6571 * After scanning is complete, we should have all the objects, so we run
6572 * through this list and fix up all the chains.
6575 switch (in->variantType) {
6576 case YAFFS_OBJECT_TYPE_UNKNOWN:
6577 /* Todo got a problem */
6579 case YAFFS_OBJECT_TYPE_FILE:
6581 if (in->variant.fileVariant.
6582 scannedFileSize < fileSize) {
6583 /* This covers the case where the file size is greater
6584 * than where the data is
6585 * This will happen if the file is resized to be larger
6586 * than its current data extents.
6588 in->variant.fileVariant.fileSize = fileSize;
6589 in->variant.fileVariant.scannedFileSize =
6590 in->variant.fileVariant.fileSize;
6594 in->variant.fileVariant.shrinkSize > fileSize) {
6595 in->variant.fileVariant.shrinkSize = fileSize;
6599 case YAFFS_OBJECT_TYPE_HARDLINK:
6601 in->variant.hardLinkVariant.equivalentObjectId =
6603 in->hardLinks.next =
6604 (struct ylist_head *) hardList;
6608 case YAFFS_OBJECT_TYPE_DIRECTORY:
6611 case YAFFS_OBJECT_TYPE_SPECIAL:
6614 case YAFFS_OBJECT_TYPE_SYMLINK:
6616 in->variant.symLinkVariant.alias =
6617 yaffs_CloneString(oh->
6619 if(!in->variant.symLinkVariant.alias)
6629 } /* End of scanning for each chunk */
6631 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6632 /* If we got this far while scanning, then the block is fully allocated. */
6633 state = YAFFS_BLOCK_STATE_FULL;
6636 bi->blockState = state;
6638 /* Now let's see if it was dirty */
6639 if (bi->pagesInUse == 0 &&
6640 !bi->hasShrinkHeader &&
6641 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6642 yaffs_BlockBecameDirty(dev, blk);
6648 YFREE_ALT(blockIndex);
6652 /* Ok, we've done all the scanning.
6653 * Fix up the hard link chains.
6654 * We should now have scanned all the objects, now it's time to add these
6657 yaffs_HardlinkFixup(dev,hardList);
6661 * Sort out state of unlinked and deleted objects.
6664 struct ylist_head *i;
6665 struct ylist_head *n;
6669 /* Soft delete all the unlinked files */
6670 ylist_for_each_safe(i, n,
6671 &dev->unlinkedDir->variant.directoryVariant.
6674 l = ylist_entry(i, yaffs_Object, siblings);
6675 yaffs_DestroyObject(l);
6679 /* Soft delete all the deletedDir files */
6680 ylist_for_each_safe(i, n,
6681 &dev->deletedDir->variant.directoryVariant.
6684 l = ylist_entry(i, yaffs_Object, siblings);
6685 yaffs_DestroyObject(l);
6691 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6697 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6702 /*------------------------------ Directory Functions ----------------------------- */
6704 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
6706 struct ylist_head *lh;
6707 yaffs_Object *listObj;
6712 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
6716 if(yaffs_SkipVerification(obj->myDev))
6720 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
6724 if(obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
6725 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
6729 /* Iterate through the objects in each hash entry */
6731 ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
6733 listObj = ylist_entry(lh, yaffs_Object, siblings);
6734 yaffs_VerifyObject(listObj);
6741 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR),count));
6747 static void yaffs_VerifyDirectory(yaffs_Object *directory)
6750 struct ylist_head *lh;
6751 yaffs_Object *listObj;
6756 if(yaffs_SkipFullVerification(directory->myDev))
6760 if(directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
6761 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR),directory->variantType));
6765 /* Iterate through the objects in each hash entry */
6767 ylist_for_each(lh, &directory->variant.directoryVariant.children) {
6769 listObj = ylist_entry(lh, yaffs_Object, siblings);
6770 if(listObj->parent != directory){
6771 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent" TENDSTR),listObj->parent));
6774 yaffs_VerifyObjectInDirectory(listObj);
6781 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
6783 yaffs_Device *dev = obj->myDev;
6784 yaffs_Object *parent;
6786 yaffs_VerifyObjectInDirectory(obj);
6787 parent = obj->parent;
6789 yaffs_VerifyDirectory(parent);
6791 if(dev && dev->removeObjectCallback)
6792 dev->removeObjectCallback(obj);
6795 ylist_del_init(&obj->siblings);
6798 yaffs_VerifyDirectory(parent);
6803 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
6808 T(YAFFS_TRACE_ALWAYS,
6810 ("tragedy: Trying to add an object to a null pointer directory"
6814 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6815 T(YAFFS_TRACE_ALWAYS,
6817 ("tragedy: Trying to add an object to a non-directory"
6822 if (obj->siblings.prev == NULL) {
6823 /* Not initialised */
6826 } else if (ylist_empty(&obj->siblings)) {
6831 yaffs_VerifyDirectory(directory);
6833 yaffs_RemoveObjectFromDirectory(obj);
6837 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
6838 obj->parent = directory;
6840 if (directory == obj->myDev->unlinkedDir
6841 || directory == obj->myDev->deletedDir) {
6843 obj->myDev->nUnlinkedFiles++;
6844 obj->renameAllowed = 0;
6847 yaffs_VerifyDirectory(directory);
6848 yaffs_VerifyObjectInDirectory(obj);
6853 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
6858 struct ylist_head *i;
6859 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
6868 T(YAFFS_TRACE_ALWAYS,
6870 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6874 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6875 T(YAFFS_TRACE_ALWAYS,
6877 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6881 sum = yaffs_CalcNameSum(name);
6883 ylist_for_each(i, &directory->variant.directoryVariant.children) {
6885 l = ylist_entry(i, yaffs_Object, siblings);
6887 if(l->parent != directory)
6890 yaffs_CheckObjectDetailsLoaded(l);
6892 /* Special case for lost-n-found */
6893 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6894 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
6897 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0){
6898 /* LostnFound chunk called Objxxx
6901 yaffs_GetObjectName(l, buffer,
6902 YAFFS_MAX_NAME_LENGTH);
6903 if (yaffs_strncmp(name, buffer,YAFFS_MAX_NAME_LENGTH) == 0) {
6916 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
6917 int (*fn) (yaffs_Object *))
6919 struct ylist_head *i;
6923 T(YAFFS_TRACE_ALWAYS,
6925 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6929 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6930 T(YAFFS_TRACE_ALWAYS,
6932 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6936 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
6938 l = ylist_entry(i, yaffs_Object, siblings);
6950 /* GetEquivalentObject dereferences any hard links to get to the
6954 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
6956 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
6957 /* We want the object id of the equivalent object, not this one */
6958 obj = obj->variant.hardLinkVariant.equivalentObject;
6959 yaffs_CheckObjectDetailsLoaded(obj);
6965 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
6967 memset(name, 0, buffSize * sizeof(YCHAR));
6969 yaffs_CheckObjectDetailsLoaded(obj);
6971 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6972 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
6973 } else if (obj->hdrChunk <= 0) {
6975 YCHAR numString[20];
6976 YCHAR *x = &numString[19];
6977 unsigned v = obj->objectId;
6981 *x = '0' + (v % 10);
6984 /* make up a name */
6985 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
6986 yaffs_strcat(locName,x);
6987 yaffs_strncpy(name, locName, buffSize - 1);
6990 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
6991 else if (obj->shortName[0]) {
6992 yaffs_strcpy(name, obj->shortName);
6997 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
6999 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
7001 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
7003 if (obj->hdrChunk > 0) {
7004 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
7005 obj->hdrChunk, buffer,
7008 yaffs_strncpy(name, oh->name, buffSize - 1);
7010 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
7013 return yaffs_strlen(name);
7016 int yaffs_GetObjectFileLength(yaffs_Object * obj)
7019 /* Dereference any hard linking */
7020 obj = yaffs_GetEquivalentObject(obj);
7022 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
7023 return obj->variant.fileVariant.fileSize;
7025 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
7026 return yaffs_strlen(obj->variant.symLinkVariant.alias);
7028 /* Only a directory should drop through to here */
7029 return obj->myDev->nDataBytesPerChunk;
7033 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
7036 struct ylist_head *i;
7038 if (!obj->unlinked) {
7039 count++; /* the object itself */
7041 ylist_for_each(i, &obj->hardLinks) {
7042 count++; /* add the hard links; */
7048 int yaffs_GetObjectInode(yaffs_Object * obj)
7050 obj = yaffs_GetEquivalentObject(obj);
7052 return obj->objectId;
7055 unsigned yaffs_GetObjectType(yaffs_Object * obj)
7057 obj = yaffs_GetEquivalentObject(obj);
7059 switch (obj->variantType) {
7060 case YAFFS_OBJECT_TYPE_FILE:
7063 case YAFFS_OBJECT_TYPE_DIRECTORY:
7066 case YAFFS_OBJECT_TYPE_SYMLINK:
7069 case YAFFS_OBJECT_TYPE_HARDLINK:
7072 case YAFFS_OBJECT_TYPE_SPECIAL:
7073 if (S_ISFIFO(obj->yst_mode))
7075 if (S_ISCHR(obj->yst_mode))
7077 if (S_ISBLK(obj->yst_mode))
7079 if (S_ISSOCK(obj->yst_mode))
7087 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
7089 obj = yaffs_GetEquivalentObject(obj);
7090 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
7091 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7093 return yaffs_CloneString(_Y(""));
7097 #ifndef CONFIG_YAFFS_WINCE
7099 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
7101 unsigned int valid = attr->ia_valid;
7103 if (valid & ATTR_MODE)
7104 obj->yst_mode = attr->ia_mode;
7105 if (valid & ATTR_UID)
7106 obj->yst_uid = attr->ia_uid;
7107 if (valid & ATTR_GID)
7108 obj->yst_gid = attr->ia_gid;
7110 if (valid & ATTR_ATIME)
7111 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7112 if (valid & ATTR_CTIME)
7113 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7114 if (valid & ATTR_MTIME)
7115 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7117 if (valid & ATTR_SIZE)
7118 yaffs_ResizeFile(obj, attr->ia_size);
7120 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7125 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
7127 unsigned int valid = 0;
7129 attr->ia_mode = obj->yst_mode;
7131 attr->ia_uid = obj->yst_uid;
7133 attr->ia_gid = obj->yst_gid;
7136 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7137 valid |= ATTR_ATIME;
7138 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7139 valid |= ATTR_CTIME;
7140 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7141 valid |= ATTR_MTIME;
7143 attr->ia_size = yaffs_GetFileSize(obj);
7146 attr->ia_valid = valid;
7155 int yaffs_DumpObject(yaffs_Object * obj)
7159 yaffs_GetObjectName(obj, name, 256);
7161 T(YAFFS_TRACE_ALWAYS,
7163 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7164 " chunk %d type %d size %d\n"
7165 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7166 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7167 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7173 /*---------------------------- Initialisation code -------------------------------------- */
7175 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
7178 /* Common functions, gotta have */
7179 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
7182 #ifdef CONFIG_YAFFS_YAFFS2
7184 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7185 if (dev->writeChunkWithTagsToNAND &&
7186 dev->readChunkWithTagsFromNAND &&
7187 !dev->writeChunkToNAND &&
7188 !dev->readChunkFromNAND &&
7189 dev->markNANDBlockBad && dev->queryNANDBlock)
7193 /* Can use the "spare" style interface for yaffs1 */
7194 if (!dev->isYaffs2 &&
7195 !dev->writeChunkWithTagsToNAND &&
7196 !dev->readChunkWithTagsFromNAND &&
7197 dev->writeChunkToNAND &&
7198 dev->readChunkFromNAND &&
7199 !dev->markNANDBlockBad && !dev->queryNANDBlock)
7206 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7208 /* Initialise the unlinked, deleted, root and lost and found directories */
7210 dev->lostNFoundDir = dev->rootDir = NULL;
7211 dev->unlinkedDir = dev->deletedDir = NULL;
7214 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7217 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7220 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7221 YAFFS_ROOT_MODE | S_IFDIR);
7222 dev->lostNFoundDir =
7223 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7224 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7226 if(dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir){
7227 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7234 int yaffs_GutsInitialise(yaffs_Device * dev)
7236 int init_failed = 0;
7240 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7242 /* Check stuff that must be set */
7245 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7249 dev->internalStartBlock = dev->startBlock;
7250 dev->internalEndBlock = dev->endBlock;
7251 dev->blockOffset = 0;
7252 dev->chunkOffset = 0;
7253 dev->nFreeChunks = 0;
7257 if (dev->startBlock == 0) {
7258 dev->internalStartBlock = dev->startBlock + 1;
7259 dev->internalEndBlock = dev->endBlock + 1;
7260 dev->blockOffset = 1;
7261 dev->chunkOffset = dev->nChunksPerBlock;
7264 /* Check geometry parameters. */
7266 if ((!dev->inbandTags && dev->isYaffs2 && dev->totalBytesPerChunk < 1024) ||
7267 (!dev->isYaffs2 && dev->totalBytesPerChunk < 512) ||
7268 (dev->inbandTags && !dev->isYaffs2 ) ||
7269 dev->nChunksPerBlock < 2 ||
7270 dev->nReservedBlocks < 2 ||
7271 dev->internalStartBlock <= 0 ||
7272 dev->internalEndBlock <= 0 ||
7273 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
7275 T(YAFFS_TRACE_ALWAYS,
7277 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7278 TENDSTR), dev->totalBytesPerChunk, dev->isYaffs2 ? "2" : "", dev->inbandTags));
7282 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7283 T(YAFFS_TRACE_ALWAYS,
7284 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7288 /* Sort out space for inband tags, if required */
7290 dev->nDataBytesPerChunk = dev->totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7292 dev->nDataBytesPerChunk = dev->totalBytesPerChunk;
7294 /* Got the right mix of functions? */
7295 if (!yaffs_CheckDevFunctions(dev)) {
7296 /* Function missing */
7297 T(YAFFS_TRACE_ALWAYS,
7299 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7304 /* This is really a compilation check. */
7305 if (!yaffs_CheckStructures()) {
7306 T(YAFFS_TRACE_ALWAYS,
7307 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7311 if (dev->isMounted) {
7312 T(YAFFS_TRACE_ALWAYS,
7313 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7317 /* Finished with most checks. One or two more checks happen later on too. */
7321 /* OK now calculate a few things for the device */
7324 * Calculate all the chunk size manipulation numbers:
7326 x = dev->nDataBytesPerChunk;
7327 /* We always use dev->chunkShift and dev->chunkDiv */
7328 dev->chunkShift = Shifts(x);
7329 x >>= dev->chunkShift;
7331 /* We only use chunk mask if chunkDiv is 1 */
7332 dev->chunkMask = (1<<dev->chunkShift) - 1;
7335 * Calculate chunkGroupBits.
7336 * We need to find the next power of 2 > than internalEndBlock
7339 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7343 /* Set up tnode width if wide tnodes are enabled. */
7344 if(!dev->wideTnodesDisabled){
7345 /* bits must be even so that we end up with 32-bit words */
7349 dev->tnodeWidth = 16;
7351 dev->tnodeWidth = bits;
7354 dev->tnodeWidth = 16;
7356 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7358 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7359 * so if the bitwidth of the
7360 * chunk range we're using is greater than 16 we need
7361 * to figure out chunk shift and chunkGroupSize
7364 if (bits <= dev->tnodeWidth)
7365 dev->chunkGroupBits = 0;
7367 dev->chunkGroupBits = bits - dev->tnodeWidth;
7370 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7372 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7373 /* We have a problem because the soft delete won't work if
7374 * the chunk group size > chunks per block.
7375 * This can be remedied by using larger "virtual blocks".
7377 T(YAFFS_TRACE_ALWAYS,
7378 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7383 /* OK, we've finished verifying the device, lets continue with initialisation */
7385 /* More device initialisation */
7386 dev->garbageCollections = 0;
7387 dev->passiveGarbageCollections = 0;
7388 dev->currentDirtyChecker = 0;
7389 dev->bufferedBlock = -1;
7390 dev->doingBufferedBlockRewrite = 0;
7391 dev->nDeletedFiles = 0;
7392 dev->nBackgroundDeletions = 0;
7393 dev->nUnlinkedFiles = 0;
7395 dev->eccUnfixed = 0;
7396 dev->tagsEccFixed = 0;
7397 dev->tagsEccUnfixed = 0;
7398 dev->nErasureFailures = 0;
7399 dev->nErasedBlocks = 0;
7401 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7403 /* Initialise temporary buffers and caches. */
7404 if(!yaffs_InitialiseTempBuffers(dev))
7407 dev->srCache = NULL;
7408 dev->gcCleanupList = NULL;
7412 dev->nShortOpCaches > 0) {
7415 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7417 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
7418 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7421 dev->srCache = YMALLOC(srCacheBytes);
7423 buf = (__u8 *) dev->srCache;
7426 memset(dev->srCache,0,srCacheBytes);
7428 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7429 dev->srCache[i].object = NULL;
7430 dev->srCache[i].lastUse = 0;
7431 dev->srCache[i].dirty = 0;
7432 dev->srCache[i].data = buf = YMALLOC_DMA(dev->totalBytesPerChunk);
7443 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7444 if(!dev->gcCleanupList)
7448 if (dev->isYaffs2) {
7449 dev->useHeaderFileSize = 1;
7451 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7454 yaffs_InitialiseTnodes(dev);
7455 yaffs_InitialiseObjects(dev);
7457 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7462 /* Now scan the flash. */
7463 if (dev->isYaffs2) {
7464 if(yaffs_CheckpointRestore(dev)) {
7465 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7466 T(YAFFS_TRACE_ALWAYS,
7467 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7470 /* Clean up the mess caused by an aborted checkpoint load
7471 * and scan backwards.
7473 yaffs_DeinitialiseBlocks(dev);
7474 yaffs_DeinitialiseTnodes(dev);
7475 yaffs_DeinitialiseObjects(dev);
7478 dev->nErasedBlocks = 0;
7479 dev->nFreeChunks = 0;
7480 dev->allocationBlock = -1;
7481 dev->allocationPage = -1;
7482 dev->nDeletedFiles = 0;
7483 dev->nUnlinkedFiles = 0;
7484 dev->nBackgroundDeletions = 0;
7485 dev->oldestDirtySequence = 0;
7487 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7490 yaffs_InitialiseTnodes(dev);
7491 yaffs_InitialiseObjects(dev);
7493 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7496 if(!init_failed && !yaffs_ScanBackwards(dev))
7500 if(!yaffs_Scan(dev))
7505 /* Clean up the mess */
7506 T(YAFFS_TRACE_TRACING,
7507 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7509 yaffs_Deinitialise(dev);
7513 /* Zero out stats */
7514 dev->nPageReads = 0;
7515 dev->nPageWrites = 0;
7516 dev->nBlockErasures = 0;
7518 dev->nRetriedWrites = 0;
7520 dev->nRetiredBlocks = 0;
7522 yaffs_VerifyFreeChunks(dev);
7523 yaffs_VerifyBlocks(dev);
7526 T(YAFFS_TRACE_TRACING,
7527 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7532 void yaffs_Deinitialise(yaffs_Device * dev)
7534 if (dev->isMounted) {
7537 yaffs_DeinitialiseBlocks(dev);
7538 yaffs_DeinitialiseTnodes(dev);
7539 yaffs_DeinitialiseObjects(dev);
7540 if (dev->nShortOpCaches > 0 &&
7543 for (i = 0; i < dev->nShortOpCaches; i++) {
7544 if(dev->srCache[i].data)
7545 YFREE(dev->srCache[i].data);
7546 dev->srCache[i].data = NULL;
7549 YFREE(dev->srCache);
7550 dev->srCache = NULL;
7553 YFREE(dev->gcCleanupList);
7555 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
7556 YFREE(dev->tempBuffer[i].buffer);
7562 if(dev->deinitialiseNAND)
7563 dev->deinitialiseNAND(dev);
7568 static int yaffs_CountFreeChunks(yaffs_Device * dev)
7573 yaffs_BlockInfo *blk;
7575 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7577 blk = yaffs_GetBlockInfo(dev, b);
7579 switch (blk->blockState) {
7580 case YAFFS_BLOCK_STATE_EMPTY:
7581 case YAFFS_BLOCK_STATE_ALLOCATING:
7582 case YAFFS_BLOCK_STATE_COLLECTING:
7583 case YAFFS_BLOCK_STATE_FULL:
7585 (dev->nChunksPerBlock - blk->pagesInUse +
7586 blk->softDeletions);
7597 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
7599 /* This is what we report to the outside world */
7602 int nDirtyCacheChunks;
7603 int blocksForCheckpoint;
7606 nFree = dev->nFreeChunks;
7608 nFree = yaffs_CountFreeChunks(dev);
7611 nFree += dev->nDeletedFiles;
7613 /* Now count the number of dirty chunks in the cache and subtract those */
7617 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7618 if (dev->srCache[i].dirty)
7619 nDirtyCacheChunks++;
7623 nFree -= nDirtyCacheChunks;
7625 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7627 /* Now we figure out how much to reserve for the checkpoint and report that... */
7628 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7629 if(blocksForCheckpoint < 0)
7630 blocksForCheckpoint = 0;
7632 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7641 static int yaffs_freeVerificationFailures;
7643 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
7648 if(yaffs_SkipVerification(dev))
7651 counted = yaffs_CountFreeChunks(dev);
7653 difference = dev->nFreeChunks - counted;
7656 T(YAFFS_TRACE_ALWAYS,
7657 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7658 dev->nFreeChunks, counted, difference));
7659 yaffs_freeVerificationFailures++;
7663 /*---------------------------------------- YAFFS test code ----------------------*/
7665 #define yaffs_CheckStruct(structure,syze, name) \
7667 if(sizeof(structure) != syze) \
7669 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
7670 name,syze,sizeof(structure))); \
7671 return YAFFS_FAIL; \
7675 static int yaffs_CheckStructures(void)
7677 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
7678 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
7679 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
7680 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7681 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode");
7683 #ifndef CONFIG_YAFFS_WINCE
7684 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");