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