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