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