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