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