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