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