Handle unfixed ecc errors better when scanning
[yaffs2.git] / yaffs_guts.c
1 /*
2  * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
3  *
4  * Copyright (C) 2002-2007 Aleph One Ltd.
5  *   for Toby Churchill Ltd and Brightstar Engineering
6  *
7  * Created by Charles Manning <charles@aleph1.co.uk>
8  *
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.
12  */
13
14
15 const char *yaffs_guts_c_version =
16     "$Id: yaffs_guts.c,v 1.72 2009-01-16 00:44:45 charles Exp $";
17
18 #include "yportenv.h"
19
20 #include "yaffsinterface.h"
21 #include "yaffs_guts.h"
22 #include "yaffs_tagsvalidity.h"
23 #include "yaffs_getblockinfo.h"
24
25 #include "yaffs_tagscompat.h"
26 #ifndef  CONFIG_YAFFS_USE_OWN_SORT
27 #include "yaffs_qsort.h"
28 #endif
29 #include "yaffs_nand.h"
30
31 #include "yaffs_checkptrw.h"
32
33 #include "yaffs_nand.h"
34 #include "yaffs_packedtags2.h"
35
36
37 #ifdef CONFIG_YAFFS_WINCE
38 void yfsd_LockYAFFS(BOOL fsLockOnly);
39 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
40 #endif
41
42 #define YAFFS_PASSIVE_GC_CHUNKS 2
43
44 #include "yaffs_ecc.h"
45
46
47 /* Robustification (if it ever comes about...) */
48 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
49 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk);
50 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
51                                      const __u8 * data,
52                                      const yaffs_ExtendedTags * tags);
53 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
54                                     const yaffs_ExtendedTags * tags);
55
56 /* Other local prototypes */
57 static int yaffs_UnlinkObject( yaffs_Object *obj);
58 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
59
60 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
61
62 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
63                                              const __u8 * buffer,
64                                              yaffs_ExtendedTags * tags,
65                                              int useReserve);
66 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
67                                   int chunkInNAND, int inScan);
68
69 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
70                                            yaffs_ObjectType type);
71 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
72                                        yaffs_Object * obj);
73 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
74                                     int force, int isShrink, int shadows);
75 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
76 static int yaffs_CheckStructures(void);
77 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
78                               int chunkOffset, int *limit);
79 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
80
81 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
82
83
84 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
85                                   int chunkInNAND);
86
87 static int yaffs_UnlinkWorker(yaffs_Object * obj);
88 static void yaffs_DestroyObject(yaffs_Object * obj);
89
90 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
91                            int chunkInObject);
92
93 loff_t yaffs_GetFileSize(yaffs_Object * obj);
94
95 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr);
96
97 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
98
99 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
100
101 static void yaffs_VerifyDirectory(yaffs_Object *directory);
102 #ifdef YAFFS_PARANOID
103 static int yaffs_CheckFileSanity(yaffs_Object * in);
104 #else
105 #define yaffs_CheckFileSanity(in)
106 #endif
107
108 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
109 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
110
111 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
112
113 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
114                                  yaffs_ExtendedTags * tags);
115
116 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos);
117 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
118                                           yaffs_FileStructure * fStruct,
119                                           __u32 chunkId);
120
121
122 /* Function to calculate chunk and offset */
123
124 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut, __u32 *offsetOut)
125 {
126         int chunk;
127         __u32 offset;
128         
129         chunk  = (__u32)(addr >> dev->chunkShift);
130                 
131         if(dev->chunkDiv == 1)
132         {
133                 /* easy power of 2 case */
134                 offset = (__u32)(addr & dev->chunkMask);
135         }
136         else
137         {
138                 /* Non power-of-2 case */
139                 
140                 loff_t chunkBase;
141                 
142                 chunk /= dev->chunkDiv;
143                 
144                 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
145                 offset = (__u32)(addr - chunkBase);
146         }
147
148         *chunkOut = chunk;
149         *offsetOut = offset;
150 }
151
152 /* Function to return the number of shifts for a power of 2 greater than or equal 
153  * to the given number
154  * Note we don't try to cater for all possible numbers and this does not have to
155  * be hellishly efficient.
156  */
157  
158 static __u32 ShiftsGE(__u32 x)
159 {
160         int extraBits;
161         int nShifts;
162         
163         nShifts = extraBits = 0;
164         
165         while(x>1){
166                 if(x & 1) extraBits++;
167                 x>>=1;
168                 nShifts++;
169         }
170
171         if(extraBits) 
172                 nShifts++;
173                 
174         return nShifts;
175 }
176
177 /* Function to return the number of shifts to get a 1 in bit 0
178  */
179  
180 static __u32 Shifts(__u32 x)
181 {
182         int nShifts;
183         
184         nShifts =  0;
185         
186         if(!x) return 0;
187         
188         while( !(x&1)){
189                 x>>=1;
190                 nShifts++;
191         }
192                 
193         return nShifts;
194 }
195
196
197
198 /* 
199  * Temporary buffer manipulations.
200  */
201
202 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)       
203 {
204         int i;
205         __u8 *buf = (__u8 *)1;
206                 
207         memset(dev->tempBuffer,0,sizeof(dev->tempBuffer));
208                 
209         for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
210                 dev->tempBuffer[i].line = 0;    /* not in use */
211                 dev->tempBuffer[i].buffer = buf =
212                     YMALLOC_DMA(dev->totalBytesPerChunk);
213         }
214                 
215         return buf ? YAFFS_OK : YAFFS_FAIL;
216         
217 }
218
219 __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
220 {
221         int i, j;
222
223         dev->tempInUse++;
224         if(dev->tempInUse > dev->maxTemp)
225                 dev->maxTemp = dev->tempInUse;
226
227         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
228                 if (dev->tempBuffer[i].line == 0) {
229                         dev->tempBuffer[i].line = lineNo;
230                         if ((i + 1) > dev->maxTemp) {
231                                 dev->maxTemp = i + 1;
232                                 for (j = 0; j <= i; j++)
233                                         dev->tempBuffer[j].maxLine =
234                                             dev->tempBuffer[j].line;
235                         }
236
237                         return dev->tempBuffer[i].buffer;
238                 }
239         }
240
241         T(YAFFS_TRACE_BUFFERS,
242           (TSTR("Out of temp buffers at line %d, other held by lines:"),
243            lineNo));
244         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
245                 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
246         }
247         T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
248
249         /*
250          * If we got here then we have to allocate an unmanaged one
251          * This is not good.
252          */
253
254         dev->unmanagedTempAllocations++;
255         return YMALLOC(dev->nDataBytesPerChunk);
256
257 }
258
259 void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
260                                     int lineNo)
261 {
262         int i;
263         
264         dev->tempInUse--;
265         
266         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
267                 if (dev->tempBuffer[i].buffer == buffer) {
268                         dev->tempBuffer[i].line = 0;
269                         return;
270                 }
271         }
272
273         if (buffer) {
274                 /* assume it is an unmanaged one. */
275                 T(YAFFS_TRACE_BUFFERS,
276                   (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
277                    lineNo));
278                 YFREE(buffer);
279                 dev->unmanagedTempDeallocations++;
280         }
281
282 }
283
284 /*
285  * Determine if we have a managed buffer.
286  */
287 int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
288 {
289         int i;
290         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
291                 if (dev->tempBuffer[i].buffer == buffer)
292                         return 1;
293
294         }
295
296     for (i = 0; i < dev->nShortOpCaches; i++) {
297         if( dev->srCache[i].data == buffer )
298             return 1;
299
300     }
301
302     if (buffer == dev->checkpointBuffer)
303       return 1;
304
305     T(YAFFS_TRACE_ALWAYS,
306           (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
307     return 0;
308 }
309
310
311
312 /*
313  * Chunk bitmap manipulations
314  */
315
316 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
317 {
318         if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
319                 T(YAFFS_TRACE_ERROR,
320                   (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
321                    blk));
322                 YBUG();
323         }
324         return dev->chunkBits +
325             (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
326 }
327
328 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
329 {
330         if(blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
331            chunk < 0 || chunk >= dev->nChunksPerBlock) {
332            T(YAFFS_TRACE_ERROR,
333             (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),blk,chunk));
334             YBUG();
335         }
336 }
337
338 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
339 {
340         __u8 *blkBits = yaffs_BlockBits(dev, blk);
341
342         memset(blkBits, 0, dev->chunkBitmapStride);
343 }
344
345 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
346 {
347         __u8 *blkBits = yaffs_BlockBits(dev, blk);
348
349         yaffs_VerifyChunkBitId(dev,blk,chunk);
350
351         blkBits[chunk / 8] &= ~(1 << (chunk & 7));
352 }
353
354 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
355 {
356         __u8 *blkBits = yaffs_BlockBits(dev, blk);
357         
358         yaffs_VerifyChunkBitId(dev,blk,chunk);
359
360         blkBits[chunk / 8] |= (1 << (chunk & 7));
361 }
362
363 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
364 {
365         __u8 *blkBits = yaffs_BlockBits(dev, blk);
366         yaffs_VerifyChunkBitId(dev,blk,chunk);
367
368         return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
369 }
370
371 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
372 {
373         __u8 *blkBits = yaffs_BlockBits(dev, blk);
374         int i;
375         for (i = 0; i < dev->chunkBitmapStride; i++) {
376                 if (*blkBits)
377                         return 1;
378                 blkBits++;
379         }
380         return 0;
381 }
382
383 static int yaffs_CountChunkBits(yaffs_Device * dev, int blk)
384 {
385         __u8 *blkBits = yaffs_BlockBits(dev, blk);
386         int i;
387         int n = 0;
388         for (i = 0; i < dev->chunkBitmapStride; i++) {
389                 __u8 x = *blkBits;
390                 while(x){
391                         if(x & 1)
392                                 n++;
393                         x >>=1;
394                 }
395                         
396                 blkBits++;
397         }
398         return n;
399 }
400
401 /* 
402  * Verification code
403  */
404  
405 static int yaffs_SkipVerification(yaffs_Device *dev)
406 {
407         return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
408 }
409
410 static int yaffs_SkipFullVerification(yaffs_Device *dev)
411 {
412         return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
413 }
414
415 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
416 {
417         return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
418 }
419
420 static const char * blockStateName[] = {
421 "Unknown",
422 "Needs scanning",
423 "Scanning",
424 "Empty",
425 "Allocating",
426 "Full",
427 "Dirty",
428 "Checkpoint",
429 "Collecting",
430 "Dead"
431 };
432
433 static void yaffs_VerifyBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
434 {
435         int actuallyUsed;
436         int inUse;
437         
438         if(yaffs_SkipVerification(dev))
439                 return;
440                 
441         /* Report illegal runtime states */
442         if(bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
443                 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has undefined state %d"TENDSTR),n,bi->blockState));
444                 
445         switch(bi->blockState){
446          case YAFFS_BLOCK_STATE_UNKNOWN:
447          case YAFFS_BLOCK_STATE_SCANNING:
448          case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
449                 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has bad run-state %s"TENDSTR),
450                 n,blockStateName[bi->blockState]));
451         }
452         
453         /* Check pages in use and soft deletions are legal */
454         
455         actuallyUsed = bi->pagesInUse - bi->softDeletions;
456         
457         if(bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
458            bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
459            actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock)
460                 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
461                 n,bi->pagesInUse,bi->softDeletions));
462         
463                 
464         /* Check chunk bitmap legal */
465         inUse = yaffs_CountChunkBits(dev,n);
466         if(inUse != bi->pagesInUse)
467                 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
468                         n,bi->pagesInUse,inUse));
469         
470         /* Check that the sequence number is valid.
471          * Ten million is legal, but is very unlikely 
472          */
473         if(dev->isYaffs2 && 
474            (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
475            (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000 ))
476                 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has suspect sequence number of %d"TENDSTR),
477                 n,bi->sequenceNumber));
478                 
479 }
480
481 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
482 {
483         yaffs_VerifyBlock(dev,bi,n);
484         
485         /* After collection the block should be in the erased state */
486         /* This will need to change if we do partial gc */
487         
488         if(bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
489            bi->blockState != YAFFS_BLOCK_STATE_EMPTY){
490                 T(YAFFS_TRACE_ERROR,(TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
491                         n,bi->blockState));
492         }
493 }
494
495 static void yaffs_VerifyBlocks(yaffs_Device *dev)
496 {
497         int i;
498         int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
499         int nIllegalBlockStates = 0;
500         
501
502         if(yaffs_SkipVerification(dev))
503                 return;
504
505         memset(nBlocksPerState,0,sizeof(nBlocksPerState));
506
507                 
508         for(i = dev->internalStartBlock; i <= dev->internalEndBlock; i++){
509                 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
510                 yaffs_VerifyBlock(dev,bi,i);
511
512                 if(bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
513                         nBlocksPerState[bi->blockState]++;
514                 else
515                         nIllegalBlockStates++;
516                                         
517         }
518         
519         T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
520         T(YAFFS_TRACE_VERIFY,(TSTR("Block summary"TENDSTR)));
521         
522         T(YAFFS_TRACE_VERIFY,(TSTR("%d blocks have illegal states"TENDSTR),nIllegalBlockStates));
523         if(nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
524                 T(YAFFS_TRACE_VERIFY,(TSTR("Too many allocating blocks"TENDSTR)));
525
526         for(i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
527                 T(YAFFS_TRACE_VERIFY,
528                   (TSTR("%s %d blocks"TENDSTR),
529                   blockStateName[i],nBlocksPerState[i]));
530         
531         if(dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
532                 T(YAFFS_TRACE_VERIFY,
533                  (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
534                  dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
535                  
536         if(dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
537                 T(YAFFS_TRACE_VERIFY,
538                  (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
539                  dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
540                  
541         if(nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
542                 T(YAFFS_TRACE_VERIFY,
543                  (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
544                  nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
545
546         T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
547
548 }
549
550 /*
551  * Verify the object header. oh must be valid, but obj and tags may be NULL in which
552  * case those tests will not be performed.
553  */
554 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
555 {
556         if(obj && yaffs_SkipVerification(obj->myDev))
557                 return;
558                 
559         if(!(tags && obj && oh)){
560                 T(YAFFS_TRACE_VERIFY,
561                                 (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR),
562                                 (__u32)tags,(__u32)obj,(__u32)oh));
563                 return;
564         }
565         
566         if(oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
567            oh->type > YAFFS_OBJECT_TYPE_MAX)
568                 T(YAFFS_TRACE_VERIFY,
569                  (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
570                  tags->objectId, oh->type));
571
572         if(tags->objectId != obj->objectId)
573                 T(YAFFS_TRACE_VERIFY,
574                  (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
575                  tags->objectId, obj->objectId));
576
577
578         /*
579          * Check that the object's parent ids match if parentCheck requested.
580          * 
581          * Tests do not apply to the root object.
582          */
583         
584         if(parentCheck && tags->objectId > 1 && !obj->parent)
585                 T(YAFFS_TRACE_VERIFY,
586                  (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
587                  tags->objectId, oh->parentObjectId));
588                 
589         
590         if(parentCheck && obj->parent &&
591            oh->parentObjectId != obj->parent->objectId && 
592            (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
593             obj->parent->objectId != YAFFS_OBJECTID_DELETED))
594                 T(YAFFS_TRACE_VERIFY,
595                  (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
596                  tags->objectId, oh->parentObjectId, obj->parent->objectId));
597                 
598         
599         if(tags->objectId > 1 && oh->name[0] == 0) /* Null name */
600                 T(YAFFS_TRACE_VERIFY,
601                 (TSTR("Obj %d header name is NULL"TENDSTR),
602                  obj->objectId));
603
604         if(tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
605                 T(YAFFS_TRACE_VERIFY,
606                 (TSTR("Obj %d header name is 0xFF"TENDSTR),
607                  obj->objectId));
608 }
609
610
611
612 static int yaffs_VerifyTnodeWorker(yaffs_Object * obj, yaffs_Tnode * tn,
613                                         __u32 level, int chunkOffset)
614 {
615         int i;
616         yaffs_Device *dev = obj->myDev;
617         int ok = 1;
618
619         if (tn) {
620                 if (level > 0) {
621
622                         for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
623                                 if (tn->internal[i]) {
624                                         ok = yaffs_VerifyTnodeWorker(obj,
625                                                         tn->internal[i],
626                                                         level - 1,
627                                                         (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
628                                 }
629                         }
630                 } else if (level == 0) {
631                         yaffs_ExtendedTags tags;
632                         __u32 objectId = obj->objectId;
633                         
634                         chunkOffset <<=  YAFFS_TNODES_LEVEL0_BITS;
635                         
636                         for(i = 0; i < YAFFS_NTNODES_LEVEL0; i++){
637                                 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
638                                 
639                                 if(theChunk > 0){
640                                         /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
641                                         yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
642                                         if(tags.objectId != objectId || tags.chunkId != chunkOffset){
643                                                 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
644                                                         objectId, chunkOffset, theChunk,
645                                                         tags.objectId, tags.chunkId));
646                                         }
647                                 }
648                                 chunkOffset++;
649                         }
650                 }
651         }
652
653         return ok;
654
655 }
656
657
658 static void yaffs_VerifyFile(yaffs_Object *obj)
659 {
660         int requiredTallness;
661         int actualTallness;
662         __u32 lastChunk;
663         __u32 x;
664         __u32 i;
665         yaffs_Device *dev;
666         yaffs_ExtendedTags tags;
667         yaffs_Tnode *tn;
668         __u32 objectId;
669         
670         if(!obj)
671                 return;
672
673         if(yaffs_SkipVerification(obj->myDev))
674                 return;
675         
676         dev = obj->myDev;
677         objectId = obj->objectId;
678         
679         /* Check file size is consistent with tnode depth */
680         lastChunk =  obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
681         x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
682         requiredTallness = 0;
683         while (x> 0) {
684                 x >>= YAFFS_TNODES_INTERNAL_BITS;
685                 requiredTallness++;
686         }
687         
688         actualTallness = obj->variant.fileVariant.topLevel;
689         
690         if(requiredTallness > actualTallness )
691                 T(YAFFS_TRACE_VERIFY,
692                 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
693                  obj->objectId,actualTallness, requiredTallness));
694         
695         
696         /* Check that the chunks in the tnode tree are all correct. 
697          * We do this by scanning through the tnode tree and
698          * checking the tags for every chunk match.
699          */
700
701         if(yaffs_SkipNANDVerification(dev))
702                 return;
703                 
704         for(i = 1; i <= lastChunk; i++){
705                 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant,i);
706
707                 if (tn) {
708                         __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
709                         if(theChunk > 0){
710                                 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
711                                 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
712                                 if(tags.objectId != objectId || tags.chunkId != i){
713                                         T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
714                                                 objectId, i, theChunk,
715                                                 tags.objectId, tags.chunkId));
716                                 }
717                         }
718                 }
719
720         }
721
722 }
723
724
725 static void yaffs_VerifyHardLink(yaffs_Object *obj)
726 {
727         if(obj && yaffs_SkipVerification(obj->myDev))
728                 return;
729                 
730         /* Verify sane equivalent object */
731 }
732
733 static void yaffs_VerifySymlink(yaffs_Object *obj)
734 {
735         if(obj && yaffs_SkipVerification(obj->myDev))
736                 return;
737                 
738         /* Verify symlink string */
739 }
740
741 static void yaffs_VerifySpecial(yaffs_Object *obj)
742 {
743         if(obj && yaffs_SkipVerification(obj->myDev))
744                 return;
745 }
746
747 static void yaffs_VerifyObject(yaffs_Object *obj)
748 {
749         yaffs_Device *dev;
750         
751         __u32 chunkMin;
752         __u32 chunkMax;
753         
754         __u32 chunkIdOk;
755         __u32 chunkIsLive;
756         
757         if(!obj)
758                 return;
759         
760         dev = obj->myDev;
761         
762         if(yaffs_SkipVerification(dev))
763                 return;
764                 
765         /* Check sane object header chunk */
766
767         chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
768         chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
769
770         chunkIdOk = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
771         chunkIsLive = chunkIdOk &&
772                         yaffs_CheckChunkBit(dev,
773                                             obj->hdrChunk / dev->nChunksPerBlock,
774                                             obj->hdrChunk % dev->nChunksPerBlock);
775         if(!obj->fake &&
776             (!chunkIdOk || !chunkIsLive)) {
777            T(YAFFS_TRACE_VERIFY,
778            (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
779            obj->objectId,obj->hdrChunk,
780            chunkIdOk ? "" : ",out of range",
781            chunkIsLive || !chunkIdOk ? "" : ",marked as deleted"));
782         }
783         
784         if(chunkIdOk && chunkIsLive &&!yaffs_SkipNANDVerification(dev)) {
785                 yaffs_ExtendedTags tags;
786                 yaffs_ObjectHeader *oh;
787                 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
788                 
789                 oh = (yaffs_ObjectHeader *)buffer;
790
791                 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk,buffer, &tags);
792
793                 yaffs_VerifyObjectHeader(obj,oh,&tags,1);
794                 
795                 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
796         }
797         
798         /* Verify it has a parent */
799         if(obj && !obj->fake &&
800            (!obj->parent || obj->parent->myDev != dev)){
801            T(YAFFS_TRACE_VERIFY,
802            (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
803            obj->objectId,obj->parent));    
804         }
805         
806         /* Verify parent is a directory */
807         if(obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
808            T(YAFFS_TRACE_VERIFY,
809            (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
810            obj->objectId,obj->parent->variantType));       
811         }
812         
813         switch(obj->variantType){
814         case YAFFS_OBJECT_TYPE_FILE:
815                 yaffs_VerifyFile(obj);
816                 break;
817         case YAFFS_OBJECT_TYPE_SYMLINK:
818                 yaffs_VerifySymlink(obj);
819                 break;
820         case YAFFS_OBJECT_TYPE_DIRECTORY:
821                 yaffs_VerifyDirectory(obj);
822                 break;
823         case YAFFS_OBJECT_TYPE_HARDLINK:
824                 yaffs_VerifyHardLink(obj);
825                 break;
826         case YAFFS_OBJECT_TYPE_SPECIAL:
827                 yaffs_VerifySpecial(obj);
828                 break;
829         case YAFFS_OBJECT_TYPE_UNKNOWN:
830         default:
831                 T(YAFFS_TRACE_VERIFY,
832                 (TSTR("Obj %d has illegaltype %d"TENDSTR),
833                 obj->objectId,obj->variantType));          
834                 break;
835         }
836         
837         
838 }
839
840 static void yaffs_VerifyObjects(yaffs_Device *dev)
841 {
842         yaffs_Object *obj;
843         int i;
844         struct ylist_head *lh;
845
846         if(yaffs_SkipVerification(dev))
847                 return;
848         
849         /* Iterate through the objects in each hash entry */
850          
851          for(i = 0; i <  YAFFS_NOBJECT_BUCKETS; i++){
852                 ylist_for_each(lh, &dev->objectBucket[i].list) {
853                         if (lh) {
854                                 obj = ylist_entry(lh, yaffs_Object, hashLink);
855                                 yaffs_VerifyObject(obj);
856                         }
857                 }
858          }
859
860 }
861
862
863 /*
864  *  Simple hash function. Needs to have a reasonable spread
865  */
866  
867 static Y_INLINE int yaffs_HashFunction(int n)
868 {
869         n = abs(n);
870         return (n % YAFFS_NOBJECT_BUCKETS);
871 }
872
873 /*
874  * Access functions to useful fake objects.
875  * Note that root might have a presence in NAND if permissions are set.
876  */
877  
878 yaffs_Object *yaffs_Root(yaffs_Device * dev)
879 {
880         return dev->rootDir;
881 }
882
883 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
884 {
885         return dev->lostNFoundDir;
886 }
887
888
889 /*
890  *  Erased NAND checking functions
891  */
892  
893 int yaffs_CheckFF(__u8 * buffer, int nBytes)
894 {
895         /* Horrible, slow implementation */
896         while (nBytes--) {
897                 if (*buffer != 0xFF)
898                         return 0;
899                 buffer++;
900         }
901         return 1;
902 }
903
904 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
905                                   int chunkInNAND)
906 {
907
908         int retval = YAFFS_OK;
909         __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
910         yaffs_ExtendedTags tags;
911         int result;
912
913         result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
914         
915         if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
916                 retval = YAFFS_FAIL;
917                 
918
919         if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
920                 T(YAFFS_TRACE_NANDACCESS,
921                   (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
922                 retval = YAFFS_FAIL;
923         }
924
925         yaffs_ReleaseTempBuffer(dev, data, __LINE__);
926
927         return retval;
928
929 }
930
931 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
932                                              const __u8 * data,
933                                              yaffs_ExtendedTags * tags,
934                                              int useReserve)
935 {
936         int attempts = 0;
937         int writeOk = 0;
938         int chunk;
939
940         yaffs_InvalidateCheckpoint(dev);
941
942         do {
943                 yaffs_BlockInfo *bi = 0;
944                 int erasedOk = 0;
945
946                 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
947                 if (chunk < 0) {
948                         /* no space */
949                         break;
950                 }
951
952                 /* First check this chunk is erased, if it needs
953                  * checking.  The checking policy (unless forced
954                  * always on) is as follows:
955                  *
956                  * Check the first page we try to write in a block.
957                  * If the check passes then we don't need to check any
958                  * more.        If the check fails, we check again...
959                  * If the block has been erased, we don't need to check.
960                  *
961                  * However, if the block has been prioritised for gc,
962                  * then we think there might be something odd about
963                  * this block and stop using it.
964                  *
965                  * Rationale: We should only ever see chunks that have
966                  * not been erased if there was a partially written
967                  * chunk due to power loss.  This checking policy should
968                  * catch that case with very few checks and thus save a
969                  * lot of checks that are most likely not needed.
970                  */
971                 if (bi->gcPrioritise) {
972                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
973                         /* try another chunk */
974                         continue;
975                 }
976
977                 /* let's give it a try */
978                 attempts++;
979
980 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
981                 bi->skipErasedCheck = 0;
982 #endif
983                 if (!bi->skipErasedCheck) {
984                         erasedOk = yaffs_CheckChunkErased(dev, chunk);
985                         if (erasedOk != YAFFS_OK) {
986                                 T(YAFFS_TRACE_ERROR,
987                                 (TSTR ("**>> yaffs chunk %d was not erased"
988                                 TENDSTR), chunk));
989
990                                 /* try another chunk */
991                                 continue;
992                         }
993                         bi->skipErasedCheck = 1;
994                 }
995
996                 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
997                                 data, tags);
998                 if (writeOk != YAFFS_OK) {
999                         yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
1000                         /* try another chunk */
1001                         continue;
1002                 }
1003
1004                 /* Copy the data into the robustification buffer */
1005                 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1006
1007         } while (writeOk != YAFFS_OK && 
1008                 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1009         
1010         if(!writeOk)
1011                 chunk = -1;
1012
1013         if (attempts > 1) {
1014                 T(YAFFS_TRACE_ERROR,
1015                         (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1016                         attempts));
1017
1018                 dev->nRetriedWrites += (attempts - 1);
1019         }
1020
1021         return chunk;
1022 }
1023
1024 /*
1025  * Block retiring for handling a broken block.
1026  */
1027  
1028 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
1029 {
1030         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1031
1032         yaffs_InvalidateCheckpoint(dev);
1033         
1034         yaffs_MarkBlockBad(dev, blockInNAND);
1035
1036         bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1037         bi->gcPrioritise = 0;
1038         bi->needsRetiring = 0;
1039
1040         dev->nRetiredBlocks++;
1041 }
1042
1043 /*
1044  * Functions for robustisizing TODO
1045  *
1046  */
1047  
1048 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
1049                                      const __u8 * data,
1050                                      const yaffs_ExtendedTags * tags)
1051 {
1052 }
1053
1054 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
1055                                     const yaffs_ExtendedTags * tags)
1056 {
1057 }
1058
1059 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1060 {
1061         if(!bi->gcPrioritise){
1062                 bi->gcPrioritise = 1;
1063                 dev->hasPendingPrioritisedGCs = 1;
1064                 bi->chunkErrorStrikes ++;
1065                 
1066                 if(bi->chunkErrorStrikes > 3){
1067                         bi->needsRetiring = 1; /* Too many stikes, so retire this */
1068                         T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1069
1070                 }
1071                 
1072         }
1073 }
1074
1075 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
1076 {
1077
1078         int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1079         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1080
1081         yaffs_HandleChunkError(dev,bi);
1082                 
1083         
1084         if(erasedOk ) {
1085                 /* Was an actual write failure, so mark the block for retirement  */
1086                 bi->needsRetiring = 1;
1087                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1088                   (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1089
1090                 
1091         }
1092         
1093         /* Delete the chunk */
1094         yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1095 }
1096
1097
1098 /*---------------- Name handling functions ------------*/ 
1099
1100 static __u16 yaffs_CalcNameSum(const YCHAR * name)
1101 {
1102         __u16 sum = 0;
1103         __u16 i = 1;
1104
1105         const YUCHAR *bname = (const YUCHAR *) name;
1106         if (bname) {
1107                 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1108
1109 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1110                         sum += yaffs_toupper(*bname) * i;
1111 #else
1112                         sum += (*bname) * i;
1113 #endif
1114                         i++;
1115                         bname++;
1116                 }
1117         }
1118         
1119         return sum;
1120 }
1121
1122 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
1123 {
1124 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1125         memset(obj->shortName,0,sizeof (YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1)); 
1126         if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
1127                 yaffs_strcpy(obj->shortName, name);
1128         } else {
1129                 obj->shortName[0] = _Y('\0');
1130         }
1131 #endif
1132         obj->sum = yaffs_CalcNameSum(name);
1133 }
1134
1135 /*-------------------- TNODES -------------------
1136
1137  * List of spare tnodes
1138  * The list is hooked together using the first pointer
1139  * in the tnode.
1140  */
1141  
1142 /* yaffs_CreateTnodes creates a bunch more tnodes and
1143  * adds them to the tnode free list.
1144  * Don't use this function directly
1145  */
1146
1147 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
1148 {
1149         int i;
1150         int tnodeSize;
1151         yaffs_Tnode *newTnodes;
1152         __u8 *mem;
1153         yaffs_Tnode *curr;
1154         yaffs_Tnode *next;
1155         yaffs_TnodeList *tnl;
1156
1157         if (nTnodes < 1)
1158                 return YAFFS_OK;
1159                 
1160         /* Calculate the tnode size in bytes for variable width tnode support.
1161          * Must be a multiple of 32-bits  */
1162         tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1163
1164         if(tnodeSize < sizeof(yaffs_Tnode))
1165                 tnodeSize = sizeof(yaffs_Tnode);
1166                 
1167
1168         /* make these things */
1169
1170         newTnodes = YMALLOC(nTnodes * tnodeSize);
1171         mem = (__u8 *)newTnodes;
1172
1173         if (!newTnodes) {
1174                 T(YAFFS_TRACE_ERROR,
1175                   (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1176                 return YAFFS_FAIL;
1177         }
1178
1179         /* Hook them into the free list */
1180 #if 0
1181         for (i = 0; i < nTnodes - 1; i++) {
1182                 newTnodes[i].internal[0] = &newTnodes[i + 1];
1183 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1184                 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1185 #endif
1186         }
1187
1188         newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1189 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1190         newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1191 #endif
1192         dev->freeTnodes = newTnodes;
1193 #else
1194         /* New hookup for wide tnodes */
1195         for(i = 0; i < nTnodes -1; i++) {
1196                 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1197                 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1198                 curr->internal[0] = next;
1199         }
1200         
1201         curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1202         curr->internal[0] = dev->freeTnodes;
1203         dev->freeTnodes = (yaffs_Tnode *)mem;
1204
1205 #endif
1206
1207
1208         dev->nFreeTnodes += nTnodes;
1209         dev->nTnodesCreated += nTnodes;
1210
1211         /* Now add this bunch of tnodes to a list for freeing up.
1212          * NB If we can't add this to the management list it isn't fatal
1213          * but it just means we can't free this bunch of tnodes later.
1214          */
1215          
1216         tnl = YMALLOC(sizeof(yaffs_TnodeList));
1217         if (!tnl) {
1218                 T(YAFFS_TRACE_ERROR,
1219                   (TSTR
1220                    ("yaffs: Could not add tnodes to management list" TENDSTR)));
1221                    return YAFFS_FAIL;
1222
1223         } else {
1224                 tnl->tnodes = newTnodes;
1225                 tnl->next = dev->allocatedTnodeList;
1226                 dev->allocatedTnodeList = tnl;
1227         }
1228
1229         T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1230
1231         return YAFFS_OK;
1232 }
1233
1234 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1235
1236 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
1237 {
1238         yaffs_Tnode *tn = NULL;
1239
1240         /* If there are none left make more */
1241         if (!dev->freeTnodes) {
1242                 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1243         }
1244
1245         if (dev->freeTnodes) {
1246                 tn = dev->freeTnodes;
1247 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1248                 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1249                         /* Hoosterman, this thing looks like it isn't in the list */
1250                         T(YAFFS_TRACE_ALWAYS,
1251                           (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1252                 }
1253 #endif
1254                 dev->freeTnodes = dev->freeTnodes->internal[0];
1255                 dev->nFreeTnodes--;
1256         }
1257
1258         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1259
1260         return tn;
1261 }
1262
1263 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
1264 {
1265         yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1266         int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1267
1268         if(tnodeSize < sizeof(yaffs_Tnode))
1269                 tnodeSize = sizeof(yaffs_Tnode);
1270         
1271         if(tn)
1272                 memset(tn, 0, tnodeSize);
1273
1274         return tn;      
1275 }
1276
1277 /* FreeTnode frees up a tnode and puts it back on the free list */
1278 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
1279 {
1280         if (tn) {
1281 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1282                 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1283                         /* Hoosterman, this thing looks like it is already in the list */
1284                         T(YAFFS_TRACE_ALWAYS,
1285                           (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1286                 }
1287                 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1288 #endif
1289                 tn->internal[0] = dev->freeTnodes;
1290                 dev->freeTnodes = tn;
1291                 dev->nFreeTnodes++;
1292         }
1293         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1294         
1295 }
1296
1297 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
1298 {
1299         /* Free the list of allocated tnodes */
1300         yaffs_TnodeList *tmp;
1301
1302         while (dev->allocatedTnodeList) {
1303                 tmp = dev->allocatedTnodeList->next;
1304
1305                 YFREE(dev->allocatedTnodeList->tnodes);
1306                 YFREE(dev->allocatedTnodeList);
1307                 dev->allocatedTnodeList = tmp;
1308
1309         }
1310
1311         dev->freeTnodes = NULL;
1312         dev->nFreeTnodes = 0;
1313 }
1314
1315 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
1316 {
1317         dev->allocatedTnodeList = NULL;
1318         dev->freeTnodes = NULL;
1319         dev->nFreeTnodes = 0;
1320         dev->nTnodesCreated = 0;
1321
1322 }
1323
1324
1325 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
1326 {
1327   __u32 *map = (__u32 *)tn;
1328   __u32 bitInMap;
1329   __u32 bitInWord;
1330   __u32 wordInMap;
1331   __u32 mask;
1332   
1333   pos &= YAFFS_TNODES_LEVEL0_MASK;
1334   val >>= dev->chunkGroupBits;
1335   
1336   bitInMap = pos * dev->tnodeWidth;
1337   wordInMap = bitInMap /32;
1338   bitInWord = bitInMap & (32 -1);
1339   
1340   mask = dev->tnodeMask << bitInWord;
1341   
1342   map[wordInMap] &= ~mask;
1343   map[wordInMap] |= (mask & (val << bitInWord));
1344   
1345   if(dev->tnodeWidth > (32-bitInWord)) {
1346     bitInWord = (32 - bitInWord);
1347     wordInMap++;;
1348     mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1349     map[wordInMap] &= ~mask;
1350     map[wordInMap] |= (mask & (val >> bitInWord));
1351   }
1352 }
1353
1354 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
1355 {
1356   __u32 *map = (__u32 *)tn;
1357   __u32 bitInMap;
1358   __u32 bitInWord;
1359   __u32 wordInMap;
1360   __u32 val;
1361   
1362   pos &= YAFFS_TNODES_LEVEL0_MASK;
1363   
1364   bitInMap = pos * dev->tnodeWidth;
1365   wordInMap = bitInMap /32;
1366   bitInWord = bitInMap & (32 -1);
1367   
1368   val = map[wordInMap] >> bitInWord;
1369   
1370   if(dev->tnodeWidth > (32-bitInWord)) {
1371     bitInWord = (32 - bitInWord);
1372     wordInMap++;;
1373     val |= (map[wordInMap] << bitInWord);
1374   }
1375   
1376   val &= dev->tnodeMask;
1377   val <<= dev->chunkGroupBits;
1378   
1379   return val;
1380 }
1381
1382 /* ------------------- End of individual tnode manipulation -----------------*/
1383
1384 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1385  * The look up tree is represented by the top tnode and the number of topLevel
1386  * in the tree. 0 means only the level 0 tnode is in the tree.
1387  */
1388
1389 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1390 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
1391                                           yaffs_FileStructure * fStruct,
1392                                           __u32 chunkId)
1393 {
1394
1395         yaffs_Tnode *tn = fStruct->top;
1396         __u32 i;
1397         int requiredTallness;
1398         int level = fStruct->topLevel;
1399
1400         /* Check sane level and chunk Id */
1401         if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
1402                 return NULL;
1403         }
1404
1405         if (chunkId > YAFFS_MAX_CHUNK_ID) {
1406                 return NULL;
1407         }
1408
1409         /* First check we're tall enough (ie enough topLevel) */
1410
1411         i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1412         requiredTallness = 0;
1413         while (i) {
1414                 i >>= YAFFS_TNODES_INTERNAL_BITS;
1415                 requiredTallness++;
1416         }
1417
1418         if (requiredTallness > fStruct->topLevel) {
1419                 /* Not tall enough, so we can't find it, return NULL. */
1420                 return NULL;
1421         }
1422
1423         /* Traverse down to level 0 */
1424         while (level > 0 && tn) {
1425                 tn = tn->
1426                     internal[(chunkId >>
1427                                ( YAFFS_TNODES_LEVEL0_BITS + 
1428                                  (level - 1) *
1429                                  YAFFS_TNODES_INTERNAL_BITS)
1430                               ) &
1431                              YAFFS_TNODES_INTERNAL_MASK];
1432                 level--;
1433
1434         }
1435
1436         return tn;
1437 }
1438
1439 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1440  * This happens in two steps:
1441  *  1. If the tree isn't tall enough, then make it taller.
1442  *  2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1443  *
1444  * Used when modifying the tree.
1445  *
1446  *  If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1447  *  be plugged into the ttree.
1448  */
1449  
1450 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
1451                                                yaffs_FileStructure * fStruct,
1452                                                __u32 chunkId,
1453                                                yaffs_Tnode *passedTn)
1454 {
1455
1456         int requiredTallness;
1457         int i;
1458         int l;
1459         yaffs_Tnode *tn;
1460
1461         __u32 x;
1462
1463
1464         /* Check sane level and page Id */
1465         if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
1466                 return NULL;
1467         }
1468
1469         if (chunkId > YAFFS_MAX_CHUNK_ID) {
1470                 return NULL;
1471         }
1472
1473         /* First check we're tall enough (ie enough topLevel) */
1474
1475         x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1476         requiredTallness = 0;
1477         while (x) {
1478                 x >>= YAFFS_TNODES_INTERNAL_BITS;
1479                 requiredTallness++;
1480         }
1481
1482
1483         if (requiredTallness > fStruct->topLevel) {
1484                 /* Not tall enough,gotta make the tree taller */
1485                 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1486                 
1487                         tn = yaffs_GetTnode(dev);
1488
1489                         if (tn) {
1490                                 tn->internal[0] = fStruct->top;
1491                                 fStruct->top = tn;
1492                         } else {
1493                                 T(YAFFS_TRACE_ERROR,
1494                                   (TSTR("yaffs: no more tnodes" TENDSTR)));
1495                         }
1496                 }
1497
1498                 fStruct->topLevel = requiredTallness;
1499         }
1500
1501         /* Traverse down to level 0, adding anything we need */
1502
1503         l = fStruct->topLevel;
1504         tn = fStruct->top;
1505         
1506         if(l > 0) {
1507                 while (l > 0 && tn) {
1508                         x = (chunkId >>
1509                              ( YAFFS_TNODES_LEVEL0_BITS +
1510                               (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1511                             YAFFS_TNODES_INTERNAL_MASK;
1512
1513
1514                         if((l>1) && !tn->internal[x]){
1515                                 /* Add missing non-level-zero tnode */
1516                                 tn->internal[x] = yaffs_GetTnode(dev);
1517
1518                         } else if(l == 1) {
1519                                 /* Looking from level 1 at level 0 */
1520                                 if (passedTn) {
1521                                         /* If we already have one, then release it.*/
1522                                         if(tn->internal[x])
1523                                                 yaffs_FreeTnode(dev,tn->internal[x]);
1524                                         tn->internal[x] = passedTn;
1525                         
1526                                 } else if(!tn->internal[x]) {
1527                                         /* Don't have one, none passed in */
1528                                         tn->internal[x] = yaffs_GetTnode(dev);
1529                                 }
1530                         }
1531                 
1532                         tn = tn->internal[x];
1533                         l--;
1534                 }
1535         } else {
1536                 /* top is level 0 */
1537                 if(passedTn) {
1538                         memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1539                         yaffs_FreeTnode(dev,passedTn);
1540                 }
1541         }
1542
1543         return tn;
1544 }
1545
1546 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1547                                   yaffs_ExtendedTags * tags, int objectId,
1548                                   int chunkInInode)
1549 {
1550         int j;
1551
1552         for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1553                 if (yaffs_CheckChunkBit
1554                     (dev, theChunk / dev->nChunksPerBlock,
1555                      theChunk % dev->nChunksPerBlock)) {
1556                         yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1557                                                         tags);
1558                         if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1559                                 /* found it; */
1560                                 return theChunk;
1561
1562                         }
1563                 }
1564                 theChunk++;
1565         }
1566         return -1;
1567 }
1568
1569
1570 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1571  * chunks and tnodes in the file
1572  * Returns 1 if the tree was deleted. 
1573  * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1574  */
1575
1576 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1577                               int chunkOffset, int *limit)
1578 {
1579         int i;
1580         int chunkInInode;
1581         int theChunk;
1582         yaffs_ExtendedTags tags;
1583         int foundChunk;
1584         yaffs_Device *dev = in->myDev;
1585
1586         int allDone = 1;
1587
1588         if (tn) {
1589                 if (level > 0) {
1590
1591                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1592                              i--) {
1593                                 if (tn->internal[i]) {
1594                                         if (limit && (*limit) < 0) {
1595                                                 allDone = 0;
1596                                         } else {
1597                                                 allDone =
1598                                                     yaffs_DeleteWorker(in,
1599                                                                        tn->
1600                                                                        internal
1601                                                                        [i],
1602                                                                        level -
1603                                                                        1,
1604                                                                        (chunkOffset
1605                                                                         <<
1606                                                                         YAFFS_TNODES_INTERNAL_BITS)
1607                                                                        + i,
1608                                                                        limit);
1609                                         }
1610                                         if (allDone) {
1611                                                 yaffs_FreeTnode(dev,
1612                                                                 tn->
1613                                                                 internal[i]);
1614                                                 tn->internal[i] = NULL;
1615                                         }
1616                                 }
1617
1618                         }
1619                         return (allDone) ? 1 : 0;
1620                 } else if (level == 0) {
1621                         int hitLimit = 0;
1622
1623                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1624                              i--) {
1625                                 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1626                                 if (theChunk) {
1627
1628                                         chunkInInode =
1629                                             (chunkOffset <<
1630                                              YAFFS_TNODES_LEVEL0_BITS) + i;
1631
1632                                         foundChunk =
1633                                             yaffs_FindChunkInGroup(dev,
1634                                                                    theChunk,
1635                                                                    &tags,
1636                                                                    in->objectId,
1637                                                                    chunkInInode);
1638
1639                                         if (foundChunk > 0) {
1640                                                 yaffs_DeleteChunk(dev,
1641                                                                   foundChunk, 1,
1642                                                                   __LINE__);
1643                                                 in->nDataChunks--;
1644                                                 if (limit) {
1645                                                         *limit = *limit - 1;
1646                                                         if (*limit <= 0) {
1647                                                                 hitLimit = 1;
1648                                                         }
1649                                                 }
1650
1651                                         }
1652
1653                                         yaffs_PutLevel0Tnode(dev,tn,i,0);
1654                                 }
1655
1656                         }
1657                         return (i < 0) ? 1 : 0;
1658
1659                 }
1660
1661         }
1662
1663         return 1;
1664
1665 }
1666
1667 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1668 {
1669
1670         yaffs_BlockInfo *theBlock;
1671
1672         T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1673
1674         theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1675         if (theBlock) {
1676                 theBlock->softDeletions++;
1677                 dev->nFreeChunks++;
1678         }
1679 }
1680
1681 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1682  * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1683  * of the tnode.
1684  * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1685  */
1686  
1687 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1688                                   __u32 level, int chunkOffset)
1689 {
1690         int i;
1691         int theChunk;
1692         int allDone = 1;
1693         yaffs_Device *dev = in->myDev;
1694
1695         if (tn) {
1696                 if (level > 0) {
1697
1698                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1699                              i--) {
1700                                 if (tn->internal[i]) {
1701                                         allDone =
1702                                             yaffs_SoftDeleteWorker(in,
1703                                                                    tn->
1704                                                                    internal[i],
1705                                                                    level - 1,
1706                                                                    (chunkOffset
1707                                                                     <<
1708                                                                     YAFFS_TNODES_INTERNAL_BITS)
1709                                                                    + i);
1710                                         if (allDone) {
1711                                                 yaffs_FreeTnode(dev,
1712                                                                 tn->
1713                                                                 internal[i]);
1714                                                 tn->internal[i] = NULL;
1715                                         } else {
1716                                                 /* Hoosterman... how could this happen? */
1717                                         }
1718                                 }
1719                         }
1720                         return (allDone) ? 1 : 0;
1721                 } else if (level == 0) {
1722
1723                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1724                                 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1725                                 if (theChunk) {
1726                                         /* Note this does not find the real chunk, only the chunk group.
1727                                          * We make an assumption that a chunk group is not larger than 
1728                                          * a block.
1729                                          */
1730                                         yaffs_SoftDeleteChunk(dev, theChunk);
1731                                         yaffs_PutLevel0Tnode(dev,tn,i,0);
1732                                 }
1733
1734                         }
1735                         return 1;
1736
1737                 }
1738
1739         }
1740
1741         return 1;
1742
1743 }
1744
1745 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1746 {
1747         if (obj->deleted &&
1748             obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1749                 if (obj->nDataChunks <= 0) {
1750                         /* Empty file with no duplicate object headers, just delete it immediately */
1751                         yaffs_FreeTnode(obj->myDev,
1752                                         obj->variant.fileVariant.top);
1753                         obj->variant.fileVariant.top = NULL;
1754                         T(YAFFS_TRACE_TRACING,
1755                           (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1756                            obj->objectId));
1757                         yaffs_DoGenericObjectDeletion(obj);
1758                 } else {
1759                         yaffs_SoftDeleteWorker(obj,
1760                                                obj->variant.fileVariant.top,
1761                                                obj->variant.fileVariant.
1762                                                topLevel, 0);
1763                         obj->softDeleted = 1;
1764                 }
1765         }
1766 }
1767
1768 /* Pruning removes any part of the file structure tree that is beyond the
1769  * bounds of the file (ie that does not point to chunks).
1770  *
1771  * A file should only get pruned when its size is reduced.
1772  *
1773  * Before pruning, the chunks must be pulled from the tree and the
1774  * level 0 tnode entries must be zeroed out.
1775  * Could also use this for file deletion, but that's probably better handled
1776  * by a special case.
1777  */
1778
1779 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1780                                       __u32 level, int del0)
1781 {
1782         int i;
1783         int hasData;
1784
1785         if (tn) {
1786                 hasData = 0;
1787
1788                 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1789                         if (tn->internal[i] && level > 0) {
1790                                 tn->internal[i] =
1791                                     yaffs_PruneWorker(dev, tn->internal[i],
1792                                                       level - 1,
1793                                                       (i == 0) ? del0 : 1);
1794                         }
1795
1796                         if (tn->internal[i]) {
1797                                 hasData++;
1798                         }
1799                 }
1800
1801                 if (hasData == 0 && del0) {
1802                         /* Free and return NULL */
1803
1804                         yaffs_FreeTnode(dev, tn);
1805                         tn = NULL;
1806                 }
1807
1808         }
1809
1810         return tn;
1811
1812 }
1813
1814 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1815                                     yaffs_FileStructure * fStruct)
1816 {
1817         int i;
1818         int hasData;
1819         int done = 0;
1820         yaffs_Tnode *tn;
1821
1822         if (fStruct->topLevel > 0) {
1823                 fStruct->top =
1824                     yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1825
1826                 /* Now we have a tree with all the non-zero branches NULL but the height
1827                  * is the same as it was.
1828                  * Let's see if we can trim internal tnodes to shorten the tree.
1829                  * We can do this if only the 0th element in the tnode is in use 
1830                  * (ie all the non-zero are NULL)
1831                  */
1832
1833                 while (fStruct->topLevel && !done) {
1834                         tn = fStruct->top;
1835
1836                         hasData = 0;
1837                         for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1838                                 if (tn->internal[i]) {
1839                                         hasData++;
1840                                 }
1841                         }
1842
1843                         if (!hasData) {
1844                                 fStruct->top = tn->internal[0];
1845                                 fStruct->topLevel--;
1846                                 yaffs_FreeTnode(dev, tn);
1847                         } else {
1848                                 done = 1;
1849                         }
1850                 }
1851         }
1852
1853         return YAFFS_OK;
1854 }
1855
1856 /*-------------------- End of File Structure functions.-------------------*/
1857
1858 /* yaffs_CreateFreeObjects creates a bunch more objects and
1859  * adds them to the object free list.
1860  */
1861 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1862 {
1863         int i;
1864         yaffs_Object *newObjects;
1865         yaffs_ObjectList *list;
1866
1867         if (nObjects < 1)
1868                 return YAFFS_OK;
1869
1870         /* make these things */
1871         newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1872         list = YMALLOC(sizeof(yaffs_ObjectList));
1873
1874         if (!newObjects || !list) {
1875                 if(newObjects)
1876                         YFREE(newObjects);
1877                 if(list)
1878                         YFREE(list);
1879                 T(YAFFS_TRACE_ALLOCATE,
1880                   (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1881                 return YAFFS_FAIL;
1882         }
1883         
1884         /* Hook them into the free list */
1885         for (i = 0; i < nObjects - 1; i++) {
1886                 newObjects[i].siblings.next =
1887                     (struct ylist_head *)(&newObjects[i + 1]);
1888         }
1889
1890         newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1891         dev->freeObjects = newObjects;
1892         dev->nFreeObjects += nObjects;
1893         dev->nObjectsCreated += nObjects;
1894
1895         /* Now add this bunch of Objects to a list for freeing up. */
1896
1897         list->objects = newObjects;
1898         list->next = dev->allocatedObjectList;
1899         dev->allocatedObjectList = list;
1900
1901         return YAFFS_OK;
1902 }
1903
1904
1905 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1906 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1907 {
1908         yaffs_Object *tn = NULL;
1909
1910 #ifdef VALGRIND_TEST
1911         tn = YMALLOC(sizeof(yaffs_Object));
1912 #else
1913         /* If there are none left make more */
1914         if (!dev->freeObjects) {
1915                 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1916         }
1917
1918         if (dev->freeObjects) {
1919                 tn = dev->freeObjects;
1920                 dev->freeObjects =
1921                     (yaffs_Object *) (dev->freeObjects->siblings.next);
1922                 dev->nFreeObjects--;
1923         }
1924 #endif
1925         if(tn){
1926                 /* Now sweeten it up... */
1927
1928                 memset(tn, 0, sizeof(yaffs_Object));
1929                 tn->myDev = dev;
1930                 tn->hdrChunk = 0;
1931                 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1932                 YINIT_LIST_HEAD(&(tn->hardLinks));
1933                 YINIT_LIST_HEAD(&(tn->hashLink));
1934                 YINIT_LIST_HEAD(&tn->siblings);
1935                 
1936
1937                 /* Now make the directory sane */
1938                 if(dev->rootDir){
1939                         tn->parent = dev->rootDir;
1940                         ylist_add(&(tn->siblings),&dev->rootDir->variant.directoryVariant.children);
1941                 }
1942
1943                 /* Add it to the lost and found directory.
1944                  * NB Can't put root or lostNFound in lostNFound so
1945                  * check if lostNFound exists first
1946                  */
1947                 if (dev->lostNFoundDir) {
1948                         yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1949                 }
1950         }
1951         
1952         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1953
1954         return tn;
1955 }
1956
1957 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1958                                                __u32 mode)
1959 {
1960
1961         yaffs_Object *obj =
1962             yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1963         if (obj) {
1964                 obj->fake = 1;          /* it is fake so it might have no NAND presence... */
1965                 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1966                 obj->unlinkAllowed = 0; /* ... or unlink it */
1967                 obj->deleted = 0;
1968                 obj->unlinked = 0;
1969                 obj->yst_mode = mode;
1970                 obj->myDev = dev;
1971                 obj->hdrChunk = 0;      /* Not a valid chunk. */
1972         }
1973
1974         return obj;
1975
1976 }
1977
1978 static void yaffs_UnhashObject(yaffs_Object * tn)
1979 {
1980         int bucket;
1981         yaffs_Device *dev = tn->myDev;
1982
1983         /* If it is still linked into the bucket list, free from the list */
1984         if (!ylist_empty(&tn->hashLink)) {
1985                 ylist_del_init(&tn->hashLink);
1986                 bucket = yaffs_HashFunction(tn->objectId);
1987                 dev->objectBucket[bucket].count--;
1988         }
1989
1990 }
1991
1992 /*  FreeObject frees up a Object and puts it back on the free list */
1993 static void yaffs_FreeObject(yaffs_Object * tn)
1994 {
1995
1996         yaffs_Device *dev = tn->myDev;
1997
1998         
1999         if(tn->parent)
2000                 YBUG();
2001         if(!ylist_empty(&tn->siblings))
2002                 YBUG();
2003
2004
2005 #ifdef  __KERNEL__
2006         if (tn->myInode) {
2007                 /* We're still hooked up to a cached inode.
2008                  * Don't delete now, but mark for later deletion
2009                  */
2010                 tn->deferedFree = 1;
2011                 return;
2012         }
2013 #endif
2014
2015         yaffs_UnhashObject(tn);
2016
2017 #ifdef VALGRIND_TEST
2018         YFREE(tn);
2019 #else
2020         /* Link into the free list. */
2021         tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2022         dev->freeObjects = tn;
2023         dev->nFreeObjects++;
2024 #endif
2025         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2026
2027 }
2028
2029 #ifdef __KERNEL__
2030
2031 void yaffs_HandleDeferedFree(yaffs_Object * obj)
2032 {
2033         if (obj->deferedFree) {
2034                 yaffs_FreeObject(obj);
2035         }
2036 }
2037
2038 #endif
2039
2040 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
2041 {
2042         /* Free the list of allocated Objects */
2043
2044         yaffs_ObjectList *tmp;
2045
2046         while (dev->allocatedObjectList) {
2047                 tmp = dev->allocatedObjectList->next;
2048                 YFREE(dev->allocatedObjectList->objects);
2049                 YFREE(dev->allocatedObjectList);
2050
2051                 dev->allocatedObjectList = tmp;
2052         }
2053
2054         dev->freeObjects = NULL;
2055         dev->nFreeObjects = 0;
2056 }
2057
2058 static void yaffs_InitialiseObjects(yaffs_Device * dev)
2059 {
2060         int i;
2061
2062         dev->allocatedObjectList = NULL;
2063         dev->freeObjects = NULL;
2064         dev->nFreeObjects = 0;
2065
2066         for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2067                 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2068                 dev->objectBucket[i].count = 0;
2069         }
2070
2071 }
2072
2073 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
2074 {
2075         static int x = 0;
2076         int i;
2077         int l = 999;
2078         int lowest = 999999;
2079
2080         /* First let's see if we can find one that's empty. */
2081
2082         for (i = 0; i < 10 && lowest > 0; i++) {
2083                 x++;
2084                 x %= YAFFS_NOBJECT_BUCKETS;
2085                 if (dev->objectBucket[x].count < lowest) {
2086                         lowest = dev->objectBucket[x].count;
2087                         l = x;
2088                 }
2089
2090         }
2091
2092         /* If we didn't find an empty list, then try
2093          * looking a bit further for a short one
2094          */
2095
2096         for (i = 0; i < 10 && lowest > 3; i++) {
2097                 x++;
2098                 x %= YAFFS_NOBJECT_BUCKETS;
2099                 if (dev->objectBucket[x].count < lowest) {
2100                         lowest = dev->objectBucket[x].count;
2101                         l = x;
2102                 }
2103
2104         }
2105
2106         return l;
2107 }
2108
2109 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
2110 {
2111         int bucket = yaffs_FindNiceObjectBucket(dev);
2112
2113         /* Now find an object value that has not already been taken
2114          * by scanning the list.
2115          */
2116
2117         int found = 0;
2118         struct ylist_head *i;
2119
2120         __u32 n = (__u32) bucket;
2121
2122         /* yaffs_CheckObjectHashSanity();  */
2123
2124         while (!found) {
2125                 found = 1;
2126                 n += YAFFS_NOBJECT_BUCKETS;
2127                 if (1 || dev->objectBucket[bucket].count > 0) {
2128                         ylist_for_each(i, &dev->objectBucket[bucket].list) {
2129                                 /* If there is already one in the list */
2130                                 if (i
2131                                     && ylist_entry(i, yaffs_Object,
2132                                                   hashLink)->objectId == n) {
2133                                         found = 0;
2134                                 }
2135                         }
2136                 }
2137         }
2138
2139
2140         return n;
2141 }
2142
2143 static void yaffs_HashObject(yaffs_Object * in)
2144 {
2145         int bucket = yaffs_HashFunction(in->objectId);
2146         yaffs_Device *dev = in->myDev;
2147
2148         ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2149         dev->objectBucket[bucket].count++;
2150
2151 }
2152
2153 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
2154 {
2155         int bucket = yaffs_HashFunction(number);
2156         struct ylist_head *i;
2157         yaffs_Object *in;
2158
2159         ylist_for_each(i, &dev->objectBucket[bucket].list) {
2160                 /* Look if it is in the list */
2161                 if (i) {
2162                         in = ylist_entry(i, yaffs_Object, hashLink);
2163                         if (in->objectId == number) {
2164 #ifdef __KERNEL__
2165                                 /* Don't tell the VFS about this one if it is defered free */
2166                                 if (in->deferedFree)
2167                                         return NULL;
2168 #endif
2169
2170                                 return in;
2171                         }
2172                 }
2173         }
2174
2175         return NULL;
2176 }
2177
2178 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
2179                                     yaffs_ObjectType type)
2180 {
2181
2182         yaffs_Object *theObject;
2183         yaffs_Tnode *tn = NULL;
2184
2185         if (number < 0) {
2186                 number = yaffs_CreateNewObjectNumber(dev);
2187         }
2188
2189         theObject = yaffs_AllocateEmptyObject(dev);
2190         if(!theObject)
2191                 return NULL;
2192                 
2193         if(type == YAFFS_OBJECT_TYPE_FILE){
2194                 tn = yaffs_GetTnode(dev);
2195                 if(!tn){
2196                         yaffs_FreeObject(theObject);
2197                         return NULL;
2198                 }
2199         }
2200                 
2201         
2202
2203         if (theObject) {
2204                 theObject->fake = 0;
2205                 theObject->renameAllowed = 1;
2206                 theObject->unlinkAllowed = 1;
2207                 theObject->objectId = number;
2208                 yaffs_HashObject(theObject);
2209                 theObject->variantType = type;
2210 #ifdef CONFIG_YAFFS_WINCE
2211                 yfsd_WinFileTimeNow(theObject->win_atime);
2212                 theObject->win_ctime[0] = theObject->win_mtime[0] =
2213                     theObject->win_atime[0];
2214                 theObject->win_ctime[1] = theObject->win_mtime[1] =
2215                     theObject->win_atime[1];
2216
2217 #else
2218
2219                 theObject->yst_atime = theObject->yst_mtime =
2220                     theObject->yst_ctime = Y_CURRENT_TIME;
2221 #endif
2222
2223 #if 0
2224                 theObject->sum_prev = 12345;
2225                 theObject->sum_trailer = 6789;
2226 #endif
2227
2228                 switch (type) {
2229                 case YAFFS_OBJECT_TYPE_FILE:
2230                         theObject->variant.fileVariant.fileSize = 0;
2231                         theObject->variant.fileVariant.scannedFileSize = 0;
2232                         theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2233                         theObject->variant.fileVariant.topLevel = 0;
2234                         theObject->variant.fileVariant.top = tn;
2235                         break;
2236                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2237                         YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2238                                        children);
2239                         break;
2240                 case YAFFS_OBJECT_TYPE_SYMLINK:
2241                 case YAFFS_OBJECT_TYPE_HARDLINK:
2242                 case YAFFS_OBJECT_TYPE_SPECIAL:
2243                         /* No action required */
2244                         break;
2245                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2246                         /* todo this should not happen */
2247                         break;
2248                 }
2249         }
2250
2251         return theObject;
2252 }
2253
2254 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
2255                                                       int number,
2256                                                       yaffs_ObjectType type)
2257 {
2258         yaffs_Object *theObject = NULL;
2259
2260         if (number > 0) {
2261                 theObject = yaffs_FindObjectByNumber(dev, number);
2262         }
2263
2264         if (!theObject) {
2265                 theObject = yaffs_CreateNewObject(dev, number, type);
2266         }
2267
2268         return theObject;
2269
2270 }
2271                         
2272
2273 static YCHAR *yaffs_CloneString(const YCHAR * str)
2274 {
2275         YCHAR *newStr = NULL;
2276
2277         if (str && *str) {
2278                 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2279                 if(newStr)
2280                         yaffs_strcpy(newStr, str);
2281         }
2282
2283         return newStr;
2284
2285 }
2286
2287 /*
2288  * Mknod (create) a new object.
2289  * equivalentObject only has meaning for a hard link;
2290  * aliasString only has meaning for a sumlink.
2291  * rdev only has meaning for devices (a subset of special objects)
2292  */
2293  
2294 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2295                                        yaffs_Object * parent,
2296                                        const YCHAR * name,
2297                                        __u32 mode,
2298                                        __u32 uid,
2299                                        __u32 gid,
2300                                        yaffs_Object * equivalentObject,
2301                                        const YCHAR * aliasString, __u32 rdev)
2302 {
2303         yaffs_Object *in;
2304         YCHAR *str = NULL;
2305
2306         yaffs_Device *dev = parent->myDev;
2307
2308         /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2309         if (yaffs_FindObjectByName(parent, name)) {
2310                 return NULL;
2311         }
2312
2313         in = yaffs_CreateNewObject(dev, -1, type);
2314
2315         if(!in)
2316                 return YAFFS_FAIL;
2317         
2318         if(type == YAFFS_OBJECT_TYPE_SYMLINK){
2319                 str = yaffs_CloneString(aliasString);
2320                 if(!str){
2321                         yaffs_FreeObject(in);
2322                         return NULL;
2323                 }
2324         }
2325         
2326         
2327
2328         if (in) {
2329                 in->hdrChunk = 0;
2330                 in->valid = 1;
2331                 in->variantType = type;
2332
2333                 in->yst_mode = mode;
2334
2335 #ifdef CONFIG_YAFFS_WINCE
2336                 yfsd_WinFileTimeNow(in->win_atime);
2337                 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2338                 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2339
2340 #else
2341                 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2342
2343                 in->yst_rdev = rdev;
2344                 in->yst_uid = uid;
2345                 in->yst_gid = gid;
2346 #endif
2347                 in->nDataChunks = 0;
2348
2349                 yaffs_SetObjectName(in, name);
2350                 in->dirty = 1;
2351
2352                 yaffs_AddObjectToDirectory(parent, in);
2353
2354                 in->myDev = parent->myDev;
2355
2356                 switch (type) {
2357                 case YAFFS_OBJECT_TYPE_SYMLINK:
2358                         in->variant.symLinkVariant.alias = str;
2359                         break;
2360                 case YAFFS_OBJECT_TYPE_HARDLINK:
2361                         in->variant.hardLinkVariant.equivalentObject =
2362                             equivalentObject;
2363                         in->variant.hardLinkVariant.equivalentObjectId =
2364                             equivalentObject->objectId;
2365                         ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2366                         break;
2367                 case YAFFS_OBJECT_TYPE_FILE:    
2368                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2369                 case YAFFS_OBJECT_TYPE_SPECIAL:
2370                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2371                         /* do nothing */
2372                         break;
2373                 }
2374
2375                 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2376                         /* Could not create the object header, fail the creation */
2377                         yaffs_DestroyObject(in);
2378                         in = NULL;
2379                 }
2380
2381         }
2382
2383         return in;
2384 }
2385
2386 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
2387                               __u32 mode, __u32 uid, __u32 gid)
2388 {
2389         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2390                                  uid, gid, NULL, NULL, 0);
2391 }
2392
2393 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
2394                                    __u32 mode, __u32 uid, __u32 gid)
2395 {
2396         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2397                                  mode, uid, gid, NULL, NULL, 0);
2398 }
2399
2400 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
2401                                  __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2402 {
2403         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2404                                  uid, gid, NULL, NULL, rdev);
2405 }
2406
2407 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
2408                                  __u32 mode, __u32 uid, __u32 gid,
2409                                  const YCHAR * alias)
2410 {
2411         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2412                                  uid, gid, NULL, alias, 0);
2413 }
2414
2415 /* yaffs_Link returns the object id of the equivalent object.*/
2416 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
2417                          yaffs_Object * equivalentObject)
2418 {
2419         /* Get the real object in case we were fed a hard link as an equivalent object */
2420         equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2421
2422         if (yaffs_MknodObject
2423             (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2424              equivalentObject, NULL, 0)) {
2425                 return equivalentObject;
2426         } else {
2427                 return NULL;
2428         }
2429
2430 }
2431
2432 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
2433                                   const YCHAR * newName, int force, int shadows)
2434 {
2435         int unlinkOp;
2436         int deleteOp;
2437
2438         yaffs_Object *existingTarget;
2439
2440         if (newDir == NULL) {
2441                 newDir = obj->parent;   /* use the old directory */
2442         }
2443
2444         if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2445                 T(YAFFS_TRACE_ALWAYS,
2446                   (TSTR
2447                    ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2448                     TENDSTR)));
2449                 YBUG();
2450         }
2451         
2452         /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2453         if (obj->myDev->isYaffs2) {
2454                 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2455         } else {
2456                 unlinkOp = (newDir == obj->myDev->unlinkedDir
2457                             && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2458         }
2459
2460         deleteOp = (newDir == obj->myDev->deletedDir);
2461
2462         existingTarget = yaffs_FindObjectByName(newDir, newName);
2463
2464         /* If the object is a file going into the unlinked directory, 
2465          *   then it is OK to just stuff it in since duplicate names are allowed.
2466          *   else only proceed if the new name does not exist and if we're putting 
2467          *   it into a directory.
2468          */
2469         if ((unlinkOp ||
2470              deleteOp ||
2471              force ||
2472              (shadows > 0) ||
2473              !existingTarget) &&
2474             newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2475                 yaffs_SetObjectName(obj, newName);
2476                 obj->dirty = 1;
2477
2478                 yaffs_AddObjectToDirectory(newDir, obj);
2479
2480                 if (unlinkOp)
2481                         obj->unlinked = 1;
2482
2483                 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2484                 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
2485                         return YAFFS_OK;
2486         }
2487
2488         return YAFFS_FAIL;
2489 }
2490
2491 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
2492                        yaffs_Object * newDir, const YCHAR * newName)
2493 {
2494         yaffs_Object *obj=NULL;
2495         yaffs_Object *existingTarget=NULL;
2496         int force = 0;
2497         
2498         
2499         if(!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2500                 YBUG();
2501         if(!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2502                 YBUG();
2503
2504 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2505         /* Special case for case insemsitive systems (eg. WinCE).
2506          * While look-up is case insensitive, the name isn't.
2507          * Therefore we might want to change x.txt to X.txt
2508         */
2509         if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
2510                 force = 1;
2511         }
2512 #endif
2513
2514         else if (yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2515           /* ENAMETOOLONG */
2516           return YAFFS_FAIL;
2517
2518         obj = yaffs_FindObjectByName(oldDir, oldName);
2519
2520         if (obj && obj->renameAllowed) {
2521
2522                 /* Now do the handling for an existing target, if there is one */
2523
2524                 existingTarget = yaffs_FindObjectByName(newDir, newName);
2525                 if (existingTarget &&
2526                     existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2527                     !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2528                         /* There is a target that is a non-empty directory, so we fail */
2529                         return YAFFS_FAIL;      /* EEXIST or ENOTEMPTY */
2530                 } else if (existingTarget && existingTarget != obj) {
2531                         /* Nuke the target first, using shadowing, 
2532                          * but only if it isn't the same object
2533                          */
2534                         yaffs_ChangeObjectName(obj, newDir, newName, force,
2535                                                existingTarget->objectId);
2536                         yaffs_UnlinkObject(existingTarget);
2537                 }
2538
2539                 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2540         }
2541         return YAFFS_FAIL;
2542 }
2543
2544 /*------------------------- Block Management and Page Allocation ----------------*/
2545
2546 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
2547 {
2548         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2549         
2550         dev->blockInfo = NULL;
2551         dev->chunkBits = NULL;
2552         
2553         dev->allocationBlock = -1;      /* force it to get a new one */
2554
2555         /* If the first allocation strategy fails, thry the alternate one */
2556         dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2557         if(!dev->blockInfo){
2558                 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2559                 dev->blockInfoAlt = 1;
2560         }
2561         else
2562                 dev->blockInfoAlt = 0;
2563                 
2564         if(dev->blockInfo){
2565         
2566                 /* Set up dynamic blockinfo stuff. */
2567                 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2568                 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2569                 if(!dev->chunkBits){
2570                         dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2571                         dev->chunkBitsAlt = 1;
2572                 }
2573                 else
2574                         dev->chunkBitsAlt = 0;
2575         }
2576         
2577         if (dev->blockInfo && dev->chunkBits) {
2578                 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2579                 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2580                 return YAFFS_OK;
2581         }
2582
2583         return YAFFS_FAIL;
2584
2585 }
2586
2587 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
2588 {
2589         if(dev->blockInfoAlt && dev->blockInfo)
2590                 YFREE_ALT(dev->blockInfo);
2591         else if(dev->blockInfo)
2592                 YFREE(dev->blockInfo);
2593
2594         dev->blockInfoAlt = 0;
2595
2596         dev->blockInfo = NULL;
2597         
2598         if(dev->chunkBitsAlt && dev->chunkBits)
2599                 YFREE_ALT(dev->chunkBits);
2600         else if(dev->chunkBits)
2601                 YFREE(dev->chunkBits);
2602         dev->chunkBitsAlt = 0;
2603         dev->chunkBits = NULL;
2604 }
2605
2606 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
2607                                             yaffs_BlockInfo * bi)
2608 {
2609         int i;
2610         __u32 seq;
2611         yaffs_BlockInfo *b;
2612
2613         if (!dev->isYaffs2)
2614                 return 1;       /* disqualification only applies to yaffs2. */
2615
2616         if (!bi->hasShrinkHeader)
2617                 return 1;       /* can gc */
2618
2619         /* Find the oldest dirty sequence number if we don't know it and save it
2620          * so we don't have to keep recomputing it.
2621          */
2622         if (!dev->oldestDirtySequence) {
2623                 seq = dev->sequenceNumber;
2624
2625                 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2626                      i++) {
2627                         b = yaffs_GetBlockInfo(dev, i);
2628                         if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2629                             (b->pagesInUse - b->softDeletions) <
2630                             dev->nChunksPerBlock && b->sequenceNumber < seq) {
2631                                 seq = b->sequenceNumber;
2632                         }
2633                 }
2634                 dev->oldestDirtySequence = seq;
2635         }
2636
2637         /* Can't do gc of this block if there are any blocks older than this one that have
2638          * discarded pages.
2639          */
2640         return (bi->sequenceNumber <= dev->oldestDirtySequence);
2641
2642 }
2643
2644 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2645  * for garbage collection.
2646  */
2647
2648 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2649                                                int aggressive)
2650 {
2651
2652         int b = dev->currentDirtyChecker;
2653
2654         int i;
2655         int iterations;
2656         int dirtiest = -1;
2657         int pagesInUse = 0;
2658         int prioritised=0;
2659         yaffs_BlockInfo *bi;
2660         int pendingPrioritisedExist = 0;
2661         
2662         /* First let's see if we need to grab a prioritised block */
2663         if(dev->hasPendingPrioritisedGCs){
2664                 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2665
2666                         bi = yaffs_GetBlockInfo(dev, i);
2667                         //yaffs_VerifyBlock(dev,bi,i);
2668                         
2669                         if(bi->gcPrioritise) {
2670                                 pendingPrioritisedExist = 1;
2671                                 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2672                                    yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2673                                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
2674                                         dirtiest = i;
2675                                         prioritised = 1;
2676                                         aggressive = 1; /* Fool the non-aggressive skip logiv below */
2677                                 }
2678                         }
2679                 }
2680                 
2681                 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2682                         dev->hasPendingPrioritisedGCs = 0;
2683         }
2684
2685         /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2686          * search harder.
2687          * else (we're doing a leasurely gc), then we only bother to do this if the
2688          * block has only a few pages in use.
2689          */
2690
2691         dev->nonAggressiveSkip--;
2692
2693         if (!aggressive && (dev->nonAggressiveSkip > 0)) {
2694                 return -1;
2695         }
2696
2697         if(!prioritised)
2698                 pagesInUse =
2699                         (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2700
2701         if (aggressive) {
2702                 iterations =
2703                     dev->internalEndBlock - dev->internalStartBlock + 1;
2704         } else {
2705                 iterations =
2706                     dev->internalEndBlock - dev->internalStartBlock + 1;
2707                 iterations = iterations / 16;
2708                 if (iterations > 200) {
2709                         iterations = 200;
2710                 }
2711         }
2712
2713         for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2714                 b++;
2715                 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2716                         b = dev->internalStartBlock;
2717                 }
2718
2719                 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2720                         T(YAFFS_TRACE_ERROR,
2721                           (TSTR("**>> Block %d is not valid" TENDSTR), b));
2722                         YBUG();
2723                 }
2724
2725                 bi = yaffs_GetBlockInfo(dev, b);
2726
2727 #if 0
2728                 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2729                         dirtiest = b;
2730                         pagesInUse = 0;
2731                 }
2732                 else 
2733 #endif
2734
2735                 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2736                        (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2737                         yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2738                         dirtiest = b;
2739                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
2740                 }
2741         }
2742
2743         dev->currentDirtyChecker = b;
2744
2745         if (dirtiest > 0) {
2746                 T(YAFFS_TRACE_GC,
2747                   (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2748                    dev->nChunksPerBlock - pagesInUse,prioritised));
2749         }
2750
2751         dev->oldestDirtySequence = 0;
2752
2753         if (dirtiest > 0) {
2754                 dev->nonAggressiveSkip = 4;
2755         }
2756
2757         return dirtiest;
2758 }
2759
2760 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2761 {
2762         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2763
2764         int erasedOk = 0;
2765
2766         /* If the block is still healthy erase it and mark as clean.
2767          * If the block has had a data failure, then retire it.
2768          */
2769          
2770         T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2771                 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2772                 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2773                 
2774         bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2775
2776         if (!bi->needsRetiring) {
2777                 yaffs_InvalidateCheckpoint(dev);
2778                 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2779                 if (!erasedOk) {
2780                         dev->nErasureFailures++;
2781                         T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2782                           (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2783                 }
2784         }
2785
2786         if (erasedOk && 
2787             ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2788                 int i;
2789                 for (i = 0; i < dev->nChunksPerBlock; i++) {
2790                         if (!yaffs_CheckChunkErased
2791                             (dev, blockNo * dev->nChunksPerBlock + i)) {
2792                                 T(YAFFS_TRACE_ERROR,
2793                                   (TSTR
2794                                    (">>Block %d erasure supposedly OK, but chunk %d not erased"
2795                                     TENDSTR), blockNo, i));
2796                         }
2797                 }
2798         }
2799
2800         if (erasedOk) {
2801                 /* Clean it up... */
2802                 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2803                 dev->nErasedBlocks++;
2804                 bi->pagesInUse = 0;
2805                 bi->softDeletions = 0;
2806                 bi->hasShrinkHeader = 0;
2807                 bi->skipErasedCheck = 1;  /* This is clean, so no need to check */
2808                 bi->gcPrioritise = 0;
2809                 yaffs_ClearChunkBits(dev, blockNo);
2810
2811                 T(YAFFS_TRACE_ERASE,
2812                   (TSTR("Erased block %d" TENDSTR), blockNo));
2813         } else {
2814                 dev->nFreeChunks -= dev->nChunksPerBlock;       /* We lost a block of free space */
2815
2816                 yaffs_RetireBlock(dev, blockNo);
2817                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2818                   (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2819         }
2820 }
2821
2822 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2823 {
2824         int i;
2825
2826         yaffs_BlockInfo *bi;
2827
2828         if (dev->nErasedBlocks < 1) {
2829                 /* Hoosterman we've got a problem.
2830                  * Can't get space to gc
2831                  */
2832                 T(YAFFS_TRACE_ERROR,
2833                   (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2834
2835                 return -1;
2836         }
2837         
2838         /* Find an empty block. */
2839
2840         for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2841                 dev->allocationBlockFinder++;
2842                 if (dev->allocationBlockFinder < dev->internalStartBlock
2843                     || dev->allocationBlockFinder > dev->internalEndBlock) {
2844                         dev->allocationBlockFinder = dev->internalStartBlock;
2845                 }
2846
2847                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2848
2849                 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2850                         bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2851                         dev->sequenceNumber++;
2852                         bi->sequenceNumber = dev->sequenceNumber;
2853                         dev->nErasedBlocks--;
2854                         T(YAFFS_TRACE_ALLOCATE,
2855                           (TSTR("Allocated block %d, seq  %d, %d left" TENDSTR),
2856                            dev->allocationBlockFinder, dev->sequenceNumber,
2857                            dev->nErasedBlocks));
2858                         return dev->allocationBlockFinder;
2859                 }
2860         }
2861
2862         T(YAFFS_TRACE_ALWAYS,
2863           (TSTR
2864            ("yaffs tragedy: no more erased blocks, but there should have been %d"
2865             TENDSTR), dev->nErasedBlocks));
2866
2867         return -1;
2868 }
2869
2870
2871
2872 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2873 {
2874         if(!dev->nCheckpointBlocksRequired &&
2875            dev->isYaffs2){
2876                 /* Not a valid value so recalculate */
2877                 int nBytes = 0;
2878                 int nBlocks;
2879                 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2880                 int tnodeSize;
2881
2882                 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2883
2884                 if(tnodeSize < sizeof(yaffs_Tnode))
2885                         tnodeSize = sizeof(yaffs_Tnode);
2886                 
2887                 nBytes += sizeof(yaffs_CheckpointValidity);
2888                 nBytes += sizeof(yaffs_CheckpointDevice);
2889                 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2890                 nBytes += devBlocks * dev->chunkBitmapStride;
2891                 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2892                 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2893                 nBytes += sizeof(yaffs_CheckpointValidity);
2894                 nBytes += sizeof(__u32); /* checksum*/
2895         
2896                 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2897         
2898                 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2899         
2900                 dev->nCheckpointBlocksRequired = nBlocks;
2901         }
2902
2903         return dev->nCheckpointBlocksRequired;
2904 }
2905
2906 // Check if there's space to allocate...
2907 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2908 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2909 {
2910         int reservedChunks;
2911         int reservedBlocks = dev->nReservedBlocks;
2912         int checkpointBlocks;
2913         
2914         if(dev->isYaffs2){
2915                 checkpointBlocks =  yaffs_CalcCheckpointBlocksRequired(dev) - 
2916                                     dev->blocksInCheckpoint;
2917                 if(checkpointBlocks < 0)
2918                         checkpointBlocks = 0;
2919         } else {
2920                 checkpointBlocks =0;
2921         }
2922         
2923         reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2924         
2925         return (dev->nFreeChunks > reservedChunks);
2926 }
2927
2928 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2929 {
2930         int retVal;
2931         yaffs_BlockInfo *bi;
2932
2933         if (dev->allocationBlock < 0) {
2934                 /* Get next block to allocate off */
2935                 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2936                 dev->allocationPage = 0;
2937         }
2938
2939         if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2940                 /* Not enough space to allocate unless we're allowed to use the reserve. */
2941                 return -1;
2942         }
2943
2944         if (dev->nErasedBlocks < dev->nReservedBlocks
2945             && dev->allocationPage == 0) {
2946                 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2947         }
2948
2949         /* Next page please.... */
2950         if (dev->allocationBlock >= 0) {
2951                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2952
2953                 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2954                     dev->allocationPage;
2955                 bi->pagesInUse++;
2956                 yaffs_SetChunkBit(dev, dev->allocationBlock,
2957                                   dev->allocationPage);
2958
2959                 dev->allocationPage++;
2960
2961                 dev->nFreeChunks--;
2962
2963                 /* If the block is full set the state to full */
2964                 if (dev->allocationPage >= dev->nChunksPerBlock) {
2965                         bi->blockState = YAFFS_BLOCK_STATE_FULL;
2966                         dev->allocationBlock = -1;
2967                 }
2968
2969                 if(blockUsedPtr)
2970                         *blockUsedPtr = bi;
2971                         
2972                 return retVal;
2973         }
2974         
2975         T(YAFFS_TRACE_ERROR,
2976           (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2977
2978         return -1;
2979 }
2980
2981 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2982 {
2983         int n;
2984
2985         n = dev->nErasedBlocks * dev->nChunksPerBlock;
2986
2987         if (dev->allocationBlock > 0) {
2988                 n += (dev->nChunksPerBlock - dev->allocationPage);
2989         }
2990
2991         return n;
2992
2993 }
2994
2995 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block, int wholeBlock)
2996 {
2997         int oldChunk;
2998         int newChunk;
2999         int markNAND;
3000         int retVal = YAFFS_OK;
3001         int cleanups = 0;
3002         int i;
3003         int isCheckpointBlock;
3004         int matchingChunk;
3005         int maxCopies;
3006
3007         int chunksBefore = yaffs_GetErasedChunks(dev);
3008         int chunksAfter;
3009
3010         yaffs_ExtendedTags tags;
3011
3012         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3013
3014         yaffs_Object *object;
3015
3016         isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3017         
3018         bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3019
3020         T(YAFFS_TRACE_TRACING,
3021           (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR), 
3022           block,
3023           bi->pagesInUse,
3024           bi->hasShrinkHeader,
3025           wholeBlock));
3026
3027         /*yaffs_VerifyFreeChunks(dev); */
3028
3029         bi->hasShrinkHeader = 0;        /* clear the flag so that the block can erase */
3030
3031         /* Take off the number of soft deleted entries because
3032          * they're going to get really deleted during GC.
3033          */
3034         dev->nFreeChunks -= bi->softDeletions;
3035
3036         dev->isDoingGC = 1;
3037
3038         if (isCheckpointBlock ||
3039             !yaffs_StillSomeChunkBits(dev, block)) {
3040                 T(YAFFS_TRACE_TRACING,
3041                   (TSTR
3042                    ("Collecting block %d that has no chunks in use" TENDSTR),
3043                    block));
3044                 yaffs_BlockBecameDirty(dev, block);
3045         } else {
3046
3047                 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3048                 
3049                 yaffs_VerifyBlock(dev,bi,block);
3050
3051                 maxCopies = (wholeBlock) ? dev->nChunksPerBlock : 10;
3052                 oldChunk = block * dev->nChunksPerBlock + dev->gcChunk;
3053                 
3054                 for ( /* init already done */;
3055                      retVal == YAFFS_OK &&
3056                      dev->gcChunk < dev->nChunksPerBlock &&
3057                      (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING)&&
3058                      maxCopies > 0;
3059                      dev->gcChunk++, oldChunk++) {
3060                         if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3061
3062                                 /* This page is in use and might need to be copied off */
3063                                 
3064                                 maxCopies--;
3065
3066                                 markNAND = 1;
3067
3068                                 yaffs_InitialiseTags(&tags);
3069
3070                                 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3071                                                                 buffer, &tags);
3072
3073                                 object =
3074                                     yaffs_FindObjectByNumber(dev,
3075                                                              tags.objectId);
3076
3077                                 T(YAFFS_TRACE_GC_DETAIL,
3078                                   (TSTR
3079                                    ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3080                                    dev->gcChunk, tags.objectId, tags.chunkId,
3081                                    tags.byteCount));
3082                                    
3083                                 if(object && !yaffs_SkipVerification(dev)){
3084                                         if(tags.chunkId == 0)
3085                                                 matchingChunk = object->hdrChunk;
3086                                         else if(object->softDeleted)
3087                                                 matchingChunk = oldChunk; /* Defeat the test */
3088                                         else
3089                                                 matchingChunk = yaffs_FindChunkInFile(object,tags.chunkId,NULL);
3090                                         
3091                                         if(oldChunk != matchingChunk)
3092                                                 T(YAFFS_TRACE_ERROR,
3093                                                   (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3094                                                   oldChunk,matchingChunk,tags.objectId, tags.chunkId));
3095                                                 
3096                                 }
3097
3098                                 if (!object) {
3099                                         T(YAFFS_TRACE_ERROR,
3100                                           (TSTR
3101                                            ("page %d in gc has no object: %d %d %d "
3102                                             TENDSTR), oldChunk,
3103                                             tags.objectId, tags.chunkId, tags.byteCount));
3104                                 }
3105
3106                                 if (object && 
3107                                     object->deleted &&
3108                                     object->softDeleted &&
3109                                     tags.chunkId != 0) {
3110                                         /* Data chunk in a soft deleted file, throw it away
3111                                          * It's a soft deleted data chunk,
3112                                          * No need to copy this, just forget about it and 
3113                                          * fix up the object.
3114                                          */
3115
3116                                         object->nDataChunks--;
3117
3118                                         if (object->nDataChunks <= 0) {
3119                                                 /* remeber to clean up the object */
3120                                                 dev->gcCleanupList[cleanups] =
3121                                                     tags.objectId;
3122                                                 cleanups++;
3123                                         }
3124                                         markNAND = 0;
3125                                 } else if (0
3126                                            /* Todo object && object->deleted && object->nDataChunks == 0 */
3127                                            ) {
3128                                         /* Deleted object header with no data chunks.
3129                                          * Can be discarded and the file deleted.
3130                                          */
3131                                         object->hdrChunk = 0;
3132                                         yaffs_FreeTnode(object->myDev,
3133                                                         object->variant.
3134                                                         fileVariant.top);
3135                                         object->variant.fileVariant.top = NULL;
3136                                         yaffs_DoGenericObjectDeletion(object);
3137
3138                                 } else if (object) {
3139                                         /* It's either a data chunk in a live file or
3140                                          * an ObjectHeader, so we're interested in it.
3141                                          * NB Need to keep the ObjectHeaders of deleted files
3142                                          * until the whole file has been deleted off
3143                                          */
3144                                         tags.serialNumber++;
3145
3146                                         dev->nGCCopies++;
3147
3148                                         if (tags.chunkId == 0) {
3149                                                 /* It is an object Id,
3150                                                  * We need to nuke the shrinkheader flags first
3151                                                  * We no longer want the shrinkHeader flag since its work is done
3152                                                  * and if it is left in place it will mess up scanning.
3153                                                  * Also, clear out any shadowing stuff
3154                                                  */
3155
3156                                                 yaffs_ObjectHeader *oh;
3157                                                 oh = (yaffs_ObjectHeader *)buffer;
3158                                                 oh->isShrink = 0;
3159                                                 tags.extraShadows = 0;
3160                                                 tags.extraIsShrinkHeader = 0;
3161                                                 
3162                                                 yaffs_VerifyObjectHeader(object,oh,&tags,1);
3163                                         }
3164
3165                                         newChunk =
3166                                             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3167
3168                                         if (newChunk < 0) {
3169                                                 retVal = YAFFS_FAIL;
3170                                         } else {
3171
3172                                                 /* Ok, now fix up the Tnodes etc. */
3173
3174                                                 if (tags.chunkId == 0) {
3175                                                         /* It's a header */
3176                                                         object->hdrChunk =  newChunk;
3177                                                         object->serial =   tags.serialNumber;
3178                                                 } else {
3179                                                         /* It's a data chunk */
3180                                                         yaffs_PutChunkIntoFile
3181                                                             (object,
3182                                                              tags.chunkId,
3183                                                              newChunk, 0);
3184                                                 }
3185                                         }
3186                                 }
3187
3188                                 if(retVal == YAFFS_OK)
3189                                         yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3190
3191                         }
3192                 }
3193
3194                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3195                 
3196
3197
3198                 /* Do any required cleanups */
3199                 for (i = 0; i < cleanups; i++) {
3200                         /* Time to delete the file too */
3201                         object =
3202                             yaffs_FindObjectByNumber(dev,
3203                                                      dev->gcCleanupList[i]);
3204                         if (object) {
3205                                 yaffs_FreeTnode(dev,
3206                                                 object->variant.fileVariant.
3207                                                 top);
3208                                 object->variant.fileVariant.top = NULL;
3209                                 T(YAFFS_TRACE_GC,
3210                                   (TSTR
3211                                    ("yaffs: About to finally delete object %d"
3212                                     TENDSTR), object->objectId));
3213                                 yaffs_DoGenericObjectDeletion(object);
3214                                 object->myDev->nDeletedFiles--;
3215                         }
3216
3217                 }
3218
3219         }
3220
3221         yaffs_VerifyCollectedBlock(dev,bi,block);
3222           
3223         if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
3224                 T(YAFFS_TRACE_GC,
3225                   (TSTR
3226                    ("gc did not increase free chunks before %d after %d"
3227                     TENDSTR), chunksBefore, chunksAfter));
3228         }
3229
3230         /* If the gc completed then clear the current gcBlock so that we find another. */
3231         if(bi->blockState != YAFFS_BLOCK_STATE_COLLECTING){
3232                 dev->gcBlock = -1;
3233                 dev->gcChunk = 0;
3234         }
3235         
3236         dev->isDoingGC = 0;
3237
3238         return retVal;
3239 }
3240
3241 /* New garbage collector
3242  * If we're very low on erased blocks then we do aggressive garbage collection
3243  * otherwise we do "leasurely" garbage collection.
3244  * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3245  * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3246  *
3247  * The idea is to help clear out space in a more spread-out manner.
3248  * Dunno if it really does anything useful.
3249  */
3250 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
3251 {
3252         int block;
3253         int aggressive;
3254         int gcOk = YAFFS_OK;
3255         int maxTries = 0;
3256         
3257         int checkpointBlockAdjust;
3258
3259         if (dev->isDoingGC) {
3260                 /* Bail out so we don't get recursive gc */
3261                 return YAFFS_OK;
3262         }
3263         
3264         /* This loop should pass the first time.
3265          * We'll only see looping here if the erase of the collected block fails.
3266          */
3267
3268         do {
3269                 maxTries++;
3270                 
3271                 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3272                 if(checkpointBlockAdjust < 0)
3273                         checkpointBlockAdjust = 0;
3274
3275                 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3276                         /* We need a block soon...*/
3277                         aggressive = 1;
3278                 } else {
3279                         /* We're in no hurry */
3280                         aggressive = 0;
3281                 }
3282
3283                 if(dev->gcBlock <= 0){
3284                         dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3285                         dev->gcChunk = 0;
3286                 }
3287                 
3288                 block = dev->gcBlock;
3289
3290                 if (block > 0) {
3291                         dev->garbageCollections++;
3292                         if (!aggressive) {
3293                                 dev->passiveGarbageCollections++;
3294                         }
3295
3296                         T(YAFFS_TRACE_GC,
3297                           (TSTR
3298                            ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3299                            dev->nErasedBlocks, aggressive));
3300
3301                         gcOk = yaffs_GarbageCollectBlock(dev,block,aggressive);
3302                 }
3303
3304                 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3305                         T(YAFFS_TRACE_GC,
3306                           (TSTR
3307                            ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3308                             TENDSTR), dev->nErasedBlocks, maxTries, block));
3309                 }
3310         } while ((dev->nErasedBlocks < dev->nReservedBlocks) && 
3311                  (block > 0) &&
3312                  (maxTries < 2));
3313
3314         return aggressive ? gcOk : YAFFS_OK;
3315 }
3316
3317 /*-------------------------  TAGS --------------------------------*/
3318
3319 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
3320                            int chunkInObject)
3321 {
3322         return (tags->chunkId == chunkInObject &&
3323                 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3324
3325 }
3326
3327
3328 /*-------------------- Data file manipulation -----------------*/
3329
3330 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
3331                                  yaffs_ExtendedTags * tags)
3332 {
3333         /*Get the Tnode, then get the level 0 offset chunk offset */
3334         yaffs_Tnode *tn;
3335         int theChunk = -1;
3336         yaffs_ExtendedTags localTags;
3337         int retVal = -1;
3338
3339         yaffs_Device *dev = in->myDev;
3340
3341         if (!tags) {
3342                 /* Passed a NULL, so use our own tags space */
3343                 tags = &localTags;
3344         }
3345
3346         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3347
3348         if (tn) {
3349                 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3350
3351                 retVal =
3352                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3353                                            chunkInInode);
3354         }
3355         return retVal;
3356 }
3357
3358 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
3359                                           yaffs_ExtendedTags * tags)
3360 {
3361         /* Get the Tnode, then get the level 0 offset chunk offset */
3362         yaffs_Tnode *tn;
3363         int theChunk = -1;
3364         yaffs_ExtendedTags localTags;
3365
3366         yaffs_Device *dev = in->myDev;
3367         int retVal = -1;
3368
3369         if (!tags) {
3370                 /* Passed a NULL, so use our own tags space */
3371                 tags = &localTags;
3372         }
3373
3374         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3375
3376         if (tn) {
3377
3378                 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3379
3380                 retVal =
3381                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3382                                            chunkInInode);
3383
3384                 /* Delete the entry in the filestructure (if found) */
3385                 if (retVal != -1) {
3386                         yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
3387                 }
3388         } else {
3389                 /*T(("No level 0 found for %d\n", chunkInInode)); */
3390         }
3391
3392         if (retVal == -1) {
3393                 /* T(("Could not find %d to delete\n",chunkInInode)); */
3394         }
3395         return retVal;
3396 }
3397
3398 #ifdef YAFFS_PARANOID
3399
3400 static int yaffs_CheckFileSanity(yaffs_Object * in)
3401 {
3402         int chunk;
3403         int nChunks;
3404         int fSize;
3405         int failed = 0;
3406         int objId;
3407         yaffs_Tnode *tn;
3408         yaffs_Tags localTags;
3409         yaffs_Tags *tags = &localTags;
3410         int theChunk;
3411         int chunkDeleted;
3412
3413         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3414                 /* T(("Object not a file\n")); */
3415                 return YAFFS_FAIL;
3416         }
3417
3418         objId = in->objectId;
3419         fSize = in->variant.fileVariant.fileSize;
3420         nChunks =
3421             (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3422
3423         for (chunk = 1; chunk <= nChunks; chunk++) {
3424                 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3425                                            chunk);
3426
3427                 if (tn) {
3428
3429                         theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
3430
3431                         if (yaffs_CheckChunkBits
3432                             (dev, theChunk / dev->nChunksPerBlock,
3433                              theChunk % dev->nChunksPerBlock)) {
3434
3435                                 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3436                                                             tags,
3437                                                             &chunkDeleted);
3438                                 if (yaffs_TagsMatch
3439                                     (tags, in->objectId, chunk, chunkDeleted)) {
3440                                         /* found it; */
3441
3442                                 }
3443                         } else {
3444
3445                                 failed = 1;
3446                         }
3447
3448                 } else {
3449                         /* T(("No level 0 found for %d\n", chunk)); */
3450                 }
3451         }
3452
3453         return failed ? YAFFS_FAIL : YAFFS_OK;
3454 }
3455
3456 #endif
3457
3458 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
3459                                   int chunkInNAND, int inScan)
3460 {
3461         /* NB inScan is zero unless scanning. 
3462          * For forward scanning, inScan is > 0; 
3463          * for backward scanning inScan is < 0
3464          */
3465          
3466         yaffs_Tnode *tn;
3467         yaffs_Device *dev = in->myDev;
3468         int existingChunk;
3469         yaffs_ExtendedTags existingTags;
3470         yaffs_ExtendedTags newTags;
3471         unsigned existingSerial, newSerial;
3472
3473         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3474                 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3475                  * If it is not during Scanning then something went wrong!
3476                  */
3477                 if (!inScan) {
3478                         T(YAFFS_TRACE_ERROR,
3479                           (TSTR
3480                            ("yaffs tragedy:attempt to put data chunk into a non-file"
3481                             TENDSTR)));
3482                         YBUG();
3483                 }
3484
3485                 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3486                 return YAFFS_OK;
3487         }
3488
3489         tn = yaffs_AddOrFindLevel0Tnode(dev, 
3490                                         &in->variant.fileVariant,
3491                                         chunkInInode,
3492                                         NULL);
3493         if (!tn) {
3494                 return YAFFS_FAIL;
3495         }
3496
3497         existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3498
3499         if (inScan != 0) {
3500                 /* If we're scanning then we need to test for duplicates
3501                  * NB This does not need to be efficient since it should only ever 
3502                  * happen when the power fails during a write, then only one
3503                  * chunk should ever be affected.
3504                  *
3505                  * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3506                  * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3507                  */
3508
3509                 if (existingChunk > 0) {
3510                         /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3511                          *    thus we have to do a FindChunkInFile to get the real chunk id.
3512                          *
3513                          * We have a duplicate now we need to decide which one to use:
3514                          *
3515                          * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3516                          * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3517                          * YAFFS1: Get both sets of tags and compare serial numbers.
3518                          */
3519
3520                         if (inScan > 0) {
3521                                 /* Only do this for forward scanning */
3522                                 yaffs_ReadChunkWithTagsFromNAND(dev,
3523                                                                 chunkInNAND,
3524                                                                 NULL, &newTags);
3525
3526                                 /* Do a proper find */
3527                                 existingChunk =
3528                                     yaffs_FindChunkInFile(in, chunkInInode,
3529                                                           &existingTags);
3530                         }
3531
3532                         if (existingChunk <= 0) {
3533                                 /*Hoosterman - how did this happen? */
3534
3535                                 T(YAFFS_TRACE_ERROR,
3536                                   (TSTR
3537                                    ("yaffs tragedy: existing chunk < 0 in scan"
3538                                     TENDSTR)));
3539
3540                         }
3541
3542                         /* NB The deleted flags should be false, otherwise the chunks will 
3543                          * not be loaded during a scan
3544                          */
3545
3546                         if(inScan > 0) {
3547                                 newSerial = newTags.serialNumber;
3548                                 existingSerial = existingTags.serialNumber;
3549                         }
3550
3551                         if ((inScan > 0) &&
3552                             (in->myDev->isYaffs2 ||
3553                              existingChunk <= 0 ||
3554                              ((existingSerial + 1) & 3) == newSerial)) {
3555                                 /* Forward scanning.                            
3556                                  * Use new
3557                                  * Delete the old one and drop through to update the tnode
3558                                  */
3559                                 yaffs_DeleteChunk(dev, existingChunk, 1,
3560                                                   __LINE__);
3561                         } else {
3562                                 /* Backward scanning or we want to use the existing one
3563                                  * Use existing.
3564                                  * Delete the new one and return early so that the tnode isn't changed
3565                                  */
3566                                 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3567                                                   __LINE__);
3568                                 return YAFFS_OK;
3569                         }
3570                 }
3571
3572         }
3573
3574         if (existingChunk == 0) {
3575                 in->nDataChunks++;
3576         }
3577
3578         yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
3579
3580         return YAFFS_OK;
3581 }
3582
3583 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
3584                                          __u8 * buffer)
3585 {
3586         int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3587
3588         if (chunkInNAND >= 0) {
3589                 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3590                                                        buffer,NULL);
3591         } else {
3592                 T(YAFFS_TRACE_NANDACCESS,
3593                   (TSTR("Chunk %d not found zero instead" TENDSTR),
3594                    chunkInNAND));
3595                 /* get sane (zero) data if you read a hole */
3596                 memset(buffer, 0, in->myDev->nDataBytesPerChunk);       
3597                 return 0;
3598         }
3599
3600 }
3601
3602 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
3603 {
3604         int block;
3605         int page;
3606         yaffs_ExtendedTags tags;
3607         yaffs_BlockInfo *bi;
3608
3609         if (chunkId <= 0)
3610                 return;
3611                 
3612
3613         dev->nDeletions++;
3614         block = chunkId / dev->nChunksPerBlock;
3615         page = chunkId % dev->nChunksPerBlock;
3616
3617
3618         if(!yaffs_CheckChunkBit(dev,block,page))
3619                 T(YAFFS_TRACE_VERIFY,
3620                         (TSTR("Deleting invalid chunk %d"TENDSTR),
3621                          chunkId));
3622
3623         bi = yaffs_GetBlockInfo(dev, block);
3624
3625         T(YAFFS_TRACE_DELETION,
3626           (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3627
3628         if (markNAND &&
3629             bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3630
3631                 yaffs_InitialiseTags(&tags);
3632
3633                 tags.chunkDeleted = 1;
3634
3635                 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3636                 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3637         } else {
3638                 dev->nUnmarkedDeletions++;
3639         }
3640
3641         /* Pull out of the management area.
3642          * If the whole block became dirty, this will kick off an erasure.
3643          */
3644         if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3645             bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3646             bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3647             bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3648                 dev->nFreeChunks++;
3649
3650                 yaffs_ClearChunkBit(dev, block, page);
3651
3652                 bi->pagesInUse--;
3653
3654                 if (bi->pagesInUse == 0 &&
3655                     !bi->hasShrinkHeader &&
3656                     bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3657                     bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3658                         yaffs_BlockBecameDirty(dev, block);
3659                 }
3660
3661         } else {
3662                 /* T(("Bad news deleting chunk %d\n",chunkId)); */
3663         }
3664
3665 }
3666
3667 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
3668                                         const __u8 * buffer, int nBytes,
3669                                         int useReserve)
3670 {
3671         /* Find old chunk Need to do this to get serial number
3672          * Write new one and patch into tree.
3673          * Invalidate old tags.
3674          */
3675
3676         int prevChunkId;
3677         yaffs_ExtendedTags prevTags;
3678
3679         int newChunkId;
3680         yaffs_ExtendedTags newTags;
3681
3682         yaffs_Device *dev = in->myDev;
3683
3684         yaffs_CheckGarbageCollection(dev);
3685
3686         /* Get the previous chunk at this location in the file if it exists */
3687         prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3688
3689         /* Set up new tags */
3690         yaffs_InitialiseTags(&newTags);
3691
3692         newTags.chunkId = chunkInInode;
3693         newTags.objectId = in->objectId;
3694         newTags.serialNumber =
3695             (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
3696         newTags.byteCount = nBytes;
3697         
3698         if(nBytes < 1 || nBytes > dev->totalBytesPerChunk){
3699           T(YAFFS_TRACE_ERROR,
3700           (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3701           while(1){}
3702         }
3703         
3704         
3705
3706         newChunkId =
3707             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3708                                               useReserve);
3709
3710         if (newChunkId >= 0) {
3711                 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3712
3713                 if (prevChunkId >= 0) {
3714                         yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3715
3716                 }
3717
3718                 yaffs_CheckFileSanity(in);
3719         }
3720         return newChunkId;
3721
3722 }
3723
3724 /* UpdateObjectHeader updates the header on NAND for an object.
3725  * If name is not NULL, then that new name is used.
3726  */
3727 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
3728                              int isShrink, int shadows)
3729 {
3730
3731         yaffs_BlockInfo *bi;
3732
3733         yaffs_Device *dev = in->myDev;
3734
3735         int prevChunkId;
3736         int retVal = 0;
3737         int result = 0;
3738
3739         int newChunkId;
3740         yaffs_ExtendedTags newTags;
3741         yaffs_ExtendedTags oldTags;
3742
3743         __u8 *buffer = NULL;
3744         YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3745
3746         yaffs_ObjectHeader *oh = NULL;
3747         
3748         yaffs_strcpy(oldName,_Y("silly old name"));
3749
3750
3751         if (!in->fake || 
3752             in == dev->rootDir || /* The rootDir should also be saved */
3753             force) {
3754
3755                 yaffs_CheckGarbageCollection(dev);
3756                 yaffs_CheckObjectDetailsLoaded(in);
3757
3758                 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3759                 oh = (yaffs_ObjectHeader *) buffer;
3760
3761                 prevChunkId = in->hdrChunk;
3762
3763                 if (prevChunkId > 0) {
3764                         result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3765                                                         buffer, &oldTags);
3766                         
3767                         yaffs_VerifyObjectHeader(in,oh,&oldTags,0);
3768                                                                                 
3769                         memcpy(oldName, oh->name, sizeof(oh->name));
3770                 }
3771
3772                 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3773
3774                 oh->type = in->variantType;
3775                 oh->yst_mode = in->yst_mode;
3776                 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3777
3778 #ifdef CONFIG_YAFFS_WINCE
3779                 oh->win_atime[0] = in->win_atime[0];
3780                 oh->win_ctime[0] = in->win_ctime[0];
3781                 oh->win_mtime[0] = in->win_mtime[0];
3782                 oh->win_atime[1] = in->win_atime[1];
3783                 oh->win_ctime[1] = in->win_ctime[1];
3784                 oh->win_mtime[1] = in->win_mtime[1];
3785 #else
3786                 oh->yst_uid = in->yst_uid;
3787                 oh->yst_gid = in->yst_gid;
3788                 oh->yst_atime = in->yst_atime;
3789                 oh->yst_mtime = in->yst_mtime;
3790                 oh->yst_ctime = in->yst_ctime;
3791                 oh->yst_rdev = in->yst_rdev;
3792 #endif
3793                 if (in->parent) {
3794                         oh->parentObjectId = in->parent->objectId;
3795                 } else {
3796                         oh->parentObjectId = 0;
3797                 }
3798
3799                 if (name && *name) {
3800                         memset(oh->name, 0, sizeof(oh->name));
3801                         yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3802                 } else if (prevChunkId>=0) {
3803                         memcpy(oh->name, oldName, sizeof(oh->name));
3804                 } else {
3805                         memset(oh->name, 0, sizeof(oh->name));
3806                 }
3807
3808                 oh->isShrink = isShrink;
3809
3810                 switch (in->variantType) {
3811                 case YAFFS_OBJECT_TYPE_UNKNOWN:
3812                         /* Should not happen */
3813                         break;
3814                 case YAFFS_OBJECT_TYPE_FILE:
3815                         oh->fileSize =
3816                             (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3817                              || oh->parentObjectId ==
3818                              YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3819                             fileVariant.fileSize;
3820                         break;
3821                 case YAFFS_OBJECT_TYPE_HARDLINK:
3822                         oh->equivalentObjectId =
3823                             in->variant.hardLinkVariant.equivalentObjectId;
3824                         break;
3825                 case YAFFS_OBJECT_TYPE_SPECIAL:
3826                         /* Do nothing */
3827                         break;
3828                 case YAFFS_OBJECT_TYPE_DIRECTORY:
3829                         /* Do nothing */
3830                         break;
3831                 case YAFFS_OBJECT_TYPE_SYMLINK:
3832                         yaffs_strncpy(oh->alias,
3833                                       in->variant.symLinkVariant.alias,
3834                                       YAFFS_MAX_ALIAS_LENGTH);
3835                         oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3836                         break;
3837                 }
3838
3839                 /* Tags */
3840                 yaffs_InitialiseTags(&newTags);
3841                 in->serial++;
3842                 newTags.chunkId = 0;
3843                 newTags.objectId = in->objectId;
3844                 newTags.serialNumber = in->serial;
3845
3846                 /* Add extra info for file header */
3847
3848                 newTags.extraHeaderInfoAvailable = 1;
3849                 newTags.extraParentObjectId = oh->parentObjectId;
3850                 newTags.extraFileLength = oh->fileSize;
3851                 newTags.extraIsShrinkHeader = oh->isShrink;
3852                 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3853                 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3854                 newTags.extraObjectType = in->variantType;
3855
3856                 yaffs_VerifyObjectHeader(in,oh,&newTags,1);
3857
3858                 /* Create new chunk in NAND */
3859                 newChunkId =
3860                     yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3861                                                       (prevChunkId >= 0) ? 1 : 0);
3862
3863                 if (newChunkId >= 0) {
3864
3865                         in->hdrChunk = newChunkId;
3866
3867                         if (prevChunkId >= 0) {
3868                                 yaffs_DeleteChunk(dev, prevChunkId, 1,
3869                                                   __LINE__);
3870                         }
3871
3872                         if(!yaffs_ObjectHasCachedWriteData(in))
3873                                 in->dirty = 0;
3874
3875                         /* If this was a shrink, then mark the block that the chunk lives on */
3876                         if (isShrink) {
3877                                 bi = yaffs_GetBlockInfo(in->myDev,
3878                                                         newChunkId /in->myDev-> nChunksPerBlock);
3879                                 bi->hasShrinkHeader = 1;
3880                         }
3881
3882                 }
3883
3884                 retVal = newChunkId;
3885
3886         }
3887
3888         if (buffer)
3889                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3890
3891         return retVal;
3892 }
3893
3894 /*------------------------ Short Operations Cache ----------------------------------------
3895  *   In many situations where there is no high level buffering (eg WinCE) a lot of
3896  *   reads might be short sequential reads, and a lot of writes may be short 
3897  *   sequential writes. eg. scanning/writing a jpeg file.
3898  *   In these cases, a short read/write cache can provide a huge perfomance benefit 
3899  *   with dumb-as-a-rock code.
3900  *   In Linux, the page cache provides read buffering aand the short op cache provides write 
3901  *   buffering.
3902  *
3903  *   There are a limited number (~10) of cache chunks per device so that we don't
3904  *   need a very intelligent search.
3905  */
3906
3907 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3908 {
3909         yaffs_Device *dev = obj->myDev;
3910         int i;
3911         yaffs_ChunkCache *cache;
3912         int nCaches = obj->myDev->nShortOpCaches;
3913         
3914         for(i = 0; i < nCaches; i++){
3915                 cache = &dev->srCache[i];
3916                 if (cache->object == obj &&
3917                     cache->dirty)
3918                         return 1;
3919         }
3920         
3921         return 0;
3922 }
3923
3924
3925 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3926 {
3927         yaffs_Device *dev = obj->myDev;
3928         int lowest = -99;       /* Stop compiler whining. */
3929         int i;
3930         yaffs_ChunkCache *cache;
3931         int chunkWritten = 0;
3932         int nCaches = obj->myDev->nShortOpCaches;
3933
3934         if (nCaches > 0) {
3935                 do {
3936                         cache = NULL;
3937
3938                         /* Find the dirty cache for this object with the lowest chunk id. */
3939                         for (i = 0; i < nCaches; i++) {
3940                                 if (dev->srCache[i].object == obj &&
3941                                     dev->srCache[i].dirty) {
3942                                         if (!cache
3943                                             || dev->srCache[i].chunkId <
3944                                             lowest) {
3945                                                 cache = &dev->srCache[i];
3946                                                 lowest = cache->chunkId;
3947                                         }
3948                                 }
3949                         }
3950
3951                         if (cache && !cache->locked) {
3952                                 /* Write it out and free it up */
3953
3954                                 chunkWritten =
3955                                     yaffs_WriteChunkDataToObject(cache->object,
3956                                                                  cache->chunkId,
3957                                                                  cache->data,
3958                                                                  cache->nBytes,
3959                                                                  1);
3960                                 cache->dirty = 0;
3961                                 cache->object = NULL;
3962                         }
3963
3964                 } while (cache && chunkWritten > 0);
3965
3966                 if (cache) {
3967                         /* Hoosterman, disk full while writing cache out. */
3968                         T(YAFFS_TRACE_ERROR,
3969                           (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3970
3971                 }
3972         }
3973
3974 }
3975
3976 /*yaffs_FlushEntireDeviceCache(dev)
3977  *
3978  *
3979  */
3980
3981 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3982 {
3983         yaffs_Object *obj;
3984         int nCaches = dev->nShortOpCaches;
3985         int i;
3986         
3987         /* Find a dirty object in the cache and flush it...
3988          * until there are no further dirty objects.
3989          */
3990         do {
3991                 obj = NULL;
3992                 for( i = 0; i < nCaches && !obj; i++) {
3993                         if (dev->srCache[i].object &&
3994                             dev->srCache[i].dirty)
3995                                 obj = dev->srCache[i].object;
3996                             
3997                 }
3998                 if(obj)
3999                         yaffs_FlushFilesChunkCache(obj);
4000                         
4001         } while(obj);
4002         
4003 }
4004
4005
4006 /* Grab us a cache chunk for use.
4007  * First look for an empty one. 
4008  * Then look for the least recently used non-dirty one.
4009  * Then look for the least recently used dirty one...., flush and look again.
4010  */
4011 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
4012 {
4013         int i;
4014
4015         if (dev->nShortOpCaches > 0) {
4016                 for (i = 0; i < dev->nShortOpCaches; i++) {
4017                         if (!dev->srCache[i].object) 
4018                                 return &dev->srCache[i];
4019                 }
4020         }
4021
4022         return NULL;
4023 }
4024
4025 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
4026 {
4027         yaffs_ChunkCache *cache;
4028         yaffs_Object *theObj;
4029         int usage;
4030         int i;
4031         int pushout;
4032
4033         if (dev->nShortOpCaches > 0) {
4034                 /* Try find a non-dirty one... */
4035
4036                 cache = yaffs_GrabChunkCacheWorker(dev);
4037
4038                 if (!cache) {
4039                         /* They were all dirty, find the last recently used object and flush
4040                          * its cache, then  find again.
4041                          * NB what's here is not very accurate, we actually flush the object
4042                          * the last recently used page.
4043                          */
4044
4045                         /* With locking we can't assume we can use entry zero */
4046
4047                         theObj = NULL;
4048                         usage = -1;
4049                         cache = NULL;
4050                         pushout = -1;
4051
4052                         for (i = 0; i < dev->nShortOpCaches; i++) {
4053                                 if (dev->srCache[i].object &&
4054                                     !dev->srCache[i].locked &&
4055                                     (dev->srCache[i].lastUse < usage || !cache))
4056                                 {
4057                                         usage = dev->srCache[i].lastUse;
4058                                         theObj = dev->srCache[i].object;
4059                                         cache = &dev->srCache[i];
4060                                         pushout = i;
4061                                 }
4062                         }
4063
4064                         if (!cache || cache->dirty) {
4065                                 /* Flush and try again */
4066                                 yaffs_FlushFilesChunkCache(theObj);
4067                                 cache = yaffs_GrabChunkCacheWorker(dev);
4068                         }
4069
4070                 }
4071                 return cache;
4072         } else
4073                 return NULL;
4074
4075 }
4076
4077 /* Find a cached chunk */
4078 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
4079                                               int chunkId)
4080 {
4081         yaffs_Device *dev = obj->myDev;
4082         int i;
4083         if (dev->nShortOpCaches > 0) {
4084                 for (i = 0; i < dev->nShortOpCaches; i++) {
4085                         if (dev->srCache[i].object == obj &&
4086                             dev->srCache[i].chunkId == chunkId) {
4087                                 dev->cacheHits++;
4088
4089                                 return &dev->srCache[i];
4090                         }
4091                 }
4092         }
4093         return NULL;
4094 }
4095
4096 /* Mark the chunk for the least recently used algorithym */
4097 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
4098                                 int isAWrite)
4099 {
4100
4101         if (dev->nShortOpCaches > 0) {
4102                 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4103                         /* Reset the cache usages */
4104                         int i;
4105                         for (i = 1; i < dev->nShortOpCaches; i++) {
4106                                 dev->srCache[i].lastUse = 0;
4107                         }
4108                         dev->srLastUse = 0;
4109                 }
4110
4111                 dev->srLastUse++;
4112
4113                 cache->lastUse = dev->srLastUse;
4114
4115                 if (isAWrite) {
4116                         cache->dirty = 1;
4117                 }
4118         }
4119 }
4120
4121 /* Invalidate a single cache page.
4122  * Do this when a whole page gets written,
4123  * ie the short cache for this page is no longer valid.
4124  */
4125 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
4126 {
4127         if (object->myDev->nShortOpCaches > 0) {
4128                 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4129
4130                 if (cache) {
4131                         cache->object = NULL;
4132                 }
4133         }
4134 }
4135
4136 /* Invalidate all the cache pages associated with this object
4137  * Do this whenever ther file is deleted or resized.
4138  */
4139 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
4140 {
4141         int i;
4142         yaffs_Device *dev = in->myDev;
4143
4144         if (dev->nShortOpCaches > 0) {
4145                 /* Invalidate it. */
4146                 for (i = 0; i < dev->nShortOpCaches; i++) {
4147                         if (dev->srCache[i].object == in) {
4148                                 dev->srCache[i].object = NULL;
4149                         }
4150                 }
4151         }
4152 }
4153
4154 /*--------------------- Checkpointing --------------------*/
4155
4156
4157 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
4158 {
4159         yaffs_CheckpointValidity cp;
4160         
4161         memset(&cp,0,sizeof(cp));
4162         
4163         cp.structType = sizeof(cp);
4164         cp.magic = YAFFS_MAGIC;
4165         cp.version = YAFFS_CHECKPOINT_VERSION;
4166         cp.head = (head) ? 1 : 0;
4167         
4168         return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
4169                 1 : 0;
4170 }
4171
4172 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4173 {
4174         yaffs_CheckpointValidity cp;
4175         int ok;
4176         
4177         ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4178         
4179         if(ok)
4180                 ok = (cp.structType == sizeof(cp)) &&
4181                      (cp.magic == YAFFS_MAGIC) &&
4182                      (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4183                      (cp.head == ((head) ? 1 : 0));
4184         return ok ? 1 : 0;
4185 }
4186
4187 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp, 
4188                                            yaffs_Device *dev)
4189 {
4190         cp->nErasedBlocks = dev->nErasedBlocks;
4191         cp->allocationBlock = dev->allocationBlock;
4192         cp->allocationPage = dev->allocationPage;
4193         cp->nFreeChunks = dev->nFreeChunks;
4194         
4195         cp->nDeletedFiles = dev->nDeletedFiles;
4196         cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4197         cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4198         cp->sequenceNumber = dev->sequenceNumber;
4199         cp->oldestDirtySequence = dev->oldestDirtySequence;
4200         
4201 }
4202
4203 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4204                                            yaffs_CheckpointDevice *cp)
4205 {
4206         dev->nErasedBlocks = cp->nErasedBlocks;
4207         dev->allocationBlock = cp->allocationBlock;
4208         dev->allocationPage = cp->allocationPage;
4209         dev->nFreeChunks = cp->nFreeChunks;
4210         
4211         dev->nDeletedFiles = cp->nDeletedFiles;
4212         dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4213         dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4214         dev->sequenceNumber = cp->sequenceNumber;
4215         dev->oldestDirtySequence = cp->oldestDirtySequence;
4216 }
4217
4218
4219 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4220 {
4221         yaffs_CheckpointDevice cp;
4222         __u32 nBytes;
4223         __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4224
4225         int ok;
4226                 
4227         /* Write device runtime values*/
4228         yaffs_DeviceToCheckpointDevice(&cp,dev);
4229         cp.structType = sizeof(cp);
4230         
4231         ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4232         
4233         /* Write block info */
4234         if(ok) {
4235                 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4236                 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
4237         }
4238                 
4239         /* Write chunk bits */          
4240         if(ok) {
4241                 nBytes = nBlocks * dev->chunkBitmapStride;
4242                 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
4243         }
4244         return   ok ? 1 : 0;
4245
4246 }
4247
4248 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4249 {
4250         yaffs_CheckpointDevice cp;
4251         __u32 nBytes;
4252         __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4253
4254         int ok; 
4255         
4256         ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4257         if(!ok)
4258                 return 0;
4259                 
4260         if(cp.structType != sizeof(cp))
4261                 return 0;
4262                 
4263         
4264         yaffs_CheckpointDeviceToDevice(dev,&cp);
4265         
4266         nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4267         
4268         ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
4269         
4270         if(!ok)
4271                 return 0;
4272         nBytes = nBlocks * dev->chunkBitmapStride;
4273         
4274         ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
4275         
4276         return ok ? 1 : 0;
4277 }
4278
4279 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4280                                            yaffs_Object *obj)
4281 {
4282
4283         cp->objectId = obj->objectId;
4284         cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4285         cp->hdrChunk = obj->hdrChunk;
4286         cp->variantType = obj->variantType;
4287         cp->deleted = obj->deleted;
4288         cp->softDeleted = obj->softDeleted;
4289         cp->unlinked = obj->unlinked;
4290         cp->fake = obj->fake;
4291         cp->renameAllowed = obj->renameAllowed;
4292         cp->unlinkAllowed = obj->unlinkAllowed;
4293         cp->serial = obj->serial;
4294         cp->nDataChunks = obj->nDataChunks;
4295         
4296         if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4297                 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4298         else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4299                 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4300 }
4301
4302 static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
4303 {
4304
4305         yaffs_Object *parent;
4306         
4307         obj->objectId = cp->objectId;
4308         
4309         if(cp->parentId)
4310                 parent = yaffs_FindOrCreateObjectByNumber(
4311                                         obj->myDev,
4312                                         cp->parentId,
4313                                         YAFFS_OBJECT_TYPE_DIRECTORY);
4314         else
4315                 parent = NULL;
4316                 
4317         if(parent)
4318                 yaffs_AddObjectToDirectory(parent, obj);
4319
4320         obj->hdrChunk = cp->hdrChunk;
4321         obj->variantType = cp->variantType;
4322         obj->deleted = cp->deleted;
4323         obj->softDeleted = cp->softDeleted;
4324         obj->unlinked = cp->unlinked;
4325         obj->fake = cp->fake;
4326         obj->renameAllowed = cp->renameAllowed;
4327         obj->unlinkAllowed = cp->unlinkAllowed;
4328         obj->serial = cp->serial;
4329         obj->nDataChunks = cp->nDataChunks;
4330         
4331         if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4332                 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4333         else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4334                 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4335
4336         if(obj->hdrChunk > 0)
4337                 obj->lazyLoaded = 1;
4338 }
4339
4340
4341
4342 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
4343                                         __u32 level, int chunkOffset)
4344 {
4345         int i;
4346         yaffs_Device *dev = in->myDev;
4347         int ok = 1;
4348         int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4349
4350         if(tnodeSize < sizeof(yaffs_Tnode))
4351                 tnodeSize = sizeof(yaffs_Tnode);
4352         
4353
4354         if (tn) {
4355                 if (level > 0) {
4356
4357                         for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
4358                                 if (tn->internal[i]) {
4359                                         ok = yaffs_CheckpointTnodeWorker(in,
4360                                                         tn->internal[i],
4361                                                         level - 1,
4362                                                         (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4363                                 }
4364                         }
4365                 } else if (level == 0) {
4366                         __u32 baseOffset = chunkOffset <<  YAFFS_TNODES_LEVEL0_BITS;
4367                         ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
4368                         if(ok)
4369                                 ok = (yaffs_CheckpointWrite(dev,tn,tnodeSize) == tnodeSize);
4370                 }
4371         }
4372
4373         return ok;
4374
4375 }
4376
4377 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4378 {
4379         __u32 endMarker = ~0;
4380         int ok = 1;
4381         
4382         if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4383                 ok = yaffs_CheckpointTnodeWorker(obj,
4384                                             obj->variant.fileVariant.top,
4385                                             obj->variant.fileVariant.topLevel,
4386                                             0);
4387                 if(ok)
4388                         ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) == 
4389                                 sizeof(endMarker));
4390         }
4391         
4392         return ok ? 1 : 0;
4393 }
4394
4395 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4396 {
4397         __u32 baseChunk;
4398         int ok = 1;
4399         yaffs_Device *dev = obj->myDev;
4400         yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4401         yaffs_Tnode *tn;
4402         int nread = 0;
4403         int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4404
4405         if(tnodeSize < sizeof(yaffs_Tnode))
4406                 tnodeSize = sizeof(yaffs_Tnode);
4407
4408         ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4409         
4410         while(ok && (~baseChunk)){
4411                 nread++;
4412                 /* Read level 0 tnode */
4413                 
4414                 
4415                 tn = yaffs_GetTnodeRaw(dev);
4416                 if(tn)
4417                         ok = (yaffs_CheckpointRead(dev,tn,tnodeSize) == tnodeSize);
4418                 else
4419                         ok = 0;
4420                         
4421                 if(tn && ok){
4422                         ok = yaffs_AddOrFindLevel0Tnode(dev,
4423                                                         fileStructPtr,
4424                                                         baseChunk,
4425                                                         tn) ? 1 : 0;
4426                                                         
4427                 }
4428                         
4429                 if(ok)
4430                         ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4431                 
4432         }
4433
4434         T(YAFFS_TRACE_CHECKPOINT,(
4435                 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4436                 nread,baseChunk,ok));
4437
4438         return ok ? 1 : 0;      
4439 }
4440  
4441
4442 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4443 {
4444         yaffs_Object *obj;
4445         yaffs_CheckpointObject cp;
4446         int i;
4447         int ok = 1;
4448         struct ylist_head *lh;
4449
4450         
4451         /* Iterate through the objects in each hash entry,
4452          * dumping them to the checkpointing stream.
4453          */
4454          
4455          for(i = 0; ok &&  i <  YAFFS_NOBJECT_BUCKETS; i++){
4456                 ylist_for_each(lh, &dev->objectBucket[i].list) {
4457                         if (lh) {
4458                                 obj = ylist_entry(lh, yaffs_Object, hashLink);
4459                                 if (!obj->deferedFree) {
4460                                         yaffs_ObjectToCheckpointObject(&cp,obj);
4461                                         cp.structType = sizeof(cp);
4462
4463                                         T(YAFFS_TRACE_CHECKPOINT,(
4464                                                 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
4465                                                 cp.objectId,cp.parentId,cp.variantType,cp.hdrChunk,(unsigned) obj));
4466
4467                                         ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4468                                         
4469                                         if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4470                                                 ok = yaffs_WriteCheckpointTnodes(obj);
4471                                         }
4472                                 }
4473                         }
4474                 }
4475          }
4476          
4477          /* Dump end of list */
4478         memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
4479         cp.structType = sizeof(cp);
4480         
4481         if(ok)
4482                 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4483                 
4484         return ok ? 1 : 0;
4485 }
4486
4487 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4488 {
4489         yaffs_Object *obj;
4490         yaffs_CheckpointObject cp;
4491         int ok = 1;
4492         int done = 0;
4493         yaffs_Object *hardList = NULL;
4494         
4495         while(ok && !done) {
4496                 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4497                 if(cp.structType != sizeof(cp)) {
4498                         T(YAFFS_TRACE_CHECKPOINT,(TSTR("struct size %d instead of %d ok %d"TENDSTR),
4499                                 cp.structType,sizeof(cp),ok));
4500                         ok = 0;
4501                 }
4502                         
4503                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4504                         cp.objectId,cp.parentId,cp.variantType,cp.hdrChunk));
4505
4506                 if(ok && cp.objectId == ~0)
4507                         done = 1;
4508                 else if(ok){
4509                         obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
4510                         if(obj) {
4511                                 yaffs_CheckpointObjectToObject(obj,&cp);
4512                                 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4513                                         ok = yaffs_ReadCheckpointTnodes(obj);
4514                                 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4515                                         obj->hardLinks.next =
4516                                                     (struct ylist_head *)
4517                                                     hardList;
4518                                         hardList = obj;
4519                                 }
4520                            
4521                         }
4522                 }
4523         }
4524         
4525         if(ok)
4526                 yaffs_HardlinkFixup(dev,hardList);
4527         
4528         return ok ? 1 : 0;
4529 }
4530
4531 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4532 {
4533         __u32 checkpointSum;
4534         int ok;
4535         
4536         yaffs_GetCheckpointSum(dev,&checkpointSum);
4537         
4538         ok = (yaffs_CheckpointWrite(dev,&checkpointSum,sizeof(checkpointSum)) == sizeof(checkpointSum));
4539         
4540         if(!ok)
4541                 return 0;
4542         
4543         return 1;
4544 }
4545
4546 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4547 {
4548         __u32 checkpointSum0;
4549         __u32 checkpointSum1;
4550         int ok;
4551         
4552         yaffs_GetCheckpointSum(dev,&checkpointSum0);
4553         
4554         ok = (yaffs_CheckpointRead(dev,&checkpointSum1,sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4555         
4556         if(!ok)
4557                 return 0;
4558                 
4559         if(checkpointSum0 != checkpointSum1)
4560                 return 0;
4561         
4562         return 1;
4563 }
4564
4565
4566 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4567 {
4568
4569         int ok = 1;
4570         
4571         if(dev->skipCheckpointWrite || !dev->isYaffs2){
4572                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint write" TENDSTR)));
4573                 ok = 0;
4574         }
4575                 
4576         if(ok)
4577                 ok = yaffs_CheckpointOpen(dev,1);
4578         
4579         if(ok){
4580                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4581                 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
4582         }
4583         if(ok){
4584                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint device" TENDSTR)));
4585                 ok = yaffs_WriteCheckpointDevice(dev);
4586         }
4587         if(ok){
4588                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint objects" TENDSTR)));
4589                 ok = yaffs_WriteCheckpointObjects(dev);
4590         }
4591         if(ok){
4592                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4593                 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
4594         }
4595         
4596         if(ok){
4597                 ok = yaffs_WriteCheckpointSum(dev);
4598         }
4599         
4600         
4601         if(!yaffs_CheckpointClose(dev))
4602                  ok = 0;
4603                  
4604         if(ok)
4605                 dev->isCheckpointed = 1;
4606          else 
4607                 dev->isCheckpointed = 0;
4608
4609         return dev->isCheckpointed;
4610 }
4611
4612 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4613 {
4614         int ok = 1;
4615         
4616         if(dev->skipCheckpointRead || !dev->isYaffs2){
4617                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint read" TENDSTR)));
4618                 ok = 0;
4619         }
4620         
4621         if(ok)
4622                 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
4623         
4624         if(ok){
4625                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));   
4626                 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
4627         }
4628         if(ok){
4629                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint device" TENDSTR)));
4630                 ok = yaffs_ReadCheckpointDevice(dev);
4631         }
4632         if(ok){
4633                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint objects" TENDSTR)));    
4634                 ok = yaffs_ReadCheckpointObjects(dev);
4635         }
4636         if(ok){
4637                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4638                 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
4639         }
4640         
4641         if(ok){
4642                 ok = yaffs_ReadCheckpointSum(dev);
4643                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint checksum %d" TENDSTR),ok));
4644         }
4645
4646         if(!yaffs_CheckpointClose(dev))
4647                 ok = 0;
4648
4649         if(ok)
4650                 dev->isCheckpointed = 1;
4651          else 
4652                 dev->isCheckpointed = 0;
4653
4654         return ok ? 1 : 0;
4655
4656 }
4657
4658 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4659 {
4660         if(dev->isCheckpointed || 
4661            dev->blocksInCheckpoint > 0){
4662                 dev->isCheckpointed = 0;
4663                 yaffs_CheckpointInvalidateStream(dev);
4664                 if(dev->superBlock && dev->markSuperBlockDirty)
4665                         dev->markSuperBlockDirty(dev->superBlock);
4666         }
4667 }
4668
4669
4670 int yaffs_CheckpointSave(yaffs_Device *dev)
4671 {
4672
4673         T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4674
4675         yaffs_VerifyObjects(dev);
4676         yaffs_VerifyBlocks(dev);
4677         yaffs_VerifyFreeChunks(dev);
4678
4679         if(!dev->isCheckpointed) {
4680                 yaffs_InvalidateCheckpoint(dev);
4681                 yaffs_WriteCheckpointData(dev);
4682         }
4683         
4684         T(YAFFS_TRACE_ALWAYS,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4685
4686         return dev->isCheckpointed;
4687 }
4688
4689 int yaffs_CheckpointRestore(yaffs_Device *dev)
4690 {
4691         int retval;
4692         T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4693                 
4694         retval = yaffs_ReadCheckpointData(dev);
4695
4696         if(dev->isCheckpointed){
4697                 yaffs_VerifyObjects(dev);
4698                 yaffs_VerifyBlocks(dev);
4699                 yaffs_VerifyFreeChunks(dev);
4700         }
4701
4702         T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4703         
4704         return retval;
4705 }
4706
4707 /*--------------------- File read/write ------------------------
4708  * Read and write have very similar structures.
4709  * In general the read/write has three parts to it
4710  * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4711  * Some complete chunks
4712  * An incomplete chunk to end off with
4713  *
4714  * Curve-balls: the first chunk might also be the last chunk.
4715  */
4716
4717 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, loff_t offset,
4718                            int nBytes)
4719 {
4720
4721         int chunk;
4722         __u32 start;
4723         int nToCopy;
4724         int n = nBytes;
4725         int nDone = 0;
4726         yaffs_ChunkCache *cache;
4727
4728         yaffs_Device *dev;
4729
4730         dev = in->myDev;
4731
4732         while (n > 0) {
4733                 //chunk = offset / dev->nDataBytesPerChunk + 1;
4734                 //start = offset % dev->nDataBytesPerChunk;
4735                 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4736                 chunk++;
4737
4738                 /* OK now check for the curveball where the start and end are in
4739                  * the same chunk.      
4740                  */
4741                 if ((start + n) < dev->nDataBytesPerChunk) {
4742                         nToCopy = n;
4743                 } else {
4744                         nToCopy = dev->nDataBytesPerChunk - start;
4745                 }
4746
4747                 cache = yaffs_FindChunkCache(in, chunk);
4748
4749                 /* If the chunk is already in the cache or it is less than a whole chunk
4750                  * or we're using inband tags then use the cache (if there is caching)
4751                  * else bypass the cache.
4752                  */
4753                 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4754                         if (dev->nShortOpCaches > 0) {
4755
4756                                 /* If we can't find the data in the cache, then load it up. */
4757
4758                                 if (!cache) {
4759                                         cache = yaffs_GrabChunkCache(in->myDev);
4760                                         cache->object = in;
4761                                         cache->chunkId = chunk;
4762                                         cache->dirty = 0;
4763                                         cache->locked = 0;
4764                                         yaffs_ReadChunkDataFromObject(in, chunk,
4765                                                                       cache->
4766                                                                       data);
4767                                         cache->nBytes = 0;
4768                                 }
4769
4770                                 yaffs_UseChunkCache(dev, cache, 0);
4771
4772                                 cache->locked = 1;
4773
4774 #ifdef CONFIG_YAFFS_WINCE
4775                                 yfsd_UnlockYAFFS(TRUE);
4776 #endif
4777                                 memcpy(buffer, &cache->data[start], nToCopy);
4778
4779 #ifdef CONFIG_YAFFS_WINCE
4780                                 yfsd_LockYAFFS(TRUE);
4781 #endif
4782                                 cache->locked = 0;
4783                         } else {
4784                                 /* Read into the local buffer then copy..*/
4785
4786                                 __u8 *localBuffer =
4787                                     yaffs_GetTempBuffer(dev, __LINE__);
4788                                 yaffs_ReadChunkDataFromObject(in, chunk,
4789                                                               localBuffer);
4790 #ifdef CONFIG_YAFFS_WINCE
4791                                 yfsd_UnlockYAFFS(TRUE);
4792 #endif
4793                                 memcpy(buffer, &localBuffer[start], nToCopy);
4794
4795 #ifdef CONFIG_YAFFS_WINCE
4796                                 yfsd_LockYAFFS(TRUE);
4797 #endif
4798                                 yaffs_ReleaseTempBuffer(dev, localBuffer,
4799                                                         __LINE__);
4800                         }
4801
4802                 } else {
4803 #ifdef CONFIG_YAFFS_WINCE
4804                         __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4805
4806                         /* Under WinCE can't do direct transfer. Need to use a local buffer.
4807                          * This is because we otherwise screw up WinCE's memory mapper
4808                          */
4809                         yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
4810
4811 #ifdef CONFIG_YAFFS_WINCE
4812                         yfsd_UnlockYAFFS(TRUE);
4813 #endif
4814                         memcpy(buffer, localBuffer, dev->nDataBytesPerChunk);
4815
4816 #ifdef CONFIG_YAFFS_WINCE
4817                         yfsd_LockYAFFS(TRUE);
4818                         yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4819 #endif
4820
4821 #else
4822                         /* A full chunk. Read directly into the supplied buffer. */
4823                         yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4824 #endif
4825                 }
4826
4827                 n -= nToCopy;
4828                 offset += nToCopy;
4829                 buffer += nToCopy;
4830                 nDone += nToCopy;
4831
4832         }
4833
4834         return nDone;
4835 }
4836
4837 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, loff_t offset,
4838                           int nBytes, int writeThrough)
4839 {
4840
4841         int chunk;
4842         __u32 start;
4843         int nToCopy;
4844         int n = nBytes;
4845         int nDone = 0;
4846         int nToWriteBack;
4847         int startOfWrite = offset;
4848         int chunkWritten = 0;
4849         __u32 nBytesRead;
4850         __u32 chunkStart;
4851
4852         yaffs_Device *dev;
4853
4854         dev = in->myDev;
4855
4856         while (n > 0 && chunkWritten >= 0) {
4857                 //chunk = offset / dev->nDataBytesPerChunk + 1;
4858                 //start = offset % dev->nDataBytesPerChunk;
4859                 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4860                 
4861                 if(chunk * dev->nDataBytesPerChunk + start != offset ||
4862                    start >= dev->nDataBytesPerChunk){
4863                    T(YAFFS_TRACE_ERROR,(TSTR("AddrToChunk of offset %d gives chunk %d start %d"TENDSTR),
4864                                         (int)offset, chunk,start));
4865                 }
4866                 chunk++;
4867
4868                 /* OK now check for the curveball where the start and end are in
4869                  * the same chunk.
4870                  */
4871
4872                 if ((start + n) < dev->nDataBytesPerChunk) {
4873                         nToCopy = n;
4874
4875                         /* Now folks, to calculate how many bytes to write back....
4876                          * If we're overwriting and not writing to then end of file then
4877                          * we need to write back as much as was there before.
4878                          */
4879
4880                         chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
4881
4882                         if(chunkStart > in->variant.fileVariant.fileSize)
4883                                 nBytesRead = 0; /* Past end of file */
4884                         else
4885                                 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
4886
4887                         if (nBytesRead > dev->nDataBytesPerChunk) {
4888                                 nBytesRead = dev->nDataBytesPerChunk;
4889                         }
4890
4891                         nToWriteBack =
4892                             (nBytesRead >
4893                              (start + n)) ? nBytesRead : (start + n);
4894                         
4895                         if(nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
4896                                 YBUG();
4897
4898                 } else {
4899                         nToCopy = dev->nDataBytesPerChunk - start;
4900                         nToWriteBack = dev->nDataBytesPerChunk;
4901                 }
4902
4903                 if (nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4904                         /* An incomplete start or end chunk (or maybe both start and end chunk), 
4905                          * or we're using inband tags, so we want to use the cache buffers.
4906                          */
4907                         if (dev->nShortOpCaches > 0) {
4908                                 yaffs_ChunkCache *cache;
4909                                 /* If we can't find the data in the cache, then load the cache */
4910                                 cache = yaffs_FindChunkCache(in, chunk);
4911                                 
4912                                 if (!cache
4913                                     && yaffs_CheckSpaceForAllocation(in->
4914                                                                      myDev)) {
4915                                         cache = yaffs_GrabChunkCache(in->myDev);
4916                                         cache->object = in;
4917                                         cache->chunkId = chunk;
4918                                         cache->dirty = 0;
4919                                         cache->locked = 0;
4920                                         yaffs_ReadChunkDataFromObject(in, chunk,
4921                                                                       cache->
4922                                                                       data);
4923                                 }
4924                                 else if(cache && 
4925                                         !cache->dirty &&
4926                                         !yaffs_CheckSpaceForAllocation(in->myDev)){
4927                                         /* Drop the cache if it was a read cache item and
4928                                          * no space check has been made for it.
4929                                          */ 
4930                                          cache = NULL;
4931                                 }
4932
4933                                 if (cache) {
4934                                         yaffs_UseChunkCache(dev, cache, 1);
4935                                         cache->locked = 1;
4936 #ifdef CONFIG_YAFFS_WINCE
4937                                         yfsd_UnlockYAFFS(TRUE);
4938 #endif
4939
4940                                         memcpy(&cache->data[start], buffer,
4941                                                nToCopy);
4942
4943 #ifdef CONFIG_YAFFS_WINCE
4944                                         yfsd_LockYAFFS(TRUE);
4945 #endif
4946                                         cache->locked = 0;
4947                                         cache->nBytes = nToWriteBack;
4948
4949                                         if (writeThrough) {
4950                                                 chunkWritten =
4951                                                     yaffs_WriteChunkDataToObject
4952                                                     (cache->object,
4953                                                      cache->chunkId,
4954                                                      cache->data, cache->nBytes,
4955                                                      1);
4956                                                 cache->dirty = 0;
4957                                         }
4958
4959                                 } else {
4960                                         chunkWritten = -1;      /* fail the write */
4961                                 }
4962                         } else {
4963                                 /* An incomplete start or end chunk (or maybe both start and end chunk)
4964                                  * Read into the local buffer then copy, then copy over and write back.
4965                                  */
4966
4967                                 __u8 *localBuffer =
4968                                     yaffs_GetTempBuffer(dev, __LINE__);
4969
4970                                 yaffs_ReadChunkDataFromObject(in, chunk,
4971                                                               localBuffer);
4972
4973 #ifdef CONFIG_YAFFS_WINCE
4974                                 yfsd_UnlockYAFFS(TRUE);
4975 #endif
4976
4977                                 memcpy(&localBuffer[start], buffer, nToCopy);
4978
4979 #ifdef CONFIG_YAFFS_WINCE
4980                                 yfsd_LockYAFFS(TRUE);
4981 #endif
4982                                 chunkWritten =
4983                                     yaffs_WriteChunkDataToObject(in, chunk,
4984                                                                  localBuffer,
4985                                                                  nToWriteBack,
4986                                                                  0);
4987
4988                                 yaffs_ReleaseTempBuffer(dev, localBuffer,
4989                                                         __LINE__);
4990
4991                         }
4992
4993                 } else {
4994                         /* A full chunk. Write directly from the supplied buffer. */
4995                         
4996 #ifdef CONFIG_YAFFS_WINCE
4997                         /* Under WinCE can't do direct transfer. Need to use a local buffer.
4998                          * This is because we otherwise screw up WinCE's memory mapper
4999                          */
5000                         __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5001 #ifdef CONFIG_YAFFS_WINCE
5002                         yfsd_UnlockYAFFS(TRUE);
5003 #endif
5004                         memcpy(localBuffer, buffer, dev->nDataBytesPerChunk);
5005 #ifdef CONFIG_YAFFS_WINCE
5006                         yfsd_LockYAFFS(TRUE);
5007 #endif
5008                         chunkWritten =
5009                             yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
5010                                                          dev->nDataBytesPerChunk,
5011                                                          0);
5012                         yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5013 #else
5014
5015                         chunkWritten =
5016                             yaffs_WriteChunkDataToObject(in, chunk, buffer,
5017                                                          dev->nDataBytesPerChunk,
5018                                                          0);
5019 #endif
5020                         /* Since we've overwritten the cached data, we better invalidate it. */
5021                         yaffs_InvalidateChunkCache(in, chunk);
5022                 }
5023
5024                 if (chunkWritten >= 0) {
5025                         n -= nToCopy;
5026                         offset += nToCopy;
5027                         buffer += nToCopy;
5028                         nDone += nToCopy;
5029                 }
5030
5031         }
5032
5033         /* Update file object */
5034
5035         if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
5036                 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
5037         }
5038
5039         in->dirty = 1;
5040
5041         return nDone;
5042 }
5043
5044
5045 /* ---------------------- File resizing stuff ------------------ */
5046
5047 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
5048 {
5049
5050         yaffs_Device *dev = in->myDev;
5051         int oldFileSize = in->variant.fileVariant.fileSize;
5052
5053         int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
5054
5055         int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
5056             dev->nDataBytesPerChunk;
5057         int i;
5058         int chunkId;
5059
5060         /* Delete backwards so that we don't end up with holes if
5061          * power is lost part-way through the operation.
5062          */
5063         for (i = lastDel; i >= startDel; i--) {
5064                 /* NB this could be optimised somewhat,
5065                  * eg. could retrieve the tags and write them without
5066                  * using yaffs_DeleteChunk
5067                  */
5068
5069                 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5070                 if (chunkId > 0) {
5071                         if (chunkId <
5072                             (dev->internalStartBlock * dev->nChunksPerBlock)
5073                             || chunkId >=
5074                             ((dev->internalEndBlock +
5075                               1) * dev->nChunksPerBlock)) {
5076                                 T(YAFFS_TRACE_ALWAYS,
5077                                   (TSTR("Found daft chunkId %d for %d" TENDSTR),
5078                                    chunkId, i));
5079                         } else {
5080                                 in->nDataChunks--;
5081                                 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5082                         }
5083                 }
5084         }
5085
5086 }
5087
5088 int yaffs_ResizeFile(yaffs_Object * in, loff_t newSize)
5089 {
5090
5091         int oldFileSize = in->variant.fileVariant.fileSize;
5092         __u32 newSizeOfPartialChunk;
5093         int newFullChunks;
5094         
5095         yaffs_Device *dev = in->myDev;
5096
5097         yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5098
5099         yaffs_FlushFilesChunkCache(in);
5100         yaffs_InvalidateWholeChunkCache(in);
5101
5102         yaffs_CheckGarbageCollection(dev);
5103
5104         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
5105                 return YAFFS_FAIL;
5106         }
5107
5108         if (newSize == oldFileSize) {
5109                 return YAFFS_OK;
5110         }
5111
5112         if (newSize < oldFileSize) {
5113
5114                 yaffs_PruneResizedChunks(in, newSize);
5115
5116                 if (newSizeOfPartialChunk != 0) {
5117                         int lastChunk = 1 + newFullChunks;
5118                         
5119                         __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5120
5121                         /* Got to read and rewrite the last chunk with its new size and zero pad */
5122                         yaffs_ReadChunkDataFromObject(in, lastChunk,
5123                                                       localBuffer);
5124
5125                         memset(localBuffer + newSizeOfPartialChunk, 0,
5126                                dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5127
5128                         yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5129                                                      newSizeOfPartialChunk, 1);
5130
5131                         yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5132                 }
5133
5134                 in->variant.fileVariant.fileSize = newSize;
5135
5136                 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5137         } else {
5138                 /* newsSize > oldFileSize */
5139                 in->variant.fileVariant.fileSize = newSize;
5140         }
5141
5142                 
5143         
5144         /* Write a new object header.
5145          * show we've shrunk the file, if need be
5146          * Do this only if the file is not in the deleted directories.
5147          */
5148         if (in->parent &&
5149             in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5150             in->parent->objectId != YAFFS_OBJECTID_DELETED) {
5151                 yaffs_UpdateObjectHeader(in, NULL, 0,
5152                                          (newSize < oldFileSize) ? 1 : 0, 0);
5153         }
5154
5155         return YAFFS_OK;
5156 }
5157
5158 loff_t yaffs_GetFileSize(yaffs_Object * obj)
5159 {
5160         obj = yaffs_GetEquivalentObject(obj);
5161
5162         switch (obj->variantType) {
5163         case YAFFS_OBJECT_TYPE_FILE:
5164                 return obj->variant.fileVariant.fileSize;
5165         case YAFFS_OBJECT_TYPE_SYMLINK:
5166                 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5167         default:
5168                 return 0;
5169         }
5170 }
5171
5172
5173
5174 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
5175 {
5176         int retVal;
5177         if (in->dirty) {
5178                 yaffs_FlushFilesChunkCache(in);
5179                 if (updateTime) {
5180 #ifdef CONFIG_YAFFS_WINCE
5181                         yfsd_WinFileTimeNow(in->win_mtime);
5182 #else
5183
5184                         in->yst_mtime = Y_CURRENT_TIME;
5185
5186 #endif
5187                 }
5188
5189                 retVal =
5190                     (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5191                      0) ? YAFFS_OK : YAFFS_FAIL;
5192         } else {
5193                 retVal = YAFFS_OK;
5194         }
5195
5196         return retVal;
5197
5198 }
5199
5200 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
5201 {
5202
5203         /* First off, invalidate the file's data in the cache, without flushing. */
5204         yaffs_InvalidateWholeChunkCache(in);
5205
5206         if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5207                 /* Move to the unlinked directory so we have a record that it was deleted. */
5208                 yaffs_ChangeObjectName(in, in->myDev->deletedDir,_Y("deleted"), 0, 0);
5209
5210         }
5211
5212         yaffs_RemoveObjectFromDirectory(in);
5213         yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5214         in->hdrChunk = 0;
5215
5216         yaffs_FreeObject(in);
5217         return YAFFS_OK;
5218
5219 }
5220
5221 /* yaffs_DeleteFile deletes the whole file data
5222  * and the inode associated with the file.
5223  * It does not delete the links associated with the file.
5224  */
5225  
5226 static int yaffs_UnlinkFile(yaffs_Object * in)
5227 {
5228
5229         int retVal;
5230         int immediateDeletion = 0;
5231
5232 #ifdef __KERNEL__
5233         if (!in->myInode) {
5234                 immediateDeletion = 1;
5235         }
5236 #else
5237         if (in->inUse <= 0) {
5238                 immediateDeletion = 1;
5239         }
5240 #endif
5241
5242         if (immediateDeletion) {
5243                 retVal =
5244                     yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5245                                            _Y("deleted"), 0, 0);
5246                 T(YAFFS_TRACE_TRACING,
5247                   (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5248                    in->objectId));
5249                 in->deleted = 1;
5250                 in->myDev->nDeletedFiles++;
5251                 if (1 || in->myDev->isYaffs2) {
5252                         yaffs_ResizeFile(in, 0);
5253                 }
5254                 yaffs_SoftDeleteFile(in);
5255         } else {
5256                 retVal =
5257                     yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5258                                            _Y("unlinked"), 0, 0);
5259         }
5260
5261
5262         return retVal;
5263 }
5264
5265 int yaffs_DeleteFile(yaffs_Object * in)
5266 {
5267         int retVal = YAFFS_OK;
5268         int deleted = in->deleted;
5269         
5270         yaffs_ResizeFile(in,0);
5271
5272         if (in->nDataChunks > 0) {
5273                 /* Use soft deletion if there is data in the file.
5274                  * That won't be the case if it has been resized to zero.
5275                  */
5276                 if (!in->unlinked) {
5277                         retVal = yaffs_UnlinkFile(in);
5278                 }
5279                 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5280                         in->deleted = deleted = 1;
5281                         in->myDev->nDeletedFiles++;
5282                         yaffs_SoftDeleteFile(in);
5283                 }
5284                 return deleted ? YAFFS_OK : YAFFS_FAIL;
5285         } else {
5286                 /* The file has no data chunks so we toss it immediately */
5287                 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5288                 in->variant.fileVariant.top = NULL;
5289                 yaffs_DoGenericObjectDeletion(in);
5290
5291                 return YAFFS_OK;
5292         }
5293 }
5294
5295 static int yaffs_DeleteDirectory(yaffs_Object * in)
5296 {
5297         /* First check that the directory is empty. */
5298         if (ylist_empty(&in->variant.directoryVariant.children)) {
5299                 return yaffs_DoGenericObjectDeletion(in);
5300         }
5301
5302         return YAFFS_FAIL;
5303
5304 }
5305
5306 static int yaffs_DeleteSymLink(yaffs_Object * in)
5307 {
5308         YFREE(in->variant.symLinkVariant.alias);
5309
5310         return yaffs_DoGenericObjectDeletion(in);
5311 }
5312
5313 static int yaffs_DeleteHardLink(yaffs_Object * in)
5314 {
5315         /* remove this hardlink from the list assocaited with the equivalent
5316          * object
5317          */
5318         ylist_del_init(&in->hardLinks);
5319         return yaffs_DoGenericObjectDeletion(in);
5320 }
5321
5322 static void yaffs_DestroyObject(yaffs_Object * obj)
5323 {
5324         switch (obj->variantType) {
5325         case YAFFS_OBJECT_TYPE_FILE:
5326                 yaffs_DeleteFile(obj);
5327                 break;
5328         case YAFFS_OBJECT_TYPE_DIRECTORY:
5329                 yaffs_DeleteDirectory(obj);
5330                 break;
5331         case YAFFS_OBJECT_TYPE_SYMLINK:
5332                 yaffs_DeleteSymLink(obj);
5333                 break;
5334         case YAFFS_OBJECT_TYPE_HARDLINK:
5335                 yaffs_DeleteHardLink(obj);
5336                 break;
5337         case YAFFS_OBJECT_TYPE_SPECIAL:
5338                 yaffs_DoGenericObjectDeletion(obj);
5339                 break;
5340         case YAFFS_OBJECT_TYPE_UNKNOWN:
5341                 break;          /* should not happen. */
5342         }
5343 }
5344
5345 static int yaffs_UnlinkWorker(yaffs_Object * obj)
5346 {
5347
5348         if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5349                 return yaffs_DeleteHardLink(obj);
5350         } else if (!ylist_empty(&obj->hardLinks)) {
5351                 /* Curve ball: We're unlinking an object that has a hardlink.
5352                  *
5353                  * This problem arises because we are not strictly following
5354                  * The Linux link/inode model.
5355                  *
5356                  * We can't really delete the object.
5357                  * Instead, we do the following:
5358                  * - Select a hardlink.
5359                  * - Unhook it from the hard links
5360                  * - Unhook it from its parent directory (so that the rename can work)
5361                  * - Rename the object to the hardlink's name.
5362                  * - Delete the hardlink
5363                  */
5364
5365                 yaffs_Object *hl;
5366                 int retVal;
5367                 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5368
5369                 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5370
5371                 ylist_del_init(&hl->hardLinks);
5372                 ylist_del_init(&hl->siblings);
5373
5374                 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5375
5376                 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
5377
5378                 if (retVal == YAFFS_OK) {
5379                         retVal = yaffs_DoGenericObjectDeletion(hl);
5380                 }
5381                 return retVal;
5382
5383         } else {
5384                 switch (obj->variantType) {
5385                 case YAFFS_OBJECT_TYPE_FILE:
5386                         return yaffs_UnlinkFile(obj);
5387                         break;
5388                 case YAFFS_OBJECT_TYPE_DIRECTORY:
5389                         return yaffs_DeleteDirectory(obj);
5390                         break;
5391                 case YAFFS_OBJECT_TYPE_SYMLINK:
5392                         return yaffs_DeleteSymLink(obj);
5393                         break;
5394                 case YAFFS_OBJECT_TYPE_SPECIAL:
5395                         return yaffs_DoGenericObjectDeletion(obj);
5396                         break;
5397                 case YAFFS_OBJECT_TYPE_HARDLINK:
5398                 case YAFFS_OBJECT_TYPE_UNKNOWN:
5399                 default:
5400                         return YAFFS_FAIL;
5401                 }
5402         }
5403 }
5404
5405
5406 static int yaffs_UnlinkObject( yaffs_Object *obj)
5407 {
5408
5409         if (obj && obj->unlinkAllowed) {
5410                 return yaffs_UnlinkWorker(obj);
5411         }
5412
5413         return YAFFS_FAIL;
5414
5415 }
5416 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
5417 {
5418         yaffs_Object *obj;
5419
5420         obj = yaffs_FindObjectByName(dir, name);
5421         return yaffs_UnlinkObject(obj);
5422 }
5423
5424 /*----------------------- Initialisation Scanning ---------------------- */
5425
5426 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
5427                                        int backwardScanning)
5428 {
5429         yaffs_Object *obj;
5430
5431         if (!backwardScanning) {
5432                 /* Handle YAFFS1 forward scanning case
5433                  * For YAFFS1 we always do the deletion
5434                  */
5435
5436         } else {
5437                 /* Handle YAFFS2 case (backward scanning)
5438                  * If the shadowed object exists then ignore.
5439                  */
5440                 if (yaffs_FindObjectByNumber(dev, objId)) {
5441                         return;
5442                 }
5443         }
5444
5445         /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5446          * We put it in unlinked dir to be cleaned up after the scanning
5447          */
5448         obj =
5449             yaffs_FindOrCreateObjectByNumber(dev, objId,
5450                                              YAFFS_OBJECT_TYPE_FILE);
5451         yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5452         obj->variant.fileVariant.shrinkSize = 0;
5453         obj->valid = 1;         /* So that we don't read any other info for this file */
5454
5455 }
5456
5457 typedef struct {
5458         int seq;
5459         int block;
5460 } yaffs_BlockIndex;
5461
5462
5463 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5464 {
5465         yaffs_Object *hl;
5466         yaffs_Object *in;
5467         
5468         while (hardList) {
5469                 hl = hardList;
5470                 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5471
5472                 in = yaffs_FindObjectByNumber(dev,
5473                                               hl->variant.hardLinkVariant.
5474                                               equivalentObjectId);
5475
5476                 if (in) {
5477                         /* Add the hardlink pointers */
5478                         hl->variant.hardLinkVariant.equivalentObject = in;
5479                         ylist_add(&hl->hardLinks, &in->hardLinks);
5480                 } else {
5481                         /* Todo Need to report/handle this better.
5482                          * Got a problem... hardlink to a non-existant object
5483                          */
5484                         hl->variant.hardLinkVariant.equivalentObject = NULL;
5485                         YINIT_LIST_HEAD(&hl->hardLinks);
5486
5487                 }
5488
5489         }
5490
5491 }
5492
5493
5494
5495
5496
5497 static int ybicmp(const void *a, const void *b){
5498     register int aseq = ((yaffs_BlockIndex *)a)->seq;
5499     register int bseq = ((yaffs_BlockIndex *)b)->seq;
5500     register int ablock = ((yaffs_BlockIndex *)a)->block;
5501     register int bblock = ((yaffs_BlockIndex *)b)->block;
5502     if( aseq == bseq )
5503         return ablock - bblock;
5504     else
5505         return aseq - bseq;
5506
5507 }
5508
5509
5510 struct yaffs_ShadowFixerStruct {
5511         int objectId;
5512         int shadowedId;
5513         struct yaffs_ShadowFixerStruct *next;
5514 };
5515
5516
5517 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5518 {
5519         /*
5520         *  Sort out state of unlinked and deleted objects after scanning.
5521         */
5522         struct ylist_head *i;
5523         struct ylist_head *n;
5524         yaffs_Object *l;
5525
5526         /* Soft delete all the unlinked files */
5527         ylist_for_each_safe(i, n,
5528                 &dev->unlinkedDir->variant.directoryVariant.children) {
5529                 if (i) {
5530                         l = ylist_entry(i, yaffs_Object, siblings);
5531                         yaffs_DestroyObject(l);
5532                 }
5533         }
5534         
5535         ylist_for_each_safe(i, n,
5536                 &dev->deletedDir->variant.directoryVariant.children) {
5537                 if (i) {
5538                         l = ylist_entry(i, yaffs_Object, siblings);
5539                         yaffs_DestroyObject(l);
5540                 }
5541         }
5542
5543 }
5544
5545 static int yaffs_Scan(yaffs_Device * dev)
5546 {
5547         yaffs_ExtendedTags tags;
5548         int blk;
5549         int blockIterator;
5550         int startIterator;
5551         int endIterator;
5552         int result;
5553
5554         int chunk;
5555         int c;
5556         int deleted;
5557         yaffs_BlockState state;
5558         yaffs_Object *hardList = NULL;
5559         yaffs_BlockInfo *bi;
5560         __u32 sequenceNumber;
5561         yaffs_ObjectHeader *oh;
5562         yaffs_Object *in;
5563         yaffs_Object *parent;
5564         
5565         int alloc_failed = 0;
5566         
5567         struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5568         
5569
5570         __u8 *chunkData;
5571
5572         
5573         
5574         T(YAFFS_TRACE_SCAN,
5575           (TSTR("yaffs_Scan starts  intstartblk %d intendblk %d..." TENDSTR),
5576            dev->internalStartBlock, dev->internalEndBlock));
5577
5578         chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5579
5580         dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5581
5582         /* Scan all the blocks to determine their state */
5583         for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5584                 bi = yaffs_GetBlockInfo(dev, blk);
5585                 yaffs_ClearChunkBits(dev, blk);
5586                 bi->pagesInUse = 0;
5587                 bi->softDeletions = 0;
5588
5589                 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5590
5591                 bi->blockState = state;
5592                 bi->sequenceNumber = sequenceNumber;
5593
5594                 T(YAFFS_TRACE_SCAN_DEBUG,
5595                   (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5596                    state, sequenceNumber));
5597
5598                 if (state == YAFFS_BLOCK_STATE_DEAD) {
5599                         T(YAFFS_TRACE_BAD_BLOCKS,
5600                           (TSTR("block %d is bad" TENDSTR), blk));
5601                 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5602                         T(YAFFS_TRACE_SCAN_DEBUG,
5603                           (TSTR("Block empty " TENDSTR)));
5604                         dev->nErasedBlocks++;
5605                         dev->nFreeChunks += dev->nChunksPerBlock;
5606                 } 
5607         }
5608
5609         startIterator = dev->internalStartBlock;
5610         endIterator = dev->internalEndBlock;
5611
5612         /* For each block.... */
5613         for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5614              blockIterator++) {
5615                 
5616                 YYIELD();
5617
5618                 YYIELD();
5619                 
5620                 blk = blockIterator;
5621
5622                 bi = yaffs_GetBlockInfo(dev, blk);
5623                 state = bi->blockState;
5624
5625                 deleted = 0;
5626
5627                 /* For each chunk in each block that needs scanning....*/
5628                 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5629                      state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5630                         /* Read the tags and decide what to do */
5631                         chunk = blk * dev->nChunksPerBlock + c;
5632
5633                         result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5634                                                         &tags);
5635
5636                         /* Let's have a good look at this chunk... */
5637
5638                         if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
5639                                 /* YAFFS1 only...
5640                                  * A deleted chunk
5641                                  */
5642                                 deleted++;
5643                                 dev->nFreeChunks++;
5644                                 /*T((" %d %d deleted\n",blk,c)); */
5645                         } else if (!tags.chunkUsed) {
5646                                 /* An unassigned chunk in the block
5647                                  * This means that either the block is empty or 
5648                                  * this is the one being allocated from
5649                                  */
5650
5651                                 if (c == 0) {
5652                                         /* We're looking at the first chunk in the block so the block is unused */
5653                                         state = YAFFS_BLOCK_STATE_EMPTY;
5654                                         dev->nErasedBlocks++;
5655                                 } else {
5656                                         /* this is the block being allocated from */
5657                                         T(YAFFS_TRACE_SCAN,
5658                                           (TSTR
5659                                            (" Allocating from %d %d" TENDSTR),
5660                                            blk, c));
5661                                         state = YAFFS_BLOCK_STATE_ALLOCATING;
5662                                         dev->allocationBlock = blk;
5663                                         dev->allocationPage = c;
5664                                         dev->allocationBlockFinder = blk;       
5665                                         /* Set it to here to encourage the allocator to go forth from here. */
5666                                         
5667                                 }
5668
5669                                 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5670                         } else if (tags.chunkId > 0) {
5671                                 /* chunkId > 0 so it is a data chunk... */
5672                                 unsigned int endpos;
5673
5674                                 yaffs_SetChunkBit(dev, blk, c);
5675                                 bi->pagesInUse++;
5676
5677                                 in = yaffs_FindOrCreateObjectByNumber(dev,
5678                                                                       tags.
5679                                                                       objectId,
5680                                                                       YAFFS_OBJECT_TYPE_FILE);
5681                                 /* PutChunkIntoFile checks for a clash (two data chunks with
5682                                  * the same chunkId).
5683                                  */
5684                                  
5685                                 if(!in)
5686                                         alloc_failed = 1;
5687
5688                                 if(in){
5689                                         if(!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,1))
5690                                                 alloc_failed = 1;
5691                                 }
5692                                 
5693                                 endpos =
5694                                     (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5695                                     tags.byteCount;
5696                                 if (in && 
5697                                     in->variantType == YAFFS_OBJECT_TYPE_FILE
5698                                     && in->variant.fileVariant.scannedFileSize <
5699                                     endpos) {
5700                                         in->variant.fileVariant.
5701                                             scannedFileSize = endpos;
5702                                         if (!dev->useHeaderFileSize) {
5703                                                 in->variant.fileVariant.
5704                                                     fileSize =
5705                                                     in->variant.fileVariant.
5706                                                     scannedFileSize;
5707                                         }
5708
5709                                 }
5710                                 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));   */
5711                         } else {
5712                                 /* chunkId == 0, so it is an ObjectHeader.
5713                                  * Thus, we read in the object header and make the object
5714                                  */
5715                                 yaffs_SetChunkBit(dev, blk, c);
5716                                 bi->pagesInUse++;
5717
5718                                 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5719                                                                 chunkData,
5720                                                                 NULL);
5721
5722                                 oh = (yaffs_ObjectHeader *) chunkData;
5723
5724                                 in = yaffs_FindObjectByNumber(dev,
5725                                                               tags.objectId);
5726                                 if (in && in->variantType != oh->type) {
5727                                         /* This should not happen, but somehow
5728                                          * Wev'e ended up with an objectId that has been reused but not yet 
5729                                          * deleted, and worse still it has changed type. Delete the old object.
5730                                          */
5731
5732                                         yaffs_DestroyObject(in);
5733
5734                                         in = 0;
5735                                 }
5736
5737                                 in = yaffs_FindOrCreateObjectByNumber(dev,
5738                                                                       tags.
5739                                                                       objectId,
5740                                                                       oh->type);
5741
5742                                 if(!in)
5743                                         alloc_failed = 1;
5744                                         
5745                                 if (in && oh->shadowsObject > 0) {
5746                                 
5747                                         struct yaffs_ShadowFixerStruct *fixer;
5748                                         fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
5749                                         if(fixer){
5750                                                 fixer-> next = shadowFixerList;
5751                                                 shadowFixerList = fixer;
5752                                                 fixer->objectId = tags.objectId;
5753                                                 fixer->shadowedId = oh->shadowsObject;
5754                                         }
5755                                         
5756                                 }
5757
5758                                 if (in && in->valid) {
5759                                         /* We have already filled this one. We have a duplicate and need to resolve it. */
5760
5761                                         unsigned existingSerial = in->serial;
5762                                         unsigned newSerial = tags.serialNumber;
5763
5764                                         if (((existingSerial + 1) & 3) == newSerial) {
5765                                                 /* Use new one - destroy the exisiting one */
5766                                                 yaffs_DeleteChunk(dev,
5767                                                                   in->hdrChunk,
5768                                                                   1, __LINE__);
5769                                                 in->valid = 0;
5770                                         } else {
5771                                                 /* Use existing - destroy this one. */
5772                                                 yaffs_DeleteChunk(dev, chunk, 1,
5773                                                                   __LINE__);
5774                                         }
5775                                 }
5776
5777                                 if (in && !in->valid &&
5778                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
5779                                      tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5780                                         /* We only load some info, don't fiddle with directory structure */
5781                                         in->valid = 1;
5782                                         in->variantType = oh->type;
5783
5784                                         in->yst_mode = oh->yst_mode;
5785 #ifdef CONFIG_YAFFS_WINCE
5786                                         in->win_atime[0] = oh->win_atime[0];
5787                                         in->win_ctime[0] = oh->win_ctime[0];
5788                                         in->win_mtime[0] = oh->win_mtime[0];
5789                                         in->win_atime[1] = oh->win_atime[1];
5790                                         in->win_ctime[1] = oh->win_ctime[1];
5791                                         in->win_mtime[1] = oh->win_mtime[1];
5792 #else
5793                                         in->yst_uid = oh->yst_uid;
5794                                         in->yst_gid = oh->yst_gid;
5795                                         in->yst_atime = oh->yst_atime;
5796                                         in->yst_mtime = oh->yst_mtime;
5797                                         in->yst_ctime = oh->yst_ctime;
5798                                         in->yst_rdev = oh->yst_rdev;
5799 #endif
5800                                         in->hdrChunk = chunk;
5801                                         in->serial = tags.serialNumber;
5802
5803                                 } else if (in && !in->valid) {
5804                                         /* we need to load this info */
5805
5806                                         in->valid = 1;
5807                                         in->variantType = oh->type;
5808
5809                                         in->yst_mode = oh->yst_mode;
5810 #ifdef CONFIG_YAFFS_WINCE
5811                                         in->win_atime[0] = oh->win_atime[0];
5812                                         in->win_ctime[0] = oh->win_ctime[0];
5813                                         in->win_mtime[0] = oh->win_mtime[0];
5814                                         in->win_atime[1] = oh->win_atime[1];
5815                                         in->win_ctime[1] = oh->win_ctime[1];
5816                                         in->win_mtime[1] = oh->win_mtime[1];
5817 #else
5818                                         in->yst_uid = oh->yst_uid;
5819                                         in->yst_gid = oh->yst_gid;
5820                                         in->yst_atime = oh->yst_atime;
5821                                         in->yst_mtime = oh->yst_mtime;
5822                                         in->yst_ctime = oh->yst_ctime;
5823                                         in->yst_rdev = oh->yst_rdev;
5824 #endif
5825                                         in->hdrChunk = chunk;
5826                                         in->serial = tags.serialNumber;
5827
5828                                         yaffs_SetObjectName(in, oh->name);
5829                                         in->dirty = 0;
5830
5831                                         /* directory stuff...
5832                                          * hook up to parent
5833                                          */
5834
5835                                         parent =
5836                                             yaffs_FindOrCreateObjectByNumber
5837                                             (dev, oh->parentObjectId,
5838                                              YAFFS_OBJECT_TYPE_DIRECTORY);
5839                                         if (parent->variantType ==
5840                                             YAFFS_OBJECT_TYPE_UNKNOWN) {
5841                                                 /* Set up as a directory */
5842                                                 parent->variantType =
5843                                                     YAFFS_OBJECT_TYPE_DIRECTORY;
5844                                                 YINIT_LIST_HEAD(&parent->variant.
5845                                                                directoryVariant.
5846                                                                children);
5847                                         } else if (parent->variantType !=
5848                                                    YAFFS_OBJECT_TYPE_DIRECTORY)
5849                                         {
5850                                                 /* Hoosterman, another problem....
5851                                                  * We're trying to use a non-directory as a directory
5852                                                  */
5853
5854                                                 T(YAFFS_TRACE_ERROR,
5855                                                   (TSTR
5856                                                    ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
5857                                                     TENDSTR)));
5858                                                 parent = dev->lostNFoundDir;
5859                                         }
5860
5861                                         yaffs_AddObjectToDirectory(parent, in);
5862
5863                                         if (0 && (parent == dev->deletedDir ||
5864                                                   parent == dev->unlinkedDir)) {
5865                                                 in->deleted = 1;        /* If it is unlinked at start up then it wants deleting */
5866                                                 dev->nDeletedFiles++;
5867                                         }
5868                                         /* Note re hardlinks.
5869                                          * Since we might scan a hardlink before its equivalent object is scanned
5870                                          * we put them all in a list.
5871                                          * After scanning is complete, we should have all the objects, so we run through this
5872                                          * list and fix up all the chains.              
5873                                          */
5874
5875                                         switch (in->variantType) {
5876                                         case YAFFS_OBJECT_TYPE_UNKNOWN: 
5877                                                 /* Todo got a problem */
5878                                                 break;
5879                                         case YAFFS_OBJECT_TYPE_FILE:
5880                                                 if (dev->useHeaderFileSize)
5881
5882                                                         in->variant.fileVariant.
5883                                                             fileSize =
5884                                                             oh->fileSize;
5885
5886                                                 break;
5887                                         case YAFFS_OBJECT_TYPE_HARDLINK:
5888                                                 in->variant.hardLinkVariant.
5889                                                     equivalentObjectId =
5890                                                     oh->equivalentObjectId;
5891                                                 in->hardLinks.next =
5892                                                     (struct ylist_head *)
5893                                                     hardList;
5894                                                 hardList = in;
5895                                                 break;
5896                                         case YAFFS_OBJECT_TYPE_DIRECTORY:
5897                                                 /* Do nothing */
5898                                                 break;
5899                                         case YAFFS_OBJECT_TYPE_SPECIAL:
5900                                                 /* Do nothing */
5901                                                 break;
5902                                         case YAFFS_OBJECT_TYPE_SYMLINK: 
5903                                                 in->variant.symLinkVariant.alias =
5904                                                     yaffs_CloneString(oh->alias);
5905                                                 if(!in->variant.symLinkVariant.alias)
5906                                                         alloc_failed = 1;
5907                                                 break;
5908                                         }
5909
5910 /*
5911                                         if (parent == dev->deletedDir) {
5912                                                 yaffs_DestroyObject(in);
5913                                                 bi->hasShrinkHeader = 1;
5914                                         }
5915 */
5916                                 }
5917                         }
5918                 }
5919
5920                 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5921                         /* If we got this far while scanning, then the block is fully allocated.*/
5922                         state = YAFFS_BLOCK_STATE_FULL;
5923                 }
5924
5925                 bi->blockState = state;
5926
5927                 /* Now let's see if it was dirty */
5928                 if (bi->pagesInUse == 0 &&
5929                     !bi->hasShrinkHeader &&
5930                     bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5931                         yaffs_BlockBecameDirty(dev, blk);
5932                 }
5933
5934         }
5935
5936         
5937         /* Ok, we've done all the scanning.
5938          * Fix up the hard link chains.
5939          * We should now have scanned all the objects, now it's time to add these 
5940          * hardlinks.
5941          */
5942
5943         yaffs_HardlinkFixup(dev,hardList);
5944         
5945         /* Fix up any shadowed objects */
5946         {
5947                 struct yaffs_ShadowFixerStruct *fixer;
5948                 yaffs_Object *obj;
5949                 
5950                 while(shadowFixerList){
5951                         fixer = shadowFixerList;
5952                         shadowFixerList = fixer->next;
5953                         /* Complete the rename transaction by deleting the shadowed object
5954                          * then setting the object header to unshadowed.
5955                          */
5956                         obj = yaffs_FindObjectByNumber(dev,fixer->shadowedId);
5957                         if(obj)
5958                                 yaffs_DestroyObject(obj);
5959         
5960                         obj = yaffs_FindObjectByNumber(dev,fixer->objectId);
5961                         if(obj){
5962                                 yaffs_UpdateObjectHeader(obj,NULL,1,0,0);
5963                         }
5964                         
5965                         YFREE(fixer);
5966                 }
5967         }
5968
5969         yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5970
5971         if(alloc_failed){
5972                 return YAFFS_FAIL;
5973         }
5974         
5975         T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5976         
5977
5978         return YAFFS_OK;
5979 }
5980
5981 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5982 {
5983         __u8 *chunkData;
5984         yaffs_ObjectHeader *oh;
5985         yaffs_Device *dev;
5986         yaffs_ExtendedTags tags;
5987         int result;
5988         int alloc_failed = 0;
5989
5990         if(!in)
5991                 return;
5992                 
5993         dev = in->myDev;
5994                 
5995 #if 0
5996         T(YAFFS_TRACE_SCAN,(TSTR("details for object %d %s loaded" TENDSTR),
5997                 in->objectId,
5998                 in->lazyLoaded ? "not yet" : "already"));
5999 #endif
6000
6001         if(in->lazyLoaded && in->hdrChunk > 0){
6002                 in->lazyLoaded = 0;
6003                 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6004
6005                 result = yaffs_ReadChunkWithTagsFromNAND(dev,in->hdrChunk,chunkData,&tags);
6006                 oh = (yaffs_ObjectHeader *) chunkData;
6007
6008                 in->yst_mode = oh->yst_mode;
6009 #ifdef CONFIG_YAFFS_WINCE
6010                 in->win_atime[0] = oh->win_atime[0];
6011                 in->win_ctime[0] = oh->win_ctime[0];
6012                 in->win_mtime[0] = oh->win_mtime[0];
6013                 in->win_atime[1] = oh->win_atime[1];
6014                 in->win_ctime[1] = oh->win_ctime[1];
6015                 in->win_mtime[1] = oh->win_mtime[1];
6016 #else
6017                 in->yst_uid = oh->yst_uid;
6018                 in->yst_gid = oh->yst_gid;
6019                 in->yst_atime = oh->yst_atime;
6020                 in->yst_mtime = oh->yst_mtime;
6021                 in->yst_ctime = oh->yst_ctime;
6022                 in->yst_rdev = oh->yst_rdev;
6023                 
6024 #endif
6025                 yaffs_SetObjectName(in, oh->name);
6026                 
6027                 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
6028                          in->variant.symLinkVariant.alias =
6029                                                     yaffs_CloneString(oh->alias);
6030                         if(!in->variant.symLinkVariant.alias)
6031                                 alloc_failed = 1; /* Not returned to caller */
6032                 }
6033                                                     
6034                 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
6035         }
6036 }
6037
6038 static int yaffs_ScanBackwards(yaffs_Device * dev)
6039 {
6040         yaffs_ExtendedTags tags;
6041         int blk;
6042         int blockIterator;
6043         int startIterator;
6044         int endIterator;
6045         int nBlocksToScan = 0;
6046
6047         int chunk;
6048         int result;
6049         int c;
6050         int deleted;
6051         yaffs_BlockState state;
6052         yaffs_Object *hardList = NULL;
6053         yaffs_BlockInfo *bi;
6054         __u32 sequenceNumber;
6055         yaffs_ObjectHeader *oh;
6056         yaffs_Object *in;
6057         yaffs_Object *parent;
6058         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6059         int itsUnlinked;
6060         __u8 *chunkData;
6061         
6062         int fileSize;
6063         int isShrink;
6064         int foundChunksInBlock;
6065         int equivalentObjectId;
6066         int alloc_failed = 0;
6067         
6068
6069         yaffs_BlockIndex *blockIndex = NULL;
6070         int altBlockIndex = 0;
6071
6072         if (!dev->isYaffs2) {
6073                 T(YAFFS_TRACE_SCAN,
6074                   (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6075                 return YAFFS_FAIL;
6076         }
6077
6078         T(YAFFS_TRACE_SCAN,
6079           (TSTR
6080            ("yaffs_ScanBackwards starts  intstartblk %d intendblk %d..."
6081             TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6082
6083
6084         dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6085
6086         blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6087         
6088         if(!blockIndex) {
6089                 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6090                 altBlockIndex = 1;
6091         }
6092         
6093         if(!blockIndex) {
6094                 T(YAFFS_TRACE_SCAN,
6095                   (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6096                 return YAFFS_FAIL;
6097         }
6098         
6099         dev->blocksInCheckpoint = 0;
6100         
6101         chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6102
6103         /* Scan all the blocks to determine their state */
6104         for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6105                 bi = yaffs_GetBlockInfo(dev, blk);
6106                 yaffs_ClearChunkBits(dev, blk);
6107                 bi->pagesInUse = 0;
6108                 bi->softDeletions = 0;
6109
6110                 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6111
6112                 bi->blockState = state;
6113                 bi->sequenceNumber = sequenceNumber;
6114
6115                 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6116                         bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6117                         
6118                 T(YAFFS_TRACE_SCAN_DEBUG,
6119                   (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6120                    state, sequenceNumber));
6121
6122                 
6123                 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
6124                         dev->blocksInCheckpoint++;
6125                         
6126                 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6127                         T(YAFFS_TRACE_BAD_BLOCKS,
6128                           (TSTR("block %d is bad" TENDSTR), blk));
6129                 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6130                         T(YAFFS_TRACE_SCAN_DEBUG,
6131                           (TSTR("Block empty " TENDSTR)));
6132                         dev->nErasedBlocks++;
6133                         dev->nFreeChunks += dev->nChunksPerBlock;
6134                 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6135
6136                         /* Determine the highest sequence number */
6137                         if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6138                             sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6139
6140                                 blockIndex[nBlocksToScan].seq = sequenceNumber;
6141                                 blockIndex[nBlocksToScan].block = blk;
6142
6143                                 nBlocksToScan++;
6144
6145                                 if (sequenceNumber >= dev->sequenceNumber) {
6146                                         dev->sequenceNumber = sequenceNumber;
6147                                 }
6148                         } else {
6149                                 /* TODO: Nasty sequence number! */
6150                                 T(YAFFS_TRACE_SCAN,
6151                                   (TSTR
6152                                    ("Block scanning block %d has bad sequence number %d"
6153                                     TENDSTR), blk, sequenceNumber));
6154
6155                         }
6156                 }
6157         }
6158
6159         T(YAFFS_TRACE_SCAN,
6160         (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6161
6162
6163
6164         YYIELD();
6165
6166         /* Sort the blocks */
6167 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6168         {
6169                 /* Use qsort now. */
6170                 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6171         }
6172 #else
6173         {
6174                 /* Dungy old bubble sort... */
6175                 
6176                 yaffs_BlockIndex temp;
6177                 int i;
6178                 int j;
6179
6180                 for (i = 0; i < nBlocksToScan; i++)
6181                         for (j = i + 1; j < nBlocksToScan; j++)
6182                                 if (blockIndex[i].seq > blockIndex[j].seq) {
6183                                         temp = blockIndex[j];
6184                                         blockIndex[j] = blockIndex[i];
6185                                         blockIndex[i] = temp;
6186                                 }
6187         }
6188 #endif
6189
6190         YYIELD();
6191
6192         T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6193
6194         /* Now scan the blocks looking at the data. */
6195         startIterator = 0;
6196         endIterator = nBlocksToScan - 1;
6197         T(YAFFS_TRACE_SCAN_DEBUG,
6198           (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6199
6200         /* For each block.... backwards */
6201         for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6202              blockIterator--) {
6203                 /* Cooperative multitasking! This loop can run for so
6204                    long that watchdog timers expire. */
6205                 YYIELD();
6206
6207                 /* get the block to scan in the correct order */
6208                 blk = blockIndex[blockIterator].block;
6209
6210                 bi = yaffs_GetBlockInfo(dev, blk);
6211                 
6212                 
6213                 state = bi->blockState;
6214
6215                 deleted = 0;
6216
6217                 /* For each chunk in each block that needs scanning.... */
6218                 foundChunksInBlock = 0;
6219                 for (c = dev->nChunksPerBlock - 1; 
6220                      !alloc_failed && c >= 0 &&
6221                      (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6222                       state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6223                         /* Scan backwards... 
6224                          * Read the tags and decide what to do
6225                          */
6226                         
6227                         chunk = blk * dev->nChunksPerBlock + c;
6228
6229                         result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6230                                                         &tags);
6231
6232                         /* Let's have a good look at this chunk... */
6233
6234                         if (!tags.chunkUsed) {
6235                                 /* An unassigned chunk in the block.
6236                                  * If there are used chunks after this one, then
6237                                  * it is a chunk that was skipped due to failing the erased
6238                                  * check. Just skip it so that it can be deleted.
6239                                  * But, more typically, We get here when this is an unallocated
6240                                  * chunk and his means that either the block is empty or 
6241                                  * this is the one being allocated from
6242                                  */
6243
6244                                 if(foundChunksInBlock)
6245                                 {
6246                                         /* This is a chunk that was skipped due to failing the erased check */
6247                                         
6248                                 } else if (c == 0) {
6249                                         /* We're looking at the first chunk in the block so the block is unused */
6250                                         state = YAFFS_BLOCK_STATE_EMPTY;
6251                                         dev->nErasedBlocks++;
6252                                 } else {
6253                                         if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6254                                             state == YAFFS_BLOCK_STATE_ALLOCATING) {
6255                                                 if(dev->sequenceNumber == bi->sequenceNumber) {
6256                                                         /* this is the block being allocated from */
6257                                                 
6258                                                         T(YAFFS_TRACE_SCAN,
6259                                                           (TSTR
6260                                                            (" Allocating from %d %d"
6261                                                             TENDSTR), blk, c));
6262
6263                                                         state = YAFFS_BLOCK_STATE_ALLOCATING;
6264                                                         dev->allocationBlock = blk;
6265                                                         dev->allocationPage = c;
6266                                                         dev->allocationBlockFinder = blk;       
6267                                                 }
6268                                                 else {
6269                                                         /* This is a partially written block that is not
6270                                                          * the current allocation block. This block must have
6271                                                          * had a write failure, so set up for retirement.
6272                                                          */
6273                                                   
6274                                                          /* bi->needsRetiring = 1; ??? TODO */
6275                                                          bi->gcPrioritise = 1;
6276                                                                                                          
6277                                                          T(YAFFS_TRACE_ALWAYS,
6278                                                          (TSTR("Partially written block %d detected" TENDSTR),
6279                                                          blk));
6280                                                 }
6281
6282                                         }
6283                                          
6284                                 }
6285
6286                                 dev->nFreeChunks++;
6287                                 
6288                         } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED){
6289                                 printf("Error in ECC\n");
6290                                 /* Don't actually delete because the chunk is not yet set up as being in use */
6291                                 /* yaffs_DeleteChunk(dev, chunk, 1, __LINE__); */
6292                         }else if (tags.chunkId > 0) {
6293                                 /* chunkId > 0 so it is a data chunk... */
6294                                 unsigned int endpos;
6295                                 __u32 chunkBase =
6296                                     (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6297                                                                 
6298                                 foundChunksInBlock = 1;
6299
6300
6301                                 yaffs_SetChunkBit(dev, blk, c);
6302                                 bi->pagesInUse++;
6303
6304                                 in = yaffs_FindOrCreateObjectByNumber(dev,
6305                                                                       tags.
6306                                                                       objectId,
6307                                                                       YAFFS_OBJECT_TYPE_FILE);
6308                                 if(!in){
6309                                         /* Out of memory */
6310                                         alloc_failed = 1;
6311                                 }
6312                                 
6313                                 if (in &&
6314                                     in->variantType == YAFFS_OBJECT_TYPE_FILE
6315                                     && chunkBase <
6316                                     in->variant.fileVariant.shrinkSize) {
6317                                         /* This has not been invalidated by a resize */
6318                                         if(!yaffs_PutChunkIntoFile(in, tags.chunkId,
6319                                                                chunk, -1)){
6320                                                 alloc_failed = 1;
6321                                         }
6322
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.
6325                                          */
6326                                         endpos =
6327                                             (tags.chunkId -
6328                                              1) * dev->nDataBytesPerChunk +
6329                                             tags.byteCount;
6330                                             
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.
6337                                                     fileSize =
6338                                                     in->variant.fileVariant.
6339                                                     scannedFileSize;
6340                                         }
6341
6342                                 } else if(in) {
6343                                         /* This chunk has been invalidated by a resize, so delete */
6344                                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6345
6346                                 }
6347                         } else {
6348                                 /* chunkId == 0, so it is an ObjectHeader.
6349                                  * Thus, we read in the object header and make the object
6350                                  */
6351                                 foundChunksInBlock = 1;
6352
6353                                 yaffs_SetChunkBit(dev, blk, c);
6354                                 bi->pagesInUse++;
6355
6356                                 oh = NULL;
6357                                 in = NULL;
6358
6359                                 if (tags.extraHeaderInfoAvailable) {
6360                                         in = yaffs_FindOrCreateObjectByNumber
6361                                             (dev, tags.objectId,
6362                                              tags.extraObjectType);
6363                                 }
6364
6365                                 if (!in ||
6366 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
6367                                     !in->valid ||
6368 #endif
6369                                     tags.extraShadows ||
6370                                     (!in->valid &&
6371                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
6372                                      tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
6373                                     ) {
6374
6375                                         /* If we don't have  valid info then we need to read the chunk
6376                                          * TODO In future we can probably defer reading the chunk and 
6377                                          * living with invalid data until needed.
6378                                          */
6379
6380                                         result = yaffs_ReadChunkWithTagsFromNAND(dev,
6381                                                                         chunk,
6382                                                                         chunkData,
6383                                                                         NULL);
6384
6385                                         oh = (yaffs_ObjectHeader *) chunkData;
6386                                         
6387                                         if(dev->inbandTags){
6388                                                 /* Fix up the header if they got corrupted by inband tags */
6389                                                 oh->shadowsObject = oh->inbandShadowsObject;
6390                                                 oh->isShrink = oh->inbandIsShrink;
6391                                         }
6392
6393                                         if (!in)
6394                                                 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6395
6396                                 }
6397
6398                                 if (!in) {
6399                                         /* TODO Hoosterman we have a problem! */
6400                                         T(YAFFS_TRACE_ERROR,
6401                                           (TSTR
6402                                            ("yaffs tragedy: Could not make object for object  %d at chunk %d during scan"
6403                                             TENDSTR), tags.objectId, chunk));
6404
6405                                 }
6406
6407                                 if (in->valid) {
6408                                         /* We have already filled this one.
6409                                          * We have a duplicate that will be discarded, but 
6410                                          * we first have to suck out resize info if it is a file.
6411                                          */
6412
6413                                         if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) && 
6414                                              ((oh && 
6415                                                oh-> type == YAFFS_OBJECT_TYPE_FILE)||
6416                                               (tags.extraHeaderInfoAvailable  &&
6417                                                tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
6418                                             ) {
6419                                                 __u32 thisSize =
6420                                                     (oh) ? oh->fileSize : tags.
6421                                                     extraFileLength;
6422                                                 __u32 parentObjectId =
6423                                                     (oh) ? oh->
6424                                                     parentObjectId : tags.
6425                                                     extraParentObjectId;
6426                                                 
6427                                                 
6428                                                 isShrink =
6429                                                     (oh) ? oh->isShrink : tags.
6430                                                     extraIsShrinkHeader;
6431
6432                                                 /* If it is deleted (unlinked at start also means deleted)
6433                                                  * we treat the file size as being zeroed at this point.
6434                                                  */
6435                                                 if (parentObjectId ==
6436                                                     YAFFS_OBJECTID_DELETED
6437                                                     || parentObjectId ==
6438                                                     YAFFS_OBJECTID_UNLINKED) {
6439                                                         thisSize = 0;
6440                                                         isShrink = 1;
6441                                                 }
6442
6443                                                 if (isShrink &&
6444                                                     in->variant.fileVariant.
6445                                                     shrinkSize > thisSize) {
6446                                                         in->variant.fileVariant.
6447                                                             shrinkSize =
6448                                                             thisSize;
6449                                                 }
6450
6451                                                 if (isShrink) {
6452                                                         bi->hasShrinkHeader = 1;
6453                                                 }
6454
6455                                         }
6456                                         /* Use existing - destroy this one. */
6457                                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6458
6459                                 }
6460
6461                                 if (!in->valid &&
6462                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
6463                                      tags.objectId ==
6464                                      YAFFS_OBJECTID_LOSTNFOUND)) {
6465                                         /* We only load some info, don't fiddle with directory structure */
6466                                         in->valid = 1;
6467                                         
6468                                         if(oh) {
6469                                                 in->variantType = oh->type;
6470
6471                                                 in->yst_mode = oh->yst_mode;
6472 #ifdef CONFIG_YAFFS_WINCE
6473                                                 in->win_atime[0] = oh->win_atime[0];
6474                                                 in->win_ctime[0] = oh->win_ctime[0];
6475                                                 in->win_mtime[0] = oh->win_mtime[0];
6476                                                 in->win_atime[1] = oh->win_atime[1];
6477                                                 in->win_ctime[1] = oh->win_ctime[1];
6478                                                 in->win_mtime[1] = oh->win_mtime[1];
6479 #else
6480                                                 in->yst_uid = oh->yst_uid;
6481                                                 in->yst_gid = oh->yst_gid;
6482                                                 in->yst_atime = oh->yst_atime;
6483                                                 in->yst_mtime = oh->yst_mtime;
6484                                                 in->yst_ctime = oh->yst_ctime;
6485                                                 in->yst_rdev = oh->yst_rdev;
6486                 
6487 #endif
6488                                         } else {
6489                                                 in->variantType = tags.extraObjectType;
6490                                                 in->lazyLoaded = 1;
6491                                         }
6492
6493                                         in->hdrChunk = chunk;
6494
6495                                 } else if (!in->valid) {
6496                                         /* we need to load this info */
6497
6498                                         in->valid = 1;
6499                                         in->hdrChunk = chunk;
6500
6501                                         if(oh) {
6502                                                 in->variantType = oh->type;
6503
6504                                                 in->yst_mode = oh->yst_mode;
6505 #ifdef CONFIG_YAFFS_WINCE
6506                                                 in->win_atime[0] = oh->win_atime[0];
6507                                                 in->win_ctime[0] = oh->win_ctime[0];
6508                                                 in->win_mtime[0] = oh->win_mtime[0];
6509                                                 in->win_atime[1] = oh->win_atime[1];
6510                                                 in->win_ctime[1] = oh->win_ctime[1];
6511                                                 in->win_mtime[1] = oh->win_mtime[1];
6512 #else
6513                                                 in->yst_uid = oh->yst_uid;
6514                                                 in->yst_gid = oh->yst_gid;
6515                                                 in->yst_atime = oh->yst_atime;
6516                                                 in->yst_mtime = oh->yst_mtime;
6517                                                 in->yst_ctime = oh->yst_ctime;
6518                                                 in->yst_rdev = oh->yst_rdev;
6519 #endif
6520
6521                                                 if (oh->shadowsObject > 0) 
6522                                                         yaffs_HandleShadowedObject(dev,
6523                                                                            oh->
6524                                                                            shadowsObject,
6525                                                                            1);
6526                                         
6527
6528                                                 yaffs_SetObjectName(in, oh->name);
6529                                                 parent =
6530                                                     yaffs_FindOrCreateObjectByNumber
6531                                                         (dev, oh->parentObjectId,
6532                                                          YAFFS_OBJECT_TYPE_DIRECTORY);
6533
6534                                                  fileSize = oh->fileSize;
6535                                                  isShrink = oh->isShrink;
6536                                                  equivalentObjectId = oh->equivalentObjectId;
6537
6538                                         }
6539                                         else {
6540                                                 in->variantType = tags.extraObjectType;
6541                                                 parent =
6542                                                     yaffs_FindOrCreateObjectByNumber
6543                                                         (dev, tags.extraParentObjectId,
6544                                                          YAFFS_OBJECT_TYPE_DIRECTORY);
6545                                                  fileSize = tags.extraFileLength;
6546                                                  isShrink = tags.extraIsShrinkHeader;
6547                                                  equivalentObjectId = tags.extraEquivalentObjectId;
6548                                                 in->lazyLoaded = 1;
6549
6550                                         }
6551                                         in->dirty = 0;
6552
6553                                         /* directory stuff...
6554                                          * hook up to parent
6555                                          */
6556
6557                                         if (parent->variantType ==
6558                                             YAFFS_OBJECT_TYPE_UNKNOWN) {
6559                                                 /* Set up as a directory */
6560                                                 parent->variantType =
6561                                                     YAFFS_OBJECT_TYPE_DIRECTORY;
6562                                                 YINIT_LIST_HEAD(&parent->variant.
6563                                                                directoryVariant.
6564                                                                children);
6565                                         } else if (parent->variantType !=
6566                                                    YAFFS_OBJECT_TYPE_DIRECTORY)
6567                                         {
6568                                                 /* Hoosterman, another problem....
6569                                                  * We're trying to use a non-directory as a directory
6570                                                  */
6571
6572                                                 T(YAFFS_TRACE_ERROR,
6573                                                   (TSTR
6574                                                    ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6575                                                     TENDSTR)));
6576                                                 parent = dev->lostNFoundDir;
6577                                         }
6578
6579                                         yaffs_AddObjectToDirectory(parent, in);
6580
6581                                         itsUnlinked = (parent == dev->deletedDir) ||
6582                                                       (parent == dev->unlinkedDir);
6583
6584                                         if (isShrink) {
6585                                                 /* Mark the block as having a shrinkHeader */
6586                                                 bi->hasShrinkHeader = 1;
6587                                         }
6588
6589                                         /* Note re hardlinks.
6590                                          * Since we might scan a hardlink before its equivalent object is scanned
6591                                          * we put them all in a list.
6592                                          * After scanning is complete, we should have all the objects, so we run
6593                                          * through this list and fix up all the chains.              
6594                                          */
6595
6596                                         switch (in->variantType) {
6597                                         case YAFFS_OBJECT_TYPE_UNKNOWN: 
6598                                                 /* Todo got a problem */
6599                                                 break;
6600                                         case YAFFS_OBJECT_TYPE_FILE:
6601
6602                                                 if (in->variant.fileVariant.
6603                                                     scannedFileSize < fileSize) {
6604                                                         /* This covers the case where the file size is greater
6605                                                          * than where the data is
6606                                                          * This will happen if the file is resized to be larger 
6607                                                          * than its current data extents.
6608                                                          */
6609                                                         in->variant.fileVariant.fileSize = fileSize;
6610                                                         in->variant.fileVariant.scannedFileSize =
6611                                                             in->variant.fileVariant.fileSize;
6612                                                 }
6613
6614                                                 if (isShrink &&
6615                                                     in->variant.fileVariant.shrinkSize > fileSize) {
6616                                                         in->variant.fileVariant.shrinkSize = fileSize;
6617                                                 }
6618
6619                                                 break;
6620                                         case YAFFS_OBJECT_TYPE_HARDLINK:
6621                                                 if(!itsUnlinked) {
6622                                                   in->variant.hardLinkVariant.equivalentObjectId =
6623                                                     equivalentObjectId;
6624                                                   in->hardLinks.next =
6625                                                     (struct ylist_head *) hardList;
6626                                                   hardList = in;
6627                                                 }
6628                                                 break;
6629                                         case YAFFS_OBJECT_TYPE_DIRECTORY:
6630                                                 /* Do nothing */
6631                                                 break;
6632                                         case YAFFS_OBJECT_TYPE_SPECIAL:
6633                                                 /* Do nothing */
6634                                                 break;
6635                                         case YAFFS_OBJECT_TYPE_SYMLINK:
6636                                                 if(oh){
6637                                                    in->variant.symLinkVariant.alias =
6638                                                     yaffs_CloneString(oh->
6639                                                                       alias);
6640                                                    if(!in->variant.symLinkVariant.alias)
6641                                                         alloc_failed = 1;
6642                                                 }
6643                                                 break;
6644                                         }
6645
6646                                 }
6647                                 
6648                         }
6649
6650                 } /* End of scanning for each chunk */
6651
6652                 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6653                         /* If we got this far while scanning, then the block is fully allocated. */
6654                         state = YAFFS_BLOCK_STATE_FULL;
6655                 }
6656
6657                 bi->blockState = state;
6658
6659                 /* Now let's see if it was dirty */
6660                 if (bi->pagesInUse == 0 &&
6661                     !bi->hasShrinkHeader &&
6662                     bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6663                         yaffs_BlockBecameDirty(dev, blk);
6664                 }
6665
6666         }
6667
6668         if (altBlockIndex) 
6669                 YFREE_ALT(blockIndex);
6670         else
6671                 YFREE(blockIndex);
6672         
6673         /* Ok, we've done all the scanning.
6674          * Fix up the hard link chains.
6675          * We should now have scanned all the objects, now it's time to add these 
6676          * hardlinks.
6677          */
6678         yaffs_HardlinkFixup(dev,hardList);
6679         
6680
6681         yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6682         
6683         if(alloc_failed){
6684                 return YAFFS_FAIL;
6685         }
6686
6687         T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6688
6689         return YAFFS_OK;
6690 }
6691
6692 /*------------------------------  Directory Functions ----------------------------- */
6693
6694 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
6695 {
6696         struct ylist_head *lh;
6697         yaffs_Object *listObj;
6698         
6699         int count = 0;
6700
6701         if(!obj){
6702                 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
6703                 YBUG();
6704         }
6705
6706         if(yaffs_SkipVerification(obj->myDev))
6707                 return;
6708
6709         if(!obj->parent){
6710                 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
6711                 YBUG();
6712         }
6713                 
6714         if(obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
6715                 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
6716                 YBUG();
6717         }
6718         
6719         /* Iterate through the objects in each hash entry */
6720          
6721         ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
6722                 if (lh) {
6723                         listObj = ylist_entry(lh, yaffs_Object, siblings);
6724                         yaffs_VerifyObject(listObj);
6725                         if(obj == listObj)
6726                                 count ++;
6727                 }
6728          }
6729          
6730          if(count != 1){
6731                 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR),count));
6732                 YBUG();
6733         }
6734
6735 }
6736
6737 static void yaffs_VerifyDirectory(yaffs_Object *directory)
6738 {
6739
6740         struct ylist_head *lh;
6741         yaffs_Object *listObj;
6742         
6743         if(!directory)
6744                 YBUG();
6745
6746         if(yaffs_SkipFullVerification(directory->myDev))
6747                 return;
6748
6749                 
6750         if(directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
6751                 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR),directory->variantType));
6752                 YBUG();
6753         }
6754         
6755         /* Iterate through the objects in each hash entry */
6756          
6757         ylist_for_each(lh, &directory->variant.directoryVariant.children) {
6758                 if (lh) {
6759                         listObj = ylist_entry(lh, yaffs_Object, siblings);
6760                         if(listObj->parent != directory){
6761                                 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR),listObj->parent));
6762                                 YBUG();
6763                         }
6764                         yaffs_VerifyObjectInDirectory(listObj);
6765                 }
6766          }
6767          
6768 }
6769
6770
6771 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
6772 {
6773         yaffs_Device *dev = obj->myDev;
6774         yaffs_Object *parent;
6775         
6776         yaffs_VerifyObjectInDirectory(obj);
6777         parent = obj->parent;
6778         
6779         yaffs_VerifyDirectory(parent);
6780
6781         if(dev && dev->removeObjectCallback)
6782                 dev->removeObjectCallback(obj);
6783
6784            
6785         ylist_del_init(&obj->siblings);
6786         obj->parent = NULL;
6787
6788         yaffs_VerifyDirectory(parent);
6789
6790 }
6791
6792
6793 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
6794                                        yaffs_Object * obj)
6795 {
6796
6797         if (!directory) {
6798                 T(YAFFS_TRACE_ALWAYS,
6799                   (TSTR
6800                    ("tragedy: Trying to add an object to a null pointer directory"
6801                     TENDSTR)));
6802                 YBUG();
6803         }
6804         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6805                 T(YAFFS_TRACE_ALWAYS,
6806                   (TSTR
6807                    ("tragedy: Trying to add an object to a non-directory"
6808                     TENDSTR)));
6809                 YBUG();
6810         }
6811
6812         if (obj->siblings.prev == NULL) {
6813                 /* Not initialised */
6814                 YBUG();
6815
6816         } else if (ylist_empty(&obj->siblings)) {
6817                 YBUG();
6818         } 
6819
6820
6821         yaffs_VerifyDirectory(directory);
6822
6823         yaffs_RemoveObjectFromDirectory(obj);
6824         
6825         
6826         /* Now add it */
6827         ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
6828         obj->parent = directory;
6829
6830         if (directory == obj->myDev->unlinkedDir
6831             || directory == obj->myDev->deletedDir) {
6832                 obj->unlinked = 1;
6833                 obj->myDev->nUnlinkedFiles++;
6834                 obj->renameAllowed = 0;
6835         }
6836
6837         yaffs_VerifyDirectory(directory);
6838         yaffs_VerifyObjectInDirectory(obj);
6839
6840
6841 }
6842
6843 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
6844                                      const YCHAR * name)
6845 {
6846         int sum;
6847
6848         struct ylist_head *i;
6849         YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
6850
6851         yaffs_Object *l;
6852
6853         if (!name) {
6854                 return NULL;
6855         }
6856
6857         if (!directory) {
6858                 T(YAFFS_TRACE_ALWAYS,
6859                   (TSTR
6860                    ("tragedy: yaffs_FindObjectByName: null pointer directory"
6861                     TENDSTR)));
6862                 YBUG();
6863         }
6864         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6865                 T(YAFFS_TRACE_ALWAYS,
6866                   (TSTR
6867                    ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6868                 YBUG();
6869         }
6870
6871         sum = yaffs_CalcNameSum(name);
6872
6873         ylist_for_each(i, &directory->variant.directoryVariant.children) {
6874                 if (i) {
6875                         l = ylist_entry(i, yaffs_Object, siblings);
6876                         
6877                         if(l->parent != directory)
6878                                 YBUG();
6879                         
6880                         yaffs_CheckObjectDetailsLoaded(l);
6881
6882                         /* Special case for lost-n-found */
6883                         if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6884                                 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
6885                                         return l;
6886                                 }
6887                         } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0){
6888                                 /* LostnFound chunk called Objxxx
6889                                  * Do a real check
6890                                  */
6891                                 yaffs_GetObjectName(l, buffer,
6892                                                     YAFFS_MAX_NAME_LENGTH);
6893                                 if (yaffs_strncmp(name, buffer,YAFFS_MAX_NAME_LENGTH) == 0) {
6894                                         return l;
6895                                 }
6896
6897                         }
6898                 }
6899         }
6900
6901         return NULL;
6902 }
6903
6904
6905 #if 0
6906 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
6907                                    int (*fn) (yaffs_Object *))
6908 {
6909         struct ylist_head *i;
6910         yaffs_Object *l;
6911
6912         if (!theDir) {
6913                 T(YAFFS_TRACE_ALWAYS,
6914                   (TSTR
6915                    ("tragedy: yaffs_FindObjectByName: null pointer directory"
6916                     TENDSTR)));
6917                 YBUG();
6918         }
6919         if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6920                 T(YAFFS_TRACE_ALWAYS,
6921                   (TSTR
6922                    ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6923                 YBUG();
6924         }
6925
6926         ylist_for_each(i, &theDir->variant.directoryVariant.children) {
6927                 if (i) {
6928                         l = ylist_entry(i, yaffs_Object, siblings);
6929                         if (l && !fn(l)) {
6930                                 return YAFFS_FAIL;
6931                         }
6932                 }
6933         }
6934
6935         return YAFFS_OK;
6936
6937 }
6938 #endif
6939
6940 /* GetEquivalentObject dereferences any hard links to get to the
6941  * actual object.
6942  */
6943
6944 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
6945 {
6946         if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
6947                 /* We want the object id of the equivalent object, not this one */
6948                 obj = obj->variant.hardLinkVariant.equivalentObject;
6949                 yaffs_CheckObjectDetailsLoaded(obj);
6950         }
6951         return obj;
6952
6953 }
6954
6955 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
6956 {
6957         memset(name, 0, buffSize * sizeof(YCHAR));
6958         
6959         yaffs_CheckObjectDetailsLoaded(obj);
6960
6961         if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6962                 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
6963         } else if (obj->hdrChunk <= 0) {
6964                 YCHAR locName[20];
6965                 YCHAR numString[20];
6966                 YCHAR *x = &numString[19];
6967                 unsigned v = obj->objectId;
6968                 numString[19] = 0;
6969                 while(v>0){
6970                         x--;
6971                         *x = '0' + (v % 10);
6972                         v /= 10;
6973                 }
6974                 /* make up a name */
6975                 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
6976                 yaffs_strcat(locName,x);
6977                 yaffs_strncpy(name, locName, buffSize - 1);
6978
6979         }
6980 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
6981         else if (obj->shortName[0]) {
6982                 yaffs_strcpy(name, obj->shortName);
6983         }
6984 #endif
6985         else {
6986                 int result;
6987                 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
6988
6989                 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
6990
6991                 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
6992
6993                 if (obj->hdrChunk > 0) {
6994                         result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
6995                                                         obj->hdrChunk, buffer,
6996                                                         NULL);
6997                 }
6998                 yaffs_strncpy(name, oh->name, buffSize - 1);
6999
7000                 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
7001         }
7002
7003         return yaffs_strlen(name);
7004 }
7005
7006 int yaffs_GetObjectFileLength(yaffs_Object * obj)
7007 {
7008
7009         /* Dereference any hard linking */
7010         obj = yaffs_GetEquivalentObject(obj);
7011
7012         if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
7013                 return obj->variant.fileVariant.fileSize;
7014         }
7015         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
7016                 return yaffs_strlen(obj->variant.symLinkVariant.alias);
7017         } else {
7018                 /* Only a directory should drop through to here */
7019                 return obj->myDev->nDataBytesPerChunk;
7020         }
7021 }
7022
7023 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
7024 {
7025         int count = 0;
7026         struct ylist_head *i;
7027
7028         if (!obj->unlinked) {
7029                 count++;        /* the object itself */
7030         }
7031         ylist_for_each(i, &obj->hardLinks) {
7032                 count++;        /* add the hard links; */
7033         }
7034         return count;
7035
7036 }
7037
7038 int yaffs_GetObjectInode(yaffs_Object * obj)
7039 {
7040         obj = yaffs_GetEquivalentObject(obj);
7041
7042         return obj->objectId;
7043 }
7044
7045 unsigned yaffs_GetObjectType(yaffs_Object * obj)
7046 {
7047         obj = yaffs_GetEquivalentObject(obj);
7048
7049         switch (obj->variantType) {
7050         case YAFFS_OBJECT_TYPE_FILE:
7051                 return DT_REG;
7052                 break;
7053         case YAFFS_OBJECT_TYPE_DIRECTORY:
7054                 return DT_DIR;
7055                 break;
7056         case YAFFS_OBJECT_TYPE_SYMLINK:
7057                 return DT_LNK;
7058                 break;
7059         case YAFFS_OBJECT_TYPE_HARDLINK:
7060                 return DT_REG;
7061                 break;
7062         case YAFFS_OBJECT_TYPE_SPECIAL:
7063                 if (S_ISFIFO(obj->yst_mode))
7064                         return DT_FIFO;
7065                 if (S_ISCHR(obj->yst_mode))
7066                         return DT_CHR;
7067                 if (S_ISBLK(obj->yst_mode))
7068                         return DT_BLK;
7069                 if (S_ISSOCK(obj->yst_mode))
7070                         return DT_SOCK;
7071         default:
7072                 return DT_REG;
7073                 break;
7074         }
7075 }
7076
7077 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
7078 {
7079         obj = yaffs_GetEquivalentObject(obj);
7080         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
7081                 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7082         } else {
7083                 return yaffs_CloneString(_Y(""));
7084         }
7085 }
7086
7087 #ifndef CONFIG_YAFFS_WINCE
7088
7089 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
7090 {
7091         unsigned int valid = attr->ia_valid;
7092
7093         if (valid & ATTR_MODE)
7094                 obj->yst_mode = attr->ia_mode;
7095         if (valid & ATTR_UID)
7096                 obj->yst_uid = attr->ia_uid;
7097         if (valid & ATTR_GID)
7098                 obj->yst_gid = attr->ia_gid;
7099
7100         if (valid & ATTR_ATIME)
7101                 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7102         if (valid & ATTR_CTIME)
7103                 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7104         if (valid & ATTR_MTIME)
7105                 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7106
7107         if (valid & ATTR_SIZE)
7108                 yaffs_ResizeFile(obj, attr->ia_size);
7109
7110         yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7111
7112         return YAFFS_OK;
7113
7114 }
7115 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
7116 {
7117         unsigned int valid = 0;
7118
7119         attr->ia_mode = obj->yst_mode;
7120         valid |= ATTR_MODE;
7121         attr->ia_uid = obj->yst_uid;
7122         valid |= ATTR_UID;
7123         attr->ia_gid = obj->yst_gid;
7124         valid |= ATTR_GID;
7125
7126         Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7127         valid |= ATTR_ATIME;
7128         Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7129         valid |= ATTR_CTIME;
7130         Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7131         valid |= ATTR_MTIME;
7132
7133         attr->ia_size = yaffs_GetFileSize(obj);
7134         valid |= ATTR_SIZE;
7135
7136         attr->ia_valid = valid;
7137
7138         return YAFFS_OK;
7139
7140 }
7141
7142 #endif
7143
7144 #if 0
7145 int yaffs_DumpObject(yaffs_Object * obj)
7146 {
7147         YCHAR name[257];
7148
7149         yaffs_GetObjectName(obj, name, 256);
7150
7151         T(YAFFS_TRACE_ALWAYS,
7152           (TSTR
7153            ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7154             " chunk %d type %d size %d\n"
7155             TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7156            obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7157            yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7158
7159         return YAFFS_OK;
7160 }
7161 #endif
7162
7163 /*---------------------------- Initialisation code -------------------------------------- */
7164
7165 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
7166 {
7167
7168         /* Common functions, gotta have */
7169         if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
7170                 return 0;
7171
7172 #ifdef CONFIG_YAFFS_YAFFS2
7173
7174         /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7175         if (dev->writeChunkWithTagsToNAND &&
7176             dev->readChunkWithTagsFromNAND &&
7177             !dev->writeChunkToNAND &&
7178             !dev->readChunkFromNAND &&
7179             dev->markNANDBlockBad && dev->queryNANDBlock)
7180                 return 1;
7181 #endif
7182
7183         /* Can use the "spare" style interface for yaffs1 */
7184         if (!dev->isYaffs2 &&
7185             !dev->writeChunkWithTagsToNAND &&
7186             !dev->readChunkWithTagsFromNAND &&
7187             dev->writeChunkToNAND &&
7188             dev->readChunkFromNAND &&
7189             !dev->markNANDBlockBad && !dev->queryNANDBlock)
7190                 return 1;
7191
7192         return 0;               /* bad */
7193 }
7194
7195
7196 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7197 {
7198         /* Initialise the unlinked, deleted, root and lost and found directories */
7199         
7200         dev->lostNFoundDir = dev->rootDir =  NULL;
7201         dev->unlinkedDir = dev->deletedDir = NULL;
7202
7203         dev->unlinkedDir =
7204             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7205         
7206         dev->deletedDir =
7207             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7208
7209         dev->rootDir =
7210             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7211                                       YAFFS_ROOT_MODE | S_IFDIR);
7212         dev->lostNFoundDir =
7213             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7214                                       YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7215         
7216         if(dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir){
7217                 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7218                 return YAFFS_OK;
7219         }
7220         
7221         return YAFFS_FAIL;
7222 }
7223
7224 int yaffs_GutsInitialise(yaffs_Device * dev)
7225 {
7226         int init_failed = 0;
7227         unsigned x;
7228         int bits;
7229
7230         T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7231
7232         /* Check stuff that must be set */
7233
7234         if (!dev) {
7235                 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7236                 return YAFFS_FAIL;
7237         }
7238
7239         dev->internalStartBlock = dev->startBlock;
7240         dev->internalEndBlock = dev->endBlock;
7241         dev->blockOffset = 0;
7242         dev->chunkOffset = 0;
7243         dev->nFreeChunks = 0;
7244         
7245         dev->gcBlock = -1;
7246
7247         if (dev->startBlock == 0) {
7248                 dev->internalStartBlock = dev->startBlock + 1;
7249                 dev->internalEndBlock = dev->endBlock + 1;
7250                 dev->blockOffset = 1;
7251                 dev->chunkOffset = dev->nChunksPerBlock;
7252         }
7253
7254         /* Check geometry parameters. */
7255
7256         if ((!dev->inbandTags && dev->isYaffs2 && dev->totalBytesPerChunk < 1024) || 
7257             (!dev->isYaffs2 && dev->totalBytesPerChunk < 512) || 
7258             (dev->inbandTags && !dev->isYaffs2 ) ||
7259              dev->nChunksPerBlock < 2 || 
7260              dev->nReservedBlocks < 2 || 
7261              dev->internalStartBlock <= 0 || 
7262              dev->internalEndBlock <= 0 || 
7263              dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2)      // otherwise it is too small
7264             ) {
7265                 T(YAFFS_TRACE_ALWAYS,
7266                   (TSTR
7267                    ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7268                     TENDSTR), dev->totalBytesPerChunk, dev->isYaffs2 ? "2" : "", dev->inbandTags));
7269                 return YAFFS_FAIL;
7270         }
7271
7272         if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7273                 T(YAFFS_TRACE_ALWAYS,
7274                   (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7275                 return YAFFS_FAIL;
7276         }
7277         
7278         /* Sort out space for inband tags, if required */
7279         if(dev->inbandTags)
7280                 dev->nDataBytesPerChunk = dev->totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7281         else 
7282                 dev->nDataBytesPerChunk = dev->totalBytesPerChunk;
7283
7284         /* Got the right mix of functions? */
7285         if (!yaffs_CheckDevFunctions(dev)) {
7286                 /* Function missing */
7287                 T(YAFFS_TRACE_ALWAYS,
7288                   (TSTR
7289                    ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7290
7291                 return YAFFS_FAIL;
7292         }
7293
7294         /* This is really a compilation check. */
7295         if (!yaffs_CheckStructures()) {
7296                 T(YAFFS_TRACE_ALWAYS,
7297                   (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7298                 return YAFFS_FAIL;
7299         }
7300
7301         if (dev->isMounted) {
7302                 T(YAFFS_TRACE_ALWAYS,
7303                   (TSTR("yaffs: device already mounted\n" TENDSTR)));
7304                 return YAFFS_FAIL;
7305         }
7306
7307         /* Finished with most checks. One or two more checks happen later on too. */
7308
7309         dev->isMounted = 1;
7310
7311         /* OK now calculate a few things for the device */
7312         
7313         /*
7314          *  Calculate all the chunk size manipulation numbers:   
7315          */
7316         x = dev->nDataBytesPerChunk;
7317         /* We always use dev->chunkShift and dev->chunkDiv */
7318         dev->chunkShift = Shifts(x);
7319         x >>= dev->chunkShift;
7320         dev->chunkDiv = x;
7321         /* We only use chunk mask if chunkDiv is 1 */
7322         dev->chunkMask = (1<<dev->chunkShift) - 1;
7323                 
7324         /*
7325          * Calculate chunkGroupBits.
7326          * We need to find the next power of 2 > than internalEndBlock
7327          */
7328
7329         x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7330         
7331         bits = ShiftsGE(x);
7332         
7333         /* Set up tnode width if wide tnodes are enabled. */
7334         if(!dev->wideTnodesDisabled){
7335                 /* bits must be even so that we end up with 32-bit words */
7336                 if(bits & 1)
7337                         bits++;
7338                 if(bits < 16)
7339                         dev->tnodeWidth = 16;
7340                 else
7341                         dev->tnodeWidth = bits;
7342         }
7343         else
7344                 dev->tnodeWidth = 16;
7345  
7346         dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7347                 
7348         /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7349          * so if the bitwidth of the
7350          * chunk range we're using is greater than 16 we need
7351          * to figure out chunk shift and chunkGroupSize
7352          */
7353                  
7354         if (bits <= dev->tnodeWidth)
7355                 dev->chunkGroupBits = 0;
7356         else
7357                 dev->chunkGroupBits = bits - dev->tnodeWidth;
7358                 
7359
7360         dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7361
7362         if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7363                 /* We have a problem because the soft delete won't work if
7364                  * the chunk group size > chunks per block.
7365                  * This can be remedied by using larger "virtual blocks".
7366                  */
7367                 T(YAFFS_TRACE_ALWAYS,
7368                   (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7369
7370                 return YAFFS_FAIL;
7371         }
7372
7373         /* OK, we've finished verifying the device, lets continue with initialisation */
7374
7375         /* More device initialisation */
7376         dev->garbageCollections = 0;
7377         dev->passiveGarbageCollections = 0;
7378         dev->currentDirtyChecker = 0;
7379         dev->bufferedBlock = -1;
7380         dev->doingBufferedBlockRewrite = 0;
7381         dev->nDeletedFiles = 0;
7382         dev->nBackgroundDeletions = 0;
7383         dev->nUnlinkedFiles = 0;
7384         dev->eccFixed = 0;
7385         dev->eccUnfixed = 0;
7386         dev->tagsEccFixed = 0;
7387         dev->tagsEccUnfixed = 0;
7388         dev->nErasureFailures = 0;
7389         dev->nErasedBlocks = 0;
7390         dev->isDoingGC = 0;
7391         dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7392
7393         /* Initialise temporary buffers and caches. */
7394         if(!yaffs_InitialiseTempBuffers(dev))
7395                 init_failed = 1;
7396         
7397         dev->srCache = NULL;
7398         dev->gcCleanupList = NULL;
7399         
7400         
7401         if (!init_failed &&
7402             dev->nShortOpCaches > 0) {
7403                 int i;
7404                 void *buf;
7405                 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7406
7407                 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
7408                         dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7409                 }
7410
7411                 dev->srCache =  YMALLOC(srCacheBytes);
7412                 
7413                 buf = (__u8 *) dev->srCache;
7414                     
7415                 if(dev->srCache)
7416                         memset(dev->srCache,0,srCacheBytes);
7417                    
7418                 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7419                         dev->srCache[i].object = NULL;
7420                         dev->srCache[i].lastUse = 0;
7421                         dev->srCache[i].dirty = 0;
7422                         dev->srCache[i].data = buf = YMALLOC_DMA(dev->totalBytesPerChunk);
7423                 }
7424                 if(!buf)
7425                         init_failed = 1;
7426                         
7427                 dev->srLastUse = 0;
7428         }
7429
7430         dev->cacheHits = 0;
7431         
7432         if(!init_failed){
7433                 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7434                 if(!dev->gcCleanupList)
7435                         init_failed = 1;
7436         }
7437
7438         if (dev->isYaffs2) {
7439                 dev->useHeaderFileSize = 1;
7440         }
7441         if(!init_failed && !yaffs_InitialiseBlocks(dev))
7442                 init_failed = 1;
7443                 
7444         yaffs_InitialiseTnodes(dev);
7445         yaffs_InitialiseObjects(dev);
7446
7447         if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7448                 init_failed = 1;
7449
7450
7451         if(!init_failed){
7452                 /* Now scan the flash. */
7453                 if (dev->isYaffs2) {
7454                         if(yaffs_CheckpointRestore(dev)) {
7455                                 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7456                                 T(YAFFS_TRACE_ALWAYS,
7457                                   (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7458                         } else {
7459
7460                                 /* Clean up the mess caused by an aborted checkpoint load 
7461                                  * and scan backwards. 
7462                                  */
7463                                 yaffs_DeinitialiseBlocks(dev);
7464                                 yaffs_DeinitialiseTnodes(dev);
7465                                 yaffs_DeinitialiseObjects(dev);
7466                                 
7467                         
7468                                 dev->nErasedBlocks = 0;
7469                                 dev->nFreeChunks = 0;
7470                                 dev->allocationBlock = -1;
7471                                 dev->allocationPage = -1;
7472                                 dev->nDeletedFiles = 0;
7473                                 dev->nUnlinkedFiles = 0;
7474                                 dev->nBackgroundDeletions = 0;
7475                                 dev->oldestDirtySequence = 0;
7476
7477                                 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7478                                         init_failed = 1;
7479                                         
7480                                 yaffs_InitialiseTnodes(dev);
7481                                 yaffs_InitialiseObjects(dev);
7482
7483                                 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7484                                         init_failed = 1;
7485
7486                                 if(!init_failed && !yaffs_ScanBackwards(dev))
7487                                         init_failed = 1;
7488                         }
7489                 }else
7490                         if(!yaffs_Scan(dev))
7491                                 init_failed = 1;
7492
7493                 yaffs_StripDeletedObjects(dev);
7494         }
7495                 
7496         if(init_failed){
7497                 /* Clean up the mess */
7498                 T(YAFFS_TRACE_TRACING,
7499                   (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7500
7501                 yaffs_Deinitialise(dev);
7502                 return YAFFS_FAIL;
7503         }
7504
7505         /* Zero out stats */
7506         dev->nPageReads = 0;
7507         dev->nPageWrites = 0;
7508         dev->nBlockErasures = 0;
7509         dev->nGCCopies = 0;
7510         dev->nRetriedWrites = 0;
7511
7512         dev->nRetiredBlocks = 0;
7513
7514         yaffs_VerifyFreeChunks(dev);
7515         yaffs_VerifyBlocks(dev);
7516         
7517
7518         T(YAFFS_TRACE_TRACING,
7519           (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7520         return YAFFS_OK;
7521
7522 }
7523
7524 void yaffs_Deinitialise(yaffs_Device * dev)
7525 {
7526         if (dev->isMounted) {
7527                 int i;
7528
7529                 yaffs_DeinitialiseBlocks(dev);
7530                 yaffs_DeinitialiseTnodes(dev);
7531                 yaffs_DeinitialiseObjects(dev);
7532                 if (dev->nShortOpCaches > 0 &&
7533                     dev->srCache) {
7534
7535                         for (i = 0; i < dev->nShortOpCaches; i++) {
7536                                 if(dev->srCache[i].data)
7537                                         YFREE(dev->srCache[i].data);
7538                                 dev->srCache[i].data = NULL;
7539                         }
7540
7541                         YFREE(dev->srCache);
7542                         dev->srCache = NULL;
7543                 }
7544
7545                 YFREE(dev->gcCleanupList);
7546
7547                 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
7548                         YFREE(dev->tempBuffer[i].buffer);
7549                 }
7550
7551
7552                 dev->isMounted = 0;
7553                 
7554                 if(dev->deinitialiseNAND)
7555                         dev->deinitialiseNAND(dev);
7556         }
7557
7558 }
7559
7560 static int yaffs_CountFreeChunks(yaffs_Device * dev)
7561 {
7562         int nFree;
7563         int b;
7564
7565         yaffs_BlockInfo *blk;
7566
7567         for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7568              b++) {
7569                 blk = yaffs_GetBlockInfo(dev, b);
7570
7571                 switch (blk->blockState) {
7572                 case YAFFS_BLOCK_STATE_EMPTY:
7573                 case YAFFS_BLOCK_STATE_ALLOCATING:
7574                 case YAFFS_BLOCK_STATE_COLLECTING:
7575                 case YAFFS_BLOCK_STATE_FULL:
7576                         nFree +=
7577                             (dev->nChunksPerBlock - blk->pagesInUse +
7578                              blk->softDeletions);
7579                         break;
7580                 default:
7581                         break;
7582                 }
7583
7584         }
7585
7586         return nFree;
7587 }
7588
7589 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
7590 {
7591         /* This is what we report to the outside world */
7592
7593         int nFree;
7594         int nDirtyCacheChunks;
7595         int blocksForCheckpoint;
7596
7597 #if 1
7598         nFree = dev->nFreeChunks;
7599 #else
7600         nFree = yaffs_CountFreeChunks(dev);
7601 #endif
7602
7603         nFree += dev->nDeletedFiles;
7604         
7605         /* Now count the number of dirty chunks in the cache and subtract those */
7606
7607         {
7608                 int i;
7609                 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7610                         if (dev->srCache[i].dirty)
7611                                 nDirtyCacheChunks++;
7612                 }
7613         }
7614
7615         nFree -= nDirtyCacheChunks;
7616
7617         nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7618         
7619         /* Now we figure out how much to reserve for the checkpoint and report that... */
7620         blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7621         if(blocksForCheckpoint < 0)
7622                 blocksForCheckpoint = 0;
7623                 
7624         nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7625
7626         if (nFree < 0)
7627                 nFree = 0;
7628
7629         return nFree;
7630
7631 }
7632
7633 static int yaffs_freeVerificationFailures;
7634
7635 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
7636 {
7637         int counted;
7638         int difference;
7639         
7640         if(yaffs_SkipVerification(dev))
7641                 return;
7642         
7643         counted = yaffs_CountFreeChunks(dev);
7644
7645         difference = dev->nFreeChunks - counted;
7646
7647         if (difference) {
7648                 T(YAFFS_TRACE_ALWAYS,
7649                   (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7650                    dev->nFreeChunks, counted, difference));
7651                 yaffs_freeVerificationFailures++;
7652         }
7653 }
7654
7655 /*---------------------------------------- YAFFS test code ----------------------*/
7656
7657 #define yaffs_CheckStruct(structure,syze, name) \
7658         do { \
7659            if(sizeof(structure) != syze) \
7660                { \
7661                  T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
7662                  name,syze,sizeof(structure))); \
7663                  return YAFFS_FAIL; \
7664                 } \
7665         } while(0)
7666
7667 static int yaffs_CheckStructures(void)
7668 {
7669 /*      yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
7670 /*      yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
7671 /*      yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
7672 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7673         yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode");
7674 #endif
7675 #ifndef CONFIG_YAFFS_WINCE
7676                 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");
7677 #endif
7678             return YAFFS_OK;
7679 }