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