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