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