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.
17 const char *yaffs_guts_c_version =
18 "$Id: yaffs_guts.c,v 1.52 2007/10/16 00:45:05 charles Exp $";
21 #include "linux/stat.h"
23 #include "yaffsinterface.h"
25 #include "yaffs_guts.h"
26 #include "yaffs_tagsvalidity.h"
28 #include "yaffs_tagscompat.h"
29 #ifndef CONFIG_YAFFS_USE_OWN_SORT
30 #include "yaffs_qsort.h"
32 #include "yaffs_nand.h"
34 #include "yaffs_checkptrw.h"
36 #include "yaffs_nand.h"
37 #include "yaffs_packedtags2.h"
41 #ifdef CONFIG_YAFFS_WINCE
42 void yfsd_LockYAFFS(BOOL fsLockOnly);
43 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
46 #define YAFFS_PASSIVE_GC_CHUNKS 2
48 #include "yaffs_ecc.h"
51 /* Robustification (if it ever comes about...) */
52 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
53 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk);
54 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
56 const yaffs_ExtendedTags * tags);
57 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
58 const yaffs_ExtendedTags * tags);
60 /* Other local prototypes */
61 static int yaffs_UnlinkObject( yaffs_Object *obj);
62 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
64 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
66 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
68 yaffs_ExtendedTags * tags,
70 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
71 int chunkInNAND, int inScan);
73 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
74 yaffs_ObjectType type);
75 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
77 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
78 int force, int isShrink, int shadows);
79 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
80 static int yaffs_CheckStructures(void);
81 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
82 int chunkOffset, int *limit);
83 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
85 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
87 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo);
88 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
91 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
94 static int yaffs_UnlinkWorker(yaffs_Object * obj);
95 static void yaffs_DestroyObject(yaffs_Object * obj);
97 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
100 loff_t yaffs_GetFileSize(yaffs_Object * obj);
102 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr);
104 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
106 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
108 #ifdef YAFFS_PARANOID
109 static int yaffs_CheckFileSanity(yaffs_Object * in);
111 #define yaffs_CheckFileSanity(in)
114 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
115 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
117 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
119 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
120 yaffs_ExtendedTags * tags);
122 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos);
123 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
124 yaffs_FileStructure * fStruct,
128 /* Function to calculate chunk and offset */
130 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, __u32 *chunk, __u32 *offset)
133 /* Easy-peasy power of 2 case */
134 *chunk = (__u32)(addr >> dev->chunkShift);
135 *offset = (__u32)(addr & dev->chunkMask);
137 else if(dev->crumbsPerChunk)
139 /* Case where we're using "crumbs" */
140 *offset = (__u32)(addr & dev->crumbMask);
141 addr >>= dev->crumbShift;
142 *chunk = ((__u32)addr)/dev->crumbsPerChunk;
143 *offset += ((addr - (*chunk * dev->crumbsPerChunk)) << dev->crumbShift);
149 /* Function to return the number of shifts for a power of 2 greater than or equal
150 * to the given number
151 * Note we don't try to cater for all possible numbers and this does not have to
152 * be hellishly efficient.
155 static __u32 ShiftsGE(__u32 x)
160 nShifts = extraBits = 0;
163 if(x & 1) extraBits++;
174 /* Function to return the number of shifts to get a 1 in bit 0
177 static __u32 ShiftDiv(__u32 x)
196 * Temporary buffer manipulations.
199 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
202 __u8 *buf = (__u8 *)1;
204 memset(dev->tempBuffer,0,sizeof(dev->tempBuffer));
206 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
207 dev->tempBuffer[i].line = 0; /* not in use */
208 dev->tempBuffer[i].buffer = buf =
209 YMALLOC_DMA(dev->nDataBytesPerChunk);
212 return buf ? YAFFS_OK : YAFFS_FAIL;
216 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
219 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
220 if (dev->tempBuffer[i].line == 0) {
221 dev->tempBuffer[i].line = lineNo;
222 if ((i + 1) > dev->maxTemp) {
223 dev->maxTemp = i + 1;
224 for (j = 0; j <= i; j++)
225 dev->tempBuffer[j].maxLine =
226 dev->tempBuffer[j].line;
229 return dev->tempBuffer[i].buffer;
233 T(YAFFS_TRACE_BUFFERS,
234 (TSTR("Out of temp buffers at line %d, other held by lines:"),
236 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
237 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
239 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
242 * If we got here then we have to allocate an unmanaged one
246 dev->unmanagedTempAllocations++;
247 return YMALLOC(dev->nDataBytesPerChunk);
251 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
255 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
256 if (dev->tempBuffer[i].buffer == buffer) {
257 dev->tempBuffer[i].line = 0;
263 /* assume it is an unmanaged one. */
264 T(YAFFS_TRACE_BUFFERS,
265 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
268 dev->unmanagedTempDeallocations++;
274 * Determine if we have a managed buffer.
276 int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
279 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
280 if (dev->tempBuffer[i].buffer == buffer)
285 for (i = 0; i < dev->nShortOpCaches; i++) {
286 if( dev->srCache[i].data == buffer )
291 if (buffer == dev->checkpointBuffer)
294 T(YAFFS_TRACE_ALWAYS,
295 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
302 * Chunk bitmap manipulations
305 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
307 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
309 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
313 return dev->chunkBits +
314 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
317 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
319 if(blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
320 chunk < 0 || chunk >= dev->nChunksPerBlock) {
322 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),blk,chunk));
327 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
329 __u8 *blkBits = yaffs_BlockBits(dev, blk);
331 memset(blkBits, 0, dev->chunkBitmapStride);
334 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
336 __u8 *blkBits = yaffs_BlockBits(dev, blk);
338 yaffs_VerifyChunkBitId(dev,blk,chunk);
340 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
343 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
345 __u8 *blkBits = yaffs_BlockBits(dev, blk);
347 yaffs_VerifyChunkBitId(dev,blk,chunk);
349 blkBits[chunk / 8] |= (1 << (chunk & 7));
352 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
354 __u8 *blkBits = yaffs_BlockBits(dev, blk);
355 yaffs_VerifyChunkBitId(dev,blk,chunk);
357 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
360 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
362 __u8 *blkBits = yaffs_BlockBits(dev, blk);
364 for (i = 0; i < dev->chunkBitmapStride; i++) {
372 static int yaffs_CountChunkBits(yaffs_Device * dev, int blk)
374 __u8 *blkBits = yaffs_BlockBits(dev, blk);
377 for (i = 0; i < dev->chunkBitmapStride; i++) {
394 static int yaffs_SkipVerification(yaffs_Device *dev)
396 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
399 static int yaffs_SkipFullVerification(yaffs_Device *dev)
401 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
404 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
406 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
409 static const char * blockStateName[] = {
422 static void yaffs_VerifyBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
427 if(yaffs_SkipVerification(dev))
430 /* Report illegal runtime states */
431 if(bi->blockState <0 || bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
432 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has undefined state %d"TENDSTR),n,bi->blockState));
434 switch(bi->blockState){
435 case YAFFS_BLOCK_STATE_UNKNOWN:
436 case YAFFS_BLOCK_STATE_SCANNING:
437 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
438 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has bad run-state %s"TENDSTR),
439 n,blockStateName[bi->blockState]));
442 /* Check pages in use and soft deletions are legal */
444 actuallyUsed = bi->pagesInUse - bi->softDeletions;
446 if(bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
447 bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
448 actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock)
449 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
450 n,bi->pagesInUse,bi->softDeletions));
453 /* Check chunk bitmap legal */
454 inUse = yaffs_CountChunkBits(dev,n);
455 if(inUse != bi->pagesInUse)
456 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
457 n,bi->pagesInUse,inUse));
459 /* Check that the sequence number is valid.
460 * Ten million is legal, but is very unlikely
463 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
464 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000 ))
465 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has suspect sequence number of %d"TENDSTR),
466 n,bi->sequenceNumber));
470 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
472 yaffs_VerifyBlock(dev,bi,n);
474 /* After collection the block should be in the erased state */
475 /* TODO: This will need to change if we do partial gc */
477 if(bi->blockState != YAFFS_BLOCK_STATE_EMPTY){
478 T(YAFFS_TRACE_ERROR,(TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
483 static void yaffs_VerifyBlocks(yaffs_Device *dev)
486 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
487 int nIllegalBlockStates = 0;
490 if(yaffs_SkipVerification(dev))
493 memset(nBlocksPerState,0,sizeof(nBlocksPerState));
496 for(i = dev->internalStartBlock; i <= dev->internalEndBlock; i++){
497 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
498 yaffs_VerifyBlock(dev,bi,i);
500 if(bi->blockState >=0 && bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
501 nBlocksPerState[bi->blockState]++;
503 nIllegalBlockStates++;
507 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
508 T(YAFFS_TRACE_VERIFY,(TSTR("Block summary"TENDSTR)));
510 T(YAFFS_TRACE_VERIFY,(TSTR("%d blocks have illegal states"TENDSTR),nIllegalBlockStates));
511 if(nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
512 T(YAFFS_TRACE_VERIFY,(TSTR("Too many allocating blocks"TENDSTR)));
514 for(i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
515 T(YAFFS_TRACE_VERIFY,
516 (TSTR("%s %d blocks"TENDSTR),
517 blockStateName[i],nBlocksPerState[i]));
519 if(dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
520 T(YAFFS_TRACE_VERIFY,
521 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
522 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
524 if(dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
525 T(YAFFS_TRACE_VERIFY,
526 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
527 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
529 if(nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
530 T(YAFFS_TRACE_VERIFY,
531 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
532 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
534 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
539 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
540 * case those tests will not be performed.
542 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
544 if(yaffs_SkipVerification(obj->myDev))
547 if(!(tags && obj && oh)){
548 T(YAFFS_TRACE_VERIFY,
549 (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR),
550 (__u32)tags,(__u32)obj,(__u32)oh));
554 if(oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
555 oh->type > YAFFS_OBJECT_TYPE_MAX)
556 T(YAFFS_TRACE_VERIFY,
557 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
558 tags->objectId, oh->type));
560 if(tags->objectId != obj->objectId)
561 T(YAFFS_TRACE_VERIFY,
562 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
563 tags->objectId, obj->objectId));
567 * Check that the object's parent ids match if parentCheck requested.
569 * Tests do not apply to the root object.
572 if(parentCheck && tags->objectId > 1 && !obj->parent)
573 T(YAFFS_TRACE_VERIFY,
574 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
575 tags->objectId, oh->parentObjectId));
578 if(parentCheck && obj->parent &&
579 oh->parentObjectId != obj->parent->objectId &&
580 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
581 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
582 T(YAFFS_TRACE_VERIFY,
583 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
584 tags->objectId, oh->parentObjectId, obj->parent->objectId));
587 if(tags->objectId > 1 && oh->name[0] == 0) /* Null name */
588 T(YAFFS_TRACE_VERIFY,
589 (TSTR("Obj %d header name is NULL"TENDSTR),
592 if(tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
593 T(YAFFS_TRACE_VERIFY,
594 (TSTR("Obj %d header name is 0xFF"TENDSTR),
600 static int yaffs_VerifyTnodeWorker(yaffs_Object * obj, yaffs_Tnode * tn,
601 __u32 level, int chunkOffset)
604 yaffs_Device *dev = obj->myDev;
610 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
611 if (tn->internal[i]) {
612 ok = yaffs_VerifyTnodeWorker(obj,
615 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
618 } else if (level == 0) {
620 yaffs_ExtendedTags tags;
621 __u32 objectId = obj->objectId;
623 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
625 for(i = 0; i < YAFFS_NTNODES_LEVEL0; i++){
626 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
629 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
630 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
631 if(tags.objectId != objectId || tags.chunkId != chunkOffset){
632 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
633 objectId, chunkOffset, theChunk,
634 tags.objectId, tags.chunkId));
647 static void yaffs_VerifyFile(yaffs_Object *obj)
649 int requiredTallness;
655 yaffs_ExtendedTags tags;
659 if(obj && yaffs_SkipVerification(obj->myDev))
663 objectId = obj->objectId;
665 /* Check file size is consistent with tnode depth */
666 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
667 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
668 requiredTallness = 0;
670 x >>= YAFFS_TNODES_INTERNAL_BITS;
674 actualTallness = obj->variant.fileVariant.topLevel;
676 if(requiredTallness > actualTallness )
677 T(YAFFS_TRACE_VERIFY,
678 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
679 obj->objectId,actualTallness, requiredTallness));
682 /* Check that the chunks in the tnode tree are all correct.
683 * We do this by scanning through the tnode tree and
684 * checking the tags for every chunk match.
687 if(yaffs_SkipNANDVerification(dev))
690 for(i = 1; i <= lastChunk; i++){
691 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant,i);
694 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
696 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
697 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
698 if(tags.objectId != objectId || tags.chunkId != i){
699 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
700 objectId, i, theChunk,
701 tags.objectId, tags.chunkId));
710 static void yaffs_VerifyDirectory(yaffs_Object *obj)
712 if(obj && yaffs_SkipVerification(obj->myDev))
717 static void yaffs_VerifyHardLink(yaffs_Object *obj)
719 if(obj && yaffs_SkipVerification(obj->myDev))
722 /* Verify sane equivalent object */
725 static void yaffs_VerifySymlink(yaffs_Object *obj)
727 if(obj && yaffs_SkipVerification(obj->myDev))
730 /* Verify symlink string */
733 static void yaffs_VerifySpecial(yaffs_Object *obj)
735 if(obj && yaffs_SkipVerification(obj->myDev))
739 static void yaffs_VerifyObject(yaffs_Object *obj)
754 if(yaffs_SkipVerification(dev))
757 /* Check sane object header chunk */
759 chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
760 chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
762 chunkIdOk = (obj->chunkId >= chunkMin && obj->chunkId <= chunkMax);
763 chunkIsLive = chunkIdOk &&
764 yaffs_CheckChunkBit(dev,
765 obj->chunkId / dev->nChunksPerBlock,
766 obj->chunkId % dev->nChunksPerBlock);
768 (!chunkIdOk || !chunkIsLive)) {
769 T(YAFFS_TRACE_VERIFY,
770 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
771 obj->objectId,obj->chunkId,
772 chunkIdOk ? "" : ",out of range",
773 chunkIsLive || !chunkIdOk ? "" : ",marked as deleted"));
776 if(chunkIdOk && chunkIsLive &&!yaffs_SkipNANDVerification(dev)) {
777 yaffs_ExtendedTags tags;
778 yaffs_ObjectHeader *oh;
779 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
781 oh = (yaffs_ObjectHeader *)buffer;
783 yaffs_ReadChunkWithTagsFromNAND(dev, obj->chunkId,buffer, &tags);
785 yaffs_VerifyObjectHeader(obj,oh,&tags,1);
787 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
790 /* Verify it has a parent */
791 if(obj && !obj->fake &&
792 (!obj->parent || obj->parent->myDev != dev)){
793 T(YAFFS_TRACE_VERIFY,
794 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
795 obj->objectId,obj->parent));
798 /* Verify parent is a directory */
799 if(obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
800 T(YAFFS_TRACE_VERIFY,
801 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
802 obj->objectId,obj->parent->variantType));
805 switch(obj->variantType){
806 case YAFFS_OBJECT_TYPE_FILE:
807 yaffs_VerifyFile(obj);
809 case YAFFS_OBJECT_TYPE_SYMLINK:
810 yaffs_VerifySymlink(obj);
812 case YAFFS_OBJECT_TYPE_DIRECTORY:
813 yaffs_VerifyDirectory(obj);
815 case YAFFS_OBJECT_TYPE_HARDLINK:
816 yaffs_VerifyHardLink(obj);
818 case YAFFS_OBJECT_TYPE_SPECIAL:
819 yaffs_VerifySpecial(obj);
821 case YAFFS_OBJECT_TYPE_UNKNOWN:
823 T(YAFFS_TRACE_VERIFY,
824 (TSTR("Obj %d has illegaltype %d"TENDSTR),
825 obj->objectId,obj->variantType));
832 static void yaffs_VerifyObjects(yaffs_Device *dev)
836 struct list_head *lh;
838 if(yaffs_SkipVerification(dev))
841 /* Iterate through the objects in each hash entry */
843 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++){
844 list_for_each(lh, &dev->objectBucket[i].list) {
846 obj = list_entry(lh, yaffs_Object, hashLink);
847 yaffs_VerifyObject(obj);
856 * Simple hash function. Needs to have a reasonable spread
859 static Y_INLINE int yaffs_HashFunction(int n)
865 return (n % YAFFS_NOBJECT_BUCKETS);
869 * Access functions to useful fake objects
872 yaffs_Object *yaffs_Root(yaffs_Device * dev)
877 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
879 return dev->lostNFoundDir;
884 * Erased NAND checking functions
887 int yaffs_CheckFF(__u8 * buffer, int nBytes)
889 /* Horrible, slow implementation */
898 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
902 int retval = YAFFS_OK;
903 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
904 yaffs_ExtendedTags tags;
907 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
909 if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
913 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
914 T(YAFFS_TRACE_NANDACCESS,
915 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
919 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
925 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
927 yaffs_ExtendedTags * tags,
934 yaffs_InvalidateCheckpoint(dev);
937 yaffs_BlockInfo *bi = 0;
940 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
946 /* First check this chunk is erased, if it needs
947 * checking. The checking policy (unless forced
948 * always on) is as follows:
950 * Check the first page we try to write in a block.
951 * If the check passes then we don't need to check any
952 * more. If the check fails, we check again...
953 * If the block has been erased, we don't need to check.
955 * However, if the block has been prioritised for gc,
956 * then we think there might be something odd about
957 * this block and stop using it.
959 * Rationale: We should only ever see chunks that have
960 * not been erased if there was a partially written
961 * chunk due to power loss. This checking policy should
962 * catch that case with very few checks and thus save a
963 * lot of checks that are most likely not needed.
965 if (bi->gcPrioritise) {
966 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
967 /* try another chunk */
971 /* let's give it a try */
974 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
975 bi->skipErasedCheck = 0;
977 if (!bi->skipErasedCheck) {
978 erasedOk = yaffs_CheckChunkErased(dev, chunk);
979 if (erasedOk != YAFFS_OK) {
981 (TSTR ("**>> yaffs chunk %d was not erased"
984 /* try another chunk */
987 bi->skipErasedCheck = 1;
990 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
992 if (writeOk != YAFFS_OK) {
993 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
994 /* try another chunk */
998 /* Copy the data into the robustification buffer */
999 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1001 } while (writeOk != YAFFS_OK &&
1002 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1008 T(YAFFS_TRACE_ERROR,
1009 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1012 dev->nRetriedWrites += (attempts - 1);
1019 * Block retiring for handling a broken block.
1022 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
1024 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1026 yaffs_InvalidateCheckpoint(dev);
1028 yaffs_MarkBlockBad(dev, blockInNAND);
1030 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1031 bi->gcPrioritise = 0;
1032 bi->needsRetiring = 0;
1034 dev->nRetiredBlocks++;
1038 * Functions for robustisizing TODO
1042 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
1044 const yaffs_ExtendedTags * tags)
1048 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
1049 const yaffs_ExtendedTags * tags)
1053 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1055 if(!bi->gcPrioritise){
1056 bi->gcPrioritise = 1;
1057 dev->hasPendingPrioritisedGCs = 1;
1058 bi->chunkErrorStrikes ++;
1060 if(bi->chunkErrorStrikes > 3){
1061 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1062 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1069 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
1072 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1073 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1075 yaffs_HandleChunkError(dev,bi);
1079 /* Was an actual write failure, so mark the block for retirement */
1080 bi->needsRetiring = 1;
1081 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1082 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1087 /* Delete the chunk */
1088 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1092 /*---------------- Name handling functions ------------*/
1094 static __u16 yaffs_CalcNameSum(const YCHAR * name)
1099 YUCHAR *bname = (YUCHAR *) name;
1101 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1103 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1104 sum += yaffs_toupper(*bname) * i;
1106 sum += (*bname) * i;
1115 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
1117 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1118 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
1119 yaffs_strcpy(obj->shortName, name);
1121 obj->shortName[0] = _Y('\0');
1124 obj->sum = yaffs_CalcNameSum(name);
1127 /*-------------------- TNODES -------------------
1129 * List of spare tnodes
1130 * The list is hooked together using the first pointer
1134 /* yaffs_CreateTnodes creates a bunch more tnodes and
1135 * adds them to the tnode free list.
1136 * Don't use this function directly
1139 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
1143 yaffs_Tnode *newTnodes;
1147 yaffs_TnodeList *tnl;
1152 /* Calculate the tnode size in bytes for variable width tnode support.
1153 * Must be a multiple of 32-bits */
1154 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1156 /* make these things */
1158 newTnodes = YMALLOC(nTnodes * tnodeSize);
1159 mem = (__u8 *)newTnodes;
1162 T(YAFFS_TRACE_ERROR,
1163 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1167 /* Hook them into the free list */
1169 for (i = 0; i < nTnodes - 1; i++) {
1170 newTnodes[i].internal[0] = &newTnodes[i + 1];
1171 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1172 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1176 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1177 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1178 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1180 dev->freeTnodes = newTnodes;
1182 /* New hookup for wide tnodes */
1183 for(i = 0; i < nTnodes -1; i++) {
1184 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1185 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1186 curr->internal[0] = next;
1189 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1190 curr->internal[0] = dev->freeTnodes;
1191 dev->freeTnodes = (yaffs_Tnode *)mem;
1196 dev->nFreeTnodes += nTnodes;
1197 dev->nTnodesCreated += nTnodes;
1199 /* Now add this bunch of tnodes to a list for freeing up.
1200 * NB If we can't add this to the management list it isn't fatal
1201 * but it just means we can't free this bunch of tnodes later.
1204 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1206 T(YAFFS_TRACE_ERROR,
1208 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1212 tnl->tnodes = newTnodes;
1213 tnl->next = dev->allocatedTnodeList;
1214 dev->allocatedTnodeList = tnl;
1217 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1222 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1224 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
1226 yaffs_Tnode *tn = NULL;
1228 /* If there are none left make more */
1229 if (!dev->freeTnodes) {
1230 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1233 if (dev->freeTnodes) {
1234 tn = dev->freeTnodes;
1235 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1236 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1237 /* Hoosterman, this thing looks like it isn't in the list */
1238 T(YAFFS_TRACE_ALWAYS,
1239 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1242 dev->freeTnodes = dev->freeTnodes->internal[0];
1249 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
1251 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1254 memset(tn, 0, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1259 /* FreeTnode frees up a tnode and puts it back on the free list */
1260 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
1263 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1264 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1265 /* Hoosterman, this thing looks like it is already in the list */
1266 T(YAFFS_TRACE_ALWAYS,
1267 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1269 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1271 tn->internal[0] = dev->freeTnodes;
1272 dev->freeTnodes = tn;
1277 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
1279 /* Free the list of allocated tnodes */
1280 yaffs_TnodeList *tmp;
1282 while (dev->allocatedTnodeList) {
1283 tmp = dev->allocatedTnodeList->next;
1285 YFREE(dev->allocatedTnodeList->tnodes);
1286 YFREE(dev->allocatedTnodeList);
1287 dev->allocatedTnodeList = tmp;
1291 dev->freeTnodes = NULL;
1292 dev->nFreeTnodes = 0;
1295 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
1297 dev->allocatedTnodeList = NULL;
1298 dev->freeTnodes = NULL;
1299 dev->nFreeTnodes = 0;
1300 dev->nTnodesCreated = 0;
1305 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
1307 __u32 *map = (__u32 *)tn;
1313 pos &= YAFFS_TNODES_LEVEL0_MASK;
1314 val >>= dev->chunkGroupBits;
1316 bitInMap = pos * dev->tnodeWidth;
1317 wordInMap = bitInMap /32;
1318 bitInWord = bitInMap & (32 -1);
1320 mask = dev->tnodeMask << bitInWord;
1322 map[wordInMap] &= ~mask;
1323 map[wordInMap] |= (mask & (val << bitInWord));
1325 if(dev->tnodeWidth > (32-bitInWord)) {
1326 bitInWord = (32 - bitInWord);
1328 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1329 map[wordInMap] &= ~mask;
1330 map[wordInMap] |= (mask & (val >> bitInWord));
1334 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
1336 __u32 *map = (__u32 *)tn;
1342 pos &= YAFFS_TNODES_LEVEL0_MASK;
1344 bitInMap = pos * dev->tnodeWidth;
1345 wordInMap = bitInMap /32;
1346 bitInWord = bitInMap & (32 -1);
1348 val = map[wordInMap] >> bitInWord;
1350 if(dev->tnodeWidth > (32-bitInWord)) {
1351 bitInWord = (32 - bitInWord);
1353 val |= (map[wordInMap] << bitInWord);
1356 val &= dev->tnodeMask;
1357 val <<= dev->chunkGroupBits;
1362 /* ------------------- End of individual tnode manipulation -----------------*/
1364 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1365 * The look up tree is represented by the top tnode and the number of topLevel
1366 * in the tree. 0 means only the level 0 tnode is in the tree.
1369 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1370 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
1371 yaffs_FileStructure * fStruct,
1375 yaffs_Tnode *tn = fStruct->top;
1377 int requiredTallness;
1378 int level = fStruct->topLevel;
1380 /* Check sane level and chunk Id */
1381 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
1385 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1389 /* First check we're tall enough (ie enough topLevel) */
1391 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1392 requiredTallness = 0;
1394 i >>= YAFFS_TNODES_INTERNAL_BITS;
1398 if (requiredTallness > fStruct->topLevel) {
1399 /* Not tall enough, so we can't find it, return NULL. */
1403 /* Traverse down to level 0 */
1404 while (level > 0 && tn) {
1406 internal[(chunkId >>
1407 ( YAFFS_TNODES_LEVEL0_BITS +
1409 YAFFS_TNODES_INTERNAL_BITS)
1411 YAFFS_TNODES_INTERNAL_MASK];
1419 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1420 * This happens in two steps:
1421 * 1. If the tree isn't tall enough, then make it taller.
1422 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1424 * Used when modifying the tree.
1426 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1427 * be plugged into the ttree.
1430 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
1431 yaffs_FileStructure * fStruct,
1433 yaffs_Tnode *passedTn)
1436 int requiredTallness;
1444 /* Check sane level and page Id */
1445 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
1449 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1453 /* First check we're tall enough (ie enough topLevel) */
1455 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1456 requiredTallness = 0;
1458 x >>= YAFFS_TNODES_INTERNAL_BITS;
1463 if (requiredTallness > fStruct->topLevel) {
1464 /* Not tall enough,gotta make the tree taller */
1465 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1467 tn = yaffs_GetTnode(dev);
1470 tn->internal[0] = fStruct->top;
1473 T(YAFFS_TRACE_ERROR,
1474 (TSTR("yaffs: no more tnodes" TENDSTR)));
1478 fStruct->topLevel = requiredTallness;
1481 /* Traverse down to level 0, adding anything we need */
1483 l = fStruct->topLevel;
1487 while (l > 0 && tn) {
1489 ( YAFFS_TNODES_LEVEL0_BITS +
1490 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1491 YAFFS_TNODES_INTERNAL_MASK;
1494 if((l>1) && !tn->internal[x]){
1495 /* Add missing non-level-zero tnode */
1496 tn->internal[x] = yaffs_GetTnode(dev);
1499 /* Looking from level 1 at level 0 */
1501 /* If we already have one, then release it.*/
1503 yaffs_FreeTnode(dev,tn->internal[x]);
1504 tn->internal[x] = passedTn;
1506 } else if(!tn->internal[x]) {
1507 /* Don't have one, none passed in */
1508 tn->internal[x] = yaffs_GetTnode(dev);
1512 tn = tn->internal[x];
1516 /* top is level 0 */
1518 memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1519 yaffs_FreeTnode(dev,passedTn);
1526 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1527 yaffs_ExtendedTags * tags, int objectId,
1532 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1533 if (yaffs_CheckChunkBit
1534 (dev, theChunk / dev->nChunksPerBlock,
1535 theChunk % dev->nChunksPerBlock)) {
1536 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1538 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1550 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1551 * chunks and tnodes in the file
1552 * Returns 1 if the tree was deleted.
1553 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1556 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1557 int chunkOffset, int *limit)
1562 yaffs_ExtendedTags tags;
1564 yaffs_Device *dev = in->myDev;
1571 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1573 if (tn->internal[i]) {
1574 if (limit && (*limit) < 0) {
1578 yaffs_DeleteWorker(in,
1586 YAFFS_TNODES_INTERNAL_BITS)
1591 yaffs_FreeTnode(dev,
1594 tn->internal[i] = NULL;
1599 return (allDone) ? 1 : 0;
1600 } else if (level == 0) {
1603 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1605 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1610 YAFFS_TNODES_LEVEL0_BITS) + i;
1613 yaffs_FindChunkInGroup(dev,
1619 if (foundChunk > 0) {
1620 yaffs_DeleteChunk(dev,
1625 *limit = *limit - 1;
1633 yaffs_PutLevel0Tnode(dev,tn,i,0);
1637 return (i < 0) ? 1 : 0;
1647 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1650 yaffs_BlockInfo *theBlock;
1652 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1654 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1656 theBlock->softDeletions++;
1661 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1662 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1664 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1667 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1668 __u32 level, int chunkOffset)
1673 yaffs_Device *dev = in->myDev;
1678 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1680 if (tn->internal[i]) {
1682 yaffs_SoftDeleteWorker(in,
1688 YAFFS_TNODES_INTERNAL_BITS)
1691 yaffs_FreeTnode(dev,
1694 tn->internal[i] = NULL;
1696 /* Hoosterman... how could this happen? */
1700 return (allDone) ? 1 : 0;
1701 } else if (level == 0) {
1703 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1704 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1706 /* Note this does not find the real chunk, only the chunk group.
1707 * We make an assumption that a chunk group is not larger than
1710 yaffs_SoftDeleteChunk(dev, theChunk);
1711 yaffs_PutLevel0Tnode(dev,tn,i,0);
1725 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1728 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1729 if (obj->nDataChunks <= 0) {
1730 /* Empty file with no duplicate object headers, just delete it immediately */
1731 yaffs_FreeTnode(obj->myDev,
1732 obj->variant.fileVariant.top);
1733 obj->variant.fileVariant.top = NULL;
1734 T(YAFFS_TRACE_TRACING,
1735 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1737 yaffs_DoGenericObjectDeletion(obj);
1739 yaffs_SoftDeleteWorker(obj,
1740 obj->variant.fileVariant.top,
1741 obj->variant.fileVariant.
1743 obj->softDeleted = 1;
1748 /* Pruning removes any part of the file structure tree that is beyond the
1749 * bounds of the file (ie that does not point to chunks).
1751 * A file should only get pruned when its size is reduced.
1753 * Before pruning, the chunks must be pulled from the tree and the
1754 * level 0 tnode entries must be zeroed out.
1755 * Could also use this for file deletion, but that's probably better handled
1756 * by a special case.
1759 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1760 __u32 level, int del0)
1768 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1769 if (tn->internal[i] && level > 0) {
1771 yaffs_PruneWorker(dev, tn->internal[i],
1773 (i == 0) ? del0 : 1);
1776 if (tn->internal[i]) {
1781 if (hasData == 0 && del0) {
1782 /* Free and return NULL */
1784 yaffs_FreeTnode(dev, tn);
1794 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1795 yaffs_FileStructure * fStruct)
1802 if (fStruct->topLevel > 0) {
1804 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1806 /* Now we have a tree with all the non-zero branches NULL but the height
1807 * is the same as it was.
1808 * Let's see if we can trim internal tnodes to shorten the tree.
1809 * We can do this if only the 0th element in the tnode is in use
1810 * (ie all the non-zero are NULL)
1813 while (fStruct->topLevel && !done) {
1817 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1818 if (tn->internal[i]) {
1824 fStruct->top = tn->internal[0];
1825 fStruct->topLevel--;
1826 yaffs_FreeTnode(dev, tn);
1836 /*-------------------- End of File Structure functions.-------------------*/
1838 /* yaffs_CreateFreeObjects creates a bunch more objects and
1839 * adds them to the object free list.
1841 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1844 yaffs_Object *newObjects;
1845 yaffs_ObjectList *list;
1850 /* make these things */
1851 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1852 list = YMALLOC(sizeof(yaffs_ObjectList));
1854 if (!newObjects || !list) {
1859 T(YAFFS_TRACE_ALLOCATE,
1860 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1864 /* Hook them into the free list */
1865 for (i = 0; i < nObjects - 1; i++) {
1866 newObjects[i].siblings.next =
1867 (struct list_head *)(&newObjects[i + 1]);
1870 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1871 dev->freeObjects = newObjects;
1872 dev->nFreeObjects += nObjects;
1873 dev->nObjectsCreated += nObjects;
1875 /* Now add this bunch of Objects to a list for freeing up. */
1877 list->objects = newObjects;
1878 list->next = dev->allocatedObjectList;
1879 dev->allocatedObjectList = list;
1885 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1886 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1888 yaffs_Object *tn = NULL;
1890 /* If there are none left make more */
1891 if (!dev->freeObjects) {
1892 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1895 if (dev->freeObjects) {
1896 tn = dev->freeObjects;
1898 (yaffs_Object *) (dev->freeObjects->siblings.next);
1899 dev->nFreeObjects--;
1901 /* Now sweeten it up... */
1903 memset(tn, 0, sizeof(yaffs_Object));
1906 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1907 INIT_LIST_HEAD(&(tn->hardLinks));
1908 INIT_LIST_HEAD(&(tn->hashLink));
1909 INIT_LIST_HEAD(&tn->siblings);
1911 /* Add it to the lost and found directory.
1912 * NB Can't put root or lostNFound in lostNFound so
1913 * check if lostNFound exists first
1915 if (dev->lostNFoundDir) {
1916 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1923 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1928 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1930 obj->fake = 1; /* it is fake so it has no NAND presence... */
1931 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1932 obj->unlinkAllowed = 0; /* ... or unlink it */
1935 obj->yst_mode = mode;
1937 obj->chunkId = 0; /* Not a valid chunk. */
1944 static void yaffs_UnhashObject(yaffs_Object * tn)
1947 yaffs_Device *dev = tn->myDev;
1949 /* If it is still linked into the bucket list, free from the list */
1950 if (!list_empty(&tn->hashLink)) {
1951 list_del_init(&tn->hashLink);
1952 bucket = yaffs_HashFunction(tn->objectId);
1953 dev->objectBucket[bucket].count--;
1958 /* FreeObject frees up a Object and puts it back on the free list */
1959 static void yaffs_FreeObject(yaffs_Object * tn)
1962 yaffs_Device *dev = tn->myDev;
1964 /* XXX U-BOOT XXX */
1968 /* We're still hooked up to a cached inode.
1969 * Don't delete now, but mark for later deletion
1971 tn->deferedFree = 1;
1976 yaffs_UnhashObject(tn);
1978 /* Link into the free list. */
1979 tn->siblings.next = (struct list_head *)(dev->freeObjects);
1980 dev->freeObjects = tn;
1981 dev->nFreeObjects++;
1984 /* XXX U-BOOT XXX */
1988 void yaffs_HandleDeferedFree(yaffs_Object * obj)
1990 if (obj->deferedFree) {
1991 yaffs_FreeObject(obj);
1998 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
2000 /* Free the list of allocated Objects */
2002 yaffs_ObjectList *tmp;
2004 while (dev->allocatedObjectList) {
2005 tmp = dev->allocatedObjectList->next;
2006 YFREE(dev->allocatedObjectList->objects);
2007 YFREE(dev->allocatedObjectList);
2009 dev->allocatedObjectList = tmp;
2012 dev->freeObjects = NULL;
2013 dev->nFreeObjects = 0;
2016 static void yaffs_InitialiseObjects(yaffs_Device * dev)
2020 dev->allocatedObjectList = NULL;
2021 dev->freeObjects = NULL;
2022 dev->nFreeObjects = 0;
2024 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2025 INIT_LIST_HEAD(&dev->objectBucket[i].list);
2026 dev->objectBucket[i].count = 0;
2031 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
2036 int lowest = 999999;
2038 /* First let's see if we can find one that's empty. */
2040 for (i = 0; i < 10 && lowest > 0; i++) {
2042 x %= YAFFS_NOBJECT_BUCKETS;
2043 if (dev->objectBucket[x].count < lowest) {
2044 lowest = dev->objectBucket[x].count;
2050 /* If we didn't find an empty list, then try
2051 * looking a bit further for a short one
2054 for (i = 0; i < 10 && lowest > 3; i++) {
2056 x %= YAFFS_NOBJECT_BUCKETS;
2057 if (dev->objectBucket[x].count < lowest) {
2058 lowest = dev->objectBucket[x].count;
2067 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
2069 int bucket = yaffs_FindNiceObjectBucket(dev);
2071 /* Now find an object value that has not already been taken
2072 * by scanning the list.
2076 struct list_head *i;
2078 __u32 n = (__u32) bucket;
2080 /* yaffs_CheckObjectHashSanity(); */
2084 n += YAFFS_NOBJECT_BUCKETS;
2085 if (1 || dev->objectBucket[bucket].count > 0) {
2086 list_for_each(i, &dev->objectBucket[bucket].list) {
2087 /* If there is already one in the list */
2089 && list_entry(i, yaffs_Object,
2090 hashLink)->objectId == n) {
2101 static void yaffs_HashObject(yaffs_Object * in)
2103 int bucket = yaffs_HashFunction(in->objectId);
2104 yaffs_Device *dev = in->myDev;
2106 list_add(&in->hashLink, &dev->objectBucket[bucket].list);
2107 dev->objectBucket[bucket].count++;
2111 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
2113 int bucket = yaffs_HashFunction(number);
2114 struct list_head *i;
2117 list_for_each(i, &dev->objectBucket[bucket].list) {
2118 /* Look if it is in the list */
2120 in = list_entry(i, yaffs_Object, hashLink);
2121 if (in->objectId == number) {
2122 /* XXX U-BOOT XXX */
2125 /* Don't tell the VFS about this one if it is defered free */
2126 if (in->deferedFree)
2138 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
2139 yaffs_ObjectType type)
2142 yaffs_Object *theObject;
2146 number = yaffs_CreateNewObjectNumber(dev);
2149 theObject = yaffs_AllocateEmptyObject(dev);
2153 if(type == YAFFS_OBJECT_TYPE_FILE){
2154 tn = yaffs_GetTnode(dev);
2156 yaffs_FreeObject(theObject);
2164 theObject->fake = 0;
2165 theObject->renameAllowed = 1;
2166 theObject->unlinkAllowed = 1;
2167 theObject->objectId = number;
2168 yaffs_HashObject(theObject);
2169 theObject->variantType = type;
2170 #ifdef CONFIG_YAFFS_WINCE
2171 yfsd_WinFileTimeNow(theObject->win_atime);
2172 theObject->win_ctime[0] = theObject->win_mtime[0] =
2173 theObject->win_atime[0];
2174 theObject->win_ctime[1] = theObject->win_mtime[1] =
2175 theObject->win_atime[1];
2179 theObject->yst_atime = theObject->yst_mtime =
2180 theObject->yst_ctime = Y_CURRENT_TIME;
2183 case YAFFS_OBJECT_TYPE_FILE:
2184 theObject->variant.fileVariant.fileSize = 0;
2185 theObject->variant.fileVariant.scannedFileSize = 0;
2186 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2187 theObject->variant.fileVariant.topLevel = 0;
2188 theObject->variant.fileVariant.top = tn;
2190 case YAFFS_OBJECT_TYPE_DIRECTORY:
2191 INIT_LIST_HEAD(&theObject->variant.directoryVariant.
2194 case YAFFS_OBJECT_TYPE_SYMLINK:
2195 case YAFFS_OBJECT_TYPE_HARDLINK:
2196 case YAFFS_OBJECT_TYPE_SPECIAL:
2197 /* No action required */
2199 case YAFFS_OBJECT_TYPE_UNKNOWN:
2200 /* todo this should not happen */
2208 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
2210 yaffs_ObjectType type)
2212 yaffs_Object *theObject = NULL;
2215 theObject = yaffs_FindObjectByNumber(dev, number);
2219 theObject = yaffs_CreateNewObject(dev, number, type);
2227 static YCHAR *yaffs_CloneString(const YCHAR * str)
2229 YCHAR *newStr = NULL;
2232 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2234 yaffs_strcpy(newStr, str);
2242 * Mknod (create) a new object.
2243 * equivalentObject only has meaning for a hard link;
2244 * aliasString only has meaning for a sumlink.
2245 * rdev only has meaning for devices (a subset of special objects)
2248 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2249 yaffs_Object * parent,
2254 yaffs_Object * equivalentObject,
2255 const YCHAR * aliasString, __u32 rdev)
2260 yaffs_Device *dev = parent->myDev;
2262 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2263 if (yaffs_FindObjectByName(parent, name)) {
2267 in = yaffs_CreateNewObject(dev, -1, type);
2269 if(type == YAFFS_OBJECT_TYPE_SYMLINK){
2270 str = yaffs_CloneString(aliasString);
2272 yaffs_FreeObject(in);
2282 in->variantType = type;
2284 in->yst_mode = mode;
2286 #ifdef CONFIG_YAFFS_WINCE
2287 yfsd_WinFileTimeNow(in->win_atime);
2288 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2289 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2292 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2294 in->yst_rdev = rdev;
2298 in->nDataChunks = 0;
2300 yaffs_SetObjectName(in, name);
2303 yaffs_AddObjectToDirectory(parent, in);
2305 in->myDev = parent->myDev;
2308 case YAFFS_OBJECT_TYPE_SYMLINK:
2309 in->variant.symLinkVariant.alias = str;
2311 case YAFFS_OBJECT_TYPE_HARDLINK:
2312 in->variant.hardLinkVariant.equivalentObject =
2314 in->variant.hardLinkVariant.equivalentObjectId =
2315 equivalentObject->objectId;
2316 list_add(&in->hardLinks, &equivalentObject->hardLinks);
2318 case YAFFS_OBJECT_TYPE_FILE:
2319 case YAFFS_OBJECT_TYPE_DIRECTORY:
2320 case YAFFS_OBJECT_TYPE_SPECIAL:
2321 case YAFFS_OBJECT_TYPE_UNKNOWN:
2326 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2327 /* Could not create the object header, fail the creation */
2328 yaffs_DestroyObject(in);
2337 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
2338 __u32 mode, __u32 uid, __u32 gid)
2340 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2341 uid, gid, NULL, NULL, 0);
2344 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
2345 __u32 mode, __u32 uid, __u32 gid)
2347 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2348 mode, uid, gid, NULL, NULL, 0);
2351 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
2352 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2354 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2355 uid, gid, NULL, NULL, rdev);
2358 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
2359 __u32 mode, __u32 uid, __u32 gid,
2360 const YCHAR * alias)
2362 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2363 uid, gid, NULL, alias, 0);
2366 /* yaffs_Link returns the object id of the equivalent object.*/
2367 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
2368 yaffs_Object * equivalentObject)
2370 /* Get the real object in case we were fed a hard link as an equivalent object */
2371 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2373 if (yaffs_MknodObject
2374 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2375 equivalentObject, NULL, 0)) {
2376 return equivalentObject;
2383 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
2384 const YCHAR * newName, int force, int shadows)
2389 yaffs_Object *existingTarget;
2391 if (newDir == NULL) {
2392 newDir = obj->parent; /* use the old directory */
2395 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2396 T(YAFFS_TRACE_ALWAYS,
2398 ("tragendy: yaffs_ChangeObjectName: newDir is not a directory"
2403 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2404 if (obj->myDev->isYaffs2) {
2405 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2407 unlinkOp = (newDir == obj->myDev->unlinkedDir
2408 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2411 deleteOp = (newDir == obj->myDev->deletedDir);
2413 existingTarget = yaffs_FindObjectByName(newDir, newName);
2415 /* If the object is a file going into the unlinked directory,
2416 * then it is OK to just stuff it in since duplicate names are allowed.
2417 * else only proceed if the new name does not exist and if we're putting
2418 * it into a directory.
2425 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2426 yaffs_SetObjectName(obj, newName);
2429 yaffs_AddObjectToDirectory(newDir, obj);
2434 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2435 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
2442 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
2443 yaffs_Object * newDir, const YCHAR * newName)
2446 yaffs_Object *existingTarget;
2449 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2450 /* Special case for case insemsitive systems (eg. WinCE).
2451 * While look-up is case insensitive, the name isn't.
2452 * Therefore we might want to change x.txt to X.txt
2454 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
2459 obj = yaffs_FindObjectByName(oldDir, oldName);
2460 /* Check new name to long. */
2461 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK &&
2462 yaffs_strlen(newName) > YAFFS_MAX_ALIAS_LENGTH)
2465 else if (obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK &&
2466 yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2470 if (obj && obj->renameAllowed) {
2472 /* Now do the handling for an existing target, if there is one */
2474 existingTarget = yaffs_FindObjectByName(newDir, newName);
2475 if (existingTarget &&
2476 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2477 !list_empty(&existingTarget->variant.directoryVariant.children)) {
2478 /* There is a target that is a non-empty directory, so we fail */
2479 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2480 } else if (existingTarget && existingTarget != obj) {
2481 /* Nuke the target first, using shadowing,
2482 * but only if it isn't the same object
2484 yaffs_ChangeObjectName(obj, newDir, newName, force,
2485 existingTarget->objectId);
2486 yaffs_UnlinkObject(existingTarget);
2489 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2494 /*------------------------- Block Management and Page Allocation ----------------*/
2496 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
2498 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2500 dev->blockInfo = NULL;
2501 dev->chunkBits = NULL;
2503 dev->allocationBlock = -1; /* force it to get a new one */
2505 /* If the first allocation strategy fails, thry the alternate one */
2506 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2507 if(!dev->blockInfo){
2508 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2509 dev->blockInfoAlt = 1;
2512 dev->blockInfoAlt = 0;
2516 /* Set up dynamic blockinfo stuff. */
2517 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2518 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2519 if(!dev->chunkBits){
2520 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2521 dev->chunkBitsAlt = 1;
2524 dev->chunkBitsAlt = 0;
2527 if (dev->blockInfo && dev->chunkBits) {
2528 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2529 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2537 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
2539 if(dev->blockInfoAlt && dev->blockInfo)
2540 YFREE_ALT(dev->blockInfo);
2541 else if(dev->blockInfo)
2542 YFREE(dev->blockInfo);
2544 dev->blockInfoAlt = 0;
2546 dev->blockInfo = NULL;
2548 if(dev->chunkBitsAlt && dev->chunkBits)
2549 YFREE_ALT(dev->chunkBits);
2550 else if(dev->chunkBits)
2551 YFREE(dev->chunkBits);
2552 dev->chunkBitsAlt = 0;
2553 dev->chunkBits = NULL;
2556 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
2557 yaffs_BlockInfo * bi)
2564 return 1; /* disqualification only applies to yaffs2. */
2566 if (!bi->hasShrinkHeader)
2567 return 1; /* can gc */
2569 /* Find the oldest dirty sequence number if we don't know it and save it
2570 * so we don't have to keep recomputing it.
2572 if (!dev->oldestDirtySequence) {
2573 seq = dev->sequenceNumber;
2575 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2577 b = yaffs_GetBlockInfo(dev, i);
2578 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2579 (b->pagesInUse - b->softDeletions) <
2580 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2581 seq = b->sequenceNumber;
2584 dev->oldestDirtySequence = seq;
2587 /* Can't do gc of this block if there are any blocks older than this one that have
2590 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2594 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2595 * for garbage collection.
2598 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2602 int b = dev->currentDirtyChecker;
2609 yaffs_BlockInfo *bi;
2610 int pendingPrioritisedExist = 0;
2612 /* First let's see if we need to grab a prioritised block */
2613 if(dev->hasPendingPrioritisedGCs){
2614 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2616 bi = yaffs_GetBlockInfo(dev, i);
2617 //yaffs_VerifyBlock(dev,bi,i);
2619 if(bi->gcPrioritise) {
2620 pendingPrioritisedExist = 1;
2621 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2622 yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2623 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2626 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2631 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2632 dev->hasPendingPrioritisedGCs = 0;
2635 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2637 * else (we're doing a leasurely gc), then we only bother to do this if the
2638 * block has only a few pages in use.
2641 dev->nonAggressiveSkip--;
2643 if (!aggressive && (dev->nonAggressiveSkip > 0)) {
2649 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2653 dev->internalEndBlock - dev->internalStartBlock + 1;
2656 dev->internalEndBlock - dev->internalStartBlock + 1;
2657 iterations = iterations / 16;
2658 if (iterations > 200) {
2663 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2665 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2666 b = dev->internalStartBlock;
2669 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2670 T(YAFFS_TRACE_ERROR,
2671 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2675 bi = yaffs_GetBlockInfo(dev, b);
2678 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2685 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2686 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2687 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2689 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2693 dev->currentDirtyChecker = b;
2697 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2698 dev->nChunksPerBlock - pagesInUse,prioritised));
2701 dev->oldestDirtySequence = 0;
2704 dev->nonAggressiveSkip = 4;
2710 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2712 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2716 /* If the block is still healthy erase it and mark as clean.
2717 * If the block has had a data failure, then retire it.
2720 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2721 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2722 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2724 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2726 if (!bi->needsRetiring) {
2727 yaffs_InvalidateCheckpoint(dev);
2728 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2730 dev->nErasureFailures++;
2731 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2732 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2737 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2739 for (i = 0; i < dev->nChunksPerBlock; i++) {
2740 if (!yaffs_CheckChunkErased
2741 (dev, blockNo * dev->nChunksPerBlock + i)) {
2742 T(YAFFS_TRACE_ERROR,
2744 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2745 TENDSTR), blockNo, i));
2751 /* Clean it up... */
2752 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2753 dev->nErasedBlocks++;
2755 bi->softDeletions = 0;
2756 bi->hasShrinkHeader = 0;
2757 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2758 bi->gcPrioritise = 0;
2759 yaffs_ClearChunkBits(dev, blockNo);
2761 T(YAFFS_TRACE_ERASE,
2762 (TSTR("Erased block %d" TENDSTR), blockNo));
2764 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2766 yaffs_RetireBlock(dev, blockNo);
2767 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2768 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2772 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2776 yaffs_BlockInfo *bi;
2778 if (dev->nErasedBlocks < 1) {
2779 /* Hoosterman we've got a problem.
2780 * Can't get space to gc
2782 T(YAFFS_TRACE_ERROR,
2783 (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2788 /* Find an empty block. */
2790 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2791 dev->allocationBlockFinder++;
2792 if (dev->allocationBlockFinder < dev->internalStartBlock
2793 || dev->allocationBlockFinder > dev->internalEndBlock) {
2794 dev->allocationBlockFinder = dev->internalStartBlock;
2797 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2799 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2800 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2801 dev->sequenceNumber++;
2802 bi->sequenceNumber = dev->sequenceNumber;
2803 dev->nErasedBlocks--;
2804 T(YAFFS_TRACE_ALLOCATE,
2805 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2806 dev->allocationBlockFinder, dev->sequenceNumber,
2807 dev->nErasedBlocks));
2808 return dev->allocationBlockFinder;
2812 T(YAFFS_TRACE_ALWAYS,
2814 ("yaffs tragedy: no more eraased blocks, but there should have been %d"
2815 TENDSTR), dev->nErasedBlocks));
2821 // Check if there's space to allocate...
2822 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2823 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2826 int reservedBlocks = dev->nReservedBlocks;
2827 int checkpointBlocks;
2829 checkpointBlocks = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
2830 if(checkpointBlocks < 0)
2831 checkpointBlocks = 0;
2833 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2835 return (dev->nFreeChunks > reservedChunks);
2838 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2841 yaffs_BlockInfo *bi;
2843 if (dev->allocationBlock < 0) {
2844 /* Get next block to allocate off */
2845 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2846 dev->allocationPage = 0;
2849 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2850 /* Not enough space to allocate unless we're allowed to use the reserve. */
2854 if (dev->nErasedBlocks < dev->nReservedBlocks
2855 && dev->allocationPage == 0) {
2856 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2859 /* Next page please.... */
2860 if (dev->allocationBlock >= 0) {
2861 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2863 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2864 dev->allocationPage;
2866 yaffs_SetChunkBit(dev, dev->allocationBlock,
2867 dev->allocationPage);
2869 dev->allocationPage++;
2873 /* If the block is full set the state to full */
2874 if (dev->allocationPage >= dev->nChunksPerBlock) {
2875 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2876 dev->allocationBlock = -1;
2885 T(YAFFS_TRACE_ERROR,
2886 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2891 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2895 n = dev->nErasedBlocks * dev->nChunksPerBlock;
2897 if (dev->allocationBlock > 0) {
2898 n += (dev->nChunksPerBlock - dev->allocationPage);
2905 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2911 int retVal = YAFFS_OK;
2914 int isCheckpointBlock;
2917 int chunksBefore = yaffs_GetErasedChunks(dev);
2920 yaffs_ExtendedTags tags;
2922 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2924 yaffs_Object *object;
2926 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2928 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2930 T(YAFFS_TRACE_TRACING,
2931 (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2932 bi->pagesInUse, bi->hasShrinkHeader));
2934 /*yaffs_VerifyFreeChunks(dev); */
2936 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
2938 /* Take off the number of soft deleted entries because
2939 * they're going to get really deleted during GC.
2941 dev->nFreeChunks -= bi->softDeletions;
2945 if (isCheckpointBlock ||
2946 !yaffs_StillSomeChunkBits(dev, block)) {
2947 T(YAFFS_TRACE_TRACING,
2949 ("Collecting block %d that has no chunks in use" TENDSTR),
2951 yaffs_BlockBecameDirty(dev, block);
2954 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2956 yaffs_VerifyBlock(dev,bi,block);
2958 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
2959 chunkInBlock < dev->nChunksPerBlock
2960 && yaffs_StillSomeChunkBits(dev, block);
2961 chunkInBlock++, oldChunk++) {
2962 if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
2964 /* This page is in use and might need to be copied off */
2968 yaffs_InitialiseTags(&tags);
2970 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2974 yaffs_FindObjectByNumber(dev,
2977 T(YAFFS_TRACE_GC_DETAIL,
2979 ("Collecting page %d, %d %d %d " TENDSTR),
2980 chunkInBlock, tags.objectId, tags.chunkId,
2983 if(object && !yaffs_SkipVerification(dev)){
2984 if(tags.chunkId == 0)
2985 matchingChunk = object->chunkId;
2986 else if(object->softDeleted)
2987 matchingChunk = oldChunk; /* Defeat the test */
2989 matchingChunk = yaffs_FindChunkInFile(object,tags.chunkId,NULL);
2991 if(oldChunk != matchingChunk)
2992 T(YAFFS_TRACE_ERROR,
2993 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
2994 oldChunk,matchingChunk,tags.objectId, tags.chunkId));
2999 T(YAFFS_TRACE_ERROR,
3001 ("page %d in gc has no object: %d %d %d "
3003 tags.objectId, tags.chunkId, tags.byteCount));
3006 if (object && object->deleted
3007 && tags.chunkId != 0) {
3008 /* Data chunk in a deleted file, throw it away
3009 * It's a soft deleted data chunk,
3010 * No need to copy this, just forget about it and
3011 * fix up the object.
3014 object->nDataChunks--;
3016 if (object->nDataChunks <= 0) {
3017 /* remeber to clean up the object */
3018 dev->gcCleanupList[cleanups] =
3024 /* Todo object && object->deleted && object->nDataChunks == 0 */
3026 /* Deleted object header with no data chunks.
3027 * Can be discarded and the file deleted.
3029 object->chunkId = 0;
3030 yaffs_FreeTnode(object->myDev,
3033 object->variant.fileVariant.top = NULL;
3034 yaffs_DoGenericObjectDeletion(object);
3036 } else if (object) {
3037 /* It's either a data chunk in a live file or
3038 * an ObjectHeader, so we're interested in it.
3039 * NB Need to keep the ObjectHeaders of deleted files
3040 * until the whole file has been deleted off
3042 tags.serialNumber++;
3046 if (tags.chunkId == 0) {
3047 /* It is an object Id,
3048 * We need to nuke the shrinkheader flags first
3049 * We no longer want the shrinkHeader flag since its work is done
3050 * and if it is left in place it will mess up scanning.
3051 * Also, clear out any shadowing stuff
3054 yaffs_ObjectHeader *oh;
3055 oh = (yaffs_ObjectHeader *)buffer;
3057 oh->shadowsObject = -1;
3058 tags.extraShadows = 0;
3059 tags.extraIsShrinkHeader = 0;
3061 yaffs_VerifyObjectHeader(object,oh,&tags,1);
3065 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3068 retVal = YAFFS_FAIL;
3071 /* Ok, now fix up the Tnodes etc. */
3073 if (tags.chunkId == 0) {
3075 object->chunkId = newChunk;
3076 object->serial = tags.serialNumber;
3078 /* It's a data chunk */
3079 yaffs_PutChunkIntoFile
3087 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3092 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3095 /* Do any required cleanups */
3096 for (i = 0; i < cleanups; i++) {
3097 /* Time to delete the file too */
3099 yaffs_FindObjectByNumber(dev,
3100 dev->gcCleanupList[i]);
3102 yaffs_FreeTnode(dev,
3103 object->variant.fileVariant.
3105 object->variant.fileVariant.top = NULL;
3108 ("yaffs: About to finally delete object %d"
3109 TENDSTR), object->objectId));
3110 yaffs_DoGenericObjectDeletion(object);
3111 object->myDev->nDeletedFiles--;
3118 yaffs_VerifyCollectedBlock(dev,bi,block);
3120 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
3123 ("gc did not increase free chunks before %d after %d"
3124 TENDSTR), chunksBefore, chunksAfter));
3132 /* New garbage collector
3133 * If we're very low on erased blocks then we do aggressive garbage collection
3134 * otherwise we do "leasurely" garbage collection.
3135 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3136 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3138 * The idea is to help clear out space in a more spread-out manner.
3139 * Dunno if it really does anything useful.
3141 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
3145 int gcOk = YAFFS_OK;
3148 int checkpointBlockAdjust;
3150 if (dev->isDoingGC) {
3151 /* Bail out so we don't get recursive gc */
3155 /* This loop should pass the first time.
3156 * We'll only see looping here if the erase of the collected block fails.
3162 checkpointBlockAdjust = (dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint);
3163 if(checkpointBlockAdjust < 0)
3164 checkpointBlockAdjust = 0;
3166 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3167 /* We need a block soon...*/
3170 /* We're in no hurry */
3174 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3177 dev->garbageCollections++;
3179 dev->passiveGarbageCollections++;
3184 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3185 dev->nErasedBlocks, aggressive));
3187 gcOk = yaffs_GarbageCollectBlock(dev, block);
3190 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3193 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3194 TENDSTR), dev->nErasedBlocks, maxTries, block));
3196 } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
3199 return aggressive ? gcOk : YAFFS_OK;
3202 /*------------------------- TAGS --------------------------------*/
3204 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
3207 return (tags->chunkId == chunkInObject &&
3208 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3213 /*-------------------- Data file manipulation -----------------*/
3215 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
3216 yaffs_ExtendedTags * tags)
3218 /*Get the Tnode, then get the level 0 offset chunk offset */
3221 yaffs_ExtendedTags localTags;
3224 yaffs_Device *dev = in->myDev;
3227 /* Passed a NULL, so use our own tags space */
3231 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3234 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3237 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3243 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
3244 yaffs_ExtendedTags * tags)
3246 /* Get the Tnode, then get the level 0 offset chunk offset */
3249 yaffs_ExtendedTags localTags;
3251 yaffs_Device *dev = in->myDev;
3255 /* Passed a NULL, so use our own tags space */
3259 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3263 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3266 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3269 /* Delete the entry in the filestructure (if found) */
3271 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
3274 /*T(("No level 0 found for %d\n", chunkInInode)); */
3278 /* T(("Could not find %d to delete\n",chunkInInode)); */
3283 #ifdef YAFFS_PARANOID
3285 static int yaffs_CheckFileSanity(yaffs_Object * in)
3293 yaffs_Tags localTags;
3294 yaffs_Tags *tags = &localTags;
3298 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3299 /* T(("Object not a file\n")); */
3303 objId = in->objectId;
3304 fSize = in->variant.fileVariant.fileSize;
3306 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3308 for (chunk = 1; chunk <= nChunks; chunk++) {
3309 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3314 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
3316 if (yaffs_CheckChunkBits
3317 (dev, theChunk / dev->nChunksPerBlock,
3318 theChunk % dev->nChunksPerBlock)) {
3320 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3324 (tags, in->objectId, chunk, chunkDeleted)) {
3334 /* T(("No level 0 found for %d\n", chunk)); */
3338 return failed ? YAFFS_FAIL : YAFFS_OK;
3343 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
3344 int chunkInNAND, int inScan)
3346 /* NB inScan is zero unless scanning.
3347 * For forward scanning, inScan is > 0;
3348 * for backward scanning inScan is < 0
3352 yaffs_Device *dev = in->myDev;
3354 yaffs_ExtendedTags existingTags;
3355 yaffs_ExtendedTags newTags;
3356 unsigned existingSerial, newSerial;
3358 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3359 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3360 * If it is not during Scanning then something went wrong!
3363 T(YAFFS_TRACE_ERROR,
3365 ("yaffs tragedy:attempt to put data chunk into a non-file"
3370 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3374 tn = yaffs_AddOrFindLevel0Tnode(dev,
3375 &in->variant.fileVariant,
3382 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3385 /* If we're scanning then we need to test for duplicates
3386 * NB This does not need to be efficient since it should only ever
3387 * happen when the power fails during a write, then only one
3388 * chunk should ever be affected.
3390 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3391 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3394 if (existingChunk != 0) {
3395 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3396 * thus we have to do a FindChunkInFile to get the real chunk id.
3398 * We have a duplicate now we need to decide which one to use:
3400 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3401 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3402 * YAFFS1: Get both sets of tags and compare serial numbers.
3406 /* Only do this for forward scanning */
3407 yaffs_ReadChunkWithTagsFromNAND(dev,
3411 /* Do a proper find */
3413 yaffs_FindChunkInFile(in, chunkInInode,
3417 if (existingChunk <= 0) {
3418 /*Hoosterman - how did this happen? */
3420 T(YAFFS_TRACE_ERROR,
3422 ("yaffs tragedy: existing chunk < 0 in scan"
3427 /* NB The deleted flags should be false, otherwise the chunks will
3428 * not be loaded during a scan
3432 newSerial = newTags.serialNumber;
3433 existingSerial = existingTags.serialNumber;
3437 (in->myDev->isYaffs2 ||
3438 existingChunk <= 0 ||
3439 ((existingSerial + 1) & 3) == newSerial)) {
3440 /* Forward scanning.
3442 * Delete the old one and drop through to update the tnode
3444 yaffs_DeleteChunk(dev, existingChunk, 1,
3447 /* Backward scanning or we want to use the existing one
3449 * Delete the new one and return early so that the tnode isn't changed
3451 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3459 if (existingChunk == 0) {
3463 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
3468 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
3471 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3473 if (chunkInNAND >= 0) {
3474 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3477 T(YAFFS_TRACE_NANDACCESS,
3478 (TSTR("Chunk %d not found zero instead" TENDSTR),
3480 /* get sane (zero) data if you read a hole */
3481 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3487 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
3491 yaffs_ExtendedTags tags;
3492 yaffs_BlockInfo *bi;
3499 block = chunkId / dev->nChunksPerBlock;
3500 page = chunkId % dev->nChunksPerBlock;
3503 if(!yaffs_CheckChunkBit(dev,block,page))
3504 T(YAFFS_TRACE_VERIFY,
3505 (TSTR("Deleting invalid chunk %d"TENDSTR),
3508 bi = yaffs_GetBlockInfo(dev, block);
3510 T(YAFFS_TRACE_DELETION,
3511 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3514 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3516 yaffs_InitialiseTags(&tags);
3518 tags.chunkDeleted = 1;
3520 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3521 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3523 dev->nUnmarkedDeletions++;
3526 /* Pull out of the management area.
3527 * If the whole block became dirty, this will kick off an erasure.
3529 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3530 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3531 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3532 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3535 yaffs_ClearChunkBit(dev, block, page);
3539 if (bi->pagesInUse == 0 &&
3540 !bi->hasShrinkHeader &&
3541 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3542 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3543 yaffs_BlockBecameDirty(dev, block);
3547 /* T(("Bad news deleting chunk %d\n",chunkId)); */
3552 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
3553 const __u8 * buffer, int nBytes,
3556 /* Find old chunk Need to do this to get serial number
3557 * Write new one and patch into tree.
3558 * Invalidate old tags.
3562 yaffs_ExtendedTags prevTags;
3565 yaffs_ExtendedTags newTags;
3567 yaffs_Device *dev = in->myDev;
3569 yaffs_CheckGarbageCollection(dev);
3571 /* Get the previous chunk at this location in the file if it exists */
3572 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3574 /* Set up new tags */
3575 yaffs_InitialiseTags(&newTags);
3577 newTags.chunkId = chunkInInode;
3578 newTags.objectId = in->objectId;
3579 newTags.serialNumber =
3580 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
3581 newTags.byteCount = nBytes;
3584 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3587 if (newChunkId >= 0) {
3588 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3590 if (prevChunkId >= 0) {
3591 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3595 yaffs_CheckFileSanity(in);
3601 /* UpdateObjectHeader updates the header on NAND for an object.
3602 * If name is not NULL, then that new name is used.
3604 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
3605 int isShrink, int shadows)
3608 yaffs_BlockInfo *bi;
3610 yaffs_Device *dev = in->myDev;
3617 yaffs_ExtendedTags newTags;
3618 yaffs_ExtendedTags oldTags;
3620 __u8 *buffer = NULL;
3621 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3623 yaffs_ObjectHeader *oh = NULL;
3625 yaffs_strcpy(oldName,"silly old name");
3627 if (!in->fake || force) {
3629 yaffs_CheckGarbageCollection(dev);
3630 yaffs_CheckObjectDetailsLoaded(in);
3632 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3633 oh = (yaffs_ObjectHeader *) buffer;
3635 prevChunkId = in->chunkId;
3637 if (prevChunkId >= 0) {
3638 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3641 yaffs_VerifyObjectHeader(in,oh,&oldTags,0);
3643 memcpy(oldName, oh->name, sizeof(oh->name));
3646 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3648 oh->type = in->variantType;
3649 oh->yst_mode = in->yst_mode;
3650 oh->shadowsObject = shadows;
3652 #ifdef CONFIG_YAFFS_WINCE
3653 oh->win_atime[0] = in->win_atime[0];
3654 oh->win_ctime[0] = in->win_ctime[0];
3655 oh->win_mtime[0] = in->win_mtime[0];
3656 oh->win_atime[1] = in->win_atime[1];
3657 oh->win_ctime[1] = in->win_ctime[1];
3658 oh->win_mtime[1] = in->win_mtime[1];
3660 oh->yst_uid = in->yst_uid;
3661 oh->yst_gid = in->yst_gid;
3662 oh->yst_atime = in->yst_atime;
3663 oh->yst_mtime = in->yst_mtime;
3664 oh->yst_ctime = in->yst_ctime;
3665 oh->yst_rdev = in->yst_rdev;
3668 oh->parentObjectId = in->parent->objectId;
3670 oh->parentObjectId = 0;
3673 if (name && *name) {
3674 memset(oh->name, 0, sizeof(oh->name));
3675 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3676 } else if (prevChunkId>=0) {
3677 memcpy(oh->name, oldName, sizeof(oh->name));
3679 memset(oh->name, 0, sizeof(oh->name));
3682 oh->isShrink = isShrink;
3684 switch (in->variantType) {
3685 case YAFFS_OBJECT_TYPE_UNKNOWN:
3686 /* Should not happen */
3688 case YAFFS_OBJECT_TYPE_FILE:
3690 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3691 || oh->parentObjectId ==
3692 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3693 fileVariant.fileSize;
3695 case YAFFS_OBJECT_TYPE_HARDLINK:
3696 oh->equivalentObjectId =
3697 in->variant.hardLinkVariant.equivalentObjectId;
3699 case YAFFS_OBJECT_TYPE_SPECIAL:
3702 case YAFFS_OBJECT_TYPE_DIRECTORY:
3705 case YAFFS_OBJECT_TYPE_SYMLINK:
3706 yaffs_strncpy(oh->alias,
3707 in->variant.symLinkVariant.alias,
3708 YAFFS_MAX_ALIAS_LENGTH);
3709 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3714 yaffs_InitialiseTags(&newTags);
3716 newTags.chunkId = 0;
3717 newTags.objectId = in->objectId;
3718 newTags.serialNumber = in->serial;
3720 /* Add extra info for file header */
3722 newTags.extraHeaderInfoAvailable = 1;
3723 newTags.extraParentObjectId = oh->parentObjectId;
3724 newTags.extraFileLength = oh->fileSize;
3725 newTags.extraIsShrinkHeader = oh->isShrink;
3726 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3727 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3728 newTags.extraObjectType = in->variantType;
3730 yaffs_VerifyObjectHeader(in,oh,&newTags,1);
3732 /* Create new chunk in NAND */
3734 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3735 (prevChunkId >= 0) ? 1 : 0);
3737 if (newChunkId >= 0) {
3739 in->chunkId = newChunkId;
3741 if (prevChunkId >= 0) {
3742 yaffs_DeleteChunk(dev, prevChunkId, 1,
3746 if(!yaffs_ObjectHasCachedWriteData(in))
3749 /* If this was a shrink, then mark the block that the chunk lives on */
3751 bi = yaffs_GetBlockInfo(in->myDev,
3752 newChunkId /in->myDev-> nChunksPerBlock);
3753 bi->hasShrinkHeader = 1;
3758 retVal = newChunkId;
3763 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3768 /*------------------------ Short Operations Cache ----------------------------------------
3769 * In many situations where there is no high level buffering (eg WinCE) a lot of
3770 * reads might be short sequential reads, and a lot of writes may be short
3771 * sequential writes. eg. scanning/writing a jpeg file.
3772 * In these cases, a short read/write cache can provide a huge perfomance benefit
3773 * with dumb-as-a-rock code.
3774 * In Linux, the page cache provides read buffering aand the short op cache provides write
3777 * There are a limited number (~10) of cache chunks per device so that we don't
3778 * need a very intelligent search.
3781 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3783 yaffs_Device *dev = obj->myDev;
3785 yaffs_ChunkCache *cache;
3786 int nCaches = obj->myDev->nShortOpCaches;
3788 for(i = 0; i < nCaches; i++){
3789 cache = &dev->srCache[i];
3790 if (cache->object == obj &&
3799 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3801 yaffs_Device *dev = obj->myDev;
3802 int lowest = -99; /* Stop compiler whining. */
3804 yaffs_ChunkCache *cache;
3805 int chunkWritten = 0;
3806 int nCaches = obj->myDev->nShortOpCaches;
3812 /* Find the dirty cache for this object with the lowest chunk id. */
3813 for (i = 0; i < nCaches; i++) {
3814 if (dev->srCache[i].object == obj &&
3815 dev->srCache[i].dirty) {
3817 || dev->srCache[i].chunkId <
3819 cache = &dev->srCache[i];
3820 lowest = cache->chunkId;
3825 if (cache && !cache->locked) {
3826 /* Write it out and free it up */
3829 yaffs_WriteChunkDataToObject(cache->object,
3835 cache->object = NULL;
3838 } while (cache && chunkWritten > 0);
3841 /* Hoosterman, disk full while writing cache out. */
3842 T(YAFFS_TRACE_ERROR,
3843 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3850 /*yaffs_FlushEntireDeviceCache(dev)
3855 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3858 int nCaches = dev->nShortOpCaches;
3861 /* Find a dirty object in the cache and flush it...
3862 * until there are no further dirty objects.
3866 for( i = 0; i < nCaches && !obj; i++) {
3867 if (dev->srCache[i].object &&
3868 dev->srCache[i].dirty)
3869 obj = dev->srCache[i].object;
3873 yaffs_FlushFilesChunkCache(obj);
3880 /* Grab us a cache chunk for use.
3881 * First look for an empty one.
3882 * Then look for the least recently used non-dirty one.
3883 * Then look for the least recently used dirty one...., flush and look again.
3885 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
3891 if (dev->nShortOpCaches > 0) {
3892 for (i = 0; i < dev->nShortOpCaches; i++) {
3893 if (!dev->srCache[i].object)
3894 return &dev->srCache[i];
3900 usage = 0; /* just to stop the compiler grizzling */
3902 for (i = 0; i < dev->nShortOpCaches; i++) {
3903 if (!dev->srCache[i].dirty &&
3904 ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
3906 usage = dev->srCache[i].lastUse;
3912 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3919 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
3921 yaffs_ChunkCache *cache;
3922 yaffs_Object *theObj;
3927 if (dev->nShortOpCaches > 0) {
3928 /* Try find a non-dirty one... */
3930 cache = yaffs_GrabChunkCacheWorker(dev);
3933 /* They were all dirty, find the last recently used object and flush
3934 * its cache, then find again.
3935 * NB what's here is not very accurate, we actually flush the object
3936 * the last recently used page.
3939 /* With locking we can't assume we can use entry zero */
3946 for (i = 0; i < dev->nShortOpCaches; i++) {
3947 if (dev->srCache[i].object &&
3948 !dev->srCache[i].locked &&
3949 (dev->srCache[i].lastUse < usage || !cache))
3951 usage = dev->srCache[i].lastUse;
3952 theObj = dev->srCache[i].object;
3953 cache = &dev->srCache[i];
3958 if (!cache || cache->dirty) {
3959 /* Flush and try again */
3960 yaffs_FlushFilesChunkCache(theObj);
3961 cache = yaffs_GrabChunkCacheWorker(dev);
3971 /* Find a cached chunk */
3972 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
3975 yaffs_Device *dev = obj->myDev;
3977 if (dev->nShortOpCaches > 0) {
3978 for (i = 0; i < dev->nShortOpCaches; i++) {
3979 if (dev->srCache[i].object == obj &&
3980 dev->srCache[i].chunkId == chunkId) {
3983 return &dev->srCache[i];
3990 /* Mark the chunk for the least recently used algorithym */
3991 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
3995 if (dev->nShortOpCaches > 0) {
3996 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
3997 /* Reset the cache usages */
3999 for (i = 1; i < dev->nShortOpCaches; i++) {
4000 dev->srCache[i].lastUse = 0;
4007 cache->lastUse = dev->srLastUse;
4015 /* Invalidate a single cache page.
4016 * Do this when a whole page gets written,
4017 * ie the short cache for this page is no longer valid.
4019 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
4021 if (object->myDev->nShortOpCaches > 0) {
4022 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4025 cache->object = NULL;
4030 /* Invalidate all the cache pages associated with this object
4031 * Do this whenever ther file is deleted or resized.
4033 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
4036 yaffs_Device *dev = in->myDev;
4038 if (dev->nShortOpCaches > 0) {
4039 /* Invalidate it. */
4040 for (i = 0; i < dev->nShortOpCaches; i++) {
4041 if (dev->srCache[i].object == in) {
4042 dev->srCache[i].object = NULL;
4048 /*--------------------- Checkpointing --------------------*/
4051 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
4053 yaffs_CheckpointValidity cp;
4055 memset(&cp,0,sizeof(cp));
4057 cp.structType = sizeof(cp);
4058 cp.magic = YAFFS_MAGIC;
4059 cp.version = YAFFS_CHECKPOINT_VERSION;
4060 cp.head = (head) ? 1 : 0;
4062 return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
4066 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4068 yaffs_CheckpointValidity cp;
4071 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4074 ok = (cp.structType == sizeof(cp)) &&
4075 (cp.magic == YAFFS_MAGIC) &&
4076 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4077 (cp.head == ((head) ? 1 : 0));
4081 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4084 cp->nErasedBlocks = dev->nErasedBlocks;
4085 cp->allocationBlock = dev->allocationBlock;
4086 cp->allocationPage = dev->allocationPage;
4087 cp->nFreeChunks = dev->nFreeChunks;
4089 cp->nDeletedFiles = dev->nDeletedFiles;
4090 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4091 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4092 cp->sequenceNumber = dev->sequenceNumber;
4093 cp->oldestDirtySequence = dev->oldestDirtySequence;
4097 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4098 yaffs_CheckpointDevice *cp)
4100 dev->nErasedBlocks = cp->nErasedBlocks;
4101 dev->allocationBlock = cp->allocationBlock;
4102 dev->allocationPage = cp->allocationPage;
4103 dev->nFreeChunks = cp->nFreeChunks;
4105 dev->nDeletedFiles = cp->nDeletedFiles;
4106 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4107 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4108 dev->sequenceNumber = cp->sequenceNumber;
4109 dev->oldestDirtySequence = cp->oldestDirtySequence;
4113 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4115 yaffs_CheckpointDevice cp;
4117 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4121 /* Write device runtime values*/
4122 yaffs_DeviceToCheckpointDevice(&cp,dev);
4123 cp.structType = sizeof(cp);
4125 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4127 /* Write block info */
4129 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4130 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
4133 /* Write chunk bits */
4135 nBytes = nBlocks * dev->chunkBitmapStride;
4136 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
4142 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4144 yaffs_CheckpointDevice cp;
4146 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4150 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4154 if(cp.structType != sizeof(cp))
4158 yaffs_CheckpointDeviceToDevice(dev,&cp);
4160 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4162 ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
4166 nBytes = nBlocks * dev->chunkBitmapStride;
4168 ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
4173 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4177 cp->objectId = obj->objectId;
4178 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4179 cp->chunkId = obj->chunkId;
4180 cp->variantType = obj->variantType;
4181 cp->deleted = obj->deleted;
4182 cp->softDeleted = obj->softDeleted;
4183 cp->unlinked = obj->unlinked;
4184 cp->fake = obj->fake;
4185 cp->renameAllowed = obj->renameAllowed;
4186 cp->unlinkAllowed = obj->unlinkAllowed;
4187 cp->serial = obj->serial;
4188 cp->nDataChunks = obj->nDataChunks;
4190 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4191 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4192 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4193 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4196 static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
4199 yaffs_Object *parent;
4201 obj->objectId = cp->objectId;
4204 parent = yaffs_FindOrCreateObjectByNumber(
4207 YAFFS_OBJECT_TYPE_DIRECTORY);
4212 yaffs_AddObjectToDirectory(parent, obj);
4214 obj->chunkId = cp->chunkId;
4215 obj->variantType = cp->variantType;
4216 obj->deleted = cp->deleted;
4217 obj->softDeleted = cp->softDeleted;
4218 obj->unlinked = cp->unlinked;
4219 obj->fake = cp->fake;
4220 obj->renameAllowed = cp->renameAllowed;
4221 obj->unlinkAllowed = cp->unlinkAllowed;
4222 obj->serial = cp->serial;
4223 obj->nDataChunks = cp->nDataChunks;
4225 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4226 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4227 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4228 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4230 if(obj->objectId >= YAFFS_NOBJECT_BUCKETS)
4231 obj->lazyLoaded = 1;
4236 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
4237 __u32 level, int chunkOffset)
4240 yaffs_Device *dev = in->myDev;
4242 int nTnodeBytes = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4247 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
4248 if (tn->internal[i]) {
4249 ok = yaffs_CheckpointTnodeWorker(in,
4252 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4255 } else if (level == 0) {
4256 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4257 /* printf("write tnode at %d\n",baseOffset); */
4258 ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
4260 ok = (yaffs_CheckpointWrite(dev,tn,nTnodeBytes) == nTnodeBytes);
4268 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4270 __u32 endMarker = ~0;
4273 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4274 ok = yaffs_CheckpointTnodeWorker(obj,
4275 obj->variant.fileVariant.top,
4276 obj->variant.fileVariant.topLevel,
4279 ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) ==
4286 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4290 yaffs_Device *dev = obj->myDev;
4291 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4295 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4297 while(ok && (~baseChunk)){
4299 /* Read level 0 tnode */
4302 /* printf("read tnode at %d\n",baseChunk); */
4303 tn = yaffs_GetTnodeRaw(dev);
4305 ok = (yaffs_CheckpointRead(dev,tn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8) ==
4306 (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
4311 ok = yaffs_AddOrFindLevel0Tnode(dev,
4319 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4323 T(YAFFS_TRACE_CHECKPOINT,(
4324 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4325 nread,baseChunk,ok));
4331 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4334 yaffs_CheckpointObject cp;
4337 struct list_head *lh;
4340 /* Iterate through the objects in each hash entry,
4341 * dumping them to the checkpointing stream.
4344 for(i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++){
4345 list_for_each(lh, &dev->objectBucket[i].list) {
4347 obj = list_entry(lh, yaffs_Object, hashLink);
4348 if (!obj->deferedFree) {
4349 yaffs_ObjectToCheckpointObject(&cp,obj);
4350 cp.structType = sizeof(cp);
4352 T(YAFFS_TRACE_CHECKPOINT,(
4353 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
4354 cp.objectId,cp.parentId,cp.variantType,cp.chunkId,(unsigned) obj));
4356 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4358 if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4359 ok = yaffs_WriteCheckpointTnodes(obj);
4366 /* Dump end of list */
4367 memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
4368 cp.structType = sizeof(cp);
4371 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4376 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4379 yaffs_CheckpointObject cp;
4382 yaffs_Object *hardList = NULL;
4384 while(ok && !done) {
4385 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4386 if(cp.structType != sizeof(cp)) {
4387 T(YAFFS_TRACE_CHECKPOINT,(TSTR("struct size %d instead of %d ok %d"TENDSTR),
4388 cp.structType,sizeof(cp),ok));
4392 T(YAFFS_TRACE_CHECKPOINT,(TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4393 cp.objectId,cp.parentId,cp.variantType,cp.chunkId));
4395 if(ok && cp.objectId == ~0)
4398 obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
4400 yaffs_CheckpointObjectToObject(obj,&cp);
4401 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4402 ok = yaffs_ReadCheckpointTnodes(obj);
4403 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4404 obj->hardLinks.next =
4405 (struct list_head *)
4415 yaffs_HardlinkFixup(dev,hardList);
4420 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4422 __u32 checkpointSum;
4425 yaffs_GetCheckpointSum(dev,&checkpointSum);
4427 ok = (yaffs_CheckpointWrite(dev,&checkpointSum,sizeof(checkpointSum)) == sizeof(checkpointSum));
4435 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4437 __u32 checkpointSum0;
4438 __u32 checkpointSum1;
4441 yaffs_GetCheckpointSum(dev,&checkpointSum0);
4443 ok = (yaffs_CheckpointRead(dev,&checkpointSum1,sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4448 if(checkpointSum0 != checkpointSum1)
4455 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4460 if(dev->skipCheckpointWrite || !dev->isYaffs2){
4461 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint write" TENDSTR)));
4466 ok = yaffs_CheckpointOpen(dev,1);
4469 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4470 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
4473 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint device" TENDSTR)));
4474 ok = yaffs_WriteCheckpointDevice(dev);
4477 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint objects" TENDSTR)));
4478 ok = yaffs_WriteCheckpointObjects(dev);
4481 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4482 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
4486 ok = yaffs_WriteCheckpointSum(dev);
4490 if(!yaffs_CheckpointClose(dev))
4494 dev->isCheckpointed = 1;
4496 dev->isCheckpointed = 0;
4498 return dev->isCheckpointed;
4501 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4505 if(dev->skipCheckpointRead || !dev->isYaffs2){
4506 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint read" TENDSTR)));
4511 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
4514 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4515 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
4518 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint device" TENDSTR)));
4519 ok = yaffs_ReadCheckpointDevice(dev);
4522 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint objects" TENDSTR)));
4523 ok = yaffs_ReadCheckpointObjects(dev);
4526 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4527 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
4531 ok = yaffs_ReadCheckpointSum(dev);
4532 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint checksum %d" TENDSTR),ok));
4535 if(!yaffs_CheckpointClose(dev))
4539 dev->isCheckpointed = 1;
4541 dev->isCheckpointed = 0;
4547 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4549 if(dev->isCheckpointed ||
4550 dev->blocksInCheckpoint > 0){
4551 dev->isCheckpointed = 0;
4552 yaffs_CheckpointInvalidateStream(dev);
4553 if(dev->superBlock && dev->markSuperBlockDirty)
4554 dev->markSuperBlockDirty(dev->superBlock);
4559 int yaffs_CheckpointSave(yaffs_Device *dev)
4562 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4564 yaffs_VerifyObjects(dev);
4565 yaffs_VerifyBlocks(dev);
4566 yaffs_VerifyFreeChunks(dev);
4568 if(!dev->isCheckpointed) {
4569 yaffs_InvalidateCheckpoint(dev);
4570 yaffs_WriteCheckpointData(dev);
4573 T(YAFFS_TRACE_ALWAYS,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4575 return dev->isCheckpointed;
4578 int yaffs_CheckpointRestore(yaffs_Device *dev)
4581 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4583 retval = yaffs_ReadCheckpointData(dev);
4585 if(dev->isCheckpointed){
4586 yaffs_VerifyObjects(dev);
4587 yaffs_VerifyBlocks(dev);
4588 yaffs_VerifyFreeChunks(dev);
4591 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4596 /*--------------------- File read/write ------------------------
4597 * Read and write have very similar structures.
4598 * In general the read/write has three parts to it
4599 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4600 * Some complete chunks
4601 * An incomplete chunk to end off with
4603 * Curve-balls: the first chunk might also be the last chunk.
4606 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, loff_t offset,
4615 yaffs_ChunkCache *cache;
4622 //chunk = offset / dev->nDataBytesPerChunk + 1;
4623 //start = offset % dev->nDataBytesPerChunk;
4624 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4627 /* OK now check for the curveball where the start and end are in
4630 if ((start + n) < dev->nDataBytesPerChunk) {
4633 nToCopy = dev->nDataBytesPerChunk - start;
4636 cache = yaffs_FindChunkCache(in, chunk);
4638 /* If the chunk is already in the cache or it is less than a whole chunk
4639 * then use the cache (if there is caching)
4640 * else bypass the cache.
4642 if (cache || nToCopy != dev->nDataBytesPerChunk) {
4643 if (dev->nShortOpCaches > 0) {
4645 /* If we can't find the data in the cache, then load it up. */
4648 cache = yaffs_GrabChunkCache(in->myDev);
4650 cache->chunkId = chunk;
4653 yaffs_ReadChunkDataFromObject(in, chunk,
4659 yaffs_UseChunkCache(dev, cache, 0);
4663 #ifdef CONFIG_YAFFS_WINCE
4664 yfsd_UnlockYAFFS(TRUE);
4666 memcpy(buffer, &cache->data[start], nToCopy);
4668 #ifdef CONFIG_YAFFS_WINCE
4669 yfsd_LockYAFFS(TRUE);
4673 /* Read into the local buffer then copy..*/
4676 yaffs_GetTempBuffer(dev, __LINE__);
4677 yaffs_ReadChunkDataFromObject(in, chunk,
4679 #ifdef CONFIG_YAFFS_WINCE
4680 yfsd_UnlockYAFFS(TRUE);
4682 memcpy(buffer, &localBuffer[start], nToCopy);
4684 #ifdef CONFIG_YAFFS_WINCE
4685 yfsd_LockYAFFS(TRUE);
4687 yaffs_ReleaseTempBuffer(dev, localBuffer,
4692 #ifdef CONFIG_YAFFS_WINCE
4693 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4695 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4696 * This is because we otherwise screw up WinCE's memory mapper
4698 yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
4700 #ifdef CONFIG_YAFFS_WINCE
4701 yfsd_UnlockYAFFS(TRUE);
4703 memcpy(buffer, localBuffer, dev->nDataBytesPerChunk);
4705 #ifdef CONFIG_YAFFS_WINCE
4706 yfsd_LockYAFFS(TRUE);
4707 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4711 /* A full chunk. Read directly into the supplied buffer. */
4712 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4726 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, loff_t offset,
4727 int nBytes, int writeThrough)
4736 int startOfWrite = offset;
4737 int chunkWritten = 0;
4744 while (n > 0 && chunkWritten >= 0) {
4745 //chunk = offset / dev->nDataBytesPerChunk + 1;
4746 //start = offset % dev->nDataBytesPerChunk;
4747 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4750 /* OK now check for the curveball where the start and end are in
4754 if ((start + n) < dev->nDataBytesPerChunk) {
4757 /* Now folks, to calculate how many bytes to write back....
4758 * If we're overwriting and not writing to then end of file then
4759 * we need to write back as much as was there before.
4763 in->variant.fileVariant.fileSize -
4764 ((chunk - 1) * dev->nDataBytesPerChunk);
4766 if (nBytesRead > dev->nDataBytesPerChunk) {
4767 nBytesRead = dev->nDataBytesPerChunk;
4772 (start + n)) ? nBytesRead : (start + n);
4775 nToCopy = dev->nDataBytesPerChunk - start;
4776 nToWriteBack = dev->nDataBytesPerChunk;
4779 if (nToCopy != dev->nDataBytesPerChunk) {
4780 /* An incomplete start or end chunk (or maybe both start and end chunk) */
4781 if (dev->nShortOpCaches > 0) {
4782 yaffs_ChunkCache *cache;
4783 /* If we can't find the data in the cache, then load the cache */
4784 cache = yaffs_FindChunkCache(in, chunk);
4787 && yaffs_CheckSpaceForAllocation(in->
4789 cache = yaffs_GrabChunkCache(in->myDev);
4791 cache->chunkId = chunk;
4794 yaffs_ReadChunkDataFromObject(in, chunk,
4800 !yaffs_CheckSpaceForAllocation(in->myDev)){
4801 /* Drop the cache if it was a read cache item and
4802 * no space check has been made for it.
4808 yaffs_UseChunkCache(dev, cache, 1);
4810 #ifdef CONFIG_YAFFS_WINCE
4811 yfsd_UnlockYAFFS(TRUE);
4814 memcpy(&cache->data[start], buffer,
4817 #ifdef CONFIG_YAFFS_WINCE
4818 yfsd_LockYAFFS(TRUE);
4821 cache->nBytes = nToWriteBack;
4825 yaffs_WriteChunkDataToObject
4828 cache->data, cache->nBytes,
4834 chunkWritten = -1; /* fail the write */
4837 /* An incomplete start or end chunk (or maybe both start and end chunk)
4838 * Read into the local buffer then copy, then copy over and write back.
4842 yaffs_GetTempBuffer(dev, __LINE__);
4844 yaffs_ReadChunkDataFromObject(in, chunk,
4847 #ifdef CONFIG_YAFFS_WINCE
4848 yfsd_UnlockYAFFS(TRUE);
4851 memcpy(&localBuffer[start], buffer, nToCopy);
4853 #ifdef CONFIG_YAFFS_WINCE
4854 yfsd_LockYAFFS(TRUE);
4857 yaffs_WriteChunkDataToObject(in, chunk,
4862 yaffs_ReleaseTempBuffer(dev, localBuffer,
4869 #ifdef CONFIG_YAFFS_WINCE
4870 /* Under WinCE can't do direct transfer. Need to use a local buffer.
4871 * This is because we otherwise screw up WinCE's memory mapper
4873 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4874 #ifdef CONFIG_YAFFS_WINCE
4875 yfsd_UnlockYAFFS(TRUE);
4877 memcpy(localBuffer, buffer, dev->nDataBytesPerChunk);
4878 #ifdef CONFIG_YAFFS_WINCE
4879 yfsd_LockYAFFS(TRUE);
4882 yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
4883 dev->nDataBytesPerChunk,
4885 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4887 /* A full chunk. Write directly from the supplied buffer. */
4889 yaffs_WriteChunkDataToObject(in, chunk, buffer,
4890 dev->nDataBytesPerChunk,
4893 /* Since we've overwritten the cached data, we better invalidate it. */
4894 yaffs_InvalidateChunkCache(in, chunk);
4897 if (chunkWritten >= 0) {
4906 /* Update file object */
4908 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
4909 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4918 /* ---------------------- File resizing stuff ------------------ */
4920 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
4923 yaffs_Device *dev = in->myDev;
4924 int oldFileSize = in->variant.fileVariant.fileSize;
4926 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
4928 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
4929 dev->nDataBytesPerChunk;
4933 /* Delete backwards so that we don't end up with holes if
4934 * power is lost part-way through the operation.
4936 for (i = lastDel; i >= startDel; i--) {
4937 /* NB this could be optimised somewhat,
4938 * eg. could retrieve the tags and write them without
4939 * using yaffs_DeleteChunk
4942 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
4945 (dev->internalStartBlock * dev->nChunksPerBlock)
4947 ((dev->internalEndBlock +
4948 1) * dev->nChunksPerBlock)) {
4949 T(YAFFS_TRACE_ALWAYS,
4950 (TSTR("Found daft chunkId %d for %d" TENDSTR),
4954 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
4961 int yaffs_ResizeFile(yaffs_Object * in, loff_t newSize)
4964 int oldFileSize = in->variant.fileVariant.fileSize;
4965 int newSizeOfPartialChunk;
4968 yaffs_Device *dev = in->myDev;
4970 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
4972 yaffs_FlushFilesChunkCache(in);
4973 yaffs_InvalidateWholeChunkCache(in);
4975 yaffs_CheckGarbageCollection(dev);
4977 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
4978 return yaffs_GetFileSize(in);
4981 if (newSize == oldFileSize) {
4985 if (newSize < oldFileSize) {
4987 yaffs_PruneResizedChunks(in, newSize);
4989 if (newSizeOfPartialChunk != 0) {
4990 int lastChunk = 1 + newFullChunks;
4992 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4994 /* Got to read and rewrite the last chunk with its new size and zero pad */
4995 yaffs_ReadChunkDataFromObject(in, lastChunk,
4998 memset(localBuffer + newSizeOfPartialChunk, 0,
4999 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5001 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5002 newSizeOfPartialChunk, 1);
5004 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5007 in->variant.fileVariant.fileSize = newSize;
5009 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5011 /* newsSize > oldFileSize */
5012 in->variant.fileVariant.fileSize = newSize;
5017 /* Write a new object header.
5018 * show we've shrunk the file, if need be
5019 * Do this only if the file is not in the deleted directories.
5021 if (in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5022 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
5023 yaffs_UpdateObjectHeader(in, NULL, 0,
5024 (newSize < oldFileSize) ? 1 : 0, 0);
5030 loff_t yaffs_GetFileSize(yaffs_Object * obj)
5032 obj = yaffs_GetEquivalentObject(obj);
5034 switch (obj->variantType) {
5035 case YAFFS_OBJECT_TYPE_FILE:
5036 return obj->variant.fileVariant.fileSize;
5037 case YAFFS_OBJECT_TYPE_SYMLINK:
5038 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5046 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
5050 yaffs_FlushFilesChunkCache(in);
5052 #ifdef CONFIG_YAFFS_WINCE
5053 yfsd_WinFileTimeNow(in->win_mtime);
5056 in->yst_mtime = Y_CURRENT_TIME;
5062 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5063 0) ? YAFFS_OK : YAFFS_FAIL;
5072 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
5075 /* First off, invalidate the file's data in the cache, without flushing. */
5076 yaffs_InvalidateWholeChunkCache(in);
5078 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5079 /* Move to the unlinked directory so we have a record that it was deleted. */
5080 yaffs_ChangeObjectName(in, in->myDev->deletedDir,"deleted", 0, 0);
5084 yaffs_RemoveObjectFromDirectory(in);
5085 yaffs_DeleteChunk(in->myDev, in->chunkId, 1, __LINE__);
5088 yaffs_FreeObject(in);
5093 /* yaffs_DeleteFile deletes the whole file data
5094 * and the inode associated with the file.
5095 * It does not delete the links associated with the file.
5097 static int yaffs_UnlinkFile(yaffs_Object * in)
5101 int immediateDeletion = 0;
5104 /* XXX U-BOOT XXX */
5108 immediateDeletion = 1;
5113 if (in->inUse <= 0) {
5114 immediateDeletion = 1;
5118 if (immediateDeletion) {
5120 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5122 T(YAFFS_TRACE_TRACING,
5123 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5126 in->myDev->nDeletedFiles++;
5127 if (0 && in->myDev->isYaffs2) {
5128 yaffs_ResizeFile(in, 0);
5130 yaffs_SoftDeleteFile(in);
5133 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5141 int yaffs_DeleteFile(yaffs_Object * in)
5143 int retVal = YAFFS_OK;
5145 if (in->nDataChunks > 0) {
5146 /* Use soft deletion if there is data in the file */
5147 if (!in->unlinked) {
5148 retVal = yaffs_UnlinkFile(in);
5150 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5152 in->myDev->nDeletedFiles++;
5153 yaffs_SoftDeleteFile(in);
5155 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
5157 /* The file has no data chunks so we toss it immediately */
5158 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5159 in->variant.fileVariant.top = NULL;
5160 yaffs_DoGenericObjectDeletion(in);
5166 static int yaffs_DeleteDirectory(yaffs_Object * in)
5168 /* First check that the directory is empty. */
5169 if (list_empty(&in->variant.directoryVariant.children)) {
5170 return yaffs_DoGenericObjectDeletion(in);
5177 static int yaffs_DeleteSymLink(yaffs_Object * in)
5179 YFREE(in->variant.symLinkVariant.alias);
5181 return yaffs_DoGenericObjectDeletion(in);
5184 static int yaffs_DeleteHardLink(yaffs_Object * in)
5186 /* remove this hardlink from the list assocaited with the equivalent
5189 list_del(&in->hardLinks);
5190 return yaffs_DoGenericObjectDeletion(in);
5193 static void yaffs_DestroyObject(yaffs_Object * obj)
5195 switch (obj->variantType) {
5196 case YAFFS_OBJECT_TYPE_FILE:
5197 yaffs_DeleteFile(obj);
5199 case YAFFS_OBJECT_TYPE_DIRECTORY:
5200 yaffs_DeleteDirectory(obj);
5202 case YAFFS_OBJECT_TYPE_SYMLINK:
5203 yaffs_DeleteSymLink(obj);
5205 case YAFFS_OBJECT_TYPE_HARDLINK:
5206 yaffs_DeleteHardLink(obj);
5208 case YAFFS_OBJECT_TYPE_SPECIAL:
5209 yaffs_DoGenericObjectDeletion(obj);
5211 case YAFFS_OBJECT_TYPE_UNKNOWN:
5212 break; /* should not happen. */
5216 static int yaffs_UnlinkWorker(yaffs_Object * obj)
5219 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5220 return yaffs_DeleteHardLink(obj);
5221 } else if (!list_empty(&obj->hardLinks)) {
5222 /* Curve ball: We're unlinking an object that has a hardlink.
5224 * This problem arises because we are not strictly following
5225 * The Linux link/inode model.
5227 * We can't really delete the object.
5228 * Instead, we do the following:
5229 * - Select a hardlink.
5230 * - Unhook it from the hard links
5231 * - Unhook it from its parent directory (so that the rename can work)
5232 * - Rename the object to the hardlink's name.
5233 * - Delete the hardlink
5238 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5240 hl = list_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5242 list_del_init(&hl->hardLinks);
5243 list_del_init(&hl->siblings);
5245 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5247 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
5249 if (retVal == YAFFS_OK) {
5250 retVal = yaffs_DoGenericObjectDeletion(hl);
5255 switch (obj->variantType) {
5256 case YAFFS_OBJECT_TYPE_FILE:
5257 return yaffs_UnlinkFile(obj);
5259 case YAFFS_OBJECT_TYPE_DIRECTORY:
5260 return yaffs_DeleteDirectory(obj);
5262 case YAFFS_OBJECT_TYPE_SYMLINK:
5263 return yaffs_DeleteSymLink(obj);
5265 case YAFFS_OBJECT_TYPE_SPECIAL:
5266 return yaffs_DoGenericObjectDeletion(obj);
5268 case YAFFS_OBJECT_TYPE_HARDLINK:
5269 case YAFFS_OBJECT_TYPE_UNKNOWN:
5277 static int yaffs_UnlinkObject( yaffs_Object *obj)
5280 if (obj && obj->unlinkAllowed) {
5281 return yaffs_UnlinkWorker(obj);
5287 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
5291 obj = yaffs_FindObjectByName(dir, name);
5292 return yaffs_UnlinkObject(obj);
5295 /*----------------------- Initialisation Scanning ---------------------- */
5297 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
5298 int backwardScanning)
5302 if (!backwardScanning) {
5303 /* Handle YAFFS1 forward scanning case
5304 * For YAFFS1 we always do the deletion
5308 /* Handle YAFFS2 case (backward scanning)
5309 * If the shadowed object exists then ignore.
5311 if (yaffs_FindObjectByNumber(dev, objId)) {
5316 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5317 * We put it in unlinked dir to be cleaned up after the scanning
5320 yaffs_FindOrCreateObjectByNumber(dev, objId,
5321 YAFFS_OBJECT_TYPE_FILE);
5322 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5323 obj->variant.fileVariant.shrinkSize = 0;
5324 obj->valid = 1; /* So that we don't read any other info for this file */
5334 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5341 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5343 in = yaffs_FindObjectByNumber(dev,
5344 hl->variant.hardLinkVariant.
5345 equivalentObjectId);
5348 /* Add the hardlink pointers */
5349 hl->variant.hardLinkVariant.equivalentObject = in;
5350 list_add(&hl->hardLinks, &in->hardLinks);
5352 /* Todo Need to report/handle this better.
5353 * Got a problem... hardlink to a non-existant object
5355 hl->variant.hardLinkVariant.equivalentObject = NULL;
5356 INIT_LIST_HEAD(&hl->hardLinks);
5368 static int ybicmp(const void *a, const void *b){
5369 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5370 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5371 register int ablock = ((yaffs_BlockIndex *)a)->block;
5372 register int bblock = ((yaffs_BlockIndex *)b)->block;
5374 return ablock - bblock;
5380 static int yaffs_Scan(yaffs_Device * dev)
5382 yaffs_ExtendedTags tags;
5387 int nBlocksToScan = 0;
5393 yaffs_BlockState state;
5394 yaffs_Object *hardList = NULL;
5395 yaffs_BlockInfo *bi;
5397 yaffs_ObjectHeader *oh;
5399 yaffs_Object *parent;
5400 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5402 int alloc_failed = 0;
5407 yaffs_BlockIndex *blockIndex = NULL;
5409 if (dev->isYaffs2) {
5411 (TSTR("yaffs_Scan is not for YAFFS2!" TENDSTR)));
5415 //TODO Throw all the yaffs2 stuuf out of yaffs_Scan since it is only for yaffs1 format.
5418 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5419 dev->internalStartBlock, dev->internalEndBlock));
5421 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5423 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5425 if (dev->isYaffs2) {
5426 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
5431 /* Scan all the blocks to determine their state */
5432 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5433 bi = yaffs_GetBlockInfo(dev, blk);
5434 yaffs_ClearChunkBits(dev, blk);
5436 bi->softDeletions = 0;
5438 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5440 bi->blockState = state;
5441 bi->sequenceNumber = sequenceNumber;
5443 T(YAFFS_TRACE_SCAN_DEBUG,
5444 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5445 state, sequenceNumber));
5447 if (state == YAFFS_BLOCK_STATE_DEAD) {
5448 T(YAFFS_TRACE_BAD_BLOCKS,
5449 (TSTR("block %d is bad" TENDSTR), blk));
5450 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5451 T(YAFFS_TRACE_SCAN_DEBUG,
5452 (TSTR("Block empty " TENDSTR)));
5453 dev->nErasedBlocks++;
5454 dev->nFreeChunks += dev->nChunksPerBlock;
5455 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5457 /* Determine the highest sequence number */
5458 if (dev->isYaffs2 &&
5459 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
5460 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
5462 blockIndex[nBlocksToScan].seq = sequenceNumber;
5463 blockIndex[nBlocksToScan].block = blk;
5467 if (sequenceNumber >= dev->sequenceNumber) {
5468 dev->sequenceNumber = sequenceNumber;
5470 } else if (dev->isYaffs2) {
5471 /* TODO: Nasty sequence number! */
5474 ("Block scanning block %d has bad sequence number %d"
5475 TENDSTR), blk, sequenceNumber));
5482 * Dungy old bubble sort for now...
5484 if (dev->isYaffs2) {
5485 yaffs_BlockIndex temp;
5489 for (i = 0; i < nBlocksToScan; i++)
5490 for (j = i + 1; j < nBlocksToScan; j++)
5491 if (blockIndex[i].seq > blockIndex[j].seq) {
5492 temp = blockIndex[j];
5493 blockIndex[j] = blockIndex[i];
5494 blockIndex[i] = temp;
5498 /* Now scan the blocks looking at the data. */
5499 if (dev->isYaffs2) {
5501 endIterator = nBlocksToScan - 1;
5502 T(YAFFS_TRACE_SCAN_DEBUG,
5503 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
5505 startIterator = dev->internalStartBlock;
5506 endIterator = dev->internalEndBlock;
5509 /* For each block.... */
5510 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5513 if (dev->isYaffs2) {
5514 /* get the block to scan in the correct order */
5515 blk = blockIndex[blockIterator].block;
5517 blk = blockIterator;
5520 bi = yaffs_GetBlockInfo(dev, blk);
5521 state = bi->blockState;
5525 /* For each chunk in each block that needs scanning....*/
5526 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5527 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5528 /* Read the tags and decide what to do */
5529 chunk = blk * dev->nChunksPerBlock + c;
5531 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5534 /* Let's have a good look at this chunk... */
5536 if (!dev->isYaffs2 && tags.chunkDeleted) {
5542 /*T((" %d %d deleted\n",blk,c)); */
5543 } else if (!tags.chunkUsed) {
5544 /* An unassigned chunk in the block
5545 * This means that either the block is empty or
5546 * this is the one being allocated from
5550 /* We're looking at the first chunk in the block so the block is unused */
5551 state = YAFFS_BLOCK_STATE_EMPTY;
5552 dev->nErasedBlocks++;
5554 /* this is the block being allocated from */
5557 (" Allocating from %d %d" TENDSTR),
5559 state = YAFFS_BLOCK_STATE_ALLOCATING;
5560 dev->allocationBlock = blk;
5561 dev->allocationPage = c;
5562 dev->allocationBlockFinder = blk;
5563 /* Set it to here to encourage the allocator to go forth from here. */
5565 /* Yaffs2 sanity check:
5566 * This should be the one with the highest sequence number
5569 && (dev->sequenceNumber !=
5570 bi->sequenceNumber)) {
5571 T(YAFFS_TRACE_ALWAYS,
5573 ("yaffs: Allocation block %d was not highest sequence id:"
5574 " block seq = %d, dev seq = %d"
5575 TENDSTR), blk,bi->sequenceNumber,dev->sequenceNumber));
5579 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5580 } else if (tags.chunkId > 0) {
5581 /* chunkId > 0 so it is a data chunk... */
5582 unsigned int endpos;
5584 yaffs_SetChunkBit(dev, blk, c);
5587 in = yaffs_FindOrCreateObjectByNumber(dev,
5590 YAFFS_OBJECT_TYPE_FILE);
5591 /* PutChunkIntoFile checks for a clash (two data chunks with
5592 * the same chunkId).
5599 if(!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,1))
5604 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5607 in->variantType == YAFFS_OBJECT_TYPE_FILE
5608 && in->variant.fileVariant.scannedFileSize <
5610 in->variant.fileVariant.
5611 scannedFileSize = endpos;
5612 if (!dev->useHeaderFileSize) {
5613 in->variant.fileVariant.
5615 in->variant.fileVariant.
5620 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
5622 /* chunkId == 0, so it is an ObjectHeader.
5623 * Thus, we read in the object header and make the object
5625 yaffs_SetChunkBit(dev, blk, c);
5628 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5632 oh = (yaffs_ObjectHeader *) chunkData;
5634 in = yaffs_FindObjectByNumber(dev,
5636 if (in && in->variantType != oh->type) {
5637 /* This should not happen, but somehow
5638 * Wev'e ended up with an objectId that has been reused but not yet
5639 * deleted, and worse still it has changed type. Delete the old object.
5642 yaffs_DestroyObject(in);
5647 in = yaffs_FindOrCreateObjectByNumber(dev,
5655 if (in && oh->shadowsObject > 0) {
5656 yaffs_HandleShadowedObject(dev,
5662 if (in && in->valid) {
5663 /* We have already filled this one. We have a duplicate and need to resolve it. */
5665 unsigned existingSerial = in->serial;
5666 unsigned newSerial = tags.serialNumber;
5668 if (dev->isYaffs2 ||
5669 ((existingSerial + 1) & 3) ==
5671 /* Use new one - destroy the exisiting one */
5672 yaffs_DeleteChunk(dev,
5677 /* Use existing - destroy this one. */
5678 yaffs_DeleteChunk(dev, chunk, 1,
5683 if (in && !in->valid &&
5684 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5685 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5686 /* We only load some info, don't fiddle with directory structure */
5688 in->variantType = oh->type;
5690 in->yst_mode = oh->yst_mode;
5691 #ifdef CONFIG_YAFFS_WINCE
5692 in->win_atime[0] = oh->win_atime[0];
5693 in->win_ctime[0] = oh->win_ctime[0];
5694 in->win_mtime[0] = oh->win_mtime[0];
5695 in->win_atime[1] = oh->win_atime[1];
5696 in->win_ctime[1] = oh->win_ctime[1];
5697 in->win_mtime[1] = oh->win_mtime[1];
5699 in->yst_uid = oh->yst_uid;
5700 in->yst_gid = oh->yst_gid;
5701 in->yst_atime = oh->yst_atime;
5702 in->yst_mtime = oh->yst_mtime;
5703 in->yst_ctime = oh->yst_ctime;
5704 in->yst_rdev = oh->yst_rdev;
5706 in->chunkId = chunk;
5708 } else if (in && !in->valid) {
5709 /* we need to load this info */
5712 in->variantType = oh->type;
5714 in->yst_mode = oh->yst_mode;
5715 #ifdef CONFIG_YAFFS_WINCE
5716 in->win_atime[0] = oh->win_atime[0];
5717 in->win_ctime[0] = oh->win_ctime[0];
5718 in->win_mtime[0] = oh->win_mtime[0];
5719 in->win_atime[1] = oh->win_atime[1];
5720 in->win_ctime[1] = oh->win_ctime[1];
5721 in->win_mtime[1] = oh->win_mtime[1];
5723 in->yst_uid = oh->yst_uid;
5724 in->yst_gid = oh->yst_gid;
5725 in->yst_atime = oh->yst_atime;
5726 in->yst_mtime = oh->yst_mtime;
5727 in->yst_ctime = oh->yst_ctime;
5728 in->yst_rdev = oh->yst_rdev;
5730 in->chunkId = chunk;
5732 yaffs_SetObjectName(in, oh->name);
5735 /* directory stuff...
5740 yaffs_FindOrCreateObjectByNumber
5741 (dev, oh->parentObjectId,
5742 YAFFS_OBJECT_TYPE_DIRECTORY);
5743 if (parent->variantType ==
5744 YAFFS_OBJECT_TYPE_UNKNOWN) {
5745 /* Set up as a directory */
5746 parent->variantType =
5747 YAFFS_OBJECT_TYPE_DIRECTORY;
5748 INIT_LIST_HEAD(&parent->variant.
5751 } else if (parent->variantType !=
5752 YAFFS_OBJECT_TYPE_DIRECTORY)
5754 /* Hoosterman, another problem....
5755 * We're trying to use a non-directory as a directory
5758 T(YAFFS_TRACE_ERROR,
5760 ("yaffs tragedy: attempting to use non-directory as"
5761 " a directory in scan. Put in lost+found."
5763 parent = dev->lostNFoundDir;
5766 yaffs_AddObjectToDirectory(parent, in);
5768 if (0 && (parent == dev->deletedDir ||
5769 parent == dev->unlinkedDir)) {
5770 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
5771 dev->nDeletedFiles++;
5773 /* Note re hardlinks.
5774 * Since we might scan a hardlink before its equivalent object is scanned
5775 * we put them all in a list.
5776 * After scanning is complete, we should have all the objects, so we run through this
5777 * list and fix up all the chains.
5780 switch (in->variantType) {
5781 case YAFFS_OBJECT_TYPE_UNKNOWN:
5782 /* Todo got a problem */
5784 case YAFFS_OBJECT_TYPE_FILE:
5787 /* Prune back the shrunken chunks */
5788 yaffs_PruneResizedChunks
5790 /* Mark the block as having a shrinkHeader */
5791 bi->hasShrinkHeader = 1;
5794 if (dev->useHeaderFileSize)
5796 in->variant.fileVariant.
5801 case YAFFS_OBJECT_TYPE_HARDLINK:
5802 in->variant.hardLinkVariant.
5803 equivalentObjectId =
5804 oh->equivalentObjectId;
5805 in->hardLinks.next =
5806 (struct list_head *)
5810 case YAFFS_OBJECT_TYPE_DIRECTORY:
5813 case YAFFS_OBJECT_TYPE_SPECIAL:
5816 case YAFFS_OBJECT_TYPE_SYMLINK:
5817 in->variant.symLinkVariant.alias =
5818 yaffs_CloneString(oh->alias);
5819 if(!in->variant.symLinkVariant.alias)
5824 if (parent == dev->deletedDir) {
5825 yaffs_DestroyObject(in);
5826 bi->hasShrinkHeader = 1;
5832 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5833 /* If we got this far while scanning, then the block is fully allocated.*/
5834 state = YAFFS_BLOCK_STATE_FULL;
5837 bi->blockState = state;
5839 /* Now let's see if it was dirty */
5840 if (bi->pagesInUse == 0 &&
5841 !bi->hasShrinkHeader &&
5842 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5843 yaffs_BlockBecameDirty(dev, blk);
5853 /* Ok, we've done all the scanning.
5854 * Fix up the hard link chains.
5855 * We should now have scanned all the objects, now it's time to add these
5859 yaffs_HardlinkFixup(dev,hardList);
5861 /* Handle the unlinked files. Since they were left in an unlinked state we should
5865 struct list_head *i;
5866 struct list_head *n;
5869 /* Soft delete all the unlinked files */
5870 list_for_each_safe(i, n,
5871 &dev->unlinkedDir->variant.directoryVariant.
5874 l = list_entry(i, yaffs_Object, siblings);
5875 yaffs_DestroyObject(l);
5880 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5886 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5892 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5895 yaffs_ObjectHeader *oh;
5896 yaffs_Device *dev = in->myDev;
5897 yaffs_ExtendedTags tags;
5899 int alloc_failed = 0;
5905 T(YAFFS_TRACE_SCAN,(TSTR("details for object %d %s loaded" TENDSTR),
5907 in->lazyLoaded ? "not yet" : "already"));
5912 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5914 result = yaffs_ReadChunkWithTagsFromNAND(dev,in->chunkId,chunkData,&tags);
5915 oh = (yaffs_ObjectHeader *) chunkData;
5917 in->yst_mode = oh->yst_mode;
5918 #ifdef CONFIG_YAFFS_WINCE
5919 in->win_atime[0] = oh->win_atime[0];
5920 in->win_ctime[0] = oh->win_ctime[0];
5921 in->win_mtime[0] = oh->win_mtime[0];
5922 in->win_atime[1] = oh->win_atime[1];
5923 in->win_ctime[1] = oh->win_ctime[1];
5924 in->win_mtime[1] = oh->win_mtime[1];
5926 in->yst_uid = oh->yst_uid;
5927 in->yst_gid = oh->yst_gid;
5928 in->yst_atime = oh->yst_atime;
5929 in->yst_mtime = oh->yst_mtime;
5930 in->yst_ctime = oh->yst_ctime;
5931 in->yst_rdev = oh->yst_rdev;
5934 yaffs_SetObjectName(in, oh->name);
5936 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
5937 in->variant.symLinkVariant.alias =
5938 yaffs_CloneString(oh->alias);
5939 if(!in->variant.symLinkVariant.alias)
5940 alloc_failed = 1; /* Not returned to caller */
5943 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
5947 static int yaffs_ScanBackwards(yaffs_Device * dev)
5949 yaffs_ExtendedTags tags;
5954 int nBlocksToScan = 0;
5960 yaffs_BlockState state;
5961 yaffs_Object *hardList = NULL;
5962 yaffs_BlockInfo *bi;
5964 yaffs_ObjectHeader *oh;
5966 yaffs_Object *parent;
5967 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5973 int foundChunksInBlock;
5974 int equivalentObjectId;
5975 int alloc_failed = 0;
5978 yaffs_BlockIndex *blockIndex = NULL;
5979 int altBlockIndex = 0;
5981 if (!dev->isYaffs2) {
5983 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
5989 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
5990 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
5993 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5995 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
5998 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6004 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6008 dev->blocksInCheckpoint = 0;
6010 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6012 /* Scan all the blocks to determine their state */
6013 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6014 bi = yaffs_GetBlockInfo(dev, blk);
6015 yaffs_ClearChunkBits(dev, blk);
6017 bi->softDeletions = 0;
6019 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6021 bi->blockState = state;
6022 bi->sequenceNumber = sequenceNumber;
6024 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6025 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6027 T(YAFFS_TRACE_SCAN_DEBUG,
6028 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6029 state, sequenceNumber));
6032 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
6033 dev->blocksInCheckpoint++;
6035 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6036 T(YAFFS_TRACE_BAD_BLOCKS,
6037 (TSTR("block %d is bad" TENDSTR), blk));
6038 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6039 T(YAFFS_TRACE_SCAN_DEBUG,
6040 (TSTR("Block empty " TENDSTR)));
6041 dev->nErasedBlocks++;
6042 dev->nFreeChunks += dev->nChunksPerBlock;
6043 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6045 /* Determine the highest sequence number */
6046 if (dev->isYaffs2 &&
6047 sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6048 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6050 blockIndex[nBlocksToScan].seq = sequenceNumber;
6051 blockIndex[nBlocksToScan].block = blk;
6055 if (sequenceNumber >= dev->sequenceNumber) {
6056 dev->sequenceNumber = sequenceNumber;
6058 } else if (dev->isYaffs2) {
6059 /* TODO: Nasty sequence number! */
6062 ("Block scanning block %d has bad sequence number %d"
6063 TENDSTR), blk, sequenceNumber));
6070 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6076 /* Sort the blocks */
6077 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6079 /* Use qsort now. */
6080 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6084 /* Dungy old bubble sort... */
6086 yaffs_BlockIndex temp;
6090 for (i = 0; i < nBlocksToScan; i++)
6091 for (j = i + 1; j < nBlocksToScan; j++)
6092 if (blockIndex[i].seq > blockIndex[j].seq) {
6093 temp = blockIndex[j];
6094 blockIndex[j] = blockIndex[i];
6095 blockIndex[i] = temp;
6102 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6104 /* Now scan the blocks looking at the data. */
6106 endIterator = nBlocksToScan - 1;
6107 T(YAFFS_TRACE_SCAN_DEBUG,
6108 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6110 /* For each block.... backwards */
6111 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6113 /* Cooperative multitasking! This loop can run for so
6114 long that watchdog timers expire. */
6117 /* get the block to scan in the correct order */
6118 blk = blockIndex[blockIterator].block;
6120 bi = yaffs_GetBlockInfo(dev, blk);
6123 state = bi->blockState;
6127 /* For each chunk in each block that needs scanning.... */
6128 foundChunksInBlock = 0;
6129 for (c = dev->nChunksPerBlock - 1;
6130 !alloc_failed && c >= 0 &&
6131 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6132 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6133 /* Scan backwards...
6134 * Read the tags and decide what to do
6137 chunk = blk * dev->nChunksPerBlock + c;
6139 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6142 /* Let's have a good look at this chunk... */
6144 if (!tags.chunkUsed) {
6145 /* An unassigned chunk in the block.
6146 * If there are used chunks after this one, then
6147 * it is a chunk that was skipped due to failing the erased
6148 * check. Just skip it so that it can be deleted.
6149 * But, more typically, We get here when this is an unallocated
6150 * chunk and his means that either the block is empty or
6151 * this is the one being allocated from
6154 if(foundChunksInBlock)
6156 /* This is a chunk that was skipped due to failing the erased check */
6158 } else if (c == 0) {
6159 /* We're looking at the first chunk in the block so the block is unused */
6160 state = YAFFS_BLOCK_STATE_EMPTY;
6161 dev->nErasedBlocks++;
6163 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6164 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6165 if(dev->sequenceNumber == bi->sequenceNumber) {
6166 /* this is the block being allocated from */
6170 (" Allocating from %d %d"
6173 state = YAFFS_BLOCK_STATE_ALLOCATING;
6174 dev->allocationBlock = blk;
6175 dev->allocationPage = c;
6176 dev->allocationBlockFinder = blk;
6179 /* This is a partially written block that is not
6180 * the current allocation block. This block must have
6181 * had a write failure, so set up for retirement.
6184 bi->needsRetiring = 1;
6185 bi->gcPrioritise = 1;
6187 T(YAFFS_TRACE_ALWAYS,
6188 (TSTR("Partially written block %d being set for retirement" TENDSTR),
6198 } else if (tags.chunkId > 0) {
6199 /* chunkId > 0 so it is a data chunk... */
6200 unsigned int endpos;
6202 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6204 foundChunksInBlock = 1;
6207 yaffs_SetChunkBit(dev, blk, c);
6210 in = yaffs_FindOrCreateObjectByNumber(dev,
6213 YAFFS_OBJECT_TYPE_FILE);
6220 in->variantType == YAFFS_OBJECT_TYPE_FILE
6222 in->variant.fileVariant.shrinkSize) {
6223 /* This has not been invalidated by a resize */
6224 if(!yaffs_PutChunkIntoFile(in, tags.chunkId,
6229 /* File size is calculated by looking at the data chunks if we have not
6230 * seen an object header yet. Stop this practice once we find an object header.
6234 1) * dev->nDataBytesPerChunk +
6237 if (!in->valid && /* have not got an object header yet */
6238 in->variant.fileVariant.
6239 scannedFileSize < endpos) {
6240 in->variant.fileVariant.
6241 scannedFileSize = endpos;
6242 in->variant.fileVariant.
6244 in->variant.fileVariant.
6249 /* This chunk has been invalidated by a resize, so delete */
6250 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6254 /* chunkId == 0, so it is an ObjectHeader.
6255 * Thus, we read in the object header and make the object
6257 foundChunksInBlock = 1;
6259 yaffs_SetChunkBit(dev, blk, c);
6265 if (tags.extraHeaderInfoAvailable) {
6266 in = yaffs_FindOrCreateObjectByNumber
6267 (dev, tags.objectId,
6268 tags.extraObjectType);
6272 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
6275 tags.extraShadows ||
6277 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6278 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
6281 /* If we don't have valid info then we need to read the chunk
6282 * TODO In future we can probably defer reading the chunk and
6283 * living with invalid data until needed.
6286 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6291 oh = (yaffs_ObjectHeader *) chunkData;
6294 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6299 /* TODO Hoosterman we have a problem! */
6300 T(YAFFS_TRACE_ERROR,
6302 ("yaffs tragedy: Could not make object for object %d "
6303 "at chunk %d during scan"
6304 TENDSTR), tags.objectId, chunk));
6309 /* We have already filled this one.
6310 * We have a duplicate that will be discarded, but
6311 * we first have to suck out resize info if it is a file.
6314 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6316 oh-> type == YAFFS_OBJECT_TYPE_FILE)||
6317 (tags.extraHeaderInfoAvailable &&
6318 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
6321 (oh) ? oh->fileSize : tags.
6323 __u32 parentObjectId =
6325 parentObjectId : tags.
6326 extraParentObjectId;
6328 (oh) ? oh->isShrink : tags.
6329 extraIsShrinkHeader;
6331 /* If it is deleted (unlinked at start also means deleted)
6332 * we treat the file size as being zeroed at this point.
6334 if (parentObjectId ==
6335 YAFFS_OBJECTID_DELETED
6336 || parentObjectId ==
6337 YAFFS_OBJECTID_UNLINKED) {
6343 in->variant.fileVariant.
6344 shrinkSize > thisSize) {
6345 in->variant.fileVariant.
6351 bi->hasShrinkHeader = 1;
6355 /* Use existing - destroy this one. */
6356 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6361 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6363 YAFFS_OBJECTID_LOSTNFOUND)) {
6364 /* We only load some info, don't fiddle with directory structure */
6368 in->variantType = oh->type;
6370 in->yst_mode = oh->yst_mode;
6371 #ifdef CONFIG_YAFFS_WINCE
6372 in->win_atime[0] = oh->win_atime[0];
6373 in->win_ctime[0] = oh->win_ctime[0];
6374 in->win_mtime[0] = oh->win_mtime[0];
6375 in->win_atime[1] = oh->win_atime[1];
6376 in->win_ctime[1] = oh->win_ctime[1];
6377 in->win_mtime[1] = oh->win_mtime[1];
6379 in->yst_uid = oh->yst_uid;
6380 in->yst_gid = oh->yst_gid;
6381 in->yst_atime = oh->yst_atime;
6382 in->yst_mtime = oh->yst_mtime;
6383 in->yst_ctime = oh->yst_ctime;
6384 in->yst_rdev = oh->yst_rdev;
6388 in->variantType = tags.extraObjectType;
6392 in->chunkId = chunk;
6394 } else if (!in->valid) {
6395 /* we need to load this info */
6398 in->chunkId = chunk;
6401 in->variantType = oh->type;
6403 in->yst_mode = oh->yst_mode;
6404 #ifdef CONFIG_YAFFS_WINCE
6405 in->win_atime[0] = oh->win_atime[0];
6406 in->win_ctime[0] = oh->win_ctime[0];
6407 in->win_mtime[0] = oh->win_mtime[0];
6408 in->win_atime[1] = oh->win_atime[1];
6409 in->win_ctime[1] = oh->win_ctime[1];
6410 in->win_mtime[1] = oh->win_mtime[1];
6412 in->yst_uid = oh->yst_uid;
6413 in->yst_gid = oh->yst_gid;
6414 in->yst_atime = oh->yst_atime;
6415 in->yst_mtime = oh->yst_mtime;
6416 in->yst_ctime = oh->yst_ctime;
6417 in->yst_rdev = oh->yst_rdev;
6420 if (oh->shadowsObject > 0)
6421 yaffs_HandleShadowedObject(dev,
6427 yaffs_SetObjectName(in, oh->name);
6429 yaffs_FindOrCreateObjectByNumber
6430 (dev, oh->parentObjectId,
6431 YAFFS_OBJECT_TYPE_DIRECTORY);
6433 fileSize = oh->fileSize;
6434 isShrink = oh->isShrink;
6435 equivalentObjectId = oh->equivalentObjectId;
6439 in->variantType = tags.extraObjectType;
6441 yaffs_FindOrCreateObjectByNumber
6442 (dev, tags.extraParentObjectId,
6443 YAFFS_OBJECT_TYPE_DIRECTORY);
6444 fileSize = tags.extraFileLength;
6445 isShrink = tags.extraIsShrinkHeader;
6446 equivalentObjectId = tags.extraEquivalentObjectId;
6455 /* directory stuff...
6459 if (parent && parent->variantType ==
6460 YAFFS_OBJECT_TYPE_UNKNOWN) {
6461 /* Set up as a directory */
6462 parent->variantType =
6463 YAFFS_OBJECT_TYPE_DIRECTORY;
6464 INIT_LIST_HEAD(&parent->variant.
6467 } else if (!parent || parent->variantType !=
6468 YAFFS_OBJECT_TYPE_DIRECTORY)
6470 /* Hoosterman, another problem....
6471 * We're trying to use a non-directory as a directory
6474 T(YAFFS_TRACE_ERROR,
6476 ("yaffs tragedy: attempting to use non-directory as"
6477 " a directory in scan. Put in lost+found."
6479 parent = dev->lostNFoundDir;
6482 yaffs_AddObjectToDirectory(parent, in);
6484 itsUnlinked = (parent == dev->deletedDir) ||
6485 (parent == dev->unlinkedDir);
6488 /* Mark the block as having a shrinkHeader */
6489 bi->hasShrinkHeader = 1;
6492 /* Note re hardlinks.
6493 * Since we might scan a hardlink before its equivalent object is scanned
6494 * we put them all in a list.
6495 * After scanning is complete, we should have all the objects, so we run
6496 * through this list and fix up all the chains.
6499 switch (in->variantType) {
6500 case YAFFS_OBJECT_TYPE_UNKNOWN:
6501 /* Todo got a problem */
6503 case YAFFS_OBJECT_TYPE_FILE:
6505 if (in->variant.fileVariant.
6506 scannedFileSize < fileSize) {
6507 /* This covers the case where the file size is greater
6508 * than where the data is
6509 * This will happen if the file is resized to be larger
6510 * than its current data extents.
6512 in->variant.fileVariant.fileSize = fileSize;
6513 in->variant.fileVariant.scannedFileSize =
6514 in->variant.fileVariant.fileSize;
6518 in->variant.fileVariant.shrinkSize > fileSize) {
6519 in->variant.fileVariant.shrinkSize = fileSize;
6523 case YAFFS_OBJECT_TYPE_HARDLINK:
6525 in->variant.hardLinkVariant.equivalentObjectId =
6527 in->hardLinks.next =
6528 (struct list_head *) hardList;
6532 case YAFFS_OBJECT_TYPE_DIRECTORY:
6535 case YAFFS_OBJECT_TYPE_SPECIAL:
6538 case YAFFS_OBJECT_TYPE_SYMLINK:
6540 in->variant.symLinkVariant.alias =
6541 yaffs_CloneString(oh->
6543 if(!in->variant.symLinkVariant.alias)
6553 } /* End of scanning for each chunk */
6555 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6556 /* If we got this far while scanning, then the block is fully allocated. */
6557 state = YAFFS_BLOCK_STATE_FULL;
6560 bi->blockState = state;
6562 /* Now let's see if it was dirty */
6563 if (bi->pagesInUse == 0 &&
6564 !bi->hasShrinkHeader &&
6565 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6566 yaffs_BlockBecameDirty(dev, blk);
6572 YFREE_ALT(blockIndex);
6576 /* Ok, we've done all the scanning.
6577 * Fix up the hard link chains.
6578 * We should now have scanned all the objects, now it's time to add these
6581 yaffs_HardlinkFixup(dev,hardList);
6584 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6590 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6595 /*------------------------------ Directory Functions ----------------------------- */
6597 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
6599 yaffs_Device *dev = obj->myDev;
6601 if(dev && dev->removeObjectCallback)
6602 dev->removeObjectCallback(obj);
6604 list_del_init(&obj->siblings);
6609 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
6614 T(YAFFS_TRACE_ALWAYS,
6616 ("tragedy: Trying to add an object to a null pointer directory"
6620 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6621 T(YAFFS_TRACE_ALWAYS,
6623 ("tragedy: Trying to add an object to a non-directory"
6628 if (obj->siblings.prev == NULL) {
6629 /* Not initialised */
6630 INIT_LIST_HEAD(&obj->siblings);
6632 } else if (!list_empty(&obj->siblings)) {
6633 /* If it is holed up somewhere else, un hook it */
6634 yaffs_RemoveObjectFromDirectory(obj);
6637 list_add(&obj->siblings, &directory->variant.directoryVariant.children);
6638 obj->parent = directory;
6640 if (directory == obj->myDev->unlinkedDir
6641 || directory == obj->myDev->deletedDir) {
6643 obj->myDev->nUnlinkedFiles++;
6644 obj->renameAllowed = 0;
6648 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
6653 struct list_head *i;
6654 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
6663 T(YAFFS_TRACE_ALWAYS,
6665 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6669 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6670 T(YAFFS_TRACE_ALWAYS,
6672 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6676 sum = yaffs_CalcNameSum(name);
6678 list_for_each(i, &directory->variant.directoryVariant.children) {
6680 l = list_entry(i, yaffs_Object, siblings);
6682 yaffs_CheckObjectDetailsLoaded(l);
6684 /* Special case for lost-n-found */
6685 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6686 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
6689 } else if (yaffs_SumCompare(l->sum, sum) || l->chunkId <= 0)
6691 /* LostnFound cunk called Objxxx
6694 yaffs_GetObjectName(l, buffer,
6695 YAFFS_MAX_NAME_LENGTH);
6696 if (yaffs_strncmp(name, buffer,YAFFS_MAX_NAME_LENGTH) == 0) {
6709 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
6710 int (*fn) (yaffs_Object *))
6712 struct list_head *i;
6716 T(YAFFS_TRACE_ALWAYS,
6718 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6722 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6723 T(YAFFS_TRACE_ALWAYS,
6725 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6729 list_for_each(i, &theDir->variant.directoryVariant.children) {
6731 l = list_entry(i, yaffs_Object, siblings);
6743 /* GetEquivalentObject dereferences any hard links to get to the
6747 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
6749 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
6750 /* We want the object id of the equivalent object, not this one */
6751 obj = obj->variant.hardLinkVariant.equivalentObject;
6752 yaffs_CheckObjectDetailsLoaded(obj);
6758 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
6760 memset(name, 0, buffSize * sizeof(YCHAR));
6762 yaffs_CheckObjectDetailsLoaded(obj);
6764 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6765 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
6766 } else if (obj->chunkId <= 0) {
6768 /* make up a name */
6769 yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX,
6771 yaffs_strncpy(name, locName, buffSize - 1);
6774 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
6775 else if (obj->shortName[0]) {
6776 yaffs_strcpy(name, obj->shortName);
6781 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
6783 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
6785 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
6787 if (obj->chunkId >= 0) {
6788 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
6789 obj->chunkId, buffer,
6792 yaffs_strncpy(name, oh->name, buffSize - 1);
6794 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
6797 return yaffs_strlen(name);
6800 int yaffs_GetObjectFileLength(yaffs_Object * obj)
6803 /* Dereference any hard linking */
6804 obj = yaffs_GetEquivalentObject(obj);
6805 printf("yaffs_GetObjectFileLength obj %x \n", obj);
6806 printf("yaffs_GetObjectFileLength obj->variantType %x \n", obj->variantType);
6807 printf("yaffs_GetObjectFileLength obj->variant.fileVariant.fileSize %x \n", obj->variant.fileVariant.fileSize);
6809 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
6810 return obj->variant.fileVariant.fileSize;
6812 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6813 return yaffs_strlen(obj->variant.symLinkVariant.alias);
6815 /* Only a directory should drop through to here */
6816 return obj->myDev->nDataBytesPerChunk;
6820 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
6823 struct list_head *i;
6825 if (!obj->unlinked) {
6826 count++; /* the object itself */
6828 list_for_each(i, &obj->hardLinks) {
6829 count++; /* add the hard links; */
6835 int yaffs_GetObjectInode(yaffs_Object * obj)
6837 obj = yaffs_GetEquivalentObject(obj);
6839 return obj->objectId;
6842 unsigned yaffs_GetObjectType(yaffs_Object * obj)
6844 obj = yaffs_GetEquivalentObject(obj);
6846 switch (obj->variantType) {
6847 case YAFFS_OBJECT_TYPE_FILE:
6850 case YAFFS_OBJECT_TYPE_DIRECTORY:
6853 case YAFFS_OBJECT_TYPE_SYMLINK:
6856 case YAFFS_OBJECT_TYPE_HARDLINK:
6859 case YAFFS_OBJECT_TYPE_SPECIAL:
6860 if (S_ISFIFO(obj->yst_mode))
6862 if (S_ISCHR(obj->yst_mode))
6864 if (S_ISBLK(obj->yst_mode))
6866 if (S_ISSOCK(obj->yst_mode))
6874 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
6876 obj = yaffs_GetEquivalentObject(obj);
6877 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6878 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
6880 return yaffs_CloneString(_Y(""));
6884 #ifndef CONFIG_YAFFS_WINCE
6886 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
6888 unsigned int valid = attr->ia_valid;
6890 if (valid & ATTR_MODE)
6891 obj->yst_mode = attr->ia_mode;
6892 if (valid & ATTR_UID)
6893 obj->yst_uid = attr->ia_uid;
6894 if (valid & ATTR_GID)
6895 obj->yst_gid = attr->ia_gid;
6897 if (valid & ATTR_ATIME)
6898 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
6899 if (valid & ATTR_CTIME)
6900 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
6901 if (valid & ATTR_MTIME)
6902 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
6904 if (valid & ATTR_SIZE)
6905 yaffs_ResizeFile(obj, attr->ia_size);
6907 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6912 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
6914 unsigned int valid = 0;
6916 attr->ia_mode = obj->yst_mode;
6918 attr->ia_uid = obj->yst_uid;
6920 attr->ia_gid = obj->yst_gid;
6923 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
6924 valid |= ATTR_ATIME;
6925 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
6926 valid |= ATTR_CTIME;
6927 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
6928 valid |= ATTR_MTIME;
6930 attr->ia_size = yaffs_GetFileSize(obj);
6933 attr->ia_valid = valid;
6942 int yaffs_DumpObject(yaffs_Object * obj)
6946 yaffs_GetObjectName(obj, name, 256);
6948 T(YAFFS_TRACE_ALWAYS,
6950 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
6951 " chunk %d type %d size %d\n"
6952 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
6953 obj->dirty, obj->valid, obj->serial, obj->sum, obj->chunkId,
6954 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
6960 /*---------------------------- Initialisation code -------------------------------------- */
6962 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
6965 /* Common functions, gotta have */
6966 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
6969 #ifdef CONFIG_YAFFS_YAFFS2
6971 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
6972 if (dev->writeChunkWithTagsToNAND &&
6973 dev->readChunkWithTagsFromNAND &&
6974 !dev->writeChunkToNAND &&
6975 !dev->readChunkFromNAND &&
6976 dev->markNANDBlockBad && dev->queryNANDBlock)
6980 /* Can use the "spare" style interface for yaffs1 */
6981 if (!dev->isYaffs2 &&
6982 !dev->writeChunkWithTagsToNAND &&
6983 !dev->readChunkWithTagsFromNAND &&
6984 dev->writeChunkToNAND &&
6985 dev->readChunkFromNAND &&
6986 !dev->markNANDBlockBad && !dev->queryNANDBlock)
6993 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
6995 /* Initialise the unlinked, deleted, root and lost and found directories */
6997 dev->lostNFoundDir = dev->rootDir = NULL;
6998 dev->unlinkedDir = dev->deletedDir = NULL;
7001 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7004 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7007 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7008 YAFFS_ROOT_MODE | S_IFDIR);
7009 dev->lostNFoundDir =
7010 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7011 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7013 if(dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir){
7014 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7021 int yaffs_GutsInitialise(yaffs_Device * dev)
7023 int init_failed = 0;
7027 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7029 /* Check stuff that must be set */
7032 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7036 dev->internalStartBlock = dev->startBlock;
7037 dev->internalEndBlock = dev->endBlock;
7038 dev->blockOffset = 0;
7039 dev->chunkOffset = 0;
7040 dev->nFreeChunks = 0;
7042 if (dev->startBlock == 0) {
7043 dev->internalStartBlock = dev->startBlock + 1;
7044 dev->internalEndBlock = dev->endBlock + 1;
7045 dev->blockOffset = 1;
7046 dev->chunkOffset = dev->nChunksPerBlock;
7049 /* Check geometry parameters. */
7051 if ((dev->isYaffs2 && dev->nDataBytesPerChunk < 1024) ||
7052 (!dev->isYaffs2 && dev->nDataBytesPerChunk != 512) ||
7053 dev->nChunksPerBlock < 2 ||
7054 dev->nReservedBlocks < 2 ||
7055 dev->internalStartBlock <= 0 ||
7056 dev->internalEndBlock <= 0 ||
7057 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
7059 T(YAFFS_TRACE_ALWAYS,
7061 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s "
7062 TENDSTR), dev->nDataBytesPerChunk, dev->isYaffs2 ? "2" : ""));
7066 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7067 T(YAFFS_TRACE_ALWAYS,
7068 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7072 /* Got the right mix of functions? */
7073 if (!yaffs_CheckDevFunctions(dev)) {
7074 /* Function missing */
7075 T(YAFFS_TRACE_ALWAYS,
7077 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7082 /* This is really a compilation check. */
7083 if (!yaffs_CheckStructures()) {
7084 T(YAFFS_TRACE_ALWAYS,
7085 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7089 if (dev->isMounted) {
7090 T(YAFFS_TRACE_ALWAYS,
7091 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7095 /* Finished with most checks. One or two more checks happen later on too. */
7101 /* OK now calculate a few things for the device */
7104 * Calculate all the chunk size manipulation numbers:
7106 /* Start off assuming it is a power of 2 */
7107 dev->chunkShift = ShiftDiv(dev->nDataBytesPerChunk);
7108 dev->chunkMask = (1<<dev->chunkShift) - 1;
7110 if(dev->nDataBytesPerChunk == (dev->chunkMask + 1)){
7111 /* Yes it is a power of 2, disable crumbs */
7113 dev->crumbShift = 0;
7114 dev->crumbsPerChunk = 0;
7116 /* Not a power of 2, use crumbs instead */
7117 dev->crumbShift = ShiftDiv(sizeof(yaffs_PackedTags2TagsPart));
7118 dev->crumbMask = (1<<dev->crumbShift)-1;
7119 dev->crumbsPerChunk = dev->nDataBytesPerChunk/(1 << dev->crumbShift);
7120 dev->chunkShift = 0;
7126 * Calculate chunkGroupBits.
7127 * We need to find the next power of 2 > than internalEndBlock
7130 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7134 /* Set up tnode width if wide tnodes are enabled. */
7135 if(!dev->wideTnodesDisabled){
7136 /* bits must be even so that we end up with 32-bit words */
7140 dev->tnodeWidth = 16;
7142 dev->tnodeWidth = bits;
7145 dev->tnodeWidth = 16;
7147 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7149 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7150 * so if the bitwidth of the
7151 * chunk range we're using is greater than 16 we need
7152 * to figure out chunk shift and chunkGroupSize
7155 if (bits <= dev->tnodeWidth)
7156 dev->chunkGroupBits = 0;
7158 dev->chunkGroupBits = bits - dev->tnodeWidth;
7161 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7163 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7164 /* We have a problem because the soft delete won't work if
7165 * the chunk group size > chunks per block.
7166 * This can be remedied by using larger "virtual blocks".
7168 T(YAFFS_TRACE_ALWAYS,
7169 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7174 /* OK, we've finished verifying the device, lets continue with initialisation */
7176 /* More device initialisation */
7177 dev->garbageCollections = 0;
7178 dev->passiveGarbageCollections = 0;
7179 dev->currentDirtyChecker = 0;
7180 dev->bufferedBlock = -1;
7181 dev->doingBufferedBlockRewrite = 0;
7182 dev->nDeletedFiles = 0;
7183 dev->nBackgroundDeletions = 0;
7184 dev->nUnlinkedFiles = 0;
7186 dev->eccUnfixed = 0;
7187 dev->tagsEccFixed = 0;
7188 dev->tagsEccUnfixed = 0;
7189 dev->nErasureFailures = 0;
7190 dev->nErasedBlocks = 0;
7192 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7194 /* Initialise temporary buffers and caches. */
7195 if(!yaffs_InitialiseTempBuffers(dev))
7198 dev->srCache = NULL;
7199 dev->gcCleanupList = NULL;
7203 dev->nShortOpCaches > 0) {
7206 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7208 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
7209 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7212 buf = dev->srCache = YMALLOC(srCacheBytes);
7215 memset(dev->srCache,0,srCacheBytes);
7217 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7218 dev->srCache[i].object = NULL;
7219 dev->srCache[i].lastUse = 0;
7220 dev->srCache[i].dirty = 0;
7221 dev->srCache[i].data = buf = YMALLOC_DMA(dev->nDataBytesPerChunk);
7232 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7233 if(!dev->gcCleanupList)
7237 if (dev->isYaffs2) {
7238 dev->useHeaderFileSize = 1;
7240 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7243 yaffs_InitialiseTnodes(dev);
7244 yaffs_InitialiseObjects(dev);
7246 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7251 /* Now scan the flash. */
7252 if (dev->isYaffs2) {
7253 if(yaffs_CheckpointRestore(dev)) {
7254 T(YAFFS_TRACE_ALWAYS,
7255 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7258 /* Clean up the mess caused by an aborted checkpoint load
7259 * and scan backwards.
7261 yaffs_DeinitialiseBlocks(dev);
7262 yaffs_DeinitialiseTnodes(dev);
7263 yaffs_DeinitialiseObjects(dev);
7266 dev->nErasedBlocks = 0;
7267 dev->nFreeChunks = 0;
7268 dev->allocationBlock = -1;
7269 dev->allocationPage = -1;
7270 dev->nDeletedFiles = 0;
7271 dev->nUnlinkedFiles = 0;
7272 dev->nBackgroundDeletions = 0;
7273 dev->oldestDirtySequence = 0;
7275 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7278 yaffs_InitialiseTnodes(dev);
7279 yaffs_InitialiseObjects(dev);
7281 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7284 if(!init_failed && !yaffs_ScanBackwards(dev))
7288 if(!yaffs_Scan(dev))
7293 /* Clean up the mess */
7294 T(YAFFS_TRACE_TRACING,
7295 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7297 yaffs_Deinitialise(dev);
7301 /* Zero out stats */
7302 dev->nPageReads = 0;
7303 dev->nPageWrites = 0;
7304 dev->nBlockErasures = 0;
7306 dev->nRetriedWrites = 0;
7308 dev->nRetiredBlocks = 0;
7310 yaffs_VerifyFreeChunks(dev);
7311 yaffs_VerifyBlocks(dev);
7314 T(YAFFS_TRACE_TRACING,
7315 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7320 void yaffs_Deinitialise(yaffs_Device * dev)
7322 if (dev->isMounted) {
7325 yaffs_DeinitialiseBlocks(dev);
7326 yaffs_DeinitialiseTnodes(dev);
7327 yaffs_DeinitialiseObjects(dev);
7328 if (dev->nShortOpCaches > 0 &&
7331 for (i = 0; i < dev->nShortOpCaches; i++) {
7332 if(dev->srCache[i].data)
7333 YFREE(dev->srCache[i].data);
7334 dev->srCache[i].data = NULL;
7337 YFREE(dev->srCache);
7338 dev->srCache = NULL;
7341 YFREE(dev->gcCleanupList);
7343 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
7344 YFREE(dev->tempBuffer[i].buffer);
7352 static int yaffs_CountFreeChunks(yaffs_Device * dev)
7357 yaffs_BlockInfo *blk;
7359 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7361 blk = yaffs_GetBlockInfo(dev, b);
7363 switch (blk->blockState) {
7364 case YAFFS_BLOCK_STATE_EMPTY:
7365 case YAFFS_BLOCK_STATE_ALLOCATING:
7366 case YAFFS_BLOCK_STATE_COLLECTING:
7367 case YAFFS_BLOCK_STATE_FULL:
7369 (dev->nChunksPerBlock - blk->pagesInUse +
7370 blk->softDeletions);
7381 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
7383 /* This is what we report to the outside world */
7386 int nDirtyCacheChunks;
7387 int blocksForCheckpoint;
7390 nFree = dev->nFreeChunks;
7392 nFree = yaffs_CountFreeChunks(dev);
7395 nFree += dev->nDeletedFiles;
7397 /* Now count the number of dirty chunks in the cache and subtract those */
7401 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7402 if (dev->srCache[i].dirty)
7403 nDirtyCacheChunks++;
7407 nFree -= nDirtyCacheChunks;
7409 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7411 /* Now we figure out how much to reserve for the checkpoint and report that... */
7412 blocksForCheckpoint = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
7413 if(blocksForCheckpoint < 0)
7414 blocksForCheckpoint = 0;
7416 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7425 static int yaffs_freeVerificationFailures;
7427 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
7432 if(yaffs_SkipVerification(dev))
7435 counted = yaffs_CountFreeChunks(dev);
7437 difference = dev->nFreeChunks - counted;
7440 T(YAFFS_TRACE_ALWAYS,
7441 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7442 dev->nFreeChunks, counted, difference));
7443 yaffs_freeVerificationFailures++;
7447 /*---------------------------------------- YAFFS test code ----------------------*/
7449 #define yaffs_CheckStruct(structure,syze, name) \
7450 if(sizeof(structure) != syze) \
7452 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
7453 name,syze,sizeof(structure))); \
7454 return YAFFS_FAIL; \
7457 static int yaffs_CheckStructures(void)
7459 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags") */
7460 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion") */
7461 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare") */
7462 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7463 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode")
7465 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader")