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