2 * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
4 * Copyright (C) 2002-2007 Aleph One Ltd.
5 * for Toby Churchill Ltd and Brightstar Engineering
7 * Created by Charles Manning <charles@aleph1.co.uk>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2 as
11 * published by the Free Software Foundation.
14 const char *yaffs_guts_c_version =
15 "$Id: yaffs_guts.c,v 1.78 2009-01-27 02:52:45 charles Exp $";
19 #include "yaffsinterface.h"
20 #include "yaffs_guts.h"
21 #include "yaffs_tagsvalidity.h"
22 #include "yaffs_getblockinfo.h"
24 #include "yaffs_tagscompat.h"
25 #ifndef CONFIG_YAFFS_USE_OWN_SORT
26 #include "yaffs_qsort.h"
28 #include "yaffs_nand.h"
30 #include "yaffs_checkptrw.h"
32 #include "yaffs_nand.h"
33 #include "yaffs_packedtags2.h"
36 #define YAFFS_PASSIVE_GC_CHUNKS 2
38 #include "yaffs_ecc.h"
41 /* Robustification (if it ever comes about...) */
42 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
43 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk);
44 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
46 const yaffs_ExtendedTags * tags);
47 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
48 const yaffs_ExtendedTags * tags);
50 /* Other local prototypes */
51 static int yaffs_UnlinkObject( yaffs_Object *obj);
52 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
54 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
56 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
58 yaffs_ExtendedTags * tags,
60 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
61 int chunkInNAND, int inScan);
63 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
64 yaffs_ObjectType type);
65 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
67 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
68 int force, int isShrink, int shadows);
69 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
70 static int yaffs_CheckStructures(void);
71 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
72 int chunkOffset, int *limit);
73 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
75 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
78 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
81 static int yaffs_UnlinkWorker(yaffs_Object * obj);
82 static void yaffs_DestroyObject(yaffs_Object * obj);
84 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
87 loff_t yaffs_GetFileSize(yaffs_Object * obj);
89 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr);
91 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
93 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
95 static void yaffs_VerifyDirectory(yaffs_Object *directory);
97 static int yaffs_CheckFileSanity(yaffs_Object * in);
99 #define yaffs_CheckFileSanity(in)
102 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
103 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
105 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
107 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
108 yaffs_ExtendedTags * tags);
110 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos);
111 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
112 yaffs_FileStructure * fStruct,
116 /* Function to calculate chunk and offset */
118 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut, __u32 *offsetOut)
123 chunk = (__u32)(addr >> dev->chunkShift);
125 if(dev->chunkDiv == 1)
127 /* easy power of 2 case */
128 offset = (__u32)(addr & dev->chunkMask);
132 /* Non power-of-2 case */
136 chunk /= dev->chunkDiv;
138 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
139 offset = (__u32)(addr - chunkBase);
146 /* Function to return the number of shifts for a power of 2 greater than or equal
147 * to the given number
148 * Note we don't try to cater for all possible numbers and this does not have to
149 * be hellishly efficient.
152 static __u32 ShiftsGE(__u32 x)
157 nShifts = extraBits = 0;
160 if(x & 1) extraBits++;
171 /* Function to return the number of shifts to get a 1 in bit 0
174 static __u32 Shifts(__u32 x)
193 * Temporary buffer manipulations.
196 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
199 __u8 *buf = (__u8 *)1;
201 memset(dev->tempBuffer,0,sizeof(dev->tempBuffer));
203 for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
204 dev->tempBuffer[i].line = 0; /* not in use */
205 dev->tempBuffer[i].buffer = buf =
206 YMALLOC_DMA(dev->totalBytesPerChunk);
209 return buf ? YAFFS_OK : YAFFS_FAIL;
213 __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
218 if(dev->tempInUse > dev->maxTemp)
219 dev->maxTemp = dev->tempInUse;
221 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
222 if (dev->tempBuffer[i].line == 0) {
223 dev->tempBuffer[i].line = lineNo;
224 if ((i + 1) > dev->maxTemp) {
225 dev->maxTemp = i + 1;
226 for (j = 0; j <= i; j++)
227 dev->tempBuffer[j].maxLine =
228 dev->tempBuffer[j].line;
231 return dev->tempBuffer[i].buffer;
235 T(YAFFS_TRACE_BUFFERS,
236 (TSTR("Out of temp buffers at line %d, other held by lines:"),
238 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
239 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
241 T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
244 * If we got here then we have to allocate an unmanaged one
248 dev->unmanagedTempAllocations++;
249 return YMALLOC(dev->nDataBytesPerChunk);
253 void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
260 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
261 if (dev->tempBuffer[i].buffer == buffer) {
262 dev->tempBuffer[i].line = 0;
268 /* assume it is an unmanaged one. */
269 T(YAFFS_TRACE_BUFFERS,
270 (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
273 dev->unmanagedTempDeallocations++;
279 * Determine if we have a managed buffer.
281 int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
284 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
285 if (dev->tempBuffer[i].buffer == buffer)
290 for (i = 0; i < dev->nShortOpCaches; i++) {
291 if( dev->srCache[i].data == buffer )
296 if (buffer == dev->checkpointBuffer)
299 T(YAFFS_TRACE_ALWAYS,
300 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
307 * Chunk bitmap manipulations
310 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
312 if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
314 (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
318 return dev->chunkBits +
319 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
322 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
324 if(blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
325 chunk < 0 || chunk >= dev->nChunksPerBlock) {
327 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),blk,chunk));
332 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
334 __u8 *blkBits = yaffs_BlockBits(dev, blk);
336 memset(blkBits, 0, dev->chunkBitmapStride);
339 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
341 __u8 *blkBits = yaffs_BlockBits(dev, blk);
343 yaffs_VerifyChunkBitId(dev,blk,chunk);
345 blkBits[chunk / 8] &= ~(1 << (chunk & 7));
348 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
350 __u8 *blkBits = yaffs_BlockBits(dev, blk);
352 yaffs_VerifyChunkBitId(dev,blk,chunk);
354 blkBits[chunk / 8] |= (1 << (chunk & 7));
357 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
359 __u8 *blkBits = yaffs_BlockBits(dev, blk);
360 yaffs_VerifyChunkBitId(dev,blk,chunk);
362 return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
365 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
367 __u8 *blkBits = yaffs_BlockBits(dev, blk);
369 for (i = 0; i < dev->chunkBitmapStride; i++) {
377 static int yaffs_CountChunkBits(yaffs_Device * dev, int blk)
379 __u8 *blkBits = yaffs_BlockBits(dev, blk);
382 for (i = 0; i < dev->chunkBitmapStride; i++) {
399 static int yaffs_SkipVerification(yaffs_Device *dev)
401 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
404 static int yaffs_SkipFullVerification(yaffs_Device *dev)
406 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
409 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
411 return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
414 static const char * blockStateName[] = {
427 static void yaffs_VerifyBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
432 if(yaffs_SkipVerification(dev))
435 /* Report illegal runtime states */
436 if(bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
437 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has undefined state %d"TENDSTR),n,bi->blockState));
439 switch(bi->blockState){
440 case YAFFS_BLOCK_STATE_UNKNOWN:
441 case YAFFS_BLOCK_STATE_SCANNING:
442 case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
443 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has bad run-state %s"TENDSTR),
444 n,blockStateName[bi->blockState]));
447 /* Check pages in use and soft deletions are legal */
449 actuallyUsed = bi->pagesInUse - bi->softDeletions;
451 if(bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
452 bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
453 actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock)
454 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
455 n,bi->pagesInUse,bi->softDeletions));
458 /* Check chunk bitmap legal */
459 inUse = yaffs_CountChunkBits(dev,n);
460 if(inUse != bi->pagesInUse)
461 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
462 n,bi->pagesInUse,inUse));
464 /* Check that the sequence number is valid.
465 * Ten million is legal, but is very unlikely
468 (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
469 (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000 ))
470 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has suspect sequence number of %d"TENDSTR),
471 n,bi->sequenceNumber));
475 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
477 yaffs_VerifyBlock(dev,bi,n);
479 /* After collection the block should be in the erased state */
480 /* This will need to change if we do partial gc */
482 if(bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
483 bi->blockState != YAFFS_BLOCK_STATE_EMPTY){
484 T(YAFFS_TRACE_ERROR,(TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
489 static void yaffs_VerifyBlocks(yaffs_Device *dev)
492 int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
493 int nIllegalBlockStates = 0;
496 if(yaffs_SkipVerification(dev))
499 memset(nBlocksPerState,0,sizeof(nBlocksPerState));
502 for(i = dev->internalStartBlock; i <= dev->internalEndBlock; i++){
503 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
504 yaffs_VerifyBlock(dev,bi,i);
506 if(bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
507 nBlocksPerState[bi->blockState]++;
509 nIllegalBlockStates++;
513 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
514 T(YAFFS_TRACE_VERIFY,(TSTR("Block summary"TENDSTR)));
516 T(YAFFS_TRACE_VERIFY,(TSTR("%d blocks have illegal states"TENDSTR),nIllegalBlockStates));
517 if(nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
518 T(YAFFS_TRACE_VERIFY,(TSTR("Too many allocating blocks"TENDSTR)));
520 for(i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
521 T(YAFFS_TRACE_VERIFY,
522 (TSTR("%s %d blocks"TENDSTR),
523 blockStateName[i],nBlocksPerState[i]));
525 if(dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
526 T(YAFFS_TRACE_VERIFY,
527 (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
528 dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
530 if(dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
531 T(YAFFS_TRACE_VERIFY,
532 (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
533 dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
535 if(nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
536 T(YAFFS_TRACE_VERIFY,
537 (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
538 nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
540 T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
545 * Verify the object header. oh must be valid, but obj and tags may be NULL in which
546 * case those tests will not be performed.
548 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
550 if(obj && yaffs_SkipVerification(obj->myDev))
553 if(!(tags && obj && oh)){
554 T(YAFFS_TRACE_VERIFY,
555 (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR),
556 (__u32)tags,(__u32)obj,(__u32)oh));
560 if(oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
561 oh->type > YAFFS_OBJECT_TYPE_MAX)
562 T(YAFFS_TRACE_VERIFY,
563 (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
564 tags->objectId, oh->type));
566 if(tags->objectId != obj->objectId)
567 T(YAFFS_TRACE_VERIFY,
568 (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
569 tags->objectId, obj->objectId));
573 * Check that the object's parent ids match if parentCheck requested.
575 * Tests do not apply to the root object.
578 if(parentCheck && tags->objectId > 1 && !obj->parent)
579 T(YAFFS_TRACE_VERIFY,
580 (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
581 tags->objectId, oh->parentObjectId));
584 if(parentCheck && obj->parent &&
585 oh->parentObjectId != obj->parent->objectId &&
586 (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
587 obj->parent->objectId != YAFFS_OBJECTID_DELETED))
588 T(YAFFS_TRACE_VERIFY,
589 (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
590 tags->objectId, oh->parentObjectId, obj->parent->objectId));
593 if(tags->objectId > 1 && oh->name[0] == 0) /* Null name */
594 T(YAFFS_TRACE_VERIFY,
595 (TSTR("Obj %d header name is NULL"TENDSTR),
598 if(tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
599 T(YAFFS_TRACE_VERIFY,
600 (TSTR("Obj %d header name is 0xFF"TENDSTR),
606 static int yaffs_VerifyTnodeWorker(yaffs_Object * obj, yaffs_Tnode * tn,
607 __u32 level, int chunkOffset)
610 yaffs_Device *dev = obj->myDev;
616 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
617 if (tn->internal[i]) {
618 ok = yaffs_VerifyTnodeWorker(obj,
621 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
624 } else if (level == 0) {
625 yaffs_ExtendedTags tags;
626 __u32 objectId = obj->objectId;
628 chunkOffset <<= YAFFS_TNODES_LEVEL0_BITS;
630 for(i = 0; i < YAFFS_NTNODES_LEVEL0; i++){
631 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
634 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
635 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
636 if(tags.objectId != objectId || tags.chunkId != chunkOffset){
637 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
638 objectId, chunkOffset, theChunk,
639 tags.objectId, tags.chunkId));
652 static void yaffs_VerifyFile(yaffs_Object *obj)
654 int requiredTallness;
660 yaffs_ExtendedTags tags;
667 if(yaffs_SkipVerification(obj->myDev))
671 objectId = obj->objectId;
673 /* Check file size is consistent with tnode depth */
674 lastChunk = obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
675 x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
676 requiredTallness = 0;
678 x >>= YAFFS_TNODES_INTERNAL_BITS;
682 actualTallness = obj->variant.fileVariant.topLevel;
684 if(requiredTallness > actualTallness )
685 T(YAFFS_TRACE_VERIFY,
686 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
687 obj->objectId,actualTallness, requiredTallness));
690 /* Check that the chunks in the tnode tree are all correct.
691 * We do this by scanning through the tnode tree and
692 * checking the tags for every chunk match.
695 if(yaffs_SkipNANDVerification(dev))
698 for(i = 1; i <= lastChunk; i++){
699 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant,i);
702 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
704 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
705 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
706 if(tags.objectId != objectId || tags.chunkId != i){
707 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
708 objectId, i, theChunk,
709 tags.objectId, tags.chunkId));
719 static void yaffs_VerifyHardLink(yaffs_Object *obj)
721 if(obj && yaffs_SkipVerification(obj->myDev))
724 /* Verify sane equivalent object */
727 static void yaffs_VerifySymlink(yaffs_Object *obj)
729 if(obj && yaffs_SkipVerification(obj->myDev))
732 /* Verify symlink string */
735 static void yaffs_VerifySpecial(yaffs_Object *obj)
737 if(obj && yaffs_SkipVerification(obj->myDev))
741 static void yaffs_VerifyObject(yaffs_Object *obj)
750 __u32 chunkShouldNotBeDeleted;
756 if(obj->beingCreated)
761 if(yaffs_SkipVerification(dev))
764 /* Check sane object header chunk */
766 chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
767 chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
769 chunkInRange = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
770 chunkIdOk = chunkInRange || obj->hdrChunk == 0;
771 chunkValid = chunkInRange &&
772 yaffs_CheckChunkBit(dev,
773 obj->hdrChunk / dev->nChunksPerBlock,
774 obj->hdrChunk % dev->nChunksPerBlock);
775 chunkShouldNotBeDeleted = chunkInRange && !chunkValid;
778 (!chunkIdOk || chunkShouldNotBeDeleted)) {
779 T(YAFFS_TRACE_VERIFY,
780 (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
781 obj->objectId,obj->hdrChunk,
782 chunkIdOk ? "" : ",out of range",
783 chunkShouldNotBeDeleted ? ",marked as deleted" : ""));
786 if(chunkValid &&!yaffs_SkipNANDVerification(dev)) {
787 yaffs_ExtendedTags tags;
788 yaffs_ObjectHeader *oh;
789 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
791 oh = (yaffs_ObjectHeader *)buffer;
793 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk,buffer, &tags);
795 yaffs_VerifyObjectHeader(obj,oh,&tags,1);
797 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
800 /* Verify it has a parent */
801 if(obj && !obj->fake &&
802 (!obj->parent || obj->parent->myDev != dev)){
803 T(YAFFS_TRACE_VERIFY,
804 (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
805 obj->objectId,obj->parent));
808 /* Verify parent is a directory */
809 if(obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
810 T(YAFFS_TRACE_VERIFY,
811 (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
812 obj->objectId,obj->parent->variantType));
815 switch(obj->variantType){
816 case YAFFS_OBJECT_TYPE_FILE:
817 yaffs_VerifyFile(obj);
819 case YAFFS_OBJECT_TYPE_SYMLINK:
820 yaffs_VerifySymlink(obj);
822 case YAFFS_OBJECT_TYPE_DIRECTORY:
823 yaffs_VerifyDirectory(obj);
825 case YAFFS_OBJECT_TYPE_HARDLINK:
826 yaffs_VerifyHardLink(obj);
828 case YAFFS_OBJECT_TYPE_SPECIAL:
829 yaffs_VerifySpecial(obj);
831 case YAFFS_OBJECT_TYPE_UNKNOWN:
833 T(YAFFS_TRACE_VERIFY,
834 (TSTR("Obj %d has illegaltype %d"TENDSTR),
835 obj->objectId,obj->variantType));
842 static void yaffs_VerifyObjects(yaffs_Device *dev)
846 struct ylist_head *lh;
848 if(yaffs_SkipVerification(dev))
851 /* Iterate through the objects in each hash entry */
853 for(i = 0; i < YAFFS_NOBJECT_BUCKETS; i++){
854 ylist_for_each(lh, &dev->objectBucket[i].list) {
856 obj = ylist_entry(lh, yaffs_Object, hashLink);
857 yaffs_VerifyObject(obj);
866 * Simple hash function. Needs to have a reasonable spread
869 static Y_INLINE int yaffs_HashFunction(int n)
872 return (n % YAFFS_NOBJECT_BUCKETS);
876 * Access functions to useful fake objects.
877 * Note that root might have a presence in NAND if permissions are set.
880 yaffs_Object *yaffs_Root(yaffs_Device * dev)
885 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
887 return dev->lostNFoundDir;
892 * Erased NAND checking functions
895 int yaffs_CheckFF(__u8 * buffer, int nBytes)
897 /* Horrible, slow implementation */
906 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
910 int retval = YAFFS_OK;
911 __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
912 yaffs_ExtendedTags tags;
915 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
917 if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
921 if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
922 T(YAFFS_TRACE_NANDACCESS,
923 (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
927 yaffs_ReleaseTempBuffer(dev, data, __LINE__);
933 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
935 yaffs_ExtendedTags * tags,
942 yaffs_InvalidateCheckpoint(dev);
945 yaffs_BlockInfo *bi = 0;
948 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
954 /* First check this chunk is erased, if it needs
955 * checking. The checking policy (unless forced
956 * always on) is as follows:
958 * Check the first page we try to write in a block.
959 * If the check passes then we don't need to check any
960 * more. If the check fails, we check again...
961 * If the block has been erased, we don't need to check.
963 * However, if the block has been prioritised for gc,
964 * then we think there might be something odd about
965 * this block and stop using it.
967 * Rationale: We should only ever see chunks that have
968 * not been erased if there was a partially written
969 * chunk due to power loss. This checking policy should
970 * catch that case with very few checks and thus save a
971 * lot of checks that are most likely not needed.
973 if (bi->gcPrioritise) {
974 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
975 /* try another chunk */
979 /* let's give it a try */
982 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
983 bi->skipErasedCheck = 0;
985 if (!bi->skipErasedCheck) {
986 erasedOk = yaffs_CheckChunkErased(dev, chunk);
987 if (erasedOk != YAFFS_OK) {
989 (TSTR ("**>> yaffs chunk %d was not erased"
992 /* try another chunk */
995 bi->skipErasedCheck = 1;
998 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
1000 if (writeOk != YAFFS_OK) {
1001 yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
1002 /* try another chunk */
1006 /* Copy the data into the robustification buffer */
1007 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1009 } while (writeOk != YAFFS_OK &&
1010 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1016 T(YAFFS_TRACE_ERROR,
1017 (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1020 dev->nRetriedWrites += (attempts - 1);
1027 * Block retiring for handling a broken block.
1030 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
1032 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1034 yaffs_InvalidateCheckpoint(dev);
1036 if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
1037 if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
1038 T(YAFFS_TRACE_ALWAYS, (TSTR(
1039 "yaffs: Failed to mark bad and erase block %d"
1040 TENDSTR), blockInNAND));
1043 yaffs_ExtendedTags tags;
1044 int chunkId = blockInNAND * dev->nChunksPerBlock;
1046 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
1048 memset(buffer, 0xff, dev->nDataBytesPerChunk);
1049 yaffs_InitialiseTags(&tags);
1050 tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
1051 if (dev->writeChunkWithTagsToNAND(dev, chunkId -
1052 dev->chunkOffset, buffer, &tags) != YAFFS_OK)
1053 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
1054 TCONT("write bad block marker to block %d")
1055 TENDSTR), blockInNAND));
1057 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
1061 bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1062 bi->gcPrioritise = 0;
1063 bi->needsRetiring = 0;
1065 dev->nRetiredBlocks++;
1069 * Functions for robustisizing TODO
1073 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
1075 const yaffs_ExtendedTags * tags)
1079 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
1080 const yaffs_ExtendedTags * tags)
1084 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1086 if(!bi->gcPrioritise){
1087 bi->gcPrioritise = 1;
1088 dev->hasPendingPrioritisedGCs = 1;
1089 bi->chunkErrorStrikes ++;
1091 if(bi->chunkErrorStrikes > 3){
1092 bi->needsRetiring = 1; /* Too many stikes, so retire this */
1093 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1100 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
1103 int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1104 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1106 yaffs_HandleChunkError(dev,bi);
1110 /* Was an actual write failure, so mark the block for retirement */
1111 bi->needsRetiring = 1;
1112 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1113 (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1118 /* Delete the chunk */
1119 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1123 /*---------------- Name handling functions ------------*/
1125 static __u16 yaffs_CalcNameSum(const YCHAR * name)
1130 const YUCHAR *bname = (const YUCHAR *) name;
1132 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1134 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1135 sum += yaffs_toupper(*bname) * i;
1137 sum += (*bname) * i;
1146 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
1148 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1149 memset(obj->shortName,0,sizeof (YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1150 if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
1151 yaffs_strcpy(obj->shortName, name);
1153 obj->shortName[0] = _Y('\0');
1156 obj->sum = yaffs_CalcNameSum(name);
1159 /*-------------------- TNODES -------------------
1161 * List of spare tnodes
1162 * The list is hooked together using the first pointer
1166 /* yaffs_CreateTnodes creates a bunch more tnodes and
1167 * adds them to the tnode free list.
1168 * Don't use this function directly
1171 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
1175 yaffs_Tnode *newTnodes;
1179 yaffs_TnodeList *tnl;
1184 /* Calculate the tnode size in bytes for variable width tnode support.
1185 * Must be a multiple of 32-bits */
1186 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1188 if(tnodeSize < sizeof(yaffs_Tnode))
1189 tnodeSize = sizeof(yaffs_Tnode);
1192 /* make these things */
1194 newTnodes = YMALLOC(nTnodes * tnodeSize);
1195 mem = (__u8 *)newTnodes;
1198 T(YAFFS_TRACE_ERROR,
1199 (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1203 /* Hook them into the free list */
1205 for (i = 0; i < nTnodes - 1; i++) {
1206 newTnodes[i].internal[0] = &newTnodes[i + 1];
1207 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1208 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1212 newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1213 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1214 newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1216 dev->freeTnodes = newTnodes;
1218 /* New hookup for wide tnodes */
1219 for(i = 0; i < nTnodes -1; i++) {
1220 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1221 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1222 curr->internal[0] = next;
1225 curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1226 curr->internal[0] = dev->freeTnodes;
1227 dev->freeTnodes = (yaffs_Tnode *)mem;
1232 dev->nFreeTnodes += nTnodes;
1233 dev->nTnodesCreated += nTnodes;
1235 /* Now add this bunch of tnodes to a list for freeing up.
1236 * NB If we can't add this to the management list it isn't fatal
1237 * but it just means we can't free this bunch of tnodes later.
1240 tnl = YMALLOC(sizeof(yaffs_TnodeList));
1242 T(YAFFS_TRACE_ERROR,
1244 ("yaffs: Could not add tnodes to management list" TENDSTR)));
1248 tnl->tnodes = newTnodes;
1249 tnl->next = dev->allocatedTnodeList;
1250 dev->allocatedTnodeList = tnl;
1253 T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1258 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1260 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
1262 yaffs_Tnode *tn = NULL;
1264 /* If there are none left make more */
1265 if (!dev->freeTnodes) {
1266 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1269 if (dev->freeTnodes) {
1270 tn = dev->freeTnodes;
1271 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1272 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1273 /* Hoosterman, this thing looks like it isn't in the list */
1274 T(YAFFS_TRACE_ALWAYS,
1275 (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1278 dev->freeTnodes = dev->freeTnodes->internal[0];
1282 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1287 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
1289 yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1290 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1292 if(tnodeSize < sizeof(yaffs_Tnode))
1293 tnodeSize = sizeof(yaffs_Tnode);
1296 memset(tn, 0, tnodeSize);
1301 /* FreeTnode frees up a tnode and puts it back on the free list */
1302 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
1305 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1306 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1307 /* Hoosterman, this thing looks like it is already in the list */
1308 T(YAFFS_TRACE_ALWAYS,
1309 (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1311 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1313 tn->internal[0] = dev->freeTnodes;
1314 dev->freeTnodes = tn;
1317 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1321 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
1323 /* Free the list of allocated tnodes */
1324 yaffs_TnodeList *tmp;
1326 while (dev->allocatedTnodeList) {
1327 tmp = dev->allocatedTnodeList->next;
1329 YFREE(dev->allocatedTnodeList->tnodes);
1330 YFREE(dev->allocatedTnodeList);
1331 dev->allocatedTnodeList = tmp;
1335 dev->freeTnodes = NULL;
1336 dev->nFreeTnodes = 0;
1339 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
1341 dev->allocatedTnodeList = NULL;
1342 dev->freeTnodes = NULL;
1343 dev->nFreeTnodes = 0;
1344 dev->nTnodesCreated = 0;
1349 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
1351 __u32 *map = (__u32 *)tn;
1357 pos &= YAFFS_TNODES_LEVEL0_MASK;
1358 val >>= dev->chunkGroupBits;
1360 bitInMap = pos * dev->tnodeWidth;
1361 wordInMap = bitInMap /32;
1362 bitInWord = bitInMap & (32 -1);
1364 mask = dev->tnodeMask << bitInWord;
1366 map[wordInMap] &= ~mask;
1367 map[wordInMap] |= (mask & (val << bitInWord));
1369 if(dev->tnodeWidth > (32-bitInWord)) {
1370 bitInWord = (32 - bitInWord);
1372 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1373 map[wordInMap] &= ~mask;
1374 map[wordInMap] |= (mask & (val >> bitInWord));
1378 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
1380 __u32 *map = (__u32 *)tn;
1386 pos &= YAFFS_TNODES_LEVEL0_MASK;
1388 bitInMap = pos * dev->tnodeWidth;
1389 wordInMap = bitInMap /32;
1390 bitInWord = bitInMap & (32 -1);
1392 val = map[wordInMap] >> bitInWord;
1394 if(dev->tnodeWidth > (32-bitInWord)) {
1395 bitInWord = (32 - bitInWord);
1397 val |= (map[wordInMap] << bitInWord);
1400 val &= dev->tnodeMask;
1401 val <<= dev->chunkGroupBits;
1406 /* ------------------- End of individual tnode manipulation -----------------*/
1408 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1409 * The look up tree is represented by the top tnode and the number of topLevel
1410 * in the tree. 0 means only the level 0 tnode is in the tree.
1413 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1414 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
1415 yaffs_FileStructure * fStruct,
1419 yaffs_Tnode *tn = fStruct->top;
1421 int requiredTallness;
1422 int level = fStruct->topLevel;
1424 /* Check sane level and chunk Id */
1425 if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
1429 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1433 /* First check we're tall enough (ie enough topLevel) */
1435 i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1436 requiredTallness = 0;
1438 i >>= YAFFS_TNODES_INTERNAL_BITS;
1442 if (requiredTallness > fStruct->topLevel) {
1443 /* Not tall enough, so we can't find it, return NULL. */
1447 /* Traverse down to level 0 */
1448 while (level > 0 && tn) {
1450 internal[(chunkId >>
1451 ( YAFFS_TNODES_LEVEL0_BITS +
1453 YAFFS_TNODES_INTERNAL_BITS)
1455 YAFFS_TNODES_INTERNAL_MASK];
1463 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1464 * This happens in two steps:
1465 * 1. If the tree isn't tall enough, then make it taller.
1466 * 2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1468 * Used when modifying the tree.
1470 * If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1471 * be plugged into the ttree.
1474 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
1475 yaffs_FileStructure * fStruct,
1477 yaffs_Tnode *passedTn)
1480 int requiredTallness;
1488 /* Check sane level and page Id */
1489 if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
1493 if (chunkId > YAFFS_MAX_CHUNK_ID) {
1497 /* First check we're tall enough (ie enough topLevel) */
1499 x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1500 requiredTallness = 0;
1502 x >>= YAFFS_TNODES_INTERNAL_BITS;
1507 if (requiredTallness > fStruct->topLevel) {
1508 /* Not tall enough,gotta make the tree taller */
1509 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1511 tn = yaffs_GetTnode(dev);
1514 tn->internal[0] = fStruct->top;
1517 T(YAFFS_TRACE_ERROR,
1518 (TSTR("yaffs: no more tnodes" TENDSTR)));
1522 fStruct->topLevel = requiredTallness;
1525 /* Traverse down to level 0, adding anything we need */
1527 l = fStruct->topLevel;
1531 while (l > 0 && tn) {
1533 ( YAFFS_TNODES_LEVEL0_BITS +
1534 (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1535 YAFFS_TNODES_INTERNAL_MASK;
1538 if((l>1) && !tn->internal[x]){
1539 /* Add missing non-level-zero tnode */
1540 tn->internal[x] = yaffs_GetTnode(dev);
1543 /* Looking from level 1 at level 0 */
1545 /* If we already have one, then release it.*/
1547 yaffs_FreeTnode(dev,tn->internal[x]);
1548 tn->internal[x] = passedTn;
1550 } else if(!tn->internal[x]) {
1551 /* Don't have one, none passed in */
1552 tn->internal[x] = yaffs_GetTnode(dev);
1556 tn = tn->internal[x];
1560 /* top is level 0 */
1562 memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1563 yaffs_FreeTnode(dev,passedTn);
1570 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1571 yaffs_ExtendedTags * tags, int objectId,
1576 for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1577 if (yaffs_CheckChunkBit
1578 (dev, theChunk / dev->nChunksPerBlock,
1579 theChunk % dev->nChunksPerBlock)) {
1580 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1582 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1594 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1595 * chunks and tnodes in the file
1596 * Returns 1 if the tree was deleted.
1597 * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1600 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1601 int chunkOffset, int *limit)
1606 yaffs_ExtendedTags tags;
1608 yaffs_Device *dev = in->myDev;
1615 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1617 if (tn->internal[i]) {
1618 if (limit && (*limit) < 0) {
1622 yaffs_DeleteWorker(in,
1630 YAFFS_TNODES_INTERNAL_BITS)
1635 yaffs_FreeTnode(dev,
1638 tn->internal[i] = NULL;
1643 return (allDone) ? 1 : 0;
1644 } else if (level == 0) {
1647 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1649 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1654 YAFFS_TNODES_LEVEL0_BITS) + i;
1657 yaffs_FindChunkInGroup(dev,
1663 if (foundChunk > 0) {
1664 yaffs_DeleteChunk(dev,
1669 *limit = *limit - 1;
1677 yaffs_PutLevel0Tnode(dev,tn,i,0);
1681 return (i < 0) ? 1 : 0;
1691 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1694 yaffs_BlockInfo *theBlock;
1696 T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1698 theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1700 theBlock->softDeletions++;
1705 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1706 * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1708 * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1711 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1712 __u32 level, int chunkOffset)
1717 yaffs_Device *dev = in->myDev;
1722 for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1724 if (tn->internal[i]) {
1726 yaffs_SoftDeleteWorker(in,
1732 YAFFS_TNODES_INTERNAL_BITS)
1735 yaffs_FreeTnode(dev,
1738 tn->internal[i] = NULL;
1740 /* Hoosterman... how could this happen? */
1744 return (allDone) ? 1 : 0;
1745 } else if (level == 0) {
1747 for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1748 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1750 /* Note this does not find the real chunk, only the chunk group.
1751 * We make an assumption that a chunk group is not larger than
1754 yaffs_SoftDeleteChunk(dev, theChunk);
1755 yaffs_PutLevel0Tnode(dev,tn,i,0);
1769 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1772 obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1773 if (obj->nDataChunks <= 0) {
1774 /* Empty file with no duplicate object headers, just delete it immediately */
1775 yaffs_FreeTnode(obj->myDev,
1776 obj->variant.fileVariant.top);
1777 obj->variant.fileVariant.top = NULL;
1778 T(YAFFS_TRACE_TRACING,
1779 (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1781 yaffs_DoGenericObjectDeletion(obj);
1783 yaffs_SoftDeleteWorker(obj,
1784 obj->variant.fileVariant.top,
1785 obj->variant.fileVariant.
1787 obj->softDeleted = 1;
1792 /* Pruning removes any part of the file structure tree that is beyond the
1793 * bounds of the file (ie that does not point to chunks).
1795 * A file should only get pruned when its size is reduced.
1797 * Before pruning, the chunks must be pulled from the tree and the
1798 * level 0 tnode entries must be zeroed out.
1799 * Could also use this for file deletion, but that's probably better handled
1800 * by a special case.
1803 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1804 __u32 level, int del0)
1812 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1813 if (tn->internal[i] && level > 0) {
1815 yaffs_PruneWorker(dev, tn->internal[i],
1817 (i == 0) ? del0 : 1);
1820 if (tn->internal[i]) {
1825 if (hasData == 0 && del0) {
1826 /* Free and return NULL */
1828 yaffs_FreeTnode(dev, tn);
1838 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1839 yaffs_FileStructure * fStruct)
1846 if (fStruct->topLevel > 0) {
1848 yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1850 /* Now we have a tree with all the non-zero branches NULL but the height
1851 * is the same as it was.
1852 * Let's see if we can trim internal tnodes to shorten the tree.
1853 * We can do this if only the 0th element in the tnode is in use
1854 * (ie all the non-zero are NULL)
1857 while (fStruct->topLevel && !done) {
1861 for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1862 if (tn->internal[i]) {
1868 fStruct->top = tn->internal[0];
1869 fStruct->topLevel--;
1870 yaffs_FreeTnode(dev, tn);
1880 /*-------------------- End of File Structure functions.-------------------*/
1882 /* yaffs_CreateFreeObjects creates a bunch more objects and
1883 * adds them to the object free list.
1885 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1888 yaffs_Object *newObjects;
1889 yaffs_ObjectList *list;
1894 /* make these things */
1895 newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1896 list = YMALLOC(sizeof(yaffs_ObjectList));
1898 if (!newObjects || !list) {
1903 T(YAFFS_TRACE_ALLOCATE,
1904 (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1908 /* Hook them into the free list */
1909 for (i = 0; i < nObjects - 1; i++) {
1910 newObjects[i].siblings.next =
1911 (struct ylist_head *)(&newObjects[i + 1]);
1914 newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1915 dev->freeObjects = newObjects;
1916 dev->nFreeObjects += nObjects;
1917 dev->nObjectsCreated += nObjects;
1919 /* Now add this bunch of Objects to a list for freeing up. */
1921 list->objects = newObjects;
1922 list->next = dev->allocatedObjectList;
1923 dev->allocatedObjectList = list;
1929 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1930 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1932 yaffs_Object *tn = NULL;
1934 #ifdef VALGRIND_TEST
1935 tn = YMALLOC(sizeof(yaffs_Object));
1937 /* If there are none left make more */
1938 if (!dev->freeObjects) {
1939 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1942 if (dev->freeObjects) {
1943 tn = dev->freeObjects;
1945 (yaffs_Object *) (dev->freeObjects->siblings.next);
1946 dev->nFreeObjects--;
1950 /* Now sweeten it up... */
1952 memset(tn, 0, sizeof(yaffs_Object));
1953 tn->beingCreated = 1;
1957 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1958 YINIT_LIST_HEAD(&(tn->hardLinks));
1959 YINIT_LIST_HEAD(&(tn->hashLink));
1960 YINIT_LIST_HEAD(&tn->siblings);
1963 /* Now make the directory sane */
1965 tn->parent = dev->rootDir;
1966 ylist_add(&(tn->siblings),&dev->rootDir->variant.directoryVariant.children);
1969 /* Add it to the lost and found directory.
1970 * NB Can't put root or lostNFound in lostNFound so
1971 * check if lostNFound exists first
1973 if (dev->lostNFoundDir) {
1974 yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1977 tn->beingCreated = 0;
1980 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1985 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1990 yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1992 obj->fake = 1; /* it is fake so it might have no NAND presence... */
1993 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1994 obj->unlinkAllowed = 0; /* ... or unlink it */
1997 obj->yst_mode = mode;
1999 obj->hdrChunk = 0; /* Not a valid chunk. */
2006 static void yaffs_UnhashObject(yaffs_Object * tn)
2009 yaffs_Device *dev = tn->myDev;
2011 /* If it is still linked into the bucket list, free from the list */
2012 if (!ylist_empty(&tn->hashLink)) {
2013 ylist_del_init(&tn->hashLink);
2014 bucket = yaffs_HashFunction(tn->objectId);
2015 dev->objectBucket[bucket].count--;
2020 /* FreeObject frees up a Object and puts it back on the free list */
2021 static void yaffs_FreeObject(yaffs_Object * tn)
2024 yaffs_Device *dev = tn->myDev;
2029 if(!ylist_empty(&tn->siblings))
2035 /* We're still hooked up to a cached inode.
2036 * Don't delete now, but mark for later deletion
2038 tn->deferedFree = 1;
2043 yaffs_UnhashObject(tn);
2045 #ifdef VALGRIND_TEST
2048 /* Link into the free list. */
2049 tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2050 dev->freeObjects = tn;
2051 dev->nFreeObjects++;
2053 dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2059 void yaffs_HandleDeferedFree(yaffs_Object * obj)
2061 if (obj->deferedFree) {
2062 yaffs_FreeObject(obj);
2068 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
2070 /* Free the list of allocated Objects */
2072 yaffs_ObjectList *tmp;
2074 while (dev->allocatedObjectList) {
2075 tmp = dev->allocatedObjectList->next;
2076 YFREE(dev->allocatedObjectList->objects);
2077 YFREE(dev->allocatedObjectList);
2079 dev->allocatedObjectList = tmp;
2082 dev->freeObjects = NULL;
2083 dev->nFreeObjects = 0;
2086 static void yaffs_InitialiseObjects(yaffs_Device * dev)
2090 dev->allocatedObjectList = NULL;
2091 dev->freeObjects = NULL;
2092 dev->nFreeObjects = 0;
2094 for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2095 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2096 dev->objectBucket[i].count = 0;
2101 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
2106 int lowest = 999999;
2108 /* First let's see if we can find one that's empty. */
2110 for (i = 0; i < 10 && lowest > 0; i++) {
2112 x %= YAFFS_NOBJECT_BUCKETS;
2113 if (dev->objectBucket[x].count < lowest) {
2114 lowest = dev->objectBucket[x].count;
2120 /* If we didn't find an empty list, then try
2121 * looking a bit further for a short one
2124 for (i = 0; i < 10 && lowest > 3; i++) {
2126 x %= YAFFS_NOBJECT_BUCKETS;
2127 if (dev->objectBucket[x].count < lowest) {
2128 lowest = dev->objectBucket[x].count;
2137 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
2139 int bucket = yaffs_FindNiceObjectBucket(dev);
2141 /* Now find an object value that has not already been taken
2142 * by scanning the list.
2146 struct ylist_head *i;
2148 __u32 n = (__u32) bucket;
2150 /* yaffs_CheckObjectHashSanity(); */
2154 n += YAFFS_NOBJECT_BUCKETS;
2155 if (1 || dev->objectBucket[bucket].count > 0) {
2156 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2157 /* If there is already one in the list */
2159 && ylist_entry(i, yaffs_Object,
2160 hashLink)->objectId == n) {
2171 static void yaffs_HashObject(yaffs_Object * in)
2173 int bucket = yaffs_HashFunction(in->objectId);
2174 yaffs_Device *dev = in->myDev;
2176 ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2177 dev->objectBucket[bucket].count++;
2181 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
2183 int bucket = yaffs_HashFunction(number);
2184 struct ylist_head *i;
2187 ylist_for_each(i, &dev->objectBucket[bucket].list) {
2188 /* Look if it is in the list */
2190 in = ylist_entry(i, yaffs_Object, hashLink);
2191 if (in->objectId == number) {
2193 /* Don't tell the VFS about this one if it is defered free */
2194 if (in->deferedFree)
2206 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
2207 yaffs_ObjectType type)
2210 yaffs_Object *theObject;
2211 yaffs_Tnode *tn = NULL;
2214 number = yaffs_CreateNewObjectNumber(dev);
2217 theObject = yaffs_AllocateEmptyObject(dev);
2221 if(type == YAFFS_OBJECT_TYPE_FILE){
2222 tn = yaffs_GetTnode(dev);
2224 yaffs_FreeObject(theObject);
2232 theObject->fake = 0;
2233 theObject->renameAllowed = 1;
2234 theObject->unlinkAllowed = 1;
2235 theObject->objectId = number;
2236 yaffs_HashObject(theObject);
2237 theObject->variantType = type;
2238 #ifdef CONFIG_YAFFS_WINCE
2239 yfsd_WinFileTimeNow(theObject->win_atime);
2240 theObject->win_ctime[0] = theObject->win_mtime[0] =
2241 theObject->win_atime[0];
2242 theObject->win_ctime[1] = theObject->win_mtime[1] =
2243 theObject->win_atime[1];
2247 theObject->yst_atime = theObject->yst_mtime =
2248 theObject->yst_ctime = Y_CURRENT_TIME;
2251 case YAFFS_OBJECT_TYPE_FILE:
2252 theObject->variant.fileVariant.fileSize = 0;
2253 theObject->variant.fileVariant.scannedFileSize = 0;
2254 theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2255 theObject->variant.fileVariant.topLevel = 0;
2256 theObject->variant.fileVariant.top = tn;
2258 case YAFFS_OBJECT_TYPE_DIRECTORY:
2259 YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2262 case YAFFS_OBJECT_TYPE_SYMLINK:
2263 case YAFFS_OBJECT_TYPE_HARDLINK:
2264 case YAFFS_OBJECT_TYPE_SPECIAL:
2265 /* No action required */
2267 case YAFFS_OBJECT_TYPE_UNKNOWN:
2268 /* todo this should not happen */
2276 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
2278 yaffs_ObjectType type)
2280 yaffs_Object *theObject = NULL;
2283 theObject = yaffs_FindObjectByNumber(dev, number);
2287 theObject = yaffs_CreateNewObject(dev, number, type);
2295 static YCHAR *yaffs_CloneString(const YCHAR * str)
2297 YCHAR *newStr = NULL;
2300 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2302 yaffs_strcpy(newStr, str);
2310 * Mknod (create) a new object.
2311 * equivalentObject only has meaning for a hard link;
2312 * aliasString only has meaning for a sumlink.
2313 * rdev only has meaning for devices (a subset of special objects)
2316 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2317 yaffs_Object * parent,
2322 yaffs_Object * equivalentObject,
2323 const YCHAR * aliasString, __u32 rdev)
2328 yaffs_Device *dev = parent->myDev;
2330 /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2331 if (yaffs_FindObjectByName(parent, name)) {
2335 in = yaffs_CreateNewObject(dev, -1, type);
2340 if(type == YAFFS_OBJECT_TYPE_SYMLINK){
2341 str = yaffs_CloneString(aliasString);
2343 yaffs_FreeObject(in);
2353 in->variantType = type;
2355 in->yst_mode = mode;
2357 #ifdef CONFIG_YAFFS_WINCE
2358 yfsd_WinFileTimeNow(in->win_atime);
2359 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2360 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2363 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2365 in->yst_rdev = rdev;
2369 in->nDataChunks = 0;
2371 yaffs_SetObjectName(in, name);
2374 yaffs_AddObjectToDirectory(parent, in);
2376 in->myDev = parent->myDev;
2379 case YAFFS_OBJECT_TYPE_SYMLINK:
2380 in->variant.symLinkVariant.alias = str;
2382 case YAFFS_OBJECT_TYPE_HARDLINK:
2383 in->variant.hardLinkVariant.equivalentObject =
2385 in->variant.hardLinkVariant.equivalentObjectId =
2386 equivalentObject->objectId;
2387 ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2389 case YAFFS_OBJECT_TYPE_FILE:
2390 case YAFFS_OBJECT_TYPE_DIRECTORY:
2391 case YAFFS_OBJECT_TYPE_SPECIAL:
2392 case YAFFS_OBJECT_TYPE_UNKNOWN:
2397 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2398 /* Could not create the object header, fail the creation */
2399 yaffs_DestroyObject(in);
2408 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
2409 __u32 mode, __u32 uid, __u32 gid)
2411 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2412 uid, gid, NULL, NULL, 0);
2415 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
2416 __u32 mode, __u32 uid, __u32 gid)
2418 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2419 mode, uid, gid, NULL, NULL, 0);
2422 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
2423 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2425 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2426 uid, gid, NULL, NULL, rdev);
2429 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
2430 __u32 mode, __u32 uid, __u32 gid,
2431 const YCHAR * alias)
2433 return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2434 uid, gid, NULL, alias, 0);
2437 /* yaffs_Link returns the object id of the equivalent object.*/
2438 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
2439 yaffs_Object * equivalentObject)
2441 /* Get the real object in case we were fed a hard link as an equivalent object */
2442 equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2444 if (yaffs_MknodObject
2445 (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2446 equivalentObject, NULL, 0)) {
2447 return equivalentObject;
2454 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
2455 const YCHAR * newName, int force, int shadows)
2460 yaffs_Object *existingTarget;
2462 if (newDir == NULL) {
2463 newDir = obj->parent; /* use the old directory */
2466 if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2467 T(YAFFS_TRACE_ALWAYS,
2469 ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2474 /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2475 if (obj->myDev->isYaffs2) {
2476 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2478 unlinkOp = (newDir == obj->myDev->unlinkedDir
2479 && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2482 deleteOp = (newDir == obj->myDev->deletedDir);
2484 existingTarget = yaffs_FindObjectByName(newDir, newName);
2486 /* If the object is a file going into the unlinked directory,
2487 * then it is OK to just stuff it in since duplicate names are allowed.
2488 * else only proceed if the new name does not exist and if we're putting
2489 * it into a directory.
2496 newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2497 yaffs_SetObjectName(obj, newName);
2500 yaffs_AddObjectToDirectory(newDir, obj);
2505 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2506 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
2513 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
2514 yaffs_Object * newDir, const YCHAR * newName)
2516 yaffs_Object *obj=NULL;
2517 yaffs_Object *existingTarget=NULL;
2521 if(!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2523 if(!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2526 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2527 /* Special case for case insemsitive systems (eg. WinCE).
2528 * While look-up is case insensitive, the name isn't.
2529 * Therefore we might want to change x.txt to X.txt
2531 if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
2536 else if (yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2540 obj = yaffs_FindObjectByName(oldDir, oldName);
2542 if (obj && obj->renameAllowed) {
2544 /* Now do the handling for an existing target, if there is one */
2546 existingTarget = yaffs_FindObjectByName(newDir, newName);
2547 if (existingTarget &&
2548 existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2549 !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2550 /* There is a target that is a non-empty directory, so we fail */
2551 return YAFFS_FAIL; /* EEXIST or ENOTEMPTY */
2552 } else if (existingTarget && existingTarget != obj) {
2553 /* Nuke the target first, using shadowing,
2554 * but only if it isn't the same object
2556 yaffs_ChangeObjectName(obj, newDir, newName, force,
2557 existingTarget->objectId);
2558 yaffs_UnlinkObject(existingTarget);
2561 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2566 /*------------------------- Block Management and Page Allocation ----------------*/
2568 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
2570 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2572 dev->blockInfo = NULL;
2573 dev->chunkBits = NULL;
2575 dev->allocationBlock = -1; /* force it to get a new one */
2577 /* If the first allocation strategy fails, thry the alternate one */
2578 dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2579 if(!dev->blockInfo){
2580 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2581 dev->blockInfoAlt = 1;
2584 dev->blockInfoAlt = 0;
2588 /* Set up dynamic blockinfo stuff. */
2589 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2590 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2591 if(!dev->chunkBits){
2592 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2593 dev->chunkBitsAlt = 1;
2596 dev->chunkBitsAlt = 0;
2599 if (dev->blockInfo && dev->chunkBits) {
2600 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2601 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2609 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
2611 if(dev->blockInfoAlt && dev->blockInfo)
2612 YFREE_ALT(dev->blockInfo);
2613 else if(dev->blockInfo)
2614 YFREE(dev->blockInfo);
2616 dev->blockInfoAlt = 0;
2618 dev->blockInfo = NULL;
2620 if(dev->chunkBitsAlt && dev->chunkBits)
2621 YFREE_ALT(dev->chunkBits);
2622 else if(dev->chunkBits)
2623 YFREE(dev->chunkBits);
2624 dev->chunkBitsAlt = 0;
2625 dev->chunkBits = NULL;
2628 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
2629 yaffs_BlockInfo * bi)
2636 return 1; /* disqualification only applies to yaffs2. */
2638 if (!bi->hasShrinkHeader)
2639 return 1; /* can gc */
2641 /* Find the oldest dirty sequence number if we don't know it and save it
2642 * so we don't have to keep recomputing it.
2644 if (!dev->oldestDirtySequence) {
2645 seq = dev->sequenceNumber;
2647 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2649 b = yaffs_GetBlockInfo(dev, i);
2650 if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2651 (b->pagesInUse - b->softDeletions) <
2652 dev->nChunksPerBlock && b->sequenceNumber < seq) {
2653 seq = b->sequenceNumber;
2656 dev->oldestDirtySequence = seq;
2659 /* Can't do gc of this block if there are any blocks older than this one that have
2662 return (bi->sequenceNumber <= dev->oldestDirtySequence);
2666 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2667 * for garbage collection.
2670 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2674 int b = dev->currentDirtyChecker;
2681 yaffs_BlockInfo *bi;
2682 int pendingPrioritisedExist = 0;
2684 /* First let's see if we need to grab a prioritised block */
2685 if(dev->hasPendingPrioritisedGCs){
2686 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2688 bi = yaffs_GetBlockInfo(dev, i);
2689 //yaffs_VerifyBlock(dev,bi,i);
2691 if(bi->gcPrioritise) {
2692 pendingPrioritisedExist = 1;
2693 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2694 yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2695 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2698 aggressive = 1; /* Fool the non-aggressive skip logiv below */
2703 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2704 dev->hasPendingPrioritisedGCs = 0;
2707 /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2709 * else (we're doing a leasurely gc), then we only bother to do this if the
2710 * block has only a few pages in use.
2713 dev->nonAggressiveSkip--;
2715 if (!aggressive && (dev->nonAggressiveSkip > 0)) {
2721 (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2725 dev->internalEndBlock - dev->internalStartBlock + 1;
2728 dev->internalEndBlock - dev->internalStartBlock + 1;
2729 iterations = iterations / 16;
2730 if (iterations > 200) {
2735 for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2737 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2738 b = dev->internalStartBlock;
2741 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2742 T(YAFFS_TRACE_ERROR,
2743 (TSTR("**>> Block %d is not valid" TENDSTR), b));
2747 bi = yaffs_GetBlockInfo(dev, b);
2750 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2757 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2758 (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2759 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2761 pagesInUse = (bi->pagesInUse - bi->softDeletions);
2765 dev->currentDirtyChecker = b;
2769 (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2770 dev->nChunksPerBlock - pagesInUse,prioritised));
2773 dev->oldestDirtySequence = 0;
2776 dev->nonAggressiveSkip = 4;
2782 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2784 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2788 /* If the block is still healthy erase it and mark as clean.
2789 * If the block has had a data failure, then retire it.
2792 T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2793 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2794 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2796 bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2798 if (!bi->needsRetiring) {
2799 yaffs_InvalidateCheckpoint(dev);
2800 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2802 dev->nErasureFailures++;
2803 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2804 (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2809 ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2811 for (i = 0; i < dev->nChunksPerBlock; i++) {
2812 if (!yaffs_CheckChunkErased
2813 (dev, blockNo * dev->nChunksPerBlock + i)) {
2814 T(YAFFS_TRACE_ERROR,
2816 (">>Block %d erasure supposedly OK, but chunk %d not erased"
2817 TENDSTR), blockNo, i));
2823 /* Clean it up... */
2824 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2825 dev->nErasedBlocks++;
2827 bi->softDeletions = 0;
2828 bi->hasShrinkHeader = 0;
2829 bi->skipErasedCheck = 1; /* This is clean, so no need to check */
2830 bi->gcPrioritise = 0;
2831 yaffs_ClearChunkBits(dev, blockNo);
2833 T(YAFFS_TRACE_ERASE,
2834 (TSTR("Erased block %d" TENDSTR), blockNo));
2836 dev->nFreeChunks -= dev->nChunksPerBlock; /* We lost a block of free space */
2838 yaffs_RetireBlock(dev, blockNo);
2839 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2840 (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2844 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2848 yaffs_BlockInfo *bi;
2850 if (dev->nErasedBlocks < 1) {
2851 /* Hoosterman we've got a problem.
2852 * Can't get space to gc
2854 T(YAFFS_TRACE_ERROR,
2855 (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2860 /* Find an empty block. */
2862 for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2863 dev->allocationBlockFinder++;
2864 if (dev->allocationBlockFinder < dev->internalStartBlock
2865 || dev->allocationBlockFinder > dev->internalEndBlock) {
2866 dev->allocationBlockFinder = dev->internalStartBlock;
2869 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2871 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2872 bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2873 dev->sequenceNumber++;
2874 bi->sequenceNumber = dev->sequenceNumber;
2875 dev->nErasedBlocks--;
2876 T(YAFFS_TRACE_ALLOCATE,
2877 (TSTR("Allocated block %d, seq %d, %d left" TENDSTR),
2878 dev->allocationBlockFinder, dev->sequenceNumber,
2879 dev->nErasedBlocks));
2880 return dev->allocationBlockFinder;
2884 T(YAFFS_TRACE_ALWAYS,
2886 ("yaffs tragedy: no more erased blocks, but there should have been %d"
2887 TENDSTR), dev->nErasedBlocks));
2894 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2896 if(!dev->nCheckpointBlocksRequired &&
2898 /* Not a valid value so recalculate */
2901 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2904 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2906 if(tnodeSize < sizeof(yaffs_Tnode))
2907 tnodeSize = sizeof(yaffs_Tnode);
2909 nBytes += sizeof(yaffs_CheckpointValidity);
2910 nBytes += sizeof(yaffs_CheckpointDevice);
2911 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2912 nBytes += devBlocks * dev->chunkBitmapStride;
2913 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2914 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2915 nBytes += sizeof(yaffs_CheckpointValidity);
2916 nBytes += sizeof(__u32); /* checksum*/
2918 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2920 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2922 dev->nCheckpointBlocksRequired = nBlocks;
2925 return dev->nCheckpointBlocksRequired;
2928 // Check if there's space to allocate...
2929 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2930 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2933 int reservedBlocks = dev->nReservedBlocks;
2934 int checkpointBlocks;
2937 checkpointBlocks = yaffs_CalcCheckpointBlocksRequired(dev) -
2938 dev->blocksInCheckpoint;
2939 if(checkpointBlocks < 0)
2940 checkpointBlocks = 0;
2942 checkpointBlocks =0;
2945 reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2947 return (dev->nFreeChunks > reservedChunks);
2950 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2953 yaffs_BlockInfo *bi;
2955 if (dev->allocationBlock < 0) {
2956 /* Get next block to allocate off */
2957 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2958 dev->allocationPage = 0;
2961 if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2962 /* Not enough space to allocate unless we're allowed to use the reserve. */
2966 if (dev->nErasedBlocks < dev->nReservedBlocks
2967 && dev->allocationPage == 0) {
2968 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2971 /* Next page please.... */
2972 if (dev->allocationBlock >= 0) {
2973 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2975 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2976 dev->allocationPage;
2978 yaffs_SetChunkBit(dev, dev->allocationBlock,
2979 dev->allocationPage);
2981 dev->allocationPage++;
2985 /* If the block is full set the state to full */
2986 if (dev->allocationPage >= dev->nChunksPerBlock) {
2987 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2988 dev->allocationBlock = -1;
2997 T(YAFFS_TRACE_ERROR,
2998 (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
3003 static int yaffs_GetErasedChunks(yaffs_Device * dev)
3007 n = dev->nErasedBlocks * dev->nChunksPerBlock;
3009 if (dev->allocationBlock > 0) {
3010 n += (dev->nChunksPerBlock - dev->allocationPage);
3017 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block, int wholeBlock)
3022 int retVal = YAFFS_OK;
3025 int isCheckpointBlock;
3029 int chunksBefore = yaffs_GetErasedChunks(dev);
3032 yaffs_ExtendedTags tags;
3034 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3036 yaffs_Object *object;
3038 isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3040 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3042 T(YAFFS_TRACE_TRACING,
3043 (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3046 bi->hasShrinkHeader,
3049 /*yaffs_VerifyFreeChunks(dev); */
3051 bi->hasShrinkHeader = 0; /* clear the flag so that the block can erase */
3053 /* Take off the number of soft deleted entries because
3054 * they're going to get really deleted during GC.
3056 dev->nFreeChunks -= bi->softDeletions;
3060 if (isCheckpointBlock ||
3061 !yaffs_StillSomeChunkBits(dev, block)) {
3062 T(YAFFS_TRACE_TRACING,
3064 ("Collecting block %d that has no chunks in use" TENDSTR),
3066 yaffs_BlockBecameDirty(dev, block);
3069 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3071 yaffs_VerifyBlock(dev,bi,block);
3073 maxCopies = (wholeBlock) ? dev->nChunksPerBlock : 10;
3074 oldChunk = block * dev->nChunksPerBlock + dev->gcChunk;
3076 for ( /* init already done */;
3077 retVal == YAFFS_OK &&
3078 dev->gcChunk < dev->nChunksPerBlock &&
3079 (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING)&&
3081 dev->gcChunk++, oldChunk++) {
3082 if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3084 /* This page is in use and might need to be copied off */
3090 yaffs_InitialiseTags(&tags);
3092 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3096 yaffs_FindObjectByNumber(dev,
3099 T(YAFFS_TRACE_GC_DETAIL,
3101 ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3102 dev->gcChunk, tags.objectId, tags.chunkId,
3105 if(object && !yaffs_SkipVerification(dev)){
3106 if(tags.chunkId == 0)
3107 matchingChunk = object->hdrChunk;
3108 else if(object->softDeleted)
3109 matchingChunk = oldChunk; /* Defeat the test */
3111 matchingChunk = yaffs_FindChunkInFile(object,tags.chunkId,NULL);
3113 if(oldChunk != matchingChunk)
3114 T(YAFFS_TRACE_ERROR,
3115 (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3116 oldChunk,matchingChunk,tags.objectId, tags.chunkId));
3121 T(YAFFS_TRACE_ERROR,
3123 ("page %d in gc has no object: %d %d %d "
3125 tags.objectId, tags.chunkId, tags.byteCount));
3130 object->softDeleted &&
3131 tags.chunkId != 0) {
3132 /* Data chunk in a soft deleted file, throw it away
3133 * It's a soft deleted data chunk,
3134 * No need to copy this, just forget about it and
3135 * fix up the object.
3138 object->nDataChunks--;
3140 if (object->nDataChunks <= 0) {
3141 /* remeber to clean up the object */
3142 dev->gcCleanupList[cleanups] =
3148 /* Todo object && object->deleted && object->nDataChunks == 0 */
3150 /* Deleted object header with no data chunks.
3151 * Can be discarded and the file deleted.
3153 object->hdrChunk = 0;
3154 yaffs_FreeTnode(object->myDev,
3157 object->variant.fileVariant.top = NULL;
3158 yaffs_DoGenericObjectDeletion(object);
3160 } else if (object) {
3161 /* It's either a data chunk in a live file or
3162 * an ObjectHeader, so we're interested in it.
3163 * NB Need to keep the ObjectHeaders of deleted files
3164 * until the whole file has been deleted off
3166 tags.serialNumber++;
3170 if (tags.chunkId == 0) {
3171 /* It is an object Id,
3172 * We need to nuke the shrinkheader flags first
3173 * We no longer want the shrinkHeader flag since its work is done
3174 * and if it is left in place it will mess up scanning.
3177 yaffs_ObjectHeader *oh;
3178 oh = (yaffs_ObjectHeader *)buffer;
3180 tags.extraIsShrinkHeader = 0;
3182 yaffs_VerifyObjectHeader(object,oh,&tags,1);
3186 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3189 retVal = YAFFS_FAIL;
3192 /* Ok, now fix up the Tnodes etc. */
3194 if (tags.chunkId == 0) {
3196 object->hdrChunk = newChunk;
3197 object->serial = tags.serialNumber;
3199 /* It's a data chunk */
3200 yaffs_PutChunkIntoFile
3208 if(retVal == YAFFS_OK)
3209 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3214 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3217 /* Do any required cleanups */
3218 for (i = 0; i < cleanups; i++) {
3219 /* Time to delete the file too */
3221 yaffs_FindObjectByNumber(dev,
3222 dev->gcCleanupList[i]);
3224 yaffs_FreeTnode(dev,
3225 object->variant.fileVariant.
3227 object->variant.fileVariant.top = NULL;
3230 ("yaffs: About to finally delete object %d"
3231 TENDSTR), object->objectId));
3232 yaffs_DoGenericObjectDeletion(object);
3233 object->myDev->nDeletedFiles--;
3240 yaffs_VerifyCollectedBlock(dev,bi,block);
3242 if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
3245 ("gc did not increase free chunks before %d after %d"
3246 TENDSTR), chunksBefore, chunksAfter));
3249 /* If the gc completed then clear the current gcBlock so that we find another. */
3250 if(bi->blockState != YAFFS_BLOCK_STATE_COLLECTING){
3260 /* New garbage collector
3261 * If we're very low on erased blocks then we do aggressive garbage collection
3262 * otherwise we do "leasurely" garbage collection.
3263 * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3264 * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3266 * The idea is to help clear out space in a more spread-out manner.
3267 * Dunno if it really does anything useful.
3269 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
3273 int gcOk = YAFFS_OK;
3276 int checkpointBlockAdjust;
3278 if (dev->isDoingGC) {
3279 /* Bail out so we don't get recursive gc */
3283 /* This loop should pass the first time.
3284 * We'll only see looping here if the erase of the collected block fails.
3290 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3291 if(checkpointBlockAdjust < 0)
3292 checkpointBlockAdjust = 0;
3294 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3295 /* We need a block soon...*/
3298 /* We're in no hurry */
3302 if(dev->gcBlock <= 0){
3303 dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3307 block = dev->gcBlock;
3310 dev->garbageCollections++;
3312 dev->passiveGarbageCollections++;
3317 ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3318 dev->nErasedBlocks, aggressive));
3320 gcOk = yaffs_GarbageCollectBlock(dev,block,aggressive);
3323 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3326 ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3327 TENDSTR), dev->nErasedBlocks, maxTries, block));
3329 } while ((dev->nErasedBlocks < dev->nReservedBlocks) &&
3333 return aggressive ? gcOk : YAFFS_OK;
3336 /*------------------------- TAGS --------------------------------*/
3338 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
3341 return (tags->chunkId == chunkInObject &&
3342 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3347 /*-------------------- Data file manipulation -----------------*/
3349 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
3350 yaffs_ExtendedTags * tags)
3352 /*Get the Tnode, then get the level 0 offset chunk offset */
3355 yaffs_ExtendedTags localTags;
3358 yaffs_Device *dev = in->myDev;
3361 /* Passed a NULL, so use our own tags space */
3365 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3368 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3371 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3377 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
3378 yaffs_ExtendedTags * tags)
3380 /* Get the Tnode, then get the level 0 offset chunk offset */
3383 yaffs_ExtendedTags localTags;
3385 yaffs_Device *dev = in->myDev;
3389 /* Passed a NULL, so use our own tags space */
3393 tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3397 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3400 yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3403 /* Delete the entry in the filestructure (if found) */
3405 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
3408 /*T(("No level 0 found for %d\n", chunkInInode)); */
3412 /* T(("Could not find %d to delete\n",chunkInInode)); */
3417 #ifdef YAFFS_PARANOID
3419 static int yaffs_CheckFileSanity(yaffs_Object * in)
3427 yaffs_Tags localTags;
3428 yaffs_Tags *tags = &localTags;
3432 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3433 /* T(("Object not a file\n")); */
3437 objId = in->objectId;
3438 fSize = in->variant.fileVariant.fileSize;
3440 (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3442 for (chunk = 1; chunk <= nChunks; chunk++) {
3443 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3448 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
3450 if (yaffs_CheckChunkBits
3451 (dev, theChunk / dev->nChunksPerBlock,
3452 theChunk % dev->nChunksPerBlock)) {
3454 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3458 (tags, in->objectId, chunk, chunkDeleted)) {
3468 /* T(("No level 0 found for %d\n", chunk)); */
3472 return failed ? YAFFS_FAIL : YAFFS_OK;
3477 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
3478 int chunkInNAND, int inScan)
3480 /* NB inScan is zero unless scanning.
3481 * For forward scanning, inScan is > 0;
3482 * for backward scanning inScan is < 0
3486 yaffs_Device *dev = in->myDev;
3488 yaffs_ExtendedTags existingTags;
3489 yaffs_ExtendedTags newTags;
3490 unsigned existingSerial, newSerial;
3492 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3493 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3494 * If it is not during Scanning then something went wrong!
3497 T(YAFFS_TRACE_ERROR,
3499 ("yaffs tragedy:attempt to put data chunk into a non-file"
3504 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3508 tn = yaffs_AddOrFindLevel0Tnode(dev,
3509 &in->variant.fileVariant,
3516 existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3519 /* If we're scanning then we need to test for duplicates
3520 * NB This does not need to be efficient since it should only ever
3521 * happen when the power fails during a write, then only one
3522 * chunk should ever be affected.
3524 * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3525 * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3528 if (existingChunk > 0) {
3529 /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3530 * thus we have to do a FindChunkInFile to get the real chunk id.
3532 * We have a duplicate now we need to decide which one to use:
3534 * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3535 * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3536 * YAFFS1: Get both sets of tags and compare serial numbers.
3540 /* Only do this for forward scanning */
3541 yaffs_ReadChunkWithTagsFromNAND(dev,
3545 /* Do a proper find */
3547 yaffs_FindChunkInFile(in, chunkInInode,
3551 if (existingChunk <= 0) {
3552 /*Hoosterman - how did this happen? */
3554 T(YAFFS_TRACE_ERROR,
3556 ("yaffs tragedy: existing chunk < 0 in scan"
3561 /* NB The deleted flags should be false, otherwise the chunks will
3562 * not be loaded during a scan
3566 newSerial = newTags.serialNumber;
3567 existingSerial = existingTags.serialNumber;
3571 (in->myDev->isYaffs2 ||
3572 existingChunk <= 0 ||
3573 ((existingSerial + 1) & 3) == newSerial)) {
3574 /* Forward scanning.
3576 * Delete the old one and drop through to update the tnode
3578 yaffs_DeleteChunk(dev, existingChunk, 1,
3581 /* Backward scanning or we want to use the existing one
3583 * Delete the new one and return early so that the tnode isn't changed
3585 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3593 if (existingChunk == 0) {
3597 yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
3602 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
3605 int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3607 if (chunkInNAND >= 0) {
3608 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3611 T(YAFFS_TRACE_NANDACCESS,
3612 (TSTR("Chunk %d not found zero instead" TENDSTR),
3614 /* get sane (zero) data if you read a hole */
3615 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3621 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
3625 yaffs_ExtendedTags tags;
3626 yaffs_BlockInfo *bi;
3633 block = chunkId / dev->nChunksPerBlock;
3634 page = chunkId % dev->nChunksPerBlock;
3637 if(!yaffs_CheckChunkBit(dev,block,page))
3638 T(YAFFS_TRACE_VERIFY,
3639 (TSTR("Deleting invalid chunk %d"TENDSTR),
3642 bi = yaffs_GetBlockInfo(dev, block);
3644 T(YAFFS_TRACE_DELETION,
3645 (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3648 bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3650 yaffs_InitialiseTags(&tags);
3652 tags.chunkDeleted = 1;
3654 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3655 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3657 dev->nUnmarkedDeletions++;
3660 /* Pull out of the management area.
3661 * If the whole block became dirty, this will kick off an erasure.
3663 if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3664 bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3665 bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3666 bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3669 yaffs_ClearChunkBit(dev, block, page);
3673 if (bi->pagesInUse == 0 &&
3674 !bi->hasShrinkHeader &&
3675 bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3676 bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3677 yaffs_BlockBecameDirty(dev, block);
3681 /* T(("Bad news deleting chunk %d\n",chunkId)); */
3686 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
3687 const __u8 * buffer, int nBytes,
3690 /* Find old chunk Need to do this to get serial number
3691 * Write new one and patch into tree.
3692 * Invalidate old tags.
3696 yaffs_ExtendedTags prevTags;
3699 yaffs_ExtendedTags newTags;
3701 yaffs_Device *dev = in->myDev;
3703 yaffs_CheckGarbageCollection(dev);
3705 /* Get the previous chunk at this location in the file if it exists */
3706 prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3708 /* Set up new tags */
3709 yaffs_InitialiseTags(&newTags);
3711 newTags.chunkId = chunkInInode;
3712 newTags.objectId = in->objectId;
3713 newTags.serialNumber =
3714 (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
3715 newTags.byteCount = nBytes;
3717 if(nBytes < 1 || nBytes > dev->totalBytesPerChunk){
3718 T(YAFFS_TRACE_ERROR,
3719 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3726 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3729 if (newChunkId >= 0) {
3730 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3732 if (prevChunkId >= 0) {
3733 yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3737 yaffs_CheckFileSanity(in);
3743 /* UpdateObjectHeader updates the header on NAND for an object.
3744 * If name is not NULL, then that new name is used.
3746 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
3747 int isShrink, int shadows)
3750 yaffs_BlockInfo *bi;
3752 yaffs_Device *dev = in->myDev;
3759 yaffs_ExtendedTags newTags;
3760 yaffs_ExtendedTags oldTags;
3762 __u8 *buffer = NULL;
3763 YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3765 yaffs_ObjectHeader *oh = NULL;
3767 yaffs_strcpy(oldName,_Y("silly old name"));
3771 in == dev->rootDir || /* The rootDir should also be saved */
3774 yaffs_CheckGarbageCollection(dev);
3775 yaffs_CheckObjectDetailsLoaded(in);
3777 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3778 oh = (yaffs_ObjectHeader *) buffer;
3780 prevChunkId = in->hdrChunk;
3782 if (prevChunkId > 0) {
3783 result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3786 yaffs_VerifyObjectHeader(in,oh,&oldTags,0);
3788 memcpy(oldName, oh->name, sizeof(oh->name));
3791 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3793 oh->type = in->variantType;
3794 oh->yst_mode = in->yst_mode;
3795 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3797 #ifdef CONFIG_YAFFS_WINCE
3798 oh->win_atime[0] = in->win_atime[0];
3799 oh->win_ctime[0] = in->win_ctime[0];
3800 oh->win_mtime[0] = in->win_mtime[0];
3801 oh->win_atime[1] = in->win_atime[1];
3802 oh->win_ctime[1] = in->win_ctime[1];
3803 oh->win_mtime[1] = in->win_mtime[1];
3805 oh->yst_uid = in->yst_uid;
3806 oh->yst_gid = in->yst_gid;
3807 oh->yst_atime = in->yst_atime;
3808 oh->yst_mtime = in->yst_mtime;
3809 oh->yst_ctime = in->yst_ctime;
3810 oh->yst_rdev = in->yst_rdev;
3813 oh->parentObjectId = in->parent->objectId;
3815 oh->parentObjectId = 0;
3818 if (name && *name) {
3819 memset(oh->name, 0, sizeof(oh->name));
3820 yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3821 } else if (prevChunkId>=0) {
3822 memcpy(oh->name, oldName, sizeof(oh->name));
3824 memset(oh->name, 0, sizeof(oh->name));
3827 oh->isShrink = isShrink;
3829 switch (in->variantType) {
3830 case YAFFS_OBJECT_TYPE_UNKNOWN:
3831 /* Should not happen */
3833 case YAFFS_OBJECT_TYPE_FILE:
3835 (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3836 || oh->parentObjectId ==
3837 YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3838 fileVariant.fileSize;
3840 case YAFFS_OBJECT_TYPE_HARDLINK:
3841 oh->equivalentObjectId =
3842 in->variant.hardLinkVariant.equivalentObjectId;
3844 case YAFFS_OBJECT_TYPE_SPECIAL:
3847 case YAFFS_OBJECT_TYPE_DIRECTORY:
3850 case YAFFS_OBJECT_TYPE_SYMLINK:
3851 yaffs_strncpy(oh->alias,
3852 in->variant.symLinkVariant.alias,
3853 YAFFS_MAX_ALIAS_LENGTH);
3854 oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3859 yaffs_InitialiseTags(&newTags);
3861 newTags.chunkId = 0;
3862 newTags.objectId = in->objectId;
3863 newTags.serialNumber = in->serial;
3865 /* Add extra info for file header */
3867 newTags.extraHeaderInfoAvailable = 1;
3868 newTags.extraParentObjectId = oh->parentObjectId;
3869 newTags.extraFileLength = oh->fileSize;
3870 newTags.extraIsShrinkHeader = oh->isShrink;
3871 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3872 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3873 newTags.extraObjectType = in->variantType;
3875 yaffs_VerifyObjectHeader(in,oh,&newTags,1);
3877 /* Create new chunk in NAND */
3879 yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3880 (prevChunkId >= 0) ? 1 : 0);
3882 if (newChunkId >= 0) {
3884 in->hdrChunk = newChunkId;
3886 if (prevChunkId >= 0) {
3887 yaffs_DeleteChunk(dev, prevChunkId, 1,
3891 if(!yaffs_ObjectHasCachedWriteData(in))
3894 /* If this was a shrink, then mark the block that the chunk lives on */
3896 bi = yaffs_GetBlockInfo(in->myDev,
3897 newChunkId /in->myDev-> nChunksPerBlock);
3898 bi->hasShrinkHeader = 1;
3903 retVal = newChunkId;
3908 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3913 /*------------------------ Short Operations Cache ----------------------------------------
3914 * In many situations where there is no high level buffering (eg WinCE) a lot of
3915 * reads might be short sequential reads, and a lot of writes may be short
3916 * sequential writes. eg. scanning/writing a jpeg file.
3917 * In these cases, a short read/write cache can provide a huge perfomance benefit
3918 * with dumb-as-a-rock code.
3919 * In Linux, the page cache provides read buffering aand the short op cache provides write
3922 * There are a limited number (~10) of cache chunks per device so that we don't
3923 * need a very intelligent search.
3926 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3928 yaffs_Device *dev = obj->myDev;
3930 yaffs_ChunkCache *cache;
3931 int nCaches = obj->myDev->nShortOpCaches;
3933 for(i = 0; i < nCaches; i++){
3934 cache = &dev->srCache[i];
3935 if (cache->object == obj &&
3944 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3946 yaffs_Device *dev = obj->myDev;
3947 int lowest = -99; /* Stop compiler whining. */
3949 yaffs_ChunkCache *cache;
3950 int chunkWritten = 0;
3951 int nCaches = obj->myDev->nShortOpCaches;
3957 /* Find the dirty cache for this object with the lowest chunk id. */
3958 for (i = 0; i < nCaches; i++) {
3959 if (dev->srCache[i].object == obj &&
3960 dev->srCache[i].dirty) {
3962 || dev->srCache[i].chunkId <
3964 cache = &dev->srCache[i];
3965 lowest = cache->chunkId;
3970 if (cache && !cache->locked) {
3971 /* Write it out and free it up */
3974 yaffs_WriteChunkDataToObject(cache->object,
3980 cache->object = NULL;
3983 } while (cache && chunkWritten > 0);
3986 /* Hoosterman, disk full while writing cache out. */
3987 T(YAFFS_TRACE_ERROR,
3988 (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3995 /*yaffs_FlushEntireDeviceCache(dev)
4000 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
4003 int nCaches = dev->nShortOpCaches;
4006 /* Find a dirty object in the cache and flush it...
4007 * until there are no further dirty objects.
4011 for( i = 0; i < nCaches && !obj; i++) {
4012 if (dev->srCache[i].object &&
4013 dev->srCache[i].dirty)
4014 obj = dev->srCache[i].object;
4018 yaffs_FlushFilesChunkCache(obj);
4025 /* Grab us a cache chunk for use.
4026 * First look for an empty one.
4027 * Then look for the least recently used non-dirty one.
4028 * Then look for the least recently used dirty one...., flush and look again.
4030 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
4034 if (dev->nShortOpCaches > 0) {
4035 for (i = 0; i < dev->nShortOpCaches; i++) {
4036 if (!dev->srCache[i].object)
4037 return &dev->srCache[i];
4044 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
4046 yaffs_ChunkCache *cache;
4047 yaffs_Object *theObj;
4052 if (dev->nShortOpCaches > 0) {
4053 /* Try find a non-dirty one... */
4055 cache = yaffs_GrabChunkCacheWorker(dev);
4058 /* They were all dirty, find the last recently used object and flush
4059 * its cache, then find again.
4060 * NB what's here is not very accurate, we actually flush the object
4061 * the last recently used page.
4064 /* With locking we can't assume we can use entry zero */
4071 for (i = 0; i < dev->nShortOpCaches; i++) {
4072 if (dev->srCache[i].object &&
4073 !dev->srCache[i].locked &&
4074 (dev->srCache[i].lastUse < usage || !cache))
4076 usage = dev->srCache[i].lastUse;
4077 theObj = dev->srCache[i].object;
4078 cache = &dev->srCache[i];
4083 if (!cache || cache->dirty) {
4084 /* Flush and try again */
4085 yaffs_FlushFilesChunkCache(theObj);
4086 cache = yaffs_GrabChunkCacheWorker(dev);
4096 /* Find a cached chunk */
4097 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
4100 yaffs_Device *dev = obj->myDev;
4102 if (dev->nShortOpCaches > 0) {
4103 for (i = 0; i < dev->nShortOpCaches; i++) {
4104 if (dev->srCache[i].object == obj &&
4105 dev->srCache[i].chunkId == chunkId) {
4108 return &dev->srCache[i];
4115 /* Mark the chunk for the least recently used algorithym */
4116 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
4120 if (dev->nShortOpCaches > 0) {
4121 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4122 /* Reset the cache usages */
4124 for (i = 1; i < dev->nShortOpCaches; i++) {
4125 dev->srCache[i].lastUse = 0;
4132 cache->lastUse = dev->srLastUse;
4140 /* Invalidate a single cache page.
4141 * Do this when a whole page gets written,
4142 * ie the short cache for this page is no longer valid.
4144 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
4146 if (object->myDev->nShortOpCaches > 0) {
4147 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4150 cache->object = NULL;
4155 /* Invalidate all the cache pages associated with this object
4156 * Do this whenever ther file is deleted or resized.
4158 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
4161 yaffs_Device *dev = in->myDev;
4163 if (dev->nShortOpCaches > 0) {
4164 /* Invalidate it. */
4165 for (i = 0; i < dev->nShortOpCaches; i++) {
4166 if (dev->srCache[i].object == in) {
4167 dev->srCache[i].object = NULL;
4173 /*--------------------- Checkpointing --------------------*/
4176 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
4178 yaffs_CheckpointValidity cp;
4180 memset(&cp,0,sizeof(cp));
4182 cp.structType = sizeof(cp);
4183 cp.magic = YAFFS_MAGIC;
4184 cp.version = YAFFS_CHECKPOINT_VERSION;
4185 cp.head = (head) ? 1 : 0;
4187 return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
4191 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4193 yaffs_CheckpointValidity cp;
4196 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4199 ok = (cp.structType == sizeof(cp)) &&
4200 (cp.magic == YAFFS_MAGIC) &&
4201 (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4202 (cp.head == ((head) ? 1 : 0));
4206 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4209 cp->nErasedBlocks = dev->nErasedBlocks;
4210 cp->allocationBlock = dev->allocationBlock;
4211 cp->allocationPage = dev->allocationPage;
4212 cp->nFreeChunks = dev->nFreeChunks;
4214 cp->nDeletedFiles = dev->nDeletedFiles;
4215 cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4216 cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4217 cp->sequenceNumber = dev->sequenceNumber;
4218 cp->oldestDirtySequence = dev->oldestDirtySequence;
4222 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4223 yaffs_CheckpointDevice *cp)
4225 dev->nErasedBlocks = cp->nErasedBlocks;
4226 dev->allocationBlock = cp->allocationBlock;
4227 dev->allocationPage = cp->allocationPage;
4228 dev->nFreeChunks = cp->nFreeChunks;
4230 dev->nDeletedFiles = cp->nDeletedFiles;
4231 dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4232 dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4233 dev->sequenceNumber = cp->sequenceNumber;
4234 dev->oldestDirtySequence = cp->oldestDirtySequence;
4238 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4240 yaffs_CheckpointDevice cp;
4242 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4246 /* Write device runtime values*/
4247 yaffs_DeviceToCheckpointDevice(&cp,dev);
4248 cp.structType = sizeof(cp);
4250 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4252 /* Write block info */
4254 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4255 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
4258 /* Write chunk bits */
4260 nBytes = nBlocks * dev->chunkBitmapStride;
4261 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
4267 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4269 yaffs_CheckpointDevice cp;
4271 __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4275 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4279 if(cp.structType != sizeof(cp))
4283 yaffs_CheckpointDeviceToDevice(dev,&cp);
4285 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4287 ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
4291 nBytes = nBlocks * dev->chunkBitmapStride;
4293 ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
4298 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4302 cp->objectId = obj->objectId;
4303 cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4304 cp->hdrChunk = obj->hdrChunk;
4305 cp->variantType = obj->variantType;
4306 cp->deleted = obj->deleted;
4307 cp->softDeleted = obj->softDeleted;
4308 cp->unlinked = obj->unlinked;
4309 cp->fake = obj->fake;
4310 cp->renameAllowed = obj->renameAllowed;
4311 cp->unlinkAllowed = obj->unlinkAllowed;
4312 cp->serial = obj->serial;
4313 cp->nDataChunks = obj->nDataChunks;
4315 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4316 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4317 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4318 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4321 static int yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
4324 yaffs_Object *parent;
4326 if (obj->variantType != cp->variantType) {
4327 T(YAFFS_TRACE_ERROR,(TSTR("Checkpoint read object %d type %d "
4328 TCONT("chunk %d does not match existing object type %d")
4329 TENDSTR), cp->objectId, cp->variantType, cp->hdrChunk,
4334 obj->objectId = cp->objectId;
4337 parent = yaffs_FindOrCreateObjectByNumber(
4340 YAFFS_OBJECT_TYPE_DIRECTORY);
4345 if (parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4346 T(YAFFS_TRACE_ALWAYS,(TSTR("Checkpoint read object %d parent %d type %d"
4347 TCONT(" chunk %d Parent type, %d, not directory")
4349 cp->objectId,cp->parentId,cp->variantType,cp->hdrChunk,parent->variantType));
4352 yaffs_AddObjectToDirectory(parent, obj);
4355 obj->hdrChunk = cp->hdrChunk;
4356 obj->variantType = cp->variantType;
4357 obj->deleted = cp->deleted;
4358 obj->softDeleted = cp->softDeleted;
4359 obj->unlinked = cp->unlinked;
4360 obj->fake = cp->fake;
4361 obj->renameAllowed = cp->renameAllowed;
4362 obj->unlinkAllowed = cp->unlinkAllowed;
4363 obj->serial = cp->serial;
4364 obj->nDataChunks = cp->nDataChunks;
4366 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4367 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4368 else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4369 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4371 if(obj->hdrChunk > 0)
4372 obj->lazyLoaded = 1;
4378 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
4379 __u32 level, int chunkOffset)
4382 yaffs_Device *dev = in->myDev;
4384 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4386 if(tnodeSize < sizeof(yaffs_Tnode))
4387 tnodeSize = sizeof(yaffs_Tnode);
4393 for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
4394 if (tn->internal[i]) {
4395 ok = yaffs_CheckpointTnodeWorker(in,
4398 (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4401 } else if (level == 0) {
4402 __u32 baseOffset = chunkOffset << YAFFS_TNODES_LEVEL0_BITS;
4403 ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
4405 ok = (yaffs_CheckpointWrite(dev,tn,tnodeSize) == tnodeSize);
4413 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4415 __u32 endMarker = ~0;
4418 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4419 ok = yaffs_CheckpointTnodeWorker(obj,
4420 obj->variant.fileVariant.top,
4421 obj->variant.fileVariant.topLevel,
4424 ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) ==
4431 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4435 yaffs_Device *dev = obj->myDev;
4436 yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4439 int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4441 if(tnodeSize < sizeof(yaffs_Tnode))
4442 tnodeSize = sizeof(yaffs_Tnode);
4444 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4446 while(ok && (~baseChunk)){
4448 /* Read level 0 tnode */
4451 tn = yaffs_GetTnodeRaw(dev);
4453 ok = (yaffs_CheckpointRead(dev,tn,tnodeSize) == tnodeSize);
4458 ok = yaffs_AddOrFindLevel0Tnode(dev,
4466 ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4470 T(YAFFS_TRACE_CHECKPOINT,(
4471 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4472 nread,baseChunk,ok));
4478 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4481 yaffs_CheckpointObject cp;
4484 struct ylist_head *lh;
4487 /* Iterate through the objects in each hash entry,
4488 * dumping them to the checkpointing stream.
4491 for(i = 0; ok && i < YAFFS_NOBJECT_BUCKETS; i++){
4492 ylist_for_each(lh, &dev->objectBucket[i].list) {
4494 obj = ylist_entry(lh, yaffs_Object, hashLink);
4495 if (!obj->deferedFree) {
4496 yaffs_ObjectToCheckpointObject(&cp,obj);
4497 cp.structType = sizeof(cp);
4499 T(YAFFS_TRACE_CHECKPOINT,(
4500 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
4501 cp.objectId,cp.parentId,cp.variantType,cp.hdrChunk,(unsigned) obj));
4503 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4505 if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4506 ok = yaffs_WriteCheckpointTnodes(obj);
4513 /* Dump end of list */
4514 memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
4515 cp.structType = sizeof(cp);
4518 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4523 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4526 yaffs_CheckpointObject cp;
4529 yaffs_Object *hardList = NULL;
4531 while(ok && !done) {
4532 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4533 if(cp.structType != sizeof(cp)) {
4534 T(YAFFS_TRACE_CHECKPOINT,(TSTR("struct size %d instead of %d ok %d"TENDSTR),
4535 cp.structType,sizeof(cp),ok));
4539 T(YAFFS_TRACE_CHECKPOINT,(TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4540 cp.objectId,cp.parentId,cp.variantType,cp.hdrChunk));
4542 if(ok && cp.objectId == ~0)
4545 obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
4547 ok = yaffs_CheckpointObjectToObject(obj,&cp);
4550 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4551 ok = yaffs_ReadCheckpointTnodes(obj);
4552 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4553 obj->hardLinks.next =
4554 (struct ylist_head *)
4566 yaffs_HardlinkFixup(dev,hardList);
4571 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4573 __u32 checkpointSum;
4576 yaffs_GetCheckpointSum(dev,&checkpointSum);
4578 ok = (yaffs_CheckpointWrite(dev,&checkpointSum,sizeof(checkpointSum)) == sizeof(checkpointSum));
4586 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4588 __u32 checkpointSum0;
4589 __u32 checkpointSum1;
4592 yaffs_GetCheckpointSum(dev,&checkpointSum0);
4594 ok = (yaffs_CheckpointRead(dev,&checkpointSum1,sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4599 if(checkpointSum0 != checkpointSum1)
4606 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4611 if(dev->skipCheckpointWrite || !dev->isYaffs2){
4612 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint write" TENDSTR)));
4617 ok = yaffs_CheckpointOpen(dev,1);
4620 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4621 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
4624 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint device" TENDSTR)));
4625 ok = yaffs_WriteCheckpointDevice(dev);
4628 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint objects" TENDSTR)));
4629 ok = yaffs_WriteCheckpointObjects(dev);
4632 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4633 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
4637 ok = yaffs_WriteCheckpointSum(dev);
4641 if(!yaffs_CheckpointClose(dev))
4645 dev->isCheckpointed = 1;
4647 dev->isCheckpointed = 0;
4649 return dev->isCheckpointed;
4652 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4656 if(dev->skipCheckpointRead || !dev->isYaffs2){
4657 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint read" TENDSTR)));
4662 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
4665 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4666 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
4669 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint device" TENDSTR)));
4670 ok = yaffs_ReadCheckpointDevice(dev);
4673 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint objects" TENDSTR)));
4674 ok = yaffs_ReadCheckpointObjects(dev);
4677 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4678 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
4682 ok = yaffs_ReadCheckpointSum(dev);
4683 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint checksum %d" TENDSTR),ok));
4686 if(!yaffs_CheckpointClose(dev))
4690 dev->isCheckpointed = 1;
4692 dev->isCheckpointed = 0;
4698 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4700 if(dev->isCheckpointed ||
4701 dev->blocksInCheckpoint > 0){
4702 dev->isCheckpointed = 0;
4703 yaffs_CheckpointInvalidateStream(dev);
4704 if(dev->superBlock && dev->markSuperBlockDirty)
4705 dev->markSuperBlockDirty(dev->superBlock);
4710 int yaffs_CheckpointSave(yaffs_Device *dev)
4713 T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4715 yaffs_VerifyObjects(dev);
4716 yaffs_VerifyBlocks(dev);
4717 yaffs_VerifyFreeChunks(dev);
4719 if(!dev->isCheckpointed) {
4720 yaffs_InvalidateCheckpoint(dev);
4721 yaffs_WriteCheckpointData(dev);
4724 T(YAFFS_TRACE_ALWAYS,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4726 return dev->isCheckpointed;
4729 int yaffs_CheckpointRestore(yaffs_Device *dev)
4732 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4734 retval = yaffs_ReadCheckpointData(dev);
4736 if(dev->isCheckpointed){
4737 yaffs_VerifyObjects(dev);
4738 yaffs_VerifyBlocks(dev);
4739 yaffs_VerifyFreeChunks(dev);
4742 T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4747 /*--------------------- File read/write ------------------------
4748 * Read and write have very similar structures.
4749 * In general the read/write has three parts to it
4750 * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4751 * Some complete chunks
4752 * An incomplete chunk to end off with
4754 * Curve-balls: the first chunk might also be the last chunk.
4757 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, loff_t offset,
4766 yaffs_ChunkCache *cache;
4773 //chunk = offset / dev->nDataBytesPerChunk + 1;
4774 //start = offset % dev->nDataBytesPerChunk;
4775 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4778 /* OK now check for the curveball where the start and end are in
4781 if ((start + n) < dev->nDataBytesPerChunk) {
4784 nToCopy = dev->nDataBytesPerChunk - start;
4787 cache = yaffs_FindChunkCache(in, chunk);
4789 /* If the chunk is already in the cache or it is less than a whole chunk
4790 * or we're using inband tags then use the cache (if there is caching)
4791 * else bypass the cache.
4793 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4794 if (dev->nShortOpCaches > 0) {
4796 /* If we can't find the data in the cache, then load it up. */
4799 cache = yaffs_GrabChunkCache(in->myDev);
4801 cache->chunkId = chunk;
4804 yaffs_ReadChunkDataFromObject(in, chunk,
4810 yaffs_UseChunkCache(dev, cache, 0);
4815 memcpy(buffer, &cache->data[start], nToCopy);
4819 /* Read into the local buffer then copy..*/
4822 yaffs_GetTempBuffer(dev, __LINE__);
4823 yaffs_ReadChunkDataFromObject(in, chunk,
4826 memcpy(buffer, &localBuffer[start], nToCopy);
4829 yaffs_ReleaseTempBuffer(dev, localBuffer,
4835 /* A full chunk. Read directly into the supplied buffer. */
4836 yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4850 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, loff_t offset,
4851 int nBytes, int writeThrough)
4860 int startOfWrite = offset;
4861 int chunkWritten = 0;
4869 while (n > 0 && chunkWritten >= 0) {
4870 //chunk = offset / dev->nDataBytesPerChunk + 1;
4871 //start = offset % dev->nDataBytesPerChunk;
4872 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4874 if(chunk * dev->nDataBytesPerChunk + start != offset ||
4875 start >= dev->nDataBytesPerChunk){
4876 T(YAFFS_TRACE_ERROR,(
4877 TSTR("AddrToChunk of offset %d gives chunk %d start %d"
4879 (int)offset, chunk,start));
4883 /* OK now check for the curveball where the start and end are in
4887 if ((start + n) < dev->nDataBytesPerChunk) {
4890 /* Now folks, to calculate how many bytes to write back....
4891 * If we're overwriting and not writing to then end of file then
4892 * we need to write back as much as was there before.
4895 chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
4897 if(chunkStart > in->variant.fileVariant.fileSize)
4898 nBytesRead = 0; /* Past end of file */
4900 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
4902 if (nBytesRead > dev->nDataBytesPerChunk) {
4903 nBytesRead = dev->nDataBytesPerChunk;
4908 (start + n)) ? nBytesRead : (start + n);
4910 if(nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
4914 nToCopy = dev->nDataBytesPerChunk - start;
4915 nToWriteBack = dev->nDataBytesPerChunk;
4918 if (nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4919 /* An incomplete start or end chunk (or maybe both start and end chunk),
4920 * or we're using inband tags, so we want to use the cache buffers.
4922 if (dev->nShortOpCaches > 0) {
4923 yaffs_ChunkCache *cache;
4924 /* If we can't find the data in the cache, then load the cache */
4925 cache = yaffs_FindChunkCache(in, chunk);
4928 && yaffs_CheckSpaceForAllocation(in->
4930 cache = yaffs_GrabChunkCache(in->myDev);
4932 cache->chunkId = chunk;
4935 yaffs_ReadChunkDataFromObject(in, chunk,
4941 !yaffs_CheckSpaceForAllocation(in->myDev)){
4942 /* Drop the cache if it was a read cache item and
4943 * no space check has been made for it.
4949 yaffs_UseChunkCache(dev, cache, 1);
4953 memcpy(&cache->data[start], buffer,
4958 cache->nBytes = nToWriteBack;
4962 yaffs_WriteChunkDataToObject
4965 cache->data, cache->nBytes,
4971 chunkWritten = -1; /* fail the write */
4974 /* An incomplete start or end chunk (or maybe both start and end chunk)
4975 * Read into the local buffer then copy, then copy over and write back.
4979 yaffs_GetTempBuffer(dev, __LINE__);
4981 yaffs_ReadChunkDataFromObject(in, chunk,
4986 memcpy(&localBuffer[start], buffer, nToCopy);
4989 yaffs_WriteChunkDataToObject(in, chunk,
4994 yaffs_ReleaseTempBuffer(dev, localBuffer,
5000 /* A full chunk. Write directly from the supplied buffer. */
5005 yaffs_WriteChunkDataToObject(in, chunk, buffer,
5006 dev->nDataBytesPerChunk,
5009 /* Since we've overwritten the cached data, we better invalidate it. */
5010 yaffs_InvalidateChunkCache(in, chunk);
5013 if (chunkWritten >= 0) {
5022 /* Update file object */
5024 if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
5025 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
5034 /* ---------------------- File resizing stuff ------------------ */
5036 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
5039 yaffs_Device *dev = in->myDev;
5040 int oldFileSize = in->variant.fileVariant.fileSize;
5042 int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
5044 int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
5045 dev->nDataBytesPerChunk;
5049 /* Delete backwards so that we don't end up with holes if
5050 * power is lost part-way through the operation.
5052 for (i = lastDel; i >= startDel; i--) {
5053 /* NB this could be optimised somewhat,
5054 * eg. could retrieve the tags and write them without
5055 * using yaffs_DeleteChunk
5058 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5061 (dev->internalStartBlock * dev->nChunksPerBlock)
5063 ((dev->internalEndBlock +
5064 1) * dev->nChunksPerBlock)) {
5065 T(YAFFS_TRACE_ALWAYS,
5066 (TSTR("Found daft chunkId %d for %d" TENDSTR),
5070 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5077 int yaffs_ResizeFile(yaffs_Object * in, loff_t newSize)
5080 int oldFileSize = in->variant.fileVariant.fileSize;
5081 __u32 newSizeOfPartialChunk;
5084 yaffs_Device *dev = in->myDev;
5086 yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5088 yaffs_FlushFilesChunkCache(in);
5089 yaffs_InvalidateWholeChunkCache(in);
5091 yaffs_CheckGarbageCollection(dev);
5093 if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
5097 if (newSize == oldFileSize) {
5101 if (newSize < oldFileSize) {
5103 yaffs_PruneResizedChunks(in, newSize);
5105 if (newSizeOfPartialChunk != 0) {
5106 int lastChunk = 1 + newFullChunks;
5108 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5110 /* Got to read and rewrite the last chunk with its new size and zero pad */
5111 yaffs_ReadChunkDataFromObject(in, lastChunk,
5114 memset(localBuffer + newSizeOfPartialChunk, 0,
5115 dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5117 yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5118 newSizeOfPartialChunk, 1);
5120 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5123 in->variant.fileVariant.fileSize = newSize;
5125 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5127 /* newsSize > oldFileSize */
5128 in->variant.fileVariant.fileSize = newSize;
5133 /* Write a new object header.
5134 * show we've shrunk the file, if need be
5135 * Do this only if the file is not in the deleted directories.
5138 in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5139 in->parent->objectId != YAFFS_OBJECTID_DELETED) {
5140 yaffs_UpdateObjectHeader(in, NULL, 0,
5141 (newSize < oldFileSize) ? 1 : 0, 0);
5147 loff_t yaffs_GetFileSize(yaffs_Object * obj)
5149 obj = yaffs_GetEquivalentObject(obj);
5151 switch (obj->variantType) {
5152 case YAFFS_OBJECT_TYPE_FILE:
5153 return obj->variant.fileVariant.fileSize;
5154 case YAFFS_OBJECT_TYPE_SYMLINK:
5155 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5163 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
5167 yaffs_FlushFilesChunkCache(in);
5169 #ifdef CONFIG_YAFFS_WINCE
5170 yfsd_WinFileTimeNow(in->win_mtime);
5173 in->yst_mtime = Y_CURRENT_TIME;
5179 (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5180 0) ? YAFFS_OK : YAFFS_FAIL;
5189 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
5192 /* First off, invalidate the file's data in the cache, without flushing. */
5193 yaffs_InvalidateWholeChunkCache(in);
5195 if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5196 /* Move to the unlinked directory so we have a record that it was deleted. */
5197 yaffs_ChangeObjectName(in, in->myDev->deletedDir,_Y("deleted"), 0, 0);
5201 yaffs_RemoveObjectFromDirectory(in);
5202 yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5205 yaffs_FreeObject(in);
5210 /* yaffs_DeleteFile deletes the whole file data
5211 * and the inode associated with the file.
5212 * It does not delete the links associated with the file.
5214 static int yaffs_UnlinkFile(yaffs_Object * in)
5218 int immediateDeletion = 0;
5222 immediateDeletion = 1;
5225 if (in->inUse <= 0) {
5226 immediateDeletion = 1;
5230 if (immediateDeletion) {
5232 yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5233 _Y("deleted"), 0, 0);
5234 T(YAFFS_TRACE_TRACING,
5235 (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5238 in->myDev->nDeletedFiles++;
5239 if (1 || in->myDev->isYaffs2) {
5240 yaffs_ResizeFile(in, 0);
5242 yaffs_SoftDeleteFile(in);
5245 yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5246 _Y("unlinked"), 0, 0);
5253 int yaffs_DeleteFile(yaffs_Object * in)
5255 int retVal = YAFFS_OK;
5256 int deleted = in->deleted;
5258 yaffs_ResizeFile(in,0);
5260 if (in->nDataChunks > 0) {
5261 /* Use soft deletion if there is data in the file.
5262 * That won't be the case if it has been resized to zero.
5264 if (!in->unlinked) {
5265 retVal = yaffs_UnlinkFile(in);
5267 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5268 in->deleted = deleted = 1;
5269 in->myDev->nDeletedFiles++;
5270 yaffs_SoftDeleteFile(in);
5272 return deleted ? YAFFS_OK : YAFFS_FAIL;
5274 /* The file has no data chunks so we toss it immediately */
5275 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5276 in->variant.fileVariant.top = NULL;
5277 yaffs_DoGenericObjectDeletion(in);
5283 static int yaffs_DeleteDirectory(yaffs_Object * in)
5285 /* First check that the directory is empty. */
5286 if (ylist_empty(&in->variant.directoryVariant.children)) {
5287 return yaffs_DoGenericObjectDeletion(in);
5294 static int yaffs_DeleteSymLink(yaffs_Object * in)
5296 YFREE(in->variant.symLinkVariant.alias);
5298 return yaffs_DoGenericObjectDeletion(in);
5301 static int yaffs_DeleteHardLink(yaffs_Object * in)
5303 /* remove this hardlink from the list assocaited with the equivalent
5306 ylist_del_init(&in->hardLinks);
5307 return yaffs_DoGenericObjectDeletion(in);
5310 static void yaffs_DestroyObject(yaffs_Object * obj)
5312 switch (obj->variantType) {
5313 case YAFFS_OBJECT_TYPE_FILE:
5314 yaffs_DeleteFile(obj);
5316 case YAFFS_OBJECT_TYPE_DIRECTORY:
5317 yaffs_DeleteDirectory(obj);
5319 case YAFFS_OBJECT_TYPE_SYMLINK:
5320 yaffs_DeleteSymLink(obj);
5322 case YAFFS_OBJECT_TYPE_HARDLINK:
5323 yaffs_DeleteHardLink(obj);
5325 case YAFFS_OBJECT_TYPE_SPECIAL:
5326 yaffs_DoGenericObjectDeletion(obj);
5328 case YAFFS_OBJECT_TYPE_UNKNOWN:
5329 break; /* should not happen. */
5333 static int yaffs_UnlinkWorker(yaffs_Object * obj)
5336 if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5337 return yaffs_DeleteHardLink(obj);
5338 } else if (!ylist_empty(&obj->hardLinks)) {
5339 /* Curve ball: We're unlinking an object that has a hardlink.
5341 * This problem arises because we are not strictly following
5342 * The Linux link/inode model.
5344 * We can't really delete the object.
5345 * Instead, we do the following:
5346 * - Select a hardlink.
5347 * - Unhook it from the hard links
5348 * - Unhook it from its parent directory (so that the rename can work)
5349 * - Rename the object to the hardlink's name.
5350 * - Delete the hardlink
5355 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5357 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5359 ylist_del_init(&hl->hardLinks);
5360 ylist_del_init(&hl->siblings);
5362 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5364 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
5366 if (retVal == YAFFS_OK) {
5367 retVal = yaffs_DoGenericObjectDeletion(hl);
5372 switch (obj->variantType) {
5373 case YAFFS_OBJECT_TYPE_FILE:
5374 return yaffs_UnlinkFile(obj);
5376 case YAFFS_OBJECT_TYPE_DIRECTORY:
5377 return yaffs_DeleteDirectory(obj);
5379 case YAFFS_OBJECT_TYPE_SYMLINK:
5380 return yaffs_DeleteSymLink(obj);
5382 case YAFFS_OBJECT_TYPE_SPECIAL:
5383 return yaffs_DoGenericObjectDeletion(obj);
5385 case YAFFS_OBJECT_TYPE_HARDLINK:
5386 case YAFFS_OBJECT_TYPE_UNKNOWN:
5394 static int yaffs_UnlinkObject( yaffs_Object *obj)
5397 if (obj && obj->unlinkAllowed) {
5398 return yaffs_UnlinkWorker(obj);
5404 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
5408 obj = yaffs_FindObjectByName(dir, name);
5409 return yaffs_UnlinkObject(obj);
5412 /*----------------------- Initialisation Scanning ---------------------- */
5414 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
5415 int backwardScanning)
5419 if (!backwardScanning) {
5420 /* Handle YAFFS1 forward scanning case
5421 * For YAFFS1 we always do the deletion
5425 /* Handle YAFFS2 case (backward scanning)
5426 * If the shadowed object exists then ignore.
5428 if (yaffs_FindObjectByNumber(dev, objId)) {
5433 /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5434 * We put it in unlinked dir to be cleaned up after the scanning
5437 yaffs_FindOrCreateObjectByNumber(dev, objId,
5438 YAFFS_OBJECT_TYPE_FILE);
5441 yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5442 obj->variant.fileVariant.shrinkSize = 0;
5443 obj->valid = 1; /* So that we don't read any other info for this file */
5453 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5460 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5462 in = yaffs_FindObjectByNumber(dev,
5463 hl->variant.hardLinkVariant.
5464 equivalentObjectId);
5467 /* Add the hardlink pointers */
5468 hl->variant.hardLinkVariant.equivalentObject = in;
5469 ylist_add(&hl->hardLinks, &in->hardLinks);
5471 /* Todo Need to report/handle this better.
5472 * Got a problem... hardlink to a non-existant object
5474 hl->variant.hardLinkVariant.equivalentObject = NULL;
5475 YINIT_LIST_HEAD(&hl->hardLinks);
5487 static int ybicmp(const void *a, const void *b){
5488 register int aseq = ((yaffs_BlockIndex *)a)->seq;
5489 register int bseq = ((yaffs_BlockIndex *)b)->seq;
5490 register int ablock = ((yaffs_BlockIndex *)a)->block;
5491 register int bblock = ((yaffs_BlockIndex *)b)->block;
5493 return ablock - bblock;
5500 struct yaffs_ShadowFixerStruct {
5503 struct yaffs_ShadowFixerStruct *next;
5507 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5510 * Sort out state of unlinked and deleted objects after scanning.
5512 struct ylist_head *i;
5513 struct ylist_head *n;
5516 /* Soft delete all the unlinked files */
5517 ylist_for_each_safe(i, n,
5518 &dev->unlinkedDir->variant.directoryVariant.children) {
5520 l = ylist_entry(i, yaffs_Object, siblings);
5521 yaffs_DestroyObject(l);
5525 ylist_for_each_safe(i, n,
5526 &dev->deletedDir->variant.directoryVariant.children) {
5528 l = ylist_entry(i, yaffs_Object, siblings);
5529 yaffs_DestroyObject(l);
5535 static int yaffs_Scan(yaffs_Device * dev)
5537 yaffs_ExtendedTags tags;
5547 yaffs_BlockState state;
5548 yaffs_Object *hardList = NULL;
5549 yaffs_BlockInfo *bi;
5550 __u32 sequenceNumber;
5551 yaffs_ObjectHeader *oh;
5553 yaffs_Object *parent;
5555 int alloc_failed = 0;
5557 struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5565 (TSTR("yaffs_Scan starts intstartblk %d intendblk %d..." TENDSTR),
5566 dev->internalStartBlock, dev->internalEndBlock));
5568 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5570 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5572 /* Scan all the blocks to determine their state */
5573 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5574 bi = yaffs_GetBlockInfo(dev, blk);
5575 yaffs_ClearChunkBits(dev, blk);
5577 bi->softDeletions = 0;
5579 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5581 bi->blockState = state;
5582 bi->sequenceNumber = sequenceNumber;
5584 if(bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
5585 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
5587 T(YAFFS_TRACE_SCAN_DEBUG,
5588 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5589 state, sequenceNumber));
5591 if (state == YAFFS_BLOCK_STATE_DEAD) {
5592 T(YAFFS_TRACE_BAD_BLOCKS,
5593 (TSTR("block %d is bad" TENDSTR), blk));
5594 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5595 T(YAFFS_TRACE_SCAN_DEBUG,
5596 (TSTR("Block empty " TENDSTR)));
5597 dev->nErasedBlocks++;
5598 dev->nFreeChunks += dev->nChunksPerBlock;
5602 startIterator = dev->internalStartBlock;
5603 endIterator = dev->internalEndBlock;
5605 /* For each block.... */
5606 for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5613 blk = blockIterator;
5615 bi = yaffs_GetBlockInfo(dev, blk);
5616 state = bi->blockState;
5620 /* For each chunk in each block that needs scanning....*/
5621 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5622 state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5623 /* Read the tags and decide what to do */
5624 chunk = blk * dev->nChunksPerBlock + c;
5626 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5629 /* Let's have a good look at this chunk... */
5631 if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
5637 /*T((" %d %d deleted\n",blk,c)); */
5638 } else if (!tags.chunkUsed) {
5639 /* An unassigned chunk in the block
5640 * This means that either the block is empty or
5641 * this is the one being allocated from
5645 /* We're looking at the first chunk in the block so the block is unused */
5646 state = YAFFS_BLOCK_STATE_EMPTY;
5647 dev->nErasedBlocks++;
5649 /* this is the block being allocated from */
5652 (" Allocating from %d %d" TENDSTR),
5654 state = YAFFS_BLOCK_STATE_ALLOCATING;
5655 dev->allocationBlock = blk;
5656 dev->allocationPage = c;
5657 dev->allocationBlockFinder = blk;
5658 /* Set it to here to encourage the allocator to go forth from here. */
5662 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5663 } else if (tags.chunkId > 0) {
5664 /* chunkId > 0 so it is a data chunk... */
5665 unsigned int endpos;
5667 yaffs_SetChunkBit(dev, blk, c);
5670 in = yaffs_FindOrCreateObjectByNumber(dev,
5673 YAFFS_OBJECT_TYPE_FILE);
5674 /* PutChunkIntoFile checks for a clash (two data chunks with
5675 * the same chunkId).
5682 if(!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,1))
5687 (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5690 in->variantType == YAFFS_OBJECT_TYPE_FILE
5691 && in->variant.fileVariant.scannedFileSize <
5693 in->variant.fileVariant.
5694 scannedFileSize = endpos;
5695 if (!dev->useHeaderFileSize) {
5696 in->variant.fileVariant.
5698 in->variant.fileVariant.
5703 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId)); */
5705 /* chunkId == 0, so it is an ObjectHeader.
5706 * Thus, we read in the object header and make the object
5708 yaffs_SetChunkBit(dev, blk, c);
5711 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5715 oh = (yaffs_ObjectHeader *) chunkData;
5717 in = yaffs_FindObjectByNumber(dev,
5719 if (in && in->variantType != oh->type) {
5720 /* This should not happen, but somehow
5721 * Wev'e ended up with an objectId that has been reused but not yet
5722 * deleted, and worse still it has changed type. Delete the old object.
5725 yaffs_DestroyObject(in);
5730 in = yaffs_FindOrCreateObjectByNumber(dev,
5738 if (in && oh->shadowsObject > 0) {
5740 struct yaffs_ShadowFixerStruct *fixer;
5741 fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
5743 fixer-> next = shadowFixerList;
5744 shadowFixerList = fixer;
5745 fixer->objectId = tags.objectId;
5746 fixer->shadowedId = oh->shadowsObject;
5751 if (in && in->valid) {
5752 /* We have already filled this one. We have a duplicate and need to resolve it. */
5754 unsigned existingSerial = in->serial;
5755 unsigned newSerial = tags.serialNumber;
5757 if (((existingSerial + 1) & 3) == newSerial) {
5758 /* Use new one - destroy the exisiting one */
5759 yaffs_DeleteChunk(dev,
5764 /* Use existing - destroy this one. */
5765 yaffs_DeleteChunk(dev, chunk, 1,
5770 if (in && !in->valid &&
5771 (tags.objectId == YAFFS_OBJECTID_ROOT ||
5772 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5773 /* We only load some info, don't fiddle with directory structure */
5775 in->variantType = oh->type;
5777 in->yst_mode = oh->yst_mode;
5778 #ifdef CONFIG_YAFFS_WINCE
5779 in->win_atime[0] = oh->win_atime[0];
5780 in->win_ctime[0] = oh->win_ctime[0];
5781 in->win_mtime[0] = oh->win_mtime[0];
5782 in->win_atime[1] = oh->win_atime[1];
5783 in->win_ctime[1] = oh->win_ctime[1];
5784 in->win_mtime[1] = oh->win_mtime[1];
5786 in->yst_uid = oh->yst_uid;
5787 in->yst_gid = oh->yst_gid;
5788 in->yst_atime = oh->yst_atime;
5789 in->yst_mtime = oh->yst_mtime;
5790 in->yst_ctime = oh->yst_ctime;
5791 in->yst_rdev = oh->yst_rdev;
5793 in->hdrChunk = chunk;
5794 in->serial = tags.serialNumber;
5796 } else if (in && !in->valid) {
5797 /* we need to load this info */
5800 in->variantType = oh->type;
5802 in->yst_mode = oh->yst_mode;
5803 #ifdef CONFIG_YAFFS_WINCE
5804 in->win_atime[0] = oh->win_atime[0];
5805 in->win_ctime[0] = oh->win_ctime[0];
5806 in->win_mtime[0] = oh->win_mtime[0];
5807 in->win_atime[1] = oh->win_atime[1];
5808 in->win_ctime[1] = oh->win_ctime[1];
5809 in->win_mtime[1] = oh->win_mtime[1];
5811 in->yst_uid = oh->yst_uid;
5812 in->yst_gid = oh->yst_gid;
5813 in->yst_atime = oh->yst_atime;
5814 in->yst_mtime = oh->yst_mtime;
5815 in->yst_ctime = oh->yst_ctime;
5816 in->yst_rdev = oh->yst_rdev;
5818 in->hdrChunk = chunk;
5819 in->serial = tags.serialNumber;
5821 yaffs_SetObjectName(in, oh->name);
5824 /* directory stuff...
5829 yaffs_FindOrCreateObjectByNumber
5830 (dev, oh->parentObjectId,
5831 YAFFS_OBJECT_TYPE_DIRECTORY);
5834 if (parent && parent->variantType ==
5835 YAFFS_OBJECT_TYPE_UNKNOWN) {
5836 /* Set up as a directory */
5837 parent->variantType =
5838 YAFFS_OBJECT_TYPE_DIRECTORY;
5839 YINIT_LIST_HEAD(&parent->variant.
5842 } else if (!parent || parent->variantType !=
5843 YAFFS_OBJECT_TYPE_DIRECTORY)
5845 /* Hoosterman, another problem....
5846 * We're trying to use a non-directory as a directory
5849 T(YAFFS_TRACE_ERROR,
5851 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
5853 parent = dev->lostNFoundDir;
5856 yaffs_AddObjectToDirectory(parent, in);
5858 if (0 && (parent == dev->deletedDir ||
5859 parent == dev->unlinkedDir)) {
5860 in->deleted = 1; /* If it is unlinked at start up then it wants deleting */
5861 dev->nDeletedFiles++;
5863 /* Note re hardlinks.
5864 * Since we might scan a hardlink before its equivalent object is scanned
5865 * we put them all in a list.
5866 * After scanning is complete, we should have all the objects, so we run through this
5867 * list and fix up all the chains.
5870 switch (in->variantType) {
5871 case YAFFS_OBJECT_TYPE_UNKNOWN:
5872 /* Todo got a problem */
5874 case YAFFS_OBJECT_TYPE_FILE:
5875 if (dev->useHeaderFileSize)
5877 in->variant.fileVariant.
5882 case YAFFS_OBJECT_TYPE_HARDLINK:
5883 in->variant.hardLinkVariant.
5884 equivalentObjectId =
5885 oh->equivalentObjectId;
5886 in->hardLinks.next =
5887 (struct ylist_head *)
5891 case YAFFS_OBJECT_TYPE_DIRECTORY:
5894 case YAFFS_OBJECT_TYPE_SPECIAL:
5897 case YAFFS_OBJECT_TYPE_SYMLINK:
5898 in->variant.symLinkVariant.alias =
5899 yaffs_CloneString(oh->alias);
5900 if(!in->variant.symLinkVariant.alias)
5906 if (parent == dev->deletedDir) {
5907 yaffs_DestroyObject(in);
5908 bi->hasShrinkHeader = 1;
5915 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5916 /* If we got this far while scanning, then the block is fully allocated.*/
5917 state = YAFFS_BLOCK_STATE_FULL;
5920 bi->blockState = state;
5922 /* Now let's see if it was dirty */
5923 if (bi->pagesInUse == 0 &&
5924 !bi->hasShrinkHeader &&
5925 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5926 yaffs_BlockBecameDirty(dev, blk);
5932 /* Ok, we've done all the scanning.
5933 * Fix up the hard link chains.
5934 * We should now have scanned all the objects, now it's time to add these
5938 yaffs_HardlinkFixup(dev,hardList);
5940 /* Fix up any shadowed objects */
5942 struct yaffs_ShadowFixerStruct *fixer;
5945 while(shadowFixerList){
5946 fixer = shadowFixerList;
5947 shadowFixerList = fixer->next;
5948 /* Complete the rename transaction by deleting the shadowed object
5949 * then setting the object header to unshadowed.
5951 obj = yaffs_FindObjectByNumber(dev,fixer->shadowedId);
5953 yaffs_DestroyObject(obj);
5955 obj = yaffs_FindObjectByNumber(dev,fixer->objectId);
5957 yaffs_UpdateObjectHeader(obj,NULL,1,0,0);
5964 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5970 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5976 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5979 yaffs_ObjectHeader *oh;
5981 yaffs_ExtendedTags tags;
5983 int alloc_failed = 0;
5991 T(YAFFS_TRACE_SCAN,(TSTR("details for object %d %s loaded" TENDSTR),
5993 in->lazyLoaded ? "not yet" : "already"));
5996 if(in->lazyLoaded && in->hdrChunk > 0){
5998 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6000 result = yaffs_ReadChunkWithTagsFromNAND(dev,in->hdrChunk,chunkData,&tags);
6001 oh = (yaffs_ObjectHeader *) chunkData;
6003 in->yst_mode = oh->yst_mode;
6004 #ifdef CONFIG_YAFFS_WINCE
6005 in->win_atime[0] = oh->win_atime[0];
6006 in->win_ctime[0] = oh->win_ctime[0];
6007 in->win_mtime[0] = oh->win_mtime[0];
6008 in->win_atime[1] = oh->win_atime[1];
6009 in->win_ctime[1] = oh->win_ctime[1];
6010 in->win_mtime[1] = oh->win_mtime[1];
6012 in->yst_uid = oh->yst_uid;
6013 in->yst_gid = oh->yst_gid;
6014 in->yst_atime = oh->yst_atime;
6015 in->yst_mtime = oh->yst_mtime;
6016 in->yst_ctime = oh->yst_ctime;
6017 in->yst_rdev = oh->yst_rdev;
6020 yaffs_SetObjectName(in, oh->name);
6022 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
6023 in->variant.symLinkVariant.alias =
6024 yaffs_CloneString(oh->alias);
6025 if(!in->variant.symLinkVariant.alias)
6026 alloc_failed = 1; /* Not returned to caller */
6029 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
6033 static int yaffs_ScanBackwards(yaffs_Device * dev)
6035 yaffs_ExtendedTags tags;
6040 int nBlocksToScan = 0;
6046 yaffs_BlockState state;
6047 yaffs_Object *hardList = NULL;
6048 yaffs_BlockInfo *bi;
6049 __u32 sequenceNumber;
6050 yaffs_ObjectHeader *oh;
6052 yaffs_Object *parent;
6053 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6059 int foundChunksInBlock;
6060 int equivalentObjectId;
6061 int alloc_failed = 0;
6064 yaffs_BlockIndex *blockIndex = NULL;
6065 int altBlockIndex = 0;
6067 if (!dev->isYaffs2) {
6069 (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6075 ("yaffs_ScanBackwards starts intstartblk %d intendblk %d..."
6076 TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6079 dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6081 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6084 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6090 (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6094 dev->blocksInCheckpoint = 0;
6096 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6098 /* Scan all the blocks to determine their state */
6099 for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6100 bi = yaffs_GetBlockInfo(dev, blk);
6101 yaffs_ClearChunkBits(dev, blk);
6103 bi->softDeletions = 0;
6105 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6107 bi->blockState = state;
6108 bi->sequenceNumber = sequenceNumber;
6110 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6111 bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6112 if(bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6113 bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6115 T(YAFFS_TRACE_SCAN_DEBUG,
6116 (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6117 state, sequenceNumber));
6120 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
6121 dev->blocksInCheckpoint++;
6123 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6124 T(YAFFS_TRACE_BAD_BLOCKS,
6125 (TSTR("block %d is bad" TENDSTR), blk));
6126 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6127 T(YAFFS_TRACE_SCAN_DEBUG,
6128 (TSTR("Block empty " TENDSTR)));
6129 dev->nErasedBlocks++;
6130 dev->nFreeChunks += dev->nChunksPerBlock;
6131 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6133 /* Determine the highest sequence number */
6134 if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6135 sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6137 blockIndex[nBlocksToScan].seq = sequenceNumber;
6138 blockIndex[nBlocksToScan].block = blk;
6142 if (sequenceNumber >= dev->sequenceNumber) {
6143 dev->sequenceNumber = sequenceNumber;
6146 /* TODO: Nasty sequence number! */
6149 ("Block scanning block %d has bad sequence number %d"
6150 TENDSTR), blk, sequenceNumber));
6157 (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6163 /* Sort the blocks */
6164 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6166 /* Use qsort now. */
6167 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6171 /* Dungy old bubble sort... */
6173 yaffs_BlockIndex temp;
6177 for (i = 0; i < nBlocksToScan; i++)
6178 for (j = i + 1; j < nBlocksToScan; j++)
6179 if (blockIndex[i].seq > blockIndex[j].seq) {
6180 temp = blockIndex[j];
6181 blockIndex[j] = blockIndex[i];
6182 blockIndex[i] = temp;
6189 T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6191 /* Now scan the blocks looking at the data. */
6193 endIterator = nBlocksToScan - 1;
6194 T(YAFFS_TRACE_SCAN_DEBUG,
6195 (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6197 /* For each block.... backwards */
6198 for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6200 /* Cooperative multitasking! This loop can run for so
6201 long that watchdog timers expire. */
6204 /* get the block to scan in the correct order */
6205 blk = blockIndex[blockIterator].block;
6207 bi = yaffs_GetBlockInfo(dev, blk);
6210 state = bi->blockState;
6214 /* For each chunk in each block that needs scanning.... */
6215 foundChunksInBlock = 0;
6216 for (c = dev->nChunksPerBlock - 1;
6217 !alloc_failed && c >= 0 &&
6218 (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6219 state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6220 /* Scan backwards...
6221 * Read the tags and decide what to do
6224 chunk = blk * dev->nChunksPerBlock + c;
6226 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6229 /* Let's have a good look at this chunk... */
6231 if (!tags.chunkUsed) {
6232 /* An unassigned chunk in the block.
6233 * If there are used chunks after this one, then
6234 * it is a chunk that was skipped due to failing the erased
6235 * check. Just skip it so that it can be deleted.
6236 * But, more typically, We get here when this is an unallocated
6237 * chunk and his means that either the block is empty or
6238 * this is the one being allocated from
6241 if(foundChunksInBlock)
6243 /* This is a chunk that was skipped due to failing the erased check */
6245 } else if (c == 0) {
6246 /* We're looking at the first chunk in the block so the block is unused */
6247 state = YAFFS_BLOCK_STATE_EMPTY;
6248 dev->nErasedBlocks++;
6250 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6251 state == YAFFS_BLOCK_STATE_ALLOCATING) {
6252 if(dev->sequenceNumber == bi->sequenceNumber) {
6253 /* this is the block being allocated from */
6257 (" Allocating from %d %d"
6260 state = YAFFS_BLOCK_STATE_ALLOCATING;
6261 dev->allocationBlock = blk;
6262 dev->allocationPage = c;
6263 dev->allocationBlockFinder = blk;
6266 /* This is a partially written block that is not
6267 * the current allocation block. This block must have
6268 * had a write failure, so set up for retirement.
6271 /* bi->needsRetiring = 1; ??? TODO */
6272 bi->gcPrioritise = 1;
6274 T(YAFFS_TRACE_ALWAYS,
6275 (TSTR("Partially written block %d detected" TENDSTR),
6285 } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED){
6287 (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
6292 }else if (tags.chunkId > 0) {
6293 /* chunkId > 0 so it is a data chunk... */
6294 unsigned int endpos;
6296 (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6298 foundChunksInBlock = 1;
6301 yaffs_SetChunkBit(dev, blk, c);
6304 in = yaffs_FindOrCreateObjectByNumber(dev,
6307 YAFFS_OBJECT_TYPE_FILE);
6314 in->variantType == YAFFS_OBJECT_TYPE_FILE
6316 in->variant.fileVariant.shrinkSize) {
6317 /* This has not been invalidated by a resize */
6318 if(!yaffs_PutChunkIntoFile(in, tags.chunkId,
6323 /* File size is calculated by looking at the data chunks if we have not
6324 * seen an object header yet. Stop this practice once we find an object header.
6328 1) * dev->nDataBytesPerChunk +
6331 if (!in->valid && /* have not got an object header yet */
6332 in->variant.fileVariant.
6333 scannedFileSize < endpos) {
6334 in->variant.fileVariant.
6335 scannedFileSize = endpos;
6336 in->variant.fileVariant.
6338 in->variant.fileVariant.
6343 /* This chunk has been invalidated by a resize, so delete */
6344 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6348 /* chunkId == 0, so it is an ObjectHeader.
6349 * Thus, we read in the object header and make the object
6351 foundChunksInBlock = 1;
6353 yaffs_SetChunkBit(dev, blk, c);
6359 if (tags.extraHeaderInfoAvailable) {
6360 in = yaffs_FindOrCreateObjectByNumber
6361 (dev, tags.objectId,
6362 tags.extraObjectType);
6368 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
6371 tags.extraShadows ||
6373 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6374 tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
6377 /* If we don't have valid info then we need to read the chunk
6378 * TODO In future we can probably defer reading the chunk and
6379 * living with invalid data until needed.
6382 result = yaffs_ReadChunkWithTagsFromNAND(dev,
6387 oh = (yaffs_ObjectHeader *) chunkData;
6389 if(dev->inbandTags){
6390 /* Fix up the header if they got corrupted by inband tags */
6391 oh->shadowsObject = oh->inbandShadowsObject;
6392 oh->isShrink = oh->inbandIsShrink;
6396 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6404 /* TODO Hoosterman we have a problem! */
6405 T(YAFFS_TRACE_ERROR,
6407 ("yaffs tragedy: Could not make object for object %d at chunk %d during scan"
6408 TENDSTR), tags.objectId, chunk));
6413 /* We have already filled this one.
6414 * We have a duplicate that will be discarded, but
6415 * we first have to suck out resize info if it is a file.
6418 if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6420 oh-> type == YAFFS_OBJECT_TYPE_FILE)||
6421 (tags.extraHeaderInfoAvailable &&
6422 tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
6425 (oh) ? oh->fileSize : tags.
6427 __u32 parentObjectId =
6429 parentObjectId : tags.
6430 extraParentObjectId;
6434 (oh) ? oh->isShrink : tags.
6435 extraIsShrinkHeader;
6437 /* If it is deleted (unlinked at start also means deleted)
6438 * we treat the file size as being zeroed at this point.
6440 if (parentObjectId ==
6441 YAFFS_OBJECTID_DELETED
6442 || parentObjectId ==
6443 YAFFS_OBJECTID_UNLINKED) {
6449 in->variant.fileVariant.
6450 shrinkSize > thisSize) {
6451 in->variant.fileVariant.
6457 bi->hasShrinkHeader = 1;
6461 /* Use existing - destroy this one. */
6462 yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6466 if (!in->valid && in->variantType !=
6467 (oh ? oh->type : tags.extraObjectType))
6468 T(YAFFS_TRACE_ERROR, (
6469 TSTR("yaffs tragedy: Bad object type, "
6470 TCONT("%d != %d, for object %d at chunk ")
6471 TCONT("%d during scan")
6473 oh->type : tags.extraObjectType,
6474 in->variantType, tags.objectId,
6478 (tags.objectId == YAFFS_OBJECTID_ROOT ||
6480 YAFFS_OBJECTID_LOSTNFOUND)) {
6481 /* We only load some info, don't fiddle with directory structure */
6485 in->variantType = oh->type;
6487 in->yst_mode = oh->yst_mode;
6488 #ifdef CONFIG_YAFFS_WINCE
6489 in->win_atime[0] = oh->win_atime[0];
6490 in->win_ctime[0] = oh->win_ctime[0];
6491 in->win_mtime[0] = oh->win_mtime[0];
6492 in->win_atime[1] = oh->win_atime[1];
6493 in->win_ctime[1] = oh->win_ctime[1];
6494 in->win_mtime[1] = oh->win_mtime[1];
6496 in->yst_uid = oh->yst_uid;
6497 in->yst_gid = oh->yst_gid;
6498 in->yst_atime = oh->yst_atime;
6499 in->yst_mtime = oh->yst_mtime;
6500 in->yst_ctime = oh->yst_ctime;
6501 in->yst_rdev = oh->yst_rdev;
6505 in->variantType = tags.extraObjectType;
6509 in->hdrChunk = chunk;
6511 } else if (!in->valid) {
6512 /* we need to load this info */
6515 in->hdrChunk = chunk;
6518 in->variantType = oh->type;
6520 in->yst_mode = oh->yst_mode;
6521 #ifdef CONFIG_YAFFS_WINCE
6522 in->win_atime[0] = oh->win_atime[0];
6523 in->win_ctime[0] = oh->win_ctime[0];
6524 in->win_mtime[0] = oh->win_mtime[0];
6525 in->win_atime[1] = oh->win_atime[1];
6526 in->win_ctime[1] = oh->win_ctime[1];
6527 in->win_mtime[1] = oh->win_mtime[1];
6529 in->yst_uid = oh->yst_uid;
6530 in->yst_gid = oh->yst_gid;
6531 in->yst_atime = oh->yst_atime;
6532 in->yst_mtime = oh->yst_mtime;
6533 in->yst_ctime = oh->yst_ctime;
6534 in->yst_rdev = oh->yst_rdev;
6537 if (oh->shadowsObject > 0)
6538 yaffs_HandleShadowedObject(dev,
6544 yaffs_SetObjectName(in, oh->name);
6546 yaffs_FindOrCreateObjectByNumber
6547 (dev, oh->parentObjectId,
6548 YAFFS_OBJECT_TYPE_DIRECTORY);
6550 fileSize = oh->fileSize;
6551 isShrink = oh->isShrink;
6552 equivalentObjectId = oh->equivalentObjectId;
6556 in->variantType = tags.extraObjectType;
6558 yaffs_FindOrCreateObjectByNumber
6559 (dev, tags.extraParentObjectId,
6560 YAFFS_OBJECT_TYPE_DIRECTORY);
6561 fileSize = tags.extraFileLength;
6562 isShrink = tags.extraIsShrinkHeader;
6563 equivalentObjectId = tags.extraEquivalentObjectId;
6572 /* directory stuff...
6576 if (parent && parent->variantType ==
6577 YAFFS_OBJECT_TYPE_UNKNOWN) {
6578 /* Set up as a directory */
6579 parent->variantType =
6580 YAFFS_OBJECT_TYPE_DIRECTORY;
6581 YINIT_LIST_HEAD(&parent->variant.
6584 } else if (!parent || parent->variantType !=
6585 YAFFS_OBJECT_TYPE_DIRECTORY)
6587 /* Hoosterman, another problem....
6588 * We're trying to use a non-directory as a directory
6591 T(YAFFS_TRACE_ERROR,
6593 ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6595 parent = dev->lostNFoundDir;
6598 yaffs_AddObjectToDirectory(parent, in);
6600 itsUnlinked = (parent == dev->deletedDir) ||
6601 (parent == dev->unlinkedDir);
6604 /* Mark the block as having a shrinkHeader */
6605 bi->hasShrinkHeader = 1;
6608 /* Note re hardlinks.
6609 * Since we might scan a hardlink before its equivalent object is scanned
6610 * we put them all in a list.
6611 * After scanning is complete, we should have all the objects, so we run
6612 * through this list and fix up all the chains.
6615 switch (in->variantType) {
6616 case YAFFS_OBJECT_TYPE_UNKNOWN:
6617 /* Todo got a problem */
6619 case YAFFS_OBJECT_TYPE_FILE:
6621 if (in->variant.fileVariant.
6622 scannedFileSize < fileSize) {
6623 /* This covers the case where the file size is greater
6624 * than where the data is
6625 * This will happen if the file is resized to be larger
6626 * than its current data extents.
6628 in->variant.fileVariant.fileSize = fileSize;
6629 in->variant.fileVariant.scannedFileSize =
6630 in->variant.fileVariant.fileSize;
6634 in->variant.fileVariant.shrinkSize > fileSize) {
6635 in->variant.fileVariant.shrinkSize = fileSize;
6639 case YAFFS_OBJECT_TYPE_HARDLINK:
6641 in->variant.hardLinkVariant.equivalentObjectId =
6643 in->hardLinks.next =
6644 (struct ylist_head *) hardList;
6648 case YAFFS_OBJECT_TYPE_DIRECTORY:
6651 case YAFFS_OBJECT_TYPE_SPECIAL:
6654 case YAFFS_OBJECT_TYPE_SYMLINK:
6656 in->variant.symLinkVariant.alias =
6657 yaffs_CloneString(oh->
6659 if(!in->variant.symLinkVariant.alias)
6669 } /* End of scanning for each chunk */
6671 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6672 /* If we got this far while scanning, then the block is fully allocated. */
6673 state = YAFFS_BLOCK_STATE_FULL;
6676 bi->blockState = state;
6678 /* Now let's see if it was dirty */
6679 if (bi->pagesInUse == 0 &&
6680 !bi->hasShrinkHeader &&
6681 bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6682 yaffs_BlockBecameDirty(dev, blk);
6688 YFREE_ALT(blockIndex);
6692 /* Ok, we've done all the scanning.
6693 * Fix up the hard link chains.
6694 * We should now have scanned all the objects, now it's time to add these
6697 yaffs_HardlinkFixup(dev,hardList);
6700 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6706 T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6711 /*------------------------------ Directory Functions ----------------------------- */
6713 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
6715 struct ylist_head *lh;
6716 yaffs_Object *listObj;
6721 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
6725 if(yaffs_SkipVerification(obj->myDev))
6729 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
6733 if(obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
6734 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
6738 /* Iterate through the objects in each hash entry */
6740 ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
6742 listObj = ylist_entry(lh, yaffs_Object, siblings);
6743 yaffs_VerifyObject(listObj);
6750 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR),count));
6756 static void yaffs_VerifyDirectory(yaffs_Object *directory)
6759 struct ylist_head *lh;
6760 yaffs_Object *listObj;
6765 if(yaffs_SkipFullVerification(directory->myDev))
6769 if(directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
6770 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR),directory->variantType));
6774 /* Iterate through the objects in each hash entry */
6776 ylist_for_each(lh, &directory->variant.directoryVariant.children) {
6778 listObj = ylist_entry(lh, yaffs_Object, siblings);
6779 if(listObj->parent != directory){
6780 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR),listObj->parent));
6783 yaffs_VerifyObjectInDirectory(listObj);
6790 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
6792 yaffs_Device *dev = obj->myDev;
6793 yaffs_Object *parent;
6795 yaffs_VerifyObjectInDirectory(obj);
6796 parent = obj->parent;
6798 yaffs_VerifyDirectory(parent);
6800 if(dev && dev->removeObjectCallback)
6801 dev->removeObjectCallback(obj);
6804 ylist_del_init(&obj->siblings);
6807 yaffs_VerifyDirectory(parent);
6812 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
6817 T(YAFFS_TRACE_ALWAYS,
6819 ("tragedy: Trying to add an object to a null pointer directory"
6823 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6824 T(YAFFS_TRACE_ALWAYS,
6826 ("tragedy: Trying to add an object to a non-directory"
6831 if (obj->siblings.prev == NULL) {
6832 /* Not initialised */
6835 } else if (ylist_empty(&obj->siblings)) {
6840 yaffs_VerifyDirectory(directory);
6842 yaffs_RemoveObjectFromDirectory(obj);
6846 ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
6847 obj->parent = directory;
6849 if (directory == obj->myDev->unlinkedDir
6850 || directory == obj->myDev->deletedDir) {
6852 obj->myDev->nUnlinkedFiles++;
6853 obj->renameAllowed = 0;
6856 yaffs_VerifyDirectory(directory);
6857 yaffs_VerifyObjectInDirectory(obj);
6862 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
6867 struct ylist_head *i;
6868 YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
6877 T(YAFFS_TRACE_ALWAYS,
6879 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6883 if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6884 T(YAFFS_TRACE_ALWAYS,
6886 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6890 sum = yaffs_CalcNameSum(name);
6892 ylist_for_each(i, &directory->variant.directoryVariant.children) {
6894 l = ylist_entry(i, yaffs_Object, siblings);
6896 if(l->parent != directory)
6899 yaffs_CheckObjectDetailsLoaded(l);
6901 /* Special case for lost-n-found */
6902 if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6903 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
6906 } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0){
6907 /* LostnFound chunk called Objxxx
6910 yaffs_GetObjectName(l, buffer,
6911 YAFFS_MAX_NAME_LENGTH);
6912 if (yaffs_strncmp(name, buffer,YAFFS_MAX_NAME_LENGTH) == 0) {
6925 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
6926 int (*fn) (yaffs_Object *))
6928 struct ylist_head *i;
6932 T(YAFFS_TRACE_ALWAYS,
6934 ("tragedy: yaffs_FindObjectByName: null pointer directory"
6938 if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6939 T(YAFFS_TRACE_ALWAYS,
6941 ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6945 ylist_for_each(i, &theDir->variant.directoryVariant.children) {
6947 l = ylist_entry(i, yaffs_Object, siblings);
6959 /* GetEquivalentObject dereferences any hard links to get to the
6963 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
6965 if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
6966 /* We want the object id of the equivalent object, not this one */
6967 obj = obj->variant.hardLinkVariant.equivalentObject;
6968 yaffs_CheckObjectDetailsLoaded(obj);
6974 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
6976 memset(name, 0, buffSize * sizeof(YCHAR));
6978 yaffs_CheckObjectDetailsLoaded(obj);
6980 if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6981 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
6982 } else if (obj->hdrChunk <= 0) {
6984 YCHAR numString[20];
6985 YCHAR *x = &numString[19];
6986 unsigned v = obj->objectId;
6990 *x = '0' + (v % 10);
6993 /* make up a name */
6994 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
6995 yaffs_strcat(locName,x);
6996 yaffs_strncpy(name, locName, buffSize - 1);
6999 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
7000 else if (obj->shortName[0]) {
7001 yaffs_strcpy(name, obj->shortName);
7006 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
7008 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
7010 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
7012 if (obj->hdrChunk > 0) {
7013 result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
7014 obj->hdrChunk, buffer,
7017 yaffs_strncpy(name, oh->name, buffSize - 1);
7019 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
7022 return yaffs_strlen(name);
7025 int yaffs_GetObjectFileLength(yaffs_Object * obj)
7028 /* Dereference any hard linking */
7029 obj = yaffs_GetEquivalentObject(obj);
7031 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
7032 return obj->variant.fileVariant.fileSize;
7034 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
7035 return yaffs_strlen(obj->variant.symLinkVariant.alias);
7037 /* Only a directory should drop through to here */
7038 return obj->myDev->nDataBytesPerChunk;
7042 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
7045 struct ylist_head *i;
7047 if (!obj->unlinked) {
7048 count++; /* the object itself */
7050 ylist_for_each(i, &obj->hardLinks) {
7051 count++; /* add the hard links; */
7057 int yaffs_GetObjectInode(yaffs_Object * obj)
7059 obj = yaffs_GetEquivalentObject(obj);
7061 return obj->objectId;
7064 unsigned yaffs_GetObjectType(yaffs_Object * obj)
7066 obj = yaffs_GetEquivalentObject(obj);
7068 switch (obj->variantType) {
7069 case YAFFS_OBJECT_TYPE_FILE:
7072 case YAFFS_OBJECT_TYPE_DIRECTORY:
7075 case YAFFS_OBJECT_TYPE_SYMLINK:
7078 case YAFFS_OBJECT_TYPE_HARDLINK:
7081 case YAFFS_OBJECT_TYPE_SPECIAL:
7082 if (S_ISFIFO(obj->yst_mode))
7084 if (S_ISCHR(obj->yst_mode))
7086 if (S_ISBLK(obj->yst_mode))
7088 if (S_ISSOCK(obj->yst_mode))
7096 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
7098 obj = yaffs_GetEquivalentObject(obj);
7099 if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
7100 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7102 return yaffs_CloneString(_Y(""));
7106 #ifndef CONFIG_YAFFS_WINCE
7108 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
7110 unsigned int valid = attr->ia_valid;
7112 if (valid & ATTR_MODE)
7113 obj->yst_mode = attr->ia_mode;
7114 if (valid & ATTR_UID)
7115 obj->yst_uid = attr->ia_uid;
7116 if (valid & ATTR_GID)
7117 obj->yst_gid = attr->ia_gid;
7119 if (valid & ATTR_ATIME)
7120 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7121 if (valid & ATTR_CTIME)
7122 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7123 if (valid & ATTR_MTIME)
7124 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7126 if (valid & ATTR_SIZE)
7127 yaffs_ResizeFile(obj, attr->ia_size);
7129 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7134 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
7136 unsigned int valid = 0;
7138 attr->ia_mode = obj->yst_mode;
7140 attr->ia_uid = obj->yst_uid;
7142 attr->ia_gid = obj->yst_gid;
7145 Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7146 valid |= ATTR_ATIME;
7147 Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7148 valid |= ATTR_CTIME;
7149 Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7150 valid |= ATTR_MTIME;
7152 attr->ia_size = yaffs_GetFileSize(obj);
7155 attr->ia_valid = valid;
7164 int yaffs_DumpObject(yaffs_Object * obj)
7168 yaffs_GetObjectName(obj, name, 256);
7170 T(YAFFS_TRACE_ALWAYS,
7172 ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7173 " chunk %d type %d size %d\n"
7174 TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7175 obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7176 yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7182 /*---------------------------- Initialisation code -------------------------------------- */
7184 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
7187 /* Common functions, gotta have */
7188 if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
7191 #ifdef CONFIG_YAFFS_YAFFS2
7193 /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7194 if (dev->writeChunkWithTagsToNAND &&
7195 dev->readChunkWithTagsFromNAND &&
7196 !dev->writeChunkToNAND &&
7197 !dev->readChunkFromNAND &&
7198 dev->markNANDBlockBad && dev->queryNANDBlock)
7202 /* Can use the "spare" style interface for yaffs1 */
7203 if (!dev->isYaffs2 &&
7204 !dev->writeChunkWithTagsToNAND &&
7205 !dev->readChunkWithTagsFromNAND &&
7206 dev->writeChunkToNAND &&
7207 dev->readChunkFromNAND &&
7208 !dev->markNANDBlockBad && !dev->queryNANDBlock)
7215 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7217 /* Initialise the unlinked, deleted, root and lost and found directories */
7219 dev->lostNFoundDir = dev->rootDir = NULL;
7220 dev->unlinkedDir = dev->deletedDir = NULL;
7223 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7226 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7229 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7230 YAFFS_ROOT_MODE | S_IFDIR);
7231 dev->lostNFoundDir =
7232 yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7233 YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7235 if(dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir){
7236 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7243 int yaffs_GutsInitialise(yaffs_Device * dev)
7245 int init_failed = 0;
7249 T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7251 /* Check stuff that must be set */
7254 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7258 dev->internalStartBlock = dev->startBlock;
7259 dev->internalEndBlock = dev->endBlock;
7260 dev->blockOffset = 0;
7261 dev->chunkOffset = 0;
7262 dev->nFreeChunks = 0;
7266 if (dev->startBlock == 0) {
7267 dev->internalStartBlock = dev->startBlock + 1;
7268 dev->internalEndBlock = dev->endBlock + 1;
7269 dev->blockOffset = 1;
7270 dev->chunkOffset = dev->nChunksPerBlock;
7273 /* Check geometry parameters. */
7275 if ((!dev->inbandTags && dev->isYaffs2 && dev->totalBytesPerChunk < 1024) ||
7276 (!dev->isYaffs2 && dev->totalBytesPerChunk < 512) ||
7277 (dev->inbandTags && !dev->isYaffs2 ) ||
7278 dev->nChunksPerBlock < 2 ||
7279 dev->nReservedBlocks < 2 ||
7280 dev->internalStartBlock <= 0 ||
7281 dev->internalEndBlock <= 0 ||
7282 dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2) // otherwise it is too small
7284 T(YAFFS_TRACE_ALWAYS,
7286 ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7287 TENDSTR), dev->totalBytesPerChunk, dev->isYaffs2 ? "2" : "", dev->inbandTags));
7291 if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7292 T(YAFFS_TRACE_ALWAYS,
7293 (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7297 /* Sort out space for inband tags, if required */
7299 dev->nDataBytesPerChunk = dev->totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7301 dev->nDataBytesPerChunk = dev->totalBytesPerChunk;
7303 /* Got the right mix of functions? */
7304 if (!yaffs_CheckDevFunctions(dev)) {
7305 /* Function missing */
7306 T(YAFFS_TRACE_ALWAYS,
7308 ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7313 /* This is really a compilation check. */
7314 if (!yaffs_CheckStructures()) {
7315 T(YAFFS_TRACE_ALWAYS,
7316 (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7320 if (dev->isMounted) {
7321 T(YAFFS_TRACE_ALWAYS,
7322 (TSTR("yaffs: device already mounted\n" TENDSTR)));
7326 /* Finished with most checks. One or two more checks happen later on too. */
7330 /* OK now calculate a few things for the device */
7333 * Calculate all the chunk size manipulation numbers:
7335 x = dev->nDataBytesPerChunk;
7336 /* We always use dev->chunkShift and dev->chunkDiv */
7337 dev->chunkShift = Shifts(x);
7338 x >>= dev->chunkShift;
7340 /* We only use chunk mask if chunkDiv is 1 */
7341 dev->chunkMask = (1<<dev->chunkShift) - 1;
7344 * Calculate chunkGroupBits.
7345 * We need to find the next power of 2 > than internalEndBlock
7348 x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7352 /* Set up tnode width if wide tnodes are enabled. */
7353 if(!dev->wideTnodesDisabled){
7354 /* bits must be even so that we end up with 32-bit words */
7358 dev->tnodeWidth = 16;
7360 dev->tnodeWidth = bits;
7363 dev->tnodeWidth = 16;
7365 dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7367 /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7368 * so if the bitwidth of the
7369 * chunk range we're using is greater than 16 we need
7370 * to figure out chunk shift and chunkGroupSize
7373 if (bits <= dev->tnodeWidth)
7374 dev->chunkGroupBits = 0;
7376 dev->chunkGroupBits = bits - dev->tnodeWidth;
7379 dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7381 if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7382 /* We have a problem because the soft delete won't work if
7383 * the chunk group size > chunks per block.
7384 * This can be remedied by using larger "virtual blocks".
7386 T(YAFFS_TRACE_ALWAYS,
7387 (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7392 /* OK, we've finished verifying the device, lets continue with initialisation */
7394 /* More device initialisation */
7395 dev->garbageCollections = 0;
7396 dev->passiveGarbageCollections = 0;
7397 dev->currentDirtyChecker = 0;
7398 dev->bufferedBlock = -1;
7399 dev->doingBufferedBlockRewrite = 0;
7400 dev->nDeletedFiles = 0;
7401 dev->nBackgroundDeletions = 0;
7402 dev->nUnlinkedFiles = 0;
7404 dev->eccUnfixed = 0;
7405 dev->tagsEccFixed = 0;
7406 dev->tagsEccUnfixed = 0;
7407 dev->nErasureFailures = 0;
7408 dev->nErasedBlocks = 0;
7410 dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7412 /* Initialise temporary buffers and caches. */
7413 if(!yaffs_InitialiseTempBuffers(dev))
7416 dev->srCache = NULL;
7417 dev->gcCleanupList = NULL;
7421 dev->nShortOpCaches > 0) {
7424 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7426 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
7427 dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7430 dev->srCache = YMALLOC(srCacheBytes);
7432 buf = (__u8 *) dev->srCache;
7435 memset(dev->srCache,0,srCacheBytes);
7437 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7438 dev->srCache[i].object = NULL;
7439 dev->srCache[i].lastUse = 0;
7440 dev->srCache[i].dirty = 0;
7441 dev->srCache[i].data = buf = YMALLOC_DMA(dev->totalBytesPerChunk);
7452 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7453 if(!dev->gcCleanupList)
7457 if (dev->isYaffs2) {
7458 dev->useHeaderFileSize = 1;
7460 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7463 yaffs_InitialiseTnodes(dev);
7464 yaffs_InitialiseObjects(dev);
7466 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7471 /* Now scan the flash. */
7472 if (dev->isYaffs2) {
7473 if(yaffs_CheckpointRestore(dev)) {
7474 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7475 T(YAFFS_TRACE_ALWAYS,
7476 (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7479 /* Clean up the mess caused by an aborted checkpoint load
7480 * and scan backwards.
7482 yaffs_DeinitialiseBlocks(dev);
7483 yaffs_DeinitialiseTnodes(dev);
7484 yaffs_DeinitialiseObjects(dev);
7487 dev->nErasedBlocks = 0;
7488 dev->nFreeChunks = 0;
7489 dev->allocationBlock = -1;
7490 dev->allocationPage = -1;
7491 dev->nDeletedFiles = 0;
7492 dev->nUnlinkedFiles = 0;
7493 dev->nBackgroundDeletions = 0;
7494 dev->oldestDirtySequence = 0;
7496 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7499 yaffs_InitialiseTnodes(dev);
7500 yaffs_InitialiseObjects(dev);
7502 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7505 if(!init_failed && !yaffs_ScanBackwards(dev))
7509 if(!yaffs_Scan(dev))
7512 yaffs_StripDeletedObjects(dev);
7516 /* Clean up the mess */
7517 T(YAFFS_TRACE_TRACING,
7518 (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7520 yaffs_Deinitialise(dev);
7524 /* Zero out stats */
7525 dev->nPageReads = 0;
7526 dev->nPageWrites = 0;
7527 dev->nBlockErasures = 0;
7529 dev->nRetriedWrites = 0;
7531 dev->nRetiredBlocks = 0;
7533 yaffs_VerifyFreeChunks(dev);
7534 yaffs_VerifyBlocks(dev);
7537 T(YAFFS_TRACE_TRACING,
7538 (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7543 void yaffs_Deinitialise(yaffs_Device * dev)
7545 if (dev->isMounted) {
7548 yaffs_DeinitialiseBlocks(dev);
7549 yaffs_DeinitialiseTnodes(dev);
7550 yaffs_DeinitialiseObjects(dev);
7551 if (dev->nShortOpCaches > 0 &&
7554 for (i = 0; i < dev->nShortOpCaches; i++) {
7555 if(dev->srCache[i].data)
7556 YFREE(dev->srCache[i].data);
7557 dev->srCache[i].data = NULL;
7560 YFREE(dev->srCache);
7561 dev->srCache = NULL;
7564 YFREE(dev->gcCleanupList);
7566 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
7567 YFREE(dev->tempBuffer[i].buffer);
7573 if(dev->deinitialiseNAND)
7574 dev->deinitialiseNAND(dev);
7579 static int yaffs_CountFreeChunks(yaffs_Device * dev)
7584 yaffs_BlockInfo *blk;
7586 for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7588 blk = yaffs_GetBlockInfo(dev, b);
7590 switch (blk->blockState) {
7591 case YAFFS_BLOCK_STATE_EMPTY:
7592 case YAFFS_BLOCK_STATE_ALLOCATING:
7593 case YAFFS_BLOCK_STATE_COLLECTING:
7594 case YAFFS_BLOCK_STATE_FULL:
7596 (dev->nChunksPerBlock - blk->pagesInUse +
7597 blk->softDeletions);
7608 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
7610 /* This is what we report to the outside world */
7613 int nDirtyCacheChunks;
7614 int blocksForCheckpoint;
7617 nFree = dev->nFreeChunks;
7619 nFree = yaffs_CountFreeChunks(dev);
7622 nFree += dev->nDeletedFiles;
7624 /* Now count the number of dirty chunks in the cache and subtract those */
7628 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7629 if (dev->srCache[i].dirty)
7630 nDirtyCacheChunks++;
7634 nFree -= nDirtyCacheChunks;
7636 nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7638 /* Now we figure out how much to reserve for the checkpoint and report that... */
7639 blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7640 if(blocksForCheckpoint < 0)
7641 blocksForCheckpoint = 0;
7643 nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7652 static int yaffs_freeVerificationFailures;
7654 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
7659 if(yaffs_SkipVerification(dev))
7662 counted = yaffs_CountFreeChunks(dev);
7664 difference = dev->nFreeChunks - counted;
7667 T(YAFFS_TRACE_ALWAYS,
7668 (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7669 dev->nFreeChunks, counted, difference));
7670 yaffs_freeVerificationFailures++;
7674 /*---------------------------------------- YAFFS test code ----------------------*/
7676 #define yaffs_CheckStruct(structure,syze, name) \
7678 if(sizeof(structure) != syze) \
7680 T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
7681 name,syze,sizeof(structure))); \
7682 return YAFFS_FAIL; \
7686 static int yaffs_CheckStructures(void)
7688 /* yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
7689 /* yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
7690 /* yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
7691 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7692 yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode");
7694 #ifndef CONFIG_YAFFS_WINCE
7695 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");