Checkpointing changes
[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.32 2006-05-08 10:13:34 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 (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
1904                     (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
1905                     yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
1906                         dirtiest = b;
1907                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
1908                 }
1909         }
1910
1911         dev->currentDirtyChecker = b;
1912
1913         if (dirtiest > 0) {
1914                 T(YAFFS_TRACE_GC,
1915                   (TSTR("GC Selected block %d with %d free" TENDSTR), dirtiest,
1916                    dev->nChunksPerBlock - pagesInUse));
1917         }
1918
1919         dev->oldestDirtySequence = 0;
1920
1921         if (dirtiest > 0) {
1922                 nonAggressiveSkip = 4;
1923         }
1924
1925         return dirtiest;
1926 }
1927
1928 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
1929 {
1930         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
1931
1932         int erasedOk = 0;
1933
1934         /* If the block is still healthy erase it and mark as clean.
1935          * If the block has had a data failure, then retire it.
1936          */
1937         bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
1938
1939         if (!bi->needsRetiring) {
1940                 yaffs_InvalidateCheckpoint(dev);
1941                 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
1942                 if (!erasedOk) {
1943                         dev->nErasureFailures++;
1944                         T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1945                           (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
1946                 }
1947         }
1948
1949         if (erasedOk && (yaffs_traceMask & YAFFS_TRACE_ERASE)) {
1950                 int i;
1951                 for (i = 0; i < dev->nChunksPerBlock; i++) {
1952                         if (!yaffs_CheckChunkErased
1953                             (dev, blockNo * dev->nChunksPerBlock + i)) {
1954                                 T(YAFFS_TRACE_ERROR,
1955                                   (TSTR
1956                                    (">>Block %d erasure supposedly OK, but chunk %d not erased"
1957                                     TENDSTR), blockNo, i));
1958                         }
1959                 }
1960         }
1961
1962         if (erasedOk) {
1963                 /* Clean it up... */
1964                 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
1965                 dev->nErasedBlocks++;
1966                 bi->pagesInUse = 0;
1967                 bi->softDeletions = 0;
1968                 bi->hasShrinkHeader = 0;
1969                 yaffs_ClearChunkBits(dev, blockNo);
1970
1971                 T(YAFFS_TRACE_ERASE,
1972                   (TSTR("Erased block %d" TENDSTR), blockNo));
1973         } else {
1974                 dev->nFreeChunks -= dev->nChunksPerBlock;       /* We lost a block of free space */
1975
1976                 yaffs_RetireBlock(dev, blockNo);
1977                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1978                   (TSTR("**>> Block %d retired" TENDSTR), blockNo));
1979         }
1980 }
1981
1982 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
1983 {
1984         int i;
1985
1986         yaffs_BlockInfo *bi;
1987
1988         if (dev->nErasedBlocks < 1) {
1989                 /* Hoosterman we've got a problem.
1990                  * Can't get space to gc
1991                  */
1992                 T(YAFFS_TRACE_ERROR,
1993                   (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
1994
1995                 return -1;
1996         }
1997         
1998         /* Find an empty block. */
1999
2000         for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2001                 dev->allocationBlockFinder++;
2002                 if (dev->allocationBlockFinder < dev->internalStartBlock
2003                     || dev->allocationBlockFinder > dev->internalEndBlock) {
2004                         dev->allocationBlockFinder = dev->internalStartBlock;
2005                 }
2006
2007                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2008
2009                 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2010                         bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2011                         dev->sequenceNumber++;
2012                         bi->sequenceNumber = dev->sequenceNumber;
2013                         dev->nErasedBlocks--;
2014                         T(YAFFS_TRACE_ALLOCATE,
2015                           (TSTR("Allocated block %d, seq  %d, %d left" TENDSTR),
2016                            dev->allocationBlockFinder, dev->sequenceNumber,
2017                            dev->nErasedBlocks));
2018                         return dev->allocationBlockFinder;
2019                 }
2020         }
2021
2022         T(YAFFS_TRACE_ALWAYS,
2023           (TSTR
2024            ("yaffs tragedy: no more eraased blocks, but there should have been %d"
2025             TENDSTR), dev->nErasedBlocks));
2026
2027         return -1;
2028 }
2029
2030
2031
2032 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2033 {
2034         int reservedChunks = (dev->nReservedBlocks * dev->nChunksPerBlock);
2035         return (dev->nFreeChunks > reservedChunks);
2036 }
2037
2038 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve)
2039 {
2040         int retVal;
2041         yaffs_BlockInfo *bi;
2042
2043         if (dev->allocationBlock < 0) {
2044                 /* Get next block to allocate off */
2045                 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2046                 dev->allocationPage = 0;
2047         }
2048
2049         if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2050                 /* Not enough space to allocate unless we're allowed to use the reserve. */
2051                 return -1;
2052         }
2053
2054         if (dev->nErasedBlocks < dev->nReservedBlocks
2055             && dev->allocationPage == 0) {
2056                 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2057         }
2058
2059         /* Next page please.... */
2060         if (dev->allocationBlock >= 0) {
2061                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2062
2063                 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2064                     dev->allocationPage;
2065                 bi->pagesInUse++;
2066                 yaffs_SetChunkBit(dev, dev->allocationBlock,
2067                                   dev->allocationPage);
2068
2069                 dev->allocationPage++;
2070
2071                 dev->nFreeChunks--;
2072
2073                 /* If the block is full set the state to full */
2074                 if (dev->allocationPage >= dev->nChunksPerBlock) {
2075                         bi->blockState = YAFFS_BLOCK_STATE_FULL;
2076                         dev->allocationBlock = -1;
2077                 }
2078
2079                 return retVal;
2080         }
2081         
2082         T(YAFFS_TRACE_ERROR,
2083           (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2084
2085         return -1;
2086 }
2087
2088 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2089 {
2090         int n;
2091
2092         n = dev->nErasedBlocks * dev->nChunksPerBlock;
2093
2094         if (dev->allocationBlock > 0) {
2095                 n += (dev->nChunksPerBlock - dev->allocationPage);
2096         }
2097
2098         return n;
2099
2100 }
2101
2102 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2103 {
2104         int oldChunk;
2105         int newChunk;
2106         int chunkInBlock;
2107         int markNAND;
2108         int retVal = YAFFS_OK;
2109         int cleanups = 0;
2110         int i;
2111
2112         int chunksBefore = yaffs_GetErasedChunks(dev);
2113         int chunksAfter;
2114
2115         yaffs_ExtendedTags tags;
2116
2117         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2118
2119         yaffs_Object *object;
2120
2121         bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2122
2123         T(YAFFS_TRACE_TRACING,
2124           (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2125            bi->pagesInUse, bi->hasShrinkHeader));
2126
2127         /*yaffs_VerifyFreeChunks(dev); */
2128
2129         bi->hasShrinkHeader = 0;        /* clear the flag so that the block can erase */
2130
2131         /* Take off the number of soft deleted entries because
2132          * they're going to get really deleted during GC.
2133          */
2134         dev->nFreeChunks -= bi->softDeletions;
2135
2136         dev->isDoingGC = 1;
2137
2138         if (!yaffs_StillSomeChunkBits(dev, block)) {
2139                 T(YAFFS_TRACE_TRACING,
2140                   (TSTR
2141                    ("Collecting block %d that has no chunks in use" TENDSTR),
2142                    block));
2143                 yaffs_BlockBecameDirty(dev, block);
2144         } else {
2145
2146                 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2147
2148                 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
2149                      chunkInBlock < dev->nChunksPerBlock
2150                      && yaffs_StillSomeChunkBits(dev, block);
2151                      chunkInBlock++, oldChunk++) {
2152                         if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
2153
2154                                 /* This page is in use and might need to be copied off */
2155
2156                                 markNAND = 1;
2157
2158                                 yaffs_InitialiseTags(&tags);
2159
2160                                 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2161                                                                 buffer, &tags);
2162
2163                                 object =
2164                                     yaffs_FindObjectByNumber(dev,
2165                                                              tags.objectId);
2166
2167                                 T(YAFFS_TRACE_GC_DETAIL,
2168                                   (TSTR
2169                                    ("Collecting page %d, %d %d %d " TENDSTR),
2170                                    chunkInBlock, tags.objectId, tags.chunkId,
2171                                    tags.byteCount));
2172
2173                                 if (!object) {
2174                                         T(YAFFS_TRACE_ERROR,
2175                                           (TSTR
2176                                            ("page %d in gc has no object "
2177                                             TENDSTR), oldChunk));
2178                                 }
2179
2180                                 if (object && object->deleted
2181                                     && tags.chunkId != 0) {
2182                                         /* Data chunk in a deleted file, throw it away
2183                                          * It's a soft deleted data chunk,
2184                                          * No need to copy this, just forget about it and 
2185                                          * fix up the object.
2186                                          */
2187
2188                                         object->nDataChunks--;
2189
2190                                         if (object->nDataChunks <= 0) {
2191                                                 /* remeber to clean up the object */
2192                                                 dev->gcCleanupList[cleanups] =
2193                                                     tags.objectId;
2194                                                 cleanups++;
2195                                         }
2196                                         markNAND = 0;
2197                                 } else if (0
2198                                            /* Todo object && object->deleted && object->nDataChunks == 0 */
2199                                            ) {
2200                                         /* Deleted object header with no data chunks.
2201                                          * Can be discarded and the file deleted.
2202                                          */
2203                                         object->chunkId = 0;
2204                                         yaffs_FreeTnode(object->myDev,
2205                                                         object->variant.
2206                                                         fileVariant.top);
2207                                         object->variant.fileVariant.top = NULL;
2208                                         yaffs_DoGenericObjectDeletion(object);
2209
2210                                 } else if (object) {
2211                                         /* It's either a data chunk in a live file or
2212                                          * an ObjectHeader, so we're interested in it.
2213                                          * NB Need to keep the ObjectHeaders of deleted files
2214                                          * until the whole file has been deleted off
2215                                          */
2216                                         tags.serialNumber++;
2217
2218                                         dev->nGCCopies++;
2219
2220                                         if (tags.chunkId == 0) {
2221                                                 /* It is an object Id,
2222                                                  * We need to nuke the shrinkheader flags first
2223                                                  * We no longer want the shrinkHeader flag since its work is done
2224                                                  * and if it is left in place it will mess up scanning.
2225                                                  * Also, clear out any shadowing stuff
2226                                                  */
2227
2228                                                 yaffs_ObjectHeader *oh;
2229                                                 oh = (yaffs_ObjectHeader *)buffer;
2230                                                 oh->isShrink = 0;
2231                                                 oh->shadowsObject = -1;
2232                                                 tags.extraShadows = 0;
2233                                                 tags.extraIsShrinkHeader = 0;
2234                                         }
2235
2236                                         newChunk =
2237                                             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
2238
2239                                         if (newChunk < 0) {
2240                                                 retVal = YAFFS_FAIL;
2241                                         } else {
2242
2243                                                 /* Ok, now fix up the Tnodes etc. */
2244
2245                                                 if (tags.chunkId == 0) {
2246                                                         /* It's a header */
2247                                                         object->chunkId =  newChunk;
2248                                                         object->serial =   tags.serialNumber;
2249                                                 } else {
2250                                                         /* It's a data chunk */
2251                                                         yaffs_PutChunkIntoFile
2252                                                             (object,
2253                                                              tags.chunkId,
2254                                                              newChunk, 0);
2255                                                 }
2256                                         }
2257                                 }
2258
2259                                 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
2260
2261                         }
2262                 }
2263
2264                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2265
2266
2267                 /* Do any required cleanups */
2268                 for (i = 0; i < cleanups; i++) {
2269                         /* Time to delete the file too */
2270                         object =
2271                             yaffs_FindObjectByNumber(dev,
2272                                                      dev->gcCleanupList[i]);
2273                         if (object) {
2274                                 yaffs_FreeTnode(dev,
2275                                                 object->variant.fileVariant.
2276                                                 top);
2277                                 object->variant.fileVariant.top = NULL;
2278                                 T(YAFFS_TRACE_GC,
2279                                   (TSTR
2280                                    ("yaffs: About to finally delete object %d"
2281                                     TENDSTR), object->objectId));
2282                                 yaffs_DoGenericObjectDeletion(object);
2283                                 object->myDev->nDeletedFiles--;
2284                         }
2285
2286                 }
2287
2288         }
2289
2290         if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
2291                 T(YAFFS_TRACE_GC,
2292                   (TSTR
2293                    ("gc did not increase free chunks before %d after %d"
2294                     TENDSTR), chunksBefore, chunksAfter));
2295         }
2296
2297         dev->isDoingGC = 0;
2298
2299         return YAFFS_OK;
2300 }
2301
2302 /* New garbage collector
2303  * If we're very low on erased blocks then we do aggressive garbage collection
2304  * otherwise we do "leasurely" garbage collection.
2305  * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2306  * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2307  *
2308  * The idea is to help clear out space in a more spread-out manner.
2309  * Dunno if it really does anything useful.
2310  */
2311 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
2312 {
2313         int block;
2314         int aggressive;
2315         int gcOk = YAFFS_OK;
2316         int maxTries = 0;
2317
2318         if (dev->isDoingGC) {
2319                 /* Bail out so we don't get recursive gc */
2320                 return YAFFS_OK;
2321         }
2322         
2323         /* This loop should pass the first time.
2324          * We'll only see looping here if the erase of the collected block fails.
2325          */
2326
2327         do {
2328                 maxTries++;
2329                 if (dev->nErasedBlocks < dev->nReservedBlocks) {
2330                         /* We need a block soon...*/
2331                         aggressive = 1;
2332                 } else {
2333                         /* We're in no hurry */
2334                         aggressive = 0;
2335                 }
2336
2337                 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
2338
2339                 if (block > 0) {
2340                         dev->garbageCollections++;
2341                         if (!aggressive) {
2342                                 dev->passiveGarbageCollections++;
2343                         }
2344
2345                         T(YAFFS_TRACE_GC,
2346                           (TSTR
2347                            ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
2348                            dev->nErasedBlocks, aggressive));
2349
2350                         gcOk = yaffs_GarbageCollectBlock(dev, block);
2351                 }
2352
2353                 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
2354                         T(YAFFS_TRACE_GC,
2355                           (TSTR
2356                            ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
2357                             TENDSTR), dev->nErasedBlocks, maxTries, block));
2358                 }
2359         } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
2360                  && (maxTries < 2));
2361
2362         return aggressive ? gcOk : YAFFS_OK;
2363 }
2364
2365 /*-------------------------  TAGS --------------------------------*/
2366
2367 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
2368                            int chunkInObject)
2369 {
2370         return (tags->chunkId == chunkInObject &&
2371                 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
2372
2373 }
2374
2375
2376 /*-------------------- Data file manipulation -----------------*/
2377
2378 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
2379                                  yaffs_ExtendedTags * tags)
2380 {
2381         /*Get the Tnode, then get the level 0 offset chunk offset */
2382         yaffs_Tnode *tn;
2383         int theChunk = -1;
2384         yaffs_ExtendedTags localTags;
2385         int retVal = -1;
2386
2387         yaffs_Device *dev = in->myDev;
2388
2389         if (!tags) {
2390                 /* Passed a NULL, so use our own tags space */
2391                 tags = &localTags;
2392         }
2393
2394         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2395
2396         if (tn) {
2397                 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2398
2399                 retVal =
2400                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2401                                            chunkInInode);
2402         }
2403         return retVal;
2404 }
2405
2406 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
2407                                           yaffs_ExtendedTags * tags)
2408 {
2409         /* Get the Tnode, then get the level 0 offset chunk offset */
2410         yaffs_Tnode *tn;
2411         int theChunk = -1;
2412         yaffs_ExtendedTags localTags;
2413
2414         yaffs_Device *dev = in->myDev;
2415         int retVal = -1;
2416
2417         if (!tags) {
2418                 /* Passed a NULL, so use our own tags space */
2419                 tags = &localTags;
2420         }
2421
2422         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2423
2424         if (tn) {
2425
2426                 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2427
2428                 retVal =
2429                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2430                                            chunkInInode);
2431
2432                 /* Delete the entry in the filestructure (if found) */
2433                 if (retVal != -1) {
2434                         yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
2435                 }
2436         } else {
2437                 /*T(("No level 0 found for %d\n", chunkInInode)); */
2438         }
2439
2440         if (retVal == -1) {
2441                 /* T(("Could not find %d to delete\n",chunkInInode)); */
2442         }
2443         return retVal;
2444 }
2445
2446 #ifdef YAFFS_PARANOID
2447
2448 static int yaffs_CheckFileSanity(yaffs_Object * in)
2449 {
2450         int chunk;
2451         int nChunks;
2452         int fSize;
2453         int failed = 0;
2454         int objId;
2455         yaffs_Tnode *tn;
2456         yaffs_Tags localTags;
2457         yaffs_Tags *tags = &localTags;
2458         int theChunk;
2459         int chunkDeleted;
2460
2461         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2462                 /* T(("Object not a file\n")); */
2463                 return YAFFS_FAIL;
2464         }
2465
2466         objId = in->objectId;
2467         fSize = in->variant.fileVariant.fileSize;
2468         nChunks =
2469             (fSize + in->myDev->nBytesPerChunk - 1) / in->myDev->nBytesPerChunk;
2470
2471         for (chunk = 1; chunk <= nChunks; chunk++) {
2472                 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
2473                                            chunk);
2474
2475                 if (tn) {
2476
2477                         theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
2478
2479                         if (yaffs_CheckChunkBits
2480                             (dev, theChunk / dev->nChunksPerBlock,
2481                              theChunk % dev->nChunksPerBlock)) {
2482
2483                                 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
2484                                                             tags,
2485                                                             &chunkDeleted);
2486                                 if (yaffs_TagsMatch
2487                                     (tags, in->objectId, chunk, chunkDeleted)) {
2488                                         /* found it; */
2489
2490                                 }
2491                         } else {
2492
2493                                 failed = 1;
2494                         }
2495
2496                 } else {
2497                         /* T(("No level 0 found for %d\n", chunk)); */
2498                 }
2499         }
2500
2501         return failed ? YAFFS_FAIL : YAFFS_OK;
2502 }
2503
2504 #endif
2505
2506 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
2507                                   int chunkInNAND, int inScan)
2508 {
2509         /* NB inScan is zero unless scanning. 
2510          * For forward scanning, inScan is > 0; 
2511          * for backward scanning inScan is < 0
2512          */
2513          
2514         yaffs_Tnode *tn;
2515         yaffs_Device *dev = in->myDev;
2516         int existingChunk;
2517         yaffs_ExtendedTags existingTags;
2518         yaffs_ExtendedTags newTags;
2519         unsigned existingSerial, newSerial;
2520
2521         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2522                 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2523                  * If it is not during Scanning then something went wrong!
2524                  */
2525                 if (!inScan) {
2526                         T(YAFFS_TRACE_ERROR,
2527                           (TSTR
2528                            ("yaffs tragedy:attempt to put data chunk into a non-file"
2529                             TENDSTR)));
2530                         YBUG();
2531                 }
2532
2533                 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
2534                 return YAFFS_OK;
2535         }
2536
2537         tn = yaffs_AddOrFindLevel0Tnode(dev, 
2538                                         &in->variant.fileVariant,
2539                                         chunkInInode,
2540                                         NULL);
2541         if (!tn) {
2542                 return YAFFS_FAIL;
2543         }
2544
2545         existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2546
2547         if (inScan != 0) {
2548                 /* If we're scanning then we need to test for duplicates
2549                  * NB This does not need to be efficient since it should only ever 
2550                  * happen when the power fails during a write, then only one
2551                  * chunk should ever be affected.
2552                  *
2553                  * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2554                  * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2555                  */
2556
2557                 if (existingChunk != 0) {
2558                         /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
2559                          *    thus we have to do a FindChunkInFile to get the real chunk id.
2560                          *
2561                          * We have a duplicate now we need to decide which one to use:
2562                          *
2563                          * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2564                          * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2565                          * YAFFS1: Get both sets of tags and compare serial numbers.
2566                          */
2567
2568                         if (inScan > 0) {
2569                                 /* Only do this for forward scanning */
2570                                 yaffs_ReadChunkWithTagsFromNAND(dev,
2571                                                                 chunkInNAND,
2572                                                                 NULL, &newTags);
2573
2574                                 /* Do a proper find */
2575                                 existingChunk =
2576                                     yaffs_FindChunkInFile(in, chunkInInode,
2577                                                           &existingTags);
2578                         }
2579
2580                         if (existingChunk <= 0) {
2581                                 /*Hoosterman - how did this happen? */
2582
2583                                 T(YAFFS_TRACE_ERROR,
2584                                   (TSTR
2585                                    ("yaffs tragedy: existing chunk < 0 in scan"
2586                                     TENDSTR)));
2587
2588                         }
2589
2590                         /* NB The deleted flags should be false, otherwise the chunks will 
2591                          * not be loaded during a scan
2592                          */
2593
2594                         newSerial = newTags.serialNumber;
2595                         existingSerial = existingTags.serialNumber;
2596
2597                         if ((inScan > 0) &&
2598                             (in->myDev->isYaffs2 ||
2599                              existingChunk <= 0 ||
2600                              ((existingSerial + 1) & 3) == newSerial)) {
2601                                 /* Forward scanning.                            
2602                                  * Use new
2603                                  * Delete the old one and drop through to update the tnode
2604                                  */
2605                                 yaffs_DeleteChunk(dev, existingChunk, 1,
2606                                                   __LINE__);
2607                         } else {
2608                                 /* Backward scanning or we want to use the existing one
2609                                  * Use existing.
2610                                  * Delete the new one and return early so that the tnode isn't changed
2611                                  */
2612                                 yaffs_DeleteChunk(dev, chunkInNAND, 1,
2613                                                   __LINE__);
2614                                 return YAFFS_OK;
2615                         }
2616                 }
2617
2618         }
2619
2620         if (existingChunk == 0) {
2621                 in->nDataChunks++;
2622         }
2623
2624         yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
2625
2626         return YAFFS_OK;
2627 }
2628
2629 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
2630                                          __u8 * buffer)
2631 {
2632         int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
2633
2634         if (chunkInNAND >= 0) {
2635                 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
2636                                                        buffer, NULL);
2637         } else {
2638                 T(YAFFS_TRACE_NANDACCESS,
2639                   (TSTR("Chunk %d not found zero instead" TENDSTR),
2640                    chunkInNAND));
2641                 /* get sane (zero) data if you read a hole */
2642                 memset(buffer, 0, in->myDev->nBytesPerChunk);   
2643                 return 0;
2644         }
2645
2646 }
2647
2648 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
2649 {
2650         int block;
2651         int page;
2652         yaffs_ExtendedTags tags;
2653         yaffs_BlockInfo *bi;
2654
2655         if (chunkId <= 0)
2656                 return;
2657
2658         dev->nDeletions++;
2659         block = chunkId / dev->nChunksPerBlock;
2660         page = chunkId % dev->nChunksPerBlock;
2661
2662         bi = yaffs_GetBlockInfo(dev, block);
2663
2664         T(YAFFS_TRACE_DELETION,
2665           (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
2666
2667         if (markNAND &&
2668             bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
2669
2670                 yaffs_InitialiseTags(&tags);
2671
2672                 tags.chunkDeleted = 1;
2673
2674                 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
2675                 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
2676         } else {
2677                 dev->nUnmarkedDeletions++;
2678         }
2679
2680         /* Pull out of the management area.
2681          * If the whole block became dirty, this will kick off an erasure.
2682          */
2683         if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2684             bi->blockState == YAFFS_BLOCK_STATE_FULL ||
2685             bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2686             bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2687                 dev->nFreeChunks++;
2688
2689                 yaffs_ClearChunkBit(dev, block, page);
2690
2691                 bi->pagesInUse--;
2692
2693                 if (bi->pagesInUse == 0 &&
2694                     !bi->hasShrinkHeader &&
2695                     bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
2696                     bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2697                         yaffs_BlockBecameDirty(dev, block);
2698                 }
2699
2700         } else {
2701                 /* T(("Bad news deleting chunk %d\n",chunkId)); */
2702         }
2703
2704 }
2705
2706 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
2707                                         const __u8 * buffer, int nBytes,
2708                                         int useReserve)
2709 {
2710         /* Find old chunk Need to do this to get serial number
2711          * Write new one and patch into tree.
2712          * Invalidate old tags.
2713          */
2714
2715         int prevChunkId;
2716         yaffs_ExtendedTags prevTags;
2717
2718         int newChunkId;
2719         yaffs_ExtendedTags newTags;
2720
2721         yaffs_Device *dev = in->myDev;
2722
2723         yaffs_CheckGarbageCollection(dev);
2724
2725         /* Get the previous chunk at this location in the file if it exists */
2726         prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
2727
2728         /* Set up new tags */
2729         yaffs_InitialiseTags(&newTags);
2730
2731         newTags.chunkId = chunkInInode;
2732         newTags.objectId = in->objectId;
2733         newTags.serialNumber =
2734             (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2735         newTags.byteCount = nBytes;
2736
2737         newChunkId =
2738             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2739                                               useReserve);
2740
2741         if (newChunkId >= 0) {
2742                 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
2743
2744                 if (prevChunkId >= 0) {
2745                         yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
2746
2747                 }
2748
2749                 yaffs_CheckFileSanity(in);
2750         }
2751         return newChunkId;
2752
2753 }
2754
2755 /* UpdateObjectHeader updates the header on NAND for an object.
2756  * If name is not NULL, then that new name is used.
2757  */
2758 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
2759                              int isShrink, int shadows)
2760 {
2761
2762         yaffs_BlockInfo *bi;
2763
2764         yaffs_Device *dev = in->myDev;
2765
2766         int prevChunkId;
2767         int retVal = 0;
2768
2769         int newChunkId;
2770         yaffs_ExtendedTags newTags;
2771
2772         __u8 *buffer = NULL;
2773         YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
2774
2775         yaffs_ObjectHeader *oh = NULL;
2776
2777         if (!in->fake || force) {
2778
2779                 yaffs_CheckGarbageCollection(dev);
2780
2781                 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
2782                 oh = (yaffs_ObjectHeader *) buffer;
2783
2784                 prevChunkId = in->chunkId;
2785
2786                 if (prevChunkId >= 0) {
2787                         yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
2788                                                         buffer, NULL);
2789                         memcpy(oldName, oh->name, sizeof(oh->name));
2790                 }
2791
2792                 memset(buffer, 0xFF, dev->nBytesPerChunk);
2793
2794                 oh->type = in->variantType;
2795                 oh->yst_mode = in->yst_mode;
2796                 oh->shadowsObject = shadows;
2797
2798 #ifdef CONFIG_YAFFS_WINCE
2799                 oh->win_atime[0] = in->win_atime[0];
2800                 oh->win_ctime[0] = in->win_ctime[0];
2801                 oh->win_mtime[0] = in->win_mtime[0];
2802                 oh->win_atime[1] = in->win_atime[1];
2803                 oh->win_ctime[1] = in->win_ctime[1];
2804                 oh->win_mtime[1] = in->win_mtime[1];
2805 #else
2806                 oh->yst_uid = in->yst_uid;
2807                 oh->yst_gid = in->yst_gid;
2808                 oh->yst_atime = in->yst_atime;
2809                 oh->yst_mtime = in->yst_mtime;
2810                 oh->yst_ctime = in->yst_ctime;
2811                 oh->yst_rdev = in->yst_rdev;
2812 #endif
2813                 if (in->parent) {
2814                         oh->parentObjectId = in->parent->objectId;
2815                 } else {
2816                         oh->parentObjectId = 0;
2817                 }
2818
2819                 if (name && *name) {
2820                         memset(oh->name, 0, sizeof(oh->name));
2821                         yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
2822                 } else if (prevChunkId) {
2823                         memcpy(oh->name, oldName, sizeof(oh->name));
2824                 } else {
2825                         memset(oh->name, 0, sizeof(oh->name));
2826                 }
2827
2828                 oh->isShrink = isShrink;
2829
2830                 switch (in->variantType) {
2831                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2832                         /* Should not happen */
2833                         break;
2834                 case YAFFS_OBJECT_TYPE_FILE:
2835                         oh->fileSize =
2836                             (oh->parentObjectId == YAFFS_OBJECTID_DELETED
2837                              || oh->parentObjectId ==
2838                              YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
2839                             fileVariant.fileSize;
2840                         break;
2841                 case YAFFS_OBJECT_TYPE_HARDLINK:
2842                         oh->equivalentObjectId =
2843                             in->variant.hardLinkVariant.equivalentObjectId;
2844                         break;
2845                 case YAFFS_OBJECT_TYPE_SPECIAL:
2846                         /* Do nothing */
2847                         break;
2848                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2849                         /* Do nothing */
2850                         break;
2851                 case YAFFS_OBJECT_TYPE_SYMLINK:
2852                         yaffs_strncpy(oh->alias,
2853                                       in->variant.symLinkVariant.alias,
2854                                       YAFFS_MAX_ALIAS_LENGTH);
2855                         oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
2856                         break;
2857                 }
2858
2859                 /* Tags */
2860                 yaffs_InitialiseTags(&newTags);
2861                 in->serial++;
2862                 newTags.chunkId = 0;
2863                 newTags.objectId = in->objectId;
2864                 newTags.serialNumber = in->serial;
2865
2866                 /* Add extra info for file header */
2867
2868                 newTags.extraHeaderInfoAvailable = 1;
2869                 newTags.extraParentObjectId = oh->parentObjectId;
2870                 newTags.extraFileLength = oh->fileSize;
2871                 newTags.extraIsShrinkHeader = oh->isShrink;
2872                 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
2873                 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
2874                 newTags.extraObjectType = in->variantType;
2875
2876                 /* Create new chunk in NAND */
2877                 newChunkId =
2878                     yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2879                                                       (prevChunkId >= 0) ? 1 : 0);
2880
2881                 if (newChunkId >= 0) {
2882
2883                         in->chunkId = newChunkId;
2884
2885                         if (prevChunkId >= 0) {
2886                                 yaffs_DeleteChunk(dev, prevChunkId, 1,
2887                                                   __LINE__);
2888                         }
2889
2890                         in->dirty = 0;
2891
2892                         /* If this was a shrink, then mark the block that the chunk lives on */
2893                         if (isShrink) {
2894                                 bi = yaffs_GetBlockInfo(in->myDev,
2895                                                         newChunkId /in->myDev-> nChunksPerBlock);
2896                                 bi->hasShrinkHeader = 1;
2897                         }
2898
2899                 }
2900
2901                 retVal = newChunkId;
2902
2903         }
2904
2905         if (buffer)
2906                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2907
2908         return retVal;
2909 }
2910
2911 /*------------------------ Short Operations Cache ----------------------------------------
2912  *   In many situations where there is no high level buffering (eg WinCE) a lot of
2913  *   reads might be short sequential reads, and a lot of writes may be short 
2914  *   sequential writes. eg. scanning/writing a jpeg file.
2915  *   In these cases, a short read/write cache can provide a huge perfomance benefit 
2916  *   with dumb-as-a-rock code.
2917  *   In Linux, the page cache provides read buffering aand the short op cache provides write 
2918  *   buffering.
2919  *
2920  *   There are a limited number (~10) of cache chunks per device so that we don't
2921  *   need a very intelligent search.
2922  */
2923
2924 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
2925 {
2926         yaffs_Device *dev = obj->myDev;
2927         int lowest = -99;       /* Stop compiler whining. */
2928         int i;
2929         yaffs_ChunkCache *cache;
2930         int chunkWritten = 0;
2931         int nCaches = obj->myDev->nShortOpCaches;
2932
2933         if (nCaches > 0) {
2934                 do {
2935                         cache = NULL;
2936
2937                         /* Find the dirty cache for this object with the lowest chunk id. */
2938                         for (i = 0; i < nCaches; i++) {
2939                                 if (dev->srCache[i].object == obj &&
2940                                     dev->srCache[i].dirty) {
2941                                         if (!cache
2942                                             || dev->srCache[i].chunkId <
2943                                             lowest) {
2944                                                 cache = &dev->srCache[i];
2945                                                 lowest = cache->chunkId;
2946                                         }
2947                                 }
2948                         }
2949
2950                         if (cache && !cache->locked) {
2951                                 /* Write it out and free it up */
2952
2953                                 chunkWritten =
2954                                     yaffs_WriteChunkDataToObject(cache->object,
2955                                                                  cache->chunkId,
2956                                                                  cache->data,
2957                                                                  cache->nBytes,
2958                                                                  1);
2959                                 cache->dirty = 0;
2960                                 cache->object = NULL;
2961                         }
2962
2963                 } while (cache && chunkWritten > 0);
2964
2965                 if (cache) {
2966                         /* Hoosterman, disk full while writing cache out. */
2967                         T(YAFFS_TRACE_ERROR,
2968                           (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
2969
2970                 }
2971         }
2972
2973 }
2974
2975 /*yaffs_FlushEntireDeviceCache(dev)
2976  *
2977  *
2978  */
2979
2980 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
2981 {
2982         yaffs_Object *obj;
2983         int nCaches = dev->nShortOpCaches;
2984         int i;
2985         
2986         /* Find a dirty object in the cache and flush it...
2987          * until there are no further dirty objects.
2988          */
2989         do {
2990                 obj = NULL;
2991                 for( i = 0; i < nCaches && !obj; i++) {
2992                         if (dev->srCache[i].object &&
2993                             dev->srCache[i].dirty)
2994                                 obj = dev->srCache[i].object;
2995                             
2996                 }
2997                 if(obj)
2998                         yaffs_FlushFilesChunkCache(obj);
2999                         
3000         } while(obj);
3001         
3002 }
3003
3004
3005 /* Grab us a cache chunk for use.
3006  * First look for an empty one. 
3007  * Then look for the least recently used non-dirty one.
3008  * Then look for the least recently used dirty one...., flush and look again.
3009  */
3010 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
3011 {
3012         int i;
3013         int usage;
3014         int theOne;
3015
3016         if (dev->nShortOpCaches > 0) {
3017                 for (i = 0; i < dev->nShortOpCaches; i++) {
3018                         if (!dev->srCache[i].object) 
3019                                 return &dev->srCache[i];
3020                 }
3021
3022                 return NULL;
3023
3024                 theOne = -1;
3025                 usage = 0;      /* just to stop the compiler grizzling */
3026
3027                 for (i = 0; i < dev->nShortOpCaches; i++) {
3028                         if (!dev->srCache[i].dirty &&
3029                             ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
3030                              theOne < 0)) {
3031                                 usage = dev->srCache[i].lastUse;
3032                                 theOne = i;
3033                         }
3034                 }
3035
3036
3037                 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3038         } else {
3039                 return NULL;
3040         }
3041
3042 }
3043
3044 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
3045 {
3046         yaffs_ChunkCache *cache;
3047         yaffs_Object *theObj;
3048         int usage;
3049         int i;
3050         int pushout;
3051
3052         if (dev->nShortOpCaches > 0) {
3053                 /* Try find a non-dirty one... */
3054
3055                 cache = yaffs_GrabChunkCacheWorker(dev);
3056
3057                 if (!cache) {
3058                         /* They were all dirty, find the last recently used object and flush
3059                          * its cache, then  find again.
3060                          * NB what's here is not very accurate, we actually flush the object
3061                          * the last recently used page.
3062                          */
3063
3064                         /* With locking we can't assume we can use entry zero */
3065
3066                         theObj = NULL;
3067                         usage = -1;
3068                         cache = NULL;
3069                         pushout = -1;
3070
3071                         for (i = 0; i < dev->nShortOpCaches; i++) {
3072                                 if (dev->srCache[i].object &&
3073                                     !dev->srCache[i].locked &&
3074                                     (dev->srCache[i].lastUse < usage || !cache))
3075                                 {
3076                                         usage = dev->srCache[i].lastUse;
3077                                         theObj = dev->srCache[i].object;
3078                                         cache = &dev->srCache[i];
3079                                         pushout = i;
3080                                 }
3081                         }
3082
3083                         if (!cache || cache->dirty) {
3084                                 /* Flush and try again */
3085                                 yaffs_FlushFilesChunkCache(theObj);
3086                                 cache = yaffs_GrabChunkCacheWorker(dev);
3087                         }
3088
3089                 }
3090                 return cache;
3091         } else
3092                 return NULL;
3093
3094 }
3095
3096 /* Find a cached chunk */
3097 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
3098                                               int chunkId)
3099 {
3100         yaffs_Device *dev = obj->myDev;
3101         int i;
3102         if (dev->nShortOpCaches > 0) {
3103                 for (i = 0; i < dev->nShortOpCaches; i++) {
3104                         if (dev->srCache[i].object == obj &&
3105                             dev->srCache[i].chunkId == chunkId) {
3106                                 dev->cacheHits++;
3107
3108                                 return &dev->srCache[i];
3109                         }
3110                 }
3111         }
3112         return NULL;
3113 }
3114
3115 /* Mark the chunk for the least recently used algorithym */
3116 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
3117                                 int isAWrite)
3118 {
3119
3120         if (dev->nShortOpCaches > 0) {
3121                 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
3122                         /* Reset the cache usages */
3123                         int i;
3124                         for (i = 1; i < dev->nShortOpCaches; i++) {
3125                                 dev->srCache[i].lastUse = 0;
3126                         }
3127                         dev->srLastUse = 0;
3128                 }
3129
3130                 dev->srLastUse++;
3131
3132                 cache->lastUse = dev->srLastUse;
3133
3134                 if (isAWrite) {
3135                         cache->dirty = 1;
3136                 }
3137         }
3138 }
3139
3140 /* Invalidate a single cache page.
3141  * Do this when a whole page gets written,
3142  * ie the short cache for this page is no longer valid.
3143  */
3144 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
3145 {
3146         if (object->myDev->nShortOpCaches > 0) {
3147                 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
3148
3149                 if (cache) {
3150                         cache->object = NULL;
3151                 }
3152         }
3153 }
3154
3155 /* Invalidate all the cache pages associated with this object
3156  * Do this whenever ther file is deleted or resized.
3157  */
3158 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
3159 {
3160         int i;
3161         yaffs_Device *dev = in->myDev;
3162
3163         if (dev->nShortOpCaches > 0) {
3164                 /* Invalidate it. */
3165                 for (i = 0; i < dev->nShortOpCaches; i++) {
3166                         if (dev->srCache[i].object == in) {
3167                                 dev->srCache[i].object = NULL;
3168                         }
3169                 }
3170         }
3171 }
3172
3173 /*--------------------- Checkpointing --------------------*/
3174
3175
3176 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
3177 {
3178         yaffs_CheckpointValidity cp;
3179         cp.structType = sizeof(cp);
3180         cp.magic = YAFFS_MAGIC;
3181         cp.version = 1;
3182         cp.head = (head) ? 1 : 0;
3183         
3184         return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
3185                 1 : 0;
3186 }
3187
3188 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
3189 {
3190         yaffs_CheckpointValidity cp;
3191         int ok;
3192         
3193         ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3194         
3195         if(ok)
3196                 ok = (cp.structType == sizeof(cp)) &&
3197                      (cp.magic == YAFFS_MAGIC) &&
3198                      (cp.version == 1) &&
3199                      (cp.head == ((head) ? 1 : 0));
3200         return ok ? 1 : 0;
3201 }
3202
3203 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp, 
3204                                            yaffs_Device *dev)
3205 {
3206         cp->nErasedBlocks = dev->nErasedBlocks;
3207         cp->allocationBlock = dev->allocationBlock;
3208         cp->allocationPage = dev->allocationPage;
3209         cp->nFreeChunks = dev->nFreeChunks;
3210         
3211         cp->nDeletedFiles = dev->nDeletedFiles;
3212         cp->nUnlinkedFiles = dev->nUnlinkedFiles;
3213         cp->nBackgroundDeletions = dev->nBackgroundDeletions;
3214         cp->sequenceNumber = dev->sequenceNumber;
3215         cp->oldestDirtySequence = dev->oldestDirtySequence;
3216         
3217 }
3218
3219 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
3220                                            yaffs_CheckpointDevice *cp)
3221 {
3222         dev->nErasedBlocks = cp->nErasedBlocks;
3223         dev->allocationBlock = cp->allocationBlock;
3224         dev->allocationPage = cp->allocationPage;
3225         dev->nFreeChunks = cp->nFreeChunks;
3226         
3227         dev->nDeletedFiles = cp->nDeletedFiles;
3228         dev->nUnlinkedFiles = cp->nUnlinkedFiles;
3229         dev->nBackgroundDeletions = cp->nBackgroundDeletions;
3230         dev->sequenceNumber = cp->sequenceNumber;
3231         dev->oldestDirtySequence = cp->oldestDirtySequence;
3232 }
3233
3234
3235 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
3236 {
3237         yaffs_CheckpointDevice cp;
3238         __u32 nBytes;
3239         __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
3240
3241         int ok;
3242                 
3243         /* Write device runtime values*/
3244         yaffs_DeviceToCheckpointDevice(&cp,dev);
3245         cp.structType = sizeof(cp);
3246         
3247         ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3248         
3249         /* Write block info */
3250         if(ok) {
3251                 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
3252                 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
3253         }
3254                 
3255         /* Write chunk bits */          
3256         if(ok) {
3257                 nBytes = nBlocks * dev->chunkBitmapStride;
3258                 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
3259         }
3260         return   ok ? 1 : 0;
3261
3262 }
3263
3264 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
3265 {
3266         yaffs_CheckpointDevice cp;
3267         __u32 nBytes;
3268         __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
3269
3270         int ok; 
3271         
3272         ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3273         if(!ok)
3274                 return 0;
3275                 
3276         if(cp.structType != sizeof(cp))
3277                 return 0;
3278                 
3279         
3280         yaffs_CheckpointDeviceToDevice(dev,&cp);
3281         
3282         nBytes = nBlocks * sizeof(yaffs_BlockInfo);
3283         
3284         ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
3285         
3286         if(!ok)
3287                 return 0;
3288         nBytes = nBlocks * dev->chunkBitmapStride;
3289         
3290         ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
3291         
3292         return ok ? 1 : 0;
3293 }
3294
3295 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
3296                                            yaffs_Object *obj)
3297 {
3298
3299         cp->objectId = obj->objectId;
3300         cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
3301         cp->chunkId = obj->chunkId;
3302         cp->variantType = obj->variantType;                     
3303         cp->deleted = obj->deleted;
3304         cp->softDeleted = obj->softDeleted;
3305         cp->unlinked = obj->unlinked;
3306         cp->fake = obj->fake;
3307         cp->renameAllowed = obj->renameAllowed;
3308         cp->unlinkAllowed = obj->unlinkAllowed;
3309         cp->serial = obj->serial;
3310         cp->nDataChunks = obj->nDataChunks;
3311         
3312         if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
3313                 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
3314         else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3315                 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
3316 }
3317
3318 static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
3319 {
3320
3321         yaffs_Object *parent;
3322         
3323         obj->objectId = cp->objectId;
3324         
3325         if(cp->parentId)
3326                 parent = yaffs_FindOrCreateObjectByNumber(
3327                                         obj->myDev,
3328                                         cp->parentId,
3329                                         YAFFS_OBJECT_TYPE_DIRECTORY);
3330         else
3331                 parent = NULL;
3332                 
3333         if(parent)
3334                 yaffs_AddObjectToDirectory(parent, obj);
3335                 
3336         obj->chunkId = cp->chunkId;
3337         obj->variantType = cp->variantType;                     
3338         obj->deleted = cp->deleted;
3339         obj->softDeleted = cp->softDeleted;
3340         obj->unlinked = cp->unlinked;
3341         obj->fake = cp->fake;
3342         obj->renameAllowed = cp->renameAllowed;
3343         obj->unlinkAllowed = cp->unlinkAllowed;
3344         obj->serial = cp->serial;
3345         obj->nDataChunks = cp->nDataChunks;
3346         
3347         if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
3348                 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
3349         else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3350                 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
3351                 
3352         if(obj->objectId >= YAFFS_NOBJECT_BUCKETS)
3353                 obj->lazyLoaded = 1;
3354 }
3355
3356
3357
3358 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
3359                                         __u32 level, int chunkOffset)
3360 {
3361         int i;
3362         yaffs_Device *dev = in->myDev;
3363
3364         if (tn) {
3365                 if (level > 0) {
3366
3367                         for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++){
3368                                 if (tn->internal[i]) {
3369                                         yaffs_CheckpointTnodeWorker(in,
3370                                                         tn->internal[i],
3371                                                         level - 1,
3372                                                         (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
3373                                 }
3374                         }
3375                 } else if (level == 0) {
3376                         __u32 baseOffset = chunkOffset <<  YAFFS_TNODES_LEVEL0_BITS;
3377                         /* printf("write tnode at %d\n",baseOffset); */
3378                         yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset));
3379                         yaffs_CheckpointWrite(dev,tn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
3380                 }
3381         }
3382
3383         return 1;
3384
3385 }
3386
3387 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
3388 {
3389         __u32 endMarker = ~0;
3390         int ok;
3391         
3392         if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
3393                 ok = yaffs_CheckpointTnodeWorker(obj,
3394                                             obj->variant.fileVariant.top,
3395                                             obj->variant.fileVariant.topLevel,
3396                                             0);
3397                 if(ok)
3398                         ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) == 
3399                                 sizeof(endMarker));
3400         }
3401         
3402         return ok ? 1 : 0;
3403 }
3404
3405 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
3406 {
3407         __u32 baseChunk;
3408         int ok = 1;
3409         yaffs_Device *dev = obj->myDev;
3410         yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
3411         yaffs_Tnode *tn;
3412         
3413         ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
3414         
3415         while(ok && (~baseChunk)){
3416                 /* Read level 0 tnode */
3417                 
3418                 /* printf("read  tnode at %d\n",baseChunk); */
3419                 tn = yaffs_GetTnodeRaw(dev);
3420                 if(tn)
3421                         ok = (yaffs_CheckpointRead(dev,tn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8) ==
3422                               (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
3423                 else
3424                         ok = 0;
3425                         
3426                 if(tn && ok){
3427                         ok = yaffs_AddOrFindLevel0Tnode(dev,
3428                                                         fileStructPtr,
3429                                                         baseChunk,
3430                                                         tn) ? 1 : 0;
3431                 }
3432                         
3433                 if(ok)
3434                         ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
3435                 
3436         }
3437
3438         return ok ? 1 : 0;      
3439 }
3440  
3441
3442 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
3443 {
3444         yaffs_Object *obj;
3445         yaffs_CheckpointObject cp;
3446         int i;
3447         int ok = 1;
3448         struct list_head *lh;
3449
3450         
3451         /* Iterate through the objects in each hash entry,
3452          * dumping them to the checkpointing stream.
3453          */
3454          
3455          for(i = 0; ok &&  i <  YAFFS_NOBJECT_BUCKETS; i++){
3456                 list_for_each(lh, &dev->objectBucket[i].list) {
3457                         if (lh) {
3458                                 obj = list_entry(lh, yaffs_Object, hashLink);
3459                                 if (!obj->deferedFree) {
3460                                         yaffs_ObjectToCheckpointObject(&cp,obj);
3461                                         cp.structType = sizeof(cp);
3462                                         /* printf("Write out object %d type %d\n",obj->objectId,obj->variantType); */
3463                                         ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3464                                         
3465                                         if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
3466                                                 ok = yaffs_WriteCheckpointTnodes(obj);
3467                                         }
3468                                 }
3469                         }
3470                 }
3471          }
3472          
3473          /* Dump end of list */
3474         memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
3475         cp.structType = sizeof(cp);
3476         
3477         if(ok)
3478                 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3479                 
3480         return ok ? 1 : 0;
3481 }
3482
3483 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
3484 {
3485         yaffs_Object *obj;
3486         yaffs_CheckpointObject cp;
3487         int ok = 1;
3488         int done = 0;
3489         yaffs_Object *hardList = NULL;
3490         
3491         while(ok && !done) {
3492                 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3493                 if(cp.structType != sizeof(cp)) {
3494                         /* printf("structure parsing failed\n"); */
3495                         ok = 0;
3496                 }
3497                         
3498                 if(ok && cp.objectId == ~0)
3499                         done = 1;
3500                 else {
3501                         /* printf("Read object %d type %d\n",cp.objectId,cp.variantType); */
3502                         obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
3503                         if(obj) {
3504                                 yaffs_CheckpointObjectToObject(obj,&cp);
3505                                 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
3506                                         yaffs_ReadCheckpointTnodes(obj);
3507                                 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
3508                                         obj->hardLinks.next =
3509                                                     (struct list_head *)
3510                                                     hardList;
3511                                         hardList = obj;
3512                                 }
3513                            
3514                         }
3515                 }
3516         }
3517         
3518         if(ok)
3519                 yaffs_HardlinkFixup(dev,hardList);
3520         
3521         return ok ? 1 : 0;
3522 }
3523
3524 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
3525 {
3526
3527         int ok;
3528         
3529         ok = yaffs_CheckpointOpen(dev,1);
3530         
3531         if(ok)
3532                 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
3533         if(ok)
3534                 ok = yaffs_WriteCheckpointDevice(dev);
3535         if(ok)
3536                 ok = yaffs_WriteCheckpointObjects(dev);
3537         if(ok)
3538                 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
3539                 
3540         yaffs_CheckpointClose(dev);
3541                 
3542         if(ok)
3543                 dev->isCheckpointed = 1;
3544          else 
3545                 dev->isCheckpointed = 0;
3546
3547         return dev->isCheckpointed;
3548 }
3549
3550 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
3551 {
3552         int ok;
3553         
3554         ok = yaffs_CheckpointOpen(dev,0); /* open for read */
3555         
3556         if(ok)
3557                 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
3558         if(ok)
3559                 ok = yaffs_ReadCheckpointDevice(dev);
3560         if(ok)
3561                 ok = yaffs_ReadCheckpointObjects(dev);
3562         if(ok)
3563                 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
3564                 
3565                 
3566         if(ok)
3567                 dev->isCheckpointed = 1;
3568          else 
3569                 dev->isCheckpointed = 0;
3570
3571         yaffs_CheckpointClose(dev);
3572
3573         return ok ? 1 : 0;
3574
3575 }
3576
3577 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
3578 {
3579         if(dev->isCheckpointed){
3580                 dev->isCheckpointed = 0;
3581                 yaffs_CheckpointInvalidateStream(dev);
3582         }
3583 }
3584
3585
3586 int yaffs_CheckpointSave(yaffs_Device *dev)
3587 {
3588         if(!dev->isCheckpointed)
3589                 yaffs_WriteCheckpointData(dev);
3590         
3591         return dev->isCheckpointed;
3592 }
3593
3594 int yaffs_CheckpointRestore(yaffs_Device *dev)
3595 {
3596         
3597         return yaffs_ReadCheckpointData(dev);
3598 }
3599
3600 /*--------------------- File read/write ------------------------
3601  * Read and write have very similar structures.
3602  * In general the read/write has three parts to it
3603  * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3604  * Some complete chunks
3605  * An incomplete chunk to end off with
3606  *
3607  * Curve-balls: the first chunk might also be the last chunk.
3608  */
3609
3610 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, __u32 offset,
3611                            int nBytes)
3612 {
3613
3614         int chunk;
3615         int start;
3616         int nToCopy;
3617         int n = nBytes;
3618         int nDone = 0;
3619         yaffs_ChunkCache *cache;
3620
3621         yaffs_Device *dev;
3622
3623         dev = in->myDev;
3624
3625         while (n > 0) {
3626                 chunk = offset / dev->nBytesPerChunk + 1;   /* The first chunk is 1 */
3627                 start = offset % dev->nBytesPerChunk;
3628
3629                 /* OK now check for the curveball where the start and end are in
3630                  * the same chunk.      
3631                  */
3632                 if ((start + n) < dev->nBytesPerChunk) {
3633                         nToCopy = n;
3634                 } else {
3635                         nToCopy = dev->nBytesPerChunk - start;
3636                 }
3637
3638                 cache = yaffs_FindChunkCache(in, chunk);
3639
3640                 /* If the chunk is already in the cache or it is less than a whole chunk
3641                  * then use the cache (if there is caching)
3642                  * else bypass the cache.
3643                  */
3644                 if (cache || nToCopy != dev->nBytesPerChunk) {
3645                         if (dev->nShortOpCaches > 0) {
3646
3647                                 /* If we can't find the data in the cache, then load it up. */
3648
3649                                 if (!cache) {
3650                                         cache = yaffs_GrabChunkCache(in->myDev);
3651                                         cache->object = in;
3652                                         cache->chunkId = chunk;
3653                                         cache->dirty = 0;
3654                                         cache->locked = 0;
3655                                         yaffs_ReadChunkDataFromObject(in, chunk,
3656                                                                       cache->
3657                                                                       data);
3658                                         cache->nBytes = 0;
3659                                 }
3660
3661                                 yaffs_UseChunkCache(dev, cache, 0);
3662
3663                                 cache->locked = 1;
3664
3665 #ifdef CONFIG_YAFFS_WINCE
3666                                 yfsd_UnlockYAFFS(TRUE);
3667 #endif
3668                                 memcpy(buffer, &cache->data[start], nToCopy);
3669
3670 #ifdef CONFIG_YAFFS_WINCE
3671                                 yfsd_LockYAFFS(TRUE);
3672 #endif
3673                                 cache->locked = 0;
3674                         } else {
3675                                 /* Read into the local buffer then copy..*/
3676
3677                                 __u8 *localBuffer =
3678                                     yaffs_GetTempBuffer(dev, __LINE__);
3679                                 yaffs_ReadChunkDataFromObject(in, chunk,
3680                                                               localBuffer);
3681 #ifdef CONFIG_YAFFS_WINCE
3682                                 yfsd_UnlockYAFFS(TRUE);
3683 #endif
3684                                 memcpy(buffer, &localBuffer[start], nToCopy);
3685
3686 #ifdef CONFIG_YAFFS_WINCE
3687                                 yfsd_LockYAFFS(TRUE);
3688 #endif
3689                                 yaffs_ReleaseTempBuffer(dev, localBuffer,
3690                                                         __LINE__);
3691                         }
3692
3693                 } else {
3694 #ifdef CONFIG_YAFFS_WINCE
3695                         __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3696
3697                         /* Under WinCE can't do direct transfer. Need to use a local buffer.
3698                          * This is because we otherwise screw up WinCE's memory mapper
3699                          */
3700                         yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
3701
3702 #ifdef CONFIG_YAFFS_WINCE
3703                         yfsd_UnlockYAFFS(TRUE);
3704 #endif
3705                         memcpy(buffer, localBuffer, dev->nBytesPerChunk);
3706
3707 #ifdef CONFIG_YAFFS_WINCE
3708                         yfsd_LockYAFFS(TRUE);
3709                         yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3710 #endif
3711
3712 #else
3713                         /* A full chunk. Read directly into the supplied buffer. */
3714                         yaffs_ReadChunkDataFromObject(in, chunk, buffer);
3715 #endif
3716                 }
3717
3718                 n -= nToCopy;
3719                 offset += nToCopy;
3720                 buffer += nToCopy;
3721                 nDone += nToCopy;
3722
3723         }
3724
3725         return nDone;
3726 }
3727
3728 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, __u32 offset,
3729                           int nBytes, int writeThrough)
3730 {
3731
3732         int chunk;
3733         int start;
3734         int nToCopy;
3735         int n = nBytes;
3736         int nDone = 0;
3737         int nToWriteBack;
3738         int startOfWrite = offset;
3739         int chunkWritten = 0;
3740         int nBytesRead;
3741
3742         yaffs_Device *dev;
3743
3744         dev = in->myDev;
3745
3746         while (n > 0 && chunkWritten >= 0) {
3747                 chunk = offset / dev->nBytesPerChunk + 1;
3748                 start = offset % dev->nBytesPerChunk;
3749
3750                 /* OK now check for the curveball where the start and end are in
3751                  * the same chunk.
3752                  */
3753
3754                 if ((start + n) < dev->nBytesPerChunk) {
3755                         nToCopy = n;
3756
3757                         /* Now folks, to calculate how many bytes to write back....
3758                          * If we're overwriting and not writing to then end of file then
3759                          * we need to write back as much as was there before.
3760                          */
3761
3762                         nBytesRead =
3763                             in->variant.fileVariant.fileSize -
3764                             ((chunk - 1) * dev->nBytesPerChunk);
3765
3766                         if (nBytesRead > dev->nBytesPerChunk) {
3767                                 nBytesRead = dev->nBytesPerChunk;
3768                         }
3769
3770                         nToWriteBack =
3771                             (nBytesRead >
3772                              (start + n)) ? nBytesRead : (start + n);
3773
3774                 } else {
3775                         nToCopy = dev->nBytesPerChunk - start;
3776                         nToWriteBack = dev->nBytesPerChunk;
3777                 }
3778
3779                 if (nToCopy != dev->nBytesPerChunk) {
3780                         /* An incomplete start or end chunk (or maybe both start and end chunk) */
3781                         if (dev->nShortOpCaches > 0) {
3782                                 yaffs_ChunkCache *cache;
3783                                 /* If we can't find the data in the cache, then load the cache */
3784                                 cache = yaffs_FindChunkCache(in, chunk);
3785                                 if (!cache
3786                                     && yaffs_CheckSpaceForAllocation(in->
3787                                                                      myDev)) {
3788                                         cache = yaffs_GrabChunkCache(in->myDev);
3789                                         cache->object = in;
3790                                         cache->chunkId = chunk;
3791                                         cache->dirty = 0;
3792                                         cache->locked = 0;
3793                                         yaffs_ReadChunkDataFromObject(in, chunk,
3794                                                                       cache->
3795                                                                       data);
3796                                 }
3797
3798                                 if (cache) {
3799                                         yaffs_UseChunkCache(dev, cache, 1);
3800                                         cache->locked = 1;
3801 #ifdef CONFIG_YAFFS_WINCE
3802                                         yfsd_UnlockYAFFS(TRUE);
3803 #endif
3804
3805                                         memcpy(&cache->data[start], buffer,
3806                                                nToCopy);
3807
3808 #ifdef CONFIG_YAFFS_WINCE
3809                                         yfsd_LockYAFFS(TRUE);
3810 #endif
3811                                         cache->locked = 0;
3812                                         cache->nBytes = nToWriteBack;
3813
3814                                         if (writeThrough) {
3815                                                 chunkWritten =
3816                                                     yaffs_WriteChunkDataToObject
3817                                                     (cache->object,
3818                                                      cache->chunkId,
3819                                                      cache->data, cache->nBytes,
3820                                                      1);
3821                                                 cache->dirty = 0;
3822                                         }
3823
3824                                 } else {
3825                                         chunkWritten = -1;      /* fail the write */
3826                                 }
3827                         } else {
3828                                 /* An incomplete start or end chunk (or maybe both start and end chunk)
3829                                  * Read into the local buffer then copy, then copy over and write back.
3830                                  */
3831
3832                                 __u8 *localBuffer =
3833                                     yaffs_GetTempBuffer(dev, __LINE__);
3834
3835                                 yaffs_ReadChunkDataFromObject(in, chunk,
3836                                                               localBuffer);
3837
3838 #ifdef CONFIG_YAFFS_WINCE
3839                                 yfsd_UnlockYAFFS(TRUE);
3840 #endif
3841
3842                                 memcpy(&localBuffer[start], buffer, nToCopy);
3843
3844 #ifdef CONFIG_YAFFS_WINCE
3845                                 yfsd_LockYAFFS(TRUE);
3846 #endif
3847                                 chunkWritten =
3848                                     yaffs_WriteChunkDataToObject(in, chunk,
3849                                                                  localBuffer,
3850                                                                  nToWriteBack,
3851                                                                  0);
3852
3853                                 yaffs_ReleaseTempBuffer(dev, localBuffer,
3854                                                         __LINE__);
3855
3856                         }
3857
3858                 } else {
3859
3860 #ifdef CONFIG_YAFFS_WINCE
3861                         /* Under WinCE can't do direct transfer. Need to use a local buffer.
3862                          * This is because we otherwise screw up WinCE's memory mapper
3863                          */
3864                         __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3865 #ifdef CONFIG_YAFFS_WINCE
3866                         yfsd_UnlockYAFFS(TRUE);
3867 #endif
3868                         memcpy(localBuffer, buffer, dev->nBytesPerChunk);
3869 #ifdef CONFIG_YAFFS_WINCE
3870                         yfsd_LockYAFFS(TRUE);
3871 #endif
3872                         chunkWritten =
3873                             yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
3874                                                          dev->nBytesPerChunk,
3875                                                          0);
3876                         yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3877 #else
3878                         /* A full chunk. Write directly from the supplied buffer. */
3879                         chunkWritten =
3880                             yaffs_WriteChunkDataToObject(in, chunk, buffer,
3881                                                          dev->nBytesPerChunk,
3882                                                          0);
3883 #endif
3884                         /* Since we've overwritten the cached data, we better invalidate it. */
3885                         yaffs_InvalidateChunkCache(in, chunk);
3886                 }
3887
3888                 if (chunkWritten >= 0) {
3889                         n -= nToCopy;
3890                         offset += nToCopy;
3891                         buffer += nToCopy;
3892                         nDone += nToCopy;
3893                 }
3894
3895         }
3896
3897         /* Update file object */
3898
3899         if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
3900                 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
3901         }
3902
3903         in->dirty = 1;
3904
3905         return nDone;
3906 }
3907
3908
3909 /* ---------------------- File resizing stuff ------------------ */
3910
3911 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
3912 {
3913
3914         yaffs_Device *dev = in->myDev;
3915         int oldFileSize = in->variant.fileVariant.fileSize;
3916
3917         int lastDel = 1 + (oldFileSize - 1) / dev->nBytesPerChunk;
3918
3919         int startDel = 1 + (newSize + dev->nBytesPerChunk - 1) /
3920             dev->nBytesPerChunk;
3921         int i;
3922         int chunkId;
3923
3924         /* Delete backwards so that we don't end up with holes if
3925          * power is lost part-way through the operation.
3926          */
3927         for (i = lastDel; i >= startDel; i--) {
3928                 /* NB this could be optimised somewhat,
3929                  * eg. could retrieve the tags and write them without
3930                  * using yaffs_DeleteChunk
3931                  */
3932
3933                 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
3934                 if (chunkId > 0) {
3935                         if (chunkId <
3936                             (dev->internalStartBlock * dev->nChunksPerBlock)
3937                             || chunkId >=
3938                             ((dev->internalEndBlock +
3939                               1) * dev->nChunksPerBlock)) {
3940                                 T(YAFFS_TRACE_ALWAYS,
3941                                   (TSTR("Found daft chunkId %d for %d" TENDSTR),
3942                                    chunkId, i));
3943                         } else {
3944                                 in->nDataChunks--;
3945                                 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
3946                         }
3947                 }
3948         }
3949
3950 }
3951
3952 int yaffs_ResizeFile(yaffs_Object * in, int newSize)
3953 {
3954
3955         int oldFileSize = in->variant.fileVariant.fileSize;
3956         int sizeOfPartialChunk;
3957         yaffs_Device *dev = in->myDev;
3958
3959         sizeOfPartialChunk = newSize % dev->nBytesPerChunk;
3960
3961         yaffs_FlushFilesChunkCache(in);
3962         yaffs_InvalidateWholeChunkCache(in);
3963
3964         yaffs_CheckGarbageCollection(dev);
3965
3966         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3967                 return yaffs_GetFileSize(in);
3968         }
3969
3970         if (newSize == oldFileSize) {
3971                 return oldFileSize;
3972         }
3973
3974         if (newSize < oldFileSize) {
3975
3976                 yaffs_PruneResizedChunks(in, newSize);
3977
3978                 if (sizeOfPartialChunk != 0) {
3979                         int lastChunk = 1 + newSize / dev->nBytesPerChunk;
3980                         __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3981
3982                         /* Got to read and rewrite the last chunk with its new size and zero pad */
3983                         yaffs_ReadChunkDataFromObject(in, lastChunk,
3984                                                       localBuffer);
3985
3986                         memset(localBuffer + sizeOfPartialChunk, 0,
3987                                dev->nBytesPerChunk - sizeOfPartialChunk);
3988
3989                         yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
3990                                                      sizeOfPartialChunk, 1);
3991
3992                         yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3993                 }
3994
3995                 in->variant.fileVariant.fileSize = newSize;
3996
3997                 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
3998         }
3999         /* Write a new object header.
4000          * show we've shrunk the file, if need be
4001          * Do this only if the file is not in the deleted directories.
4002          */
4003         if (in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
4004             in->parent->objectId != YAFFS_OBJECTID_DELETED) {
4005                 yaffs_UpdateObjectHeader(in, NULL, 0,
4006                                          (newSize < oldFileSize) ? 1 : 0, 0);
4007         }
4008
4009         return newSize;
4010 }
4011
4012 loff_t yaffs_GetFileSize(yaffs_Object * obj)
4013 {
4014         obj = yaffs_GetEquivalentObject(obj);
4015
4016         switch (obj->variantType) {
4017         case YAFFS_OBJECT_TYPE_FILE:
4018                 return obj->variant.fileVariant.fileSize;
4019         case YAFFS_OBJECT_TYPE_SYMLINK:
4020                 return yaffs_strlen(obj->variant.symLinkVariant.alias);
4021         default:
4022                 return 0;
4023         }
4024 }
4025
4026
4027
4028 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
4029 {
4030         int retVal;
4031         if (in->dirty) {
4032                 yaffs_FlushFilesChunkCache(in);
4033                 if (updateTime) {
4034 #ifdef CONFIG_YAFFS_WINCE
4035                         yfsd_WinFileTimeNow(in->win_mtime);
4036 #else
4037
4038                         in->yst_mtime = Y_CURRENT_TIME;
4039
4040 #endif
4041                 }
4042
4043                 retVal =
4044                     (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
4045                      0) ? YAFFS_OK : YAFFS_FAIL;
4046         } else {
4047                 retVal = YAFFS_OK;
4048         }
4049
4050         return retVal;
4051
4052 }
4053
4054 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
4055 {
4056
4057         /* First off, invalidate the file's data in the cache, without flushing. */
4058         yaffs_InvalidateWholeChunkCache(in);
4059
4060         if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
4061                 /* Move to the unlinked directory so we have a record that it was deleted. */
4062                 yaffs_ChangeObjectName(in, in->myDev->deletedDir, NULL, 0, 0);
4063
4064         }
4065
4066         yaffs_RemoveObjectFromDirectory(in);
4067         yaffs_DeleteChunk(in->myDev, in->chunkId, 1, __LINE__);
4068         in->chunkId = -1;
4069
4070         yaffs_FreeObject(in);
4071         return YAFFS_OK;
4072
4073 }
4074
4075 /* yaffs_DeleteFile deletes the whole file data
4076  * and the inode associated with the file.
4077  * It does not delete the links associated with the file.
4078  */
4079 static int yaffs_UnlinkFile(yaffs_Object * in)
4080 {
4081
4082         int retVal;
4083         int immediateDeletion = 0;
4084
4085         if (1) {
4086 #ifdef __KERNEL__
4087                 if (!in->myInode) {
4088                         immediateDeletion = 1;
4089
4090                 }
4091 #else
4092                 if (in->inUse <= 0) {
4093                         immediateDeletion = 1;
4094
4095                 }
4096 #endif
4097                 if (immediateDeletion) {
4098                         retVal =
4099                             yaffs_ChangeObjectName(in, in->myDev->deletedDir,
4100                                                    NULL, 0, 0);
4101                         T(YAFFS_TRACE_TRACING,
4102                           (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
4103                            in->objectId));
4104                         in->deleted = 1;
4105                         in->myDev->nDeletedFiles++;
4106                         if (0 && in->myDev->isYaffs2) {
4107                                 yaffs_ResizeFile(in, 0);
4108                         }
4109                         yaffs_SoftDeleteFile(in);
4110                 } else {
4111                         retVal =
4112                             yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
4113                                                    NULL, 0, 0);
4114                 }
4115
4116         }
4117         return retVal;
4118 }
4119
4120 int yaffs_DeleteFile(yaffs_Object * in)
4121 {
4122         int retVal = YAFFS_OK;
4123
4124         if (in->nDataChunks > 0) {
4125                 /* Use soft deletion if there is data in the file */
4126                 if (!in->unlinked) {
4127                         retVal = yaffs_UnlinkFile(in);
4128                 }
4129                 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
4130                         in->deleted = 1;
4131                         in->myDev->nDeletedFiles++;
4132                         yaffs_SoftDeleteFile(in);
4133                 }
4134                 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
4135         } else {
4136                 /* The file has no data chunks so we toss it immediately */
4137                 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
4138                 in->variant.fileVariant.top = NULL;
4139                 yaffs_DoGenericObjectDeletion(in);
4140
4141                 return YAFFS_OK;
4142         }
4143 }
4144
4145 static int yaffs_DeleteDirectory(yaffs_Object * in)
4146 {
4147         /* First check that the directory is empty. */
4148         if (list_empty(&in->variant.directoryVariant.children)) {
4149                 return yaffs_DoGenericObjectDeletion(in);
4150         }
4151
4152         return YAFFS_FAIL;
4153
4154 }
4155
4156 static int yaffs_DeleteSymLink(yaffs_Object * in)
4157 {
4158         YFREE(in->variant.symLinkVariant.alias);
4159
4160         return yaffs_DoGenericObjectDeletion(in);
4161 }
4162
4163 static int yaffs_DeleteHardLink(yaffs_Object * in)
4164 {
4165         /* remove this hardlink from the list assocaited with the equivalent
4166          * object
4167          */
4168         list_del(&in->hardLinks);
4169         return yaffs_DoGenericObjectDeletion(in);
4170 }
4171
4172 static void yaffs_DestroyObject(yaffs_Object * obj)
4173 {
4174         switch (obj->variantType) {
4175         case YAFFS_OBJECT_TYPE_FILE:
4176                 yaffs_DeleteFile(obj);
4177                 break;
4178         case YAFFS_OBJECT_TYPE_DIRECTORY:
4179                 yaffs_DeleteDirectory(obj);
4180                 break;
4181         case YAFFS_OBJECT_TYPE_SYMLINK:
4182                 yaffs_DeleteSymLink(obj);
4183                 break;
4184         case YAFFS_OBJECT_TYPE_HARDLINK:
4185                 yaffs_DeleteHardLink(obj);
4186                 break;
4187         case YAFFS_OBJECT_TYPE_SPECIAL:
4188                 yaffs_DoGenericObjectDeletion(obj);
4189                 break;
4190         case YAFFS_OBJECT_TYPE_UNKNOWN:
4191                 break;          /* should not happen. */
4192         }
4193 }
4194
4195 static int yaffs_UnlinkWorker(yaffs_Object * obj)
4196 {
4197
4198         if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4199                 return yaffs_DeleteHardLink(obj);
4200         } else if (!list_empty(&obj->hardLinks)) {
4201                 /* Curve ball: We're unlinking an object that has a hardlink.
4202                  *
4203                  * This problem arises because we are not strictly following
4204                  * The Linux link/inode model.
4205                  *
4206                  * We can't really delete the object.
4207                  * Instead, we do the following:
4208                  * - Select a hardlink.
4209                  * - Unhook it from the hard links
4210                  * - Unhook it from its parent directory (so that the rename can work)
4211                  * - Rename the object to the hardlink's name.
4212                  * - Delete the hardlink
4213                  */
4214
4215                 yaffs_Object *hl;
4216                 int retVal;
4217                 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
4218
4219                 hl = list_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
4220
4221                 list_del_init(&hl->hardLinks);
4222                 list_del_init(&hl->siblings);
4223
4224                 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
4225
4226                 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
4227
4228                 if (retVal == YAFFS_OK) {
4229                         retVal = yaffs_DoGenericObjectDeletion(hl);
4230                 }
4231                 return retVal;
4232
4233         } else {
4234                 switch (obj->variantType) {
4235                 case YAFFS_OBJECT_TYPE_FILE:
4236                         return yaffs_UnlinkFile(obj);
4237                         break;
4238                 case YAFFS_OBJECT_TYPE_DIRECTORY:
4239                         return yaffs_DeleteDirectory(obj);
4240                         break;
4241                 case YAFFS_OBJECT_TYPE_SYMLINK:
4242                         return yaffs_DeleteSymLink(obj);
4243                         break;
4244                 case YAFFS_OBJECT_TYPE_SPECIAL:
4245                         return yaffs_DoGenericObjectDeletion(obj);
4246                         break;
4247                 case YAFFS_OBJECT_TYPE_HARDLINK:
4248                 case YAFFS_OBJECT_TYPE_UNKNOWN:
4249                 default:
4250                         return YAFFS_FAIL;
4251                 }
4252         }
4253 }
4254
4255
4256 static int yaffs_UnlinkObject( yaffs_Object *obj)
4257 {
4258
4259         if (obj && obj->unlinkAllowed) {
4260                 return yaffs_UnlinkWorker(obj);
4261         }
4262
4263         return YAFFS_FAIL;
4264
4265 }
4266 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
4267 {
4268         yaffs_Object *obj;
4269
4270         obj = yaffs_FindObjectByName(dir, name);
4271         return yaffs_UnlinkObject(obj);
4272 }
4273
4274 /*----------------------- Initialisation Scanning ---------------------- */
4275
4276 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
4277                                        int backwardScanning)
4278 {
4279         yaffs_Object *obj;
4280
4281         if (!backwardScanning) {
4282                 /* Handle YAFFS1 forward scanning case
4283                  * For YAFFS1 we always do the deletion
4284                  */
4285
4286         } else {
4287                 /* Handle YAFFS2 case (backward scanning)
4288                  * If the shadowed object exists then ignore.
4289                  */
4290                 if (yaffs_FindObjectByNumber(dev, objId)) {
4291                         return;
4292                 }
4293         }
4294
4295         /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
4296          * We put it in unlinked dir to be cleaned up after the scanning
4297          */
4298         obj =
4299             yaffs_FindOrCreateObjectByNumber(dev, objId,
4300                                              YAFFS_OBJECT_TYPE_FILE);
4301         yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
4302         obj->variant.fileVariant.shrinkSize = 0;
4303         obj->valid = 1;         /* So that we don't read any other info for this file */
4304
4305 }
4306
4307 typedef struct {
4308         int seq;
4309         int block;
4310 } yaffs_BlockIndex;
4311
4312
4313 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
4314 {
4315         yaffs_Object *hl;
4316         yaffs_Object *in;
4317         
4318         while (hardList) {
4319                 hl = hardList;
4320                 hardList = (yaffs_Object *) (hardList->hardLinks.next);
4321
4322                 in = yaffs_FindObjectByNumber(dev,
4323                                               hl->variant.hardLinkVariant.
4324                                               equivalentObjectId);
4325
4326                 if (in) {
4327                         /* Add the hardlink pointers */
4328                         hl->variant.hardLinkVariant.equivalentObject = in;
4329                         list_add(&hl->hardLinks, &in->hardLinks);
4330                 } else {
4331                         /* Todo Need to report/handle this better.
4332                          * Got a problem... hardlink to a non-existant object
4333                          */
4334                         hl->variant.hardLinkVariant.equivalentObject = NULL;
4335                         INIT_LIST_HEAD(&hl->hardLinks);
4336
4337                 }
4338
4339         }
4340
4341 }
4342
4343
4344
4345
4346
4347 static int yaffs_Scan(yaffs_Device * dev)
4348 {
4349         yaffs_ExtendedTags tags;
4350         int blk;
4351         int blockIterator;
4352         int startIterator;
4353         int endIterator;
4354         int nBlocksToScan = 0;
4355
4356         int chunk;
4357         int c;
4358         int deleted;
4359         yaffs_BlockState state;
4360         yaffs_Object *hardList = NULL;
4361         yaffs_Object *hl;
4362         yaffs_BlockInfo *bi;
4363         int sequenceNumber;
4364         yaffs_ObjectHeader *oh;
4365         yaffs_Object *in;
4366         yaffs_Object *parent;
4367         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
4368
4369         __u8 *chunkData;
4370
4371         yaffs_BlockIndex *blockIndex = NULL;
4372
4373         T(YAFFS_TRACE_SCAN,
4374           (TSTR("yaffs_Scan starts  intstartblk %d intendblk %d..." TENDSTR),
4375            dev->internalStartBlock, dev->internalEndBlock));
4376
4377         chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4378
4379         dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
4380
4381         if (dev->isYaffs2) {
4382                 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
4383         }
4384
4385         /* Scan all the blocks to determine their state */
4386         for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
4387                 bi = yaffs_GetBlockInfo(dev, blk);
4388                 yaffs_ClearChunkBits(dev, blk);
4389                 bi->pagesInUse = 0;
4390                 bi->softDeletions = 0;
4391
4392                 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
4393
4394                 bi->blockState = state;
4395                 bi->sequenceNumber = sequenceNumber;
4396
4397                 T(YAFFS_TRACE_SCAN_DEBUG,
4398                   (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
4399                    state, sequenceNumber));
4400
4401                 if (state == YAFFS_BLOCK_STATE_DEAD) {
4402                         T(YAFFS_TRACE_BAD_BLOCKS,
4403                           (TSTR("block %d is bad" TENDSTR), blk));
4404                 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
4405                         T(YAFFS_TRACE_SCAN_DEBUG,
4406                           (TSTR("Block empty " TENDSTR)));
4407                         dev->nErasedBlocks++;
4408                         dev->nFreeChunks += dev->nChunksPerBlock;
4409                 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4410
4411                         /* Determine the highest sequence number */
4412                         if (dev->isYaffs2 &&
4413                             sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
4414                             sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
4415
4416                                 blockIndex[nBlocksToScan].seq = sequenceNumber;
4417                                 blockIndex[nBlocksToScan].block = blk;
4418
4419                                 nBlocksToScan++;
4420
4421                                 if (sequenceNumber >= dev->sequenceNumber) {
4422                                         dev->sequenceNumber = sequenceNumber;
4423                                 }
4424                         } else if (dev->isYaffs2) {
4425                                 /* TODO: Nasty sequence number! */
4426                                 T(YAFFS_TRACE_SCAN,
4427                                   (TSTR
4428                                    ("Block scanning block %d has bad sequence number %d"
4429                                     TENDSTR), blk, sequenceNumber));
4430
4431                         }
4432                 }
4433         }
4434
4435         /* Sort the blocks
4436          * Dungy old bubble sort for now...
4437          */
4438         if (dev->isYaffs2) {
4439                 yaffs_BlockIndex temp;
4440                 int i;
4441                 int j;
4442
4443                 for (i = 0; i < nBlocksToScan; i++)
4444                         for (j = i + 1; j < nBlocksToScan; j++)
4445                                 if (blockIndex[i].seq > blockIndex[j].seq) {
4446                                         temp = blockIndex[j];
4447                                         blockIndex[j] = blockIndex[i];
4448                                         blockIndex[i] = temp;
4449                                 }
4450         }
4451
4452         /* Now scan the blocks looking at the data. */
4453         if (dev->isYaffs2) {
4454                 startIterator = 0;
4455                 endIterator = nBlocksToScan - 1;
4456                 T(YAFFS_TRACE_SCAN_DEBUG,
4457                   (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
4458         } else {
4459                 startIterator = dev->internalStartBlock;
4460                 endIterator = dev->internalEndBlock;
4461         }
4462
4463         /* For each block.... */
4464         for (blockIterator = startIterator; blockIterator <= endIterator;
4465              blockIterator++) {
4466
4467                 if (dev->isYaffs2) {
4468                         /* get the block to scan in the correct order */
4469                         blk = blockIndex[blockIterator].block;
4470                 } else {
4471                         blk = blockIterator;
4472                 }
4473
4474                 bi = yaffs_GetBlockInfo(dev, blk);
4475                 state = bi->blockState;
4476
4477                 deleted = 0;
4478
4479                 /* For each chunk in each block that needs scanning....*/
4480                 for (c = 0; c < dev->nChunksPerBlock &&
4481                      state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
4482                         /* Read the tags and decide what to do */
4483                         chunk = blk * dev->nChunksPerBlock + c;
4484
4485                         yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
4486                                                         &tags);
4487
4488                         /* Let's have a good look at this chunk... */
4489
4490                         if (!dev->isYaffs2 && tags.chunkDeleted) {
4491                                 /* YAFFS1 only...
4492                                  * A deleted chunk
4493                                  */
4494                                 deleted++;
4495                                 dev->nFreeChunks++;
4496                                 /*T((" %d %d deleted\n",blk,c)); */
4497                         } else if (!tags.chunkUsed) {
4498                                 /* An unassigned chunk in the block
4499                                  * This means that either the block is empty or 
4500                                  * this is the one being allocated from
4501                                  */
4502
4503                                 if (c == 0) {
4504                                         /* We're looking at the first chunk in the block so the block is unused */
4505                                         state = YAFFS_BLOCK_STATE_EMPTY;
4506                                         dev->nErasedBlocks++;
4507                                 } else {
4508                                         /* this is the block being allocated from */
4509                                         T(YAFFS_TRACE_SCAN,
4510                                           (TSTR
4511                                            (" Allocating from %d %d" TENDSTR),
4512                                            blk, c));
4513                                         state = YAFFS_BLOCK_STATE_ALLOCATING;
4514                                         dev->allocationBlock = blk;
4515                                         dev->allocationPage = c;
4516                                         dev->allocationBlockFinder = blk;       
4517                                         /* Set it to here to encourage the allocator to go forth from here. */
4518                                         
4519                                         /* Yaffs2 sanity check:
4520                                          * This should be the one with the highest sequence number
4521                                          */
4522                                         if (dev->isYaffs2
4523                                             && (dev->sequenceNumber !=
4524                                                 bi->sequenceNumber)) {
4525                                                 T(YAFFS_TRACE_ALWAYS,
4526                                                   (TSTR
4527                                                    ("yaffs: Allocation block %d was not highest sequence id:"
4528                                                     " block seq = %d, dev seq = %d"
4529                                                     TENDSTR), blk,bi->sequenceNumber,dev->sequenceNumber));
4530                                         }
4531                                 }
4532
4533                                 dev->nFreeChunks += (dev->nChunksPerBlock - c);
4534                         } else if (tags.chunkId > 0) {
4535                                 /* chunkId > 0 so it is a data chunk... */
4536                                 unsigned int endpos;
4537
4538                                 yaffs_SetChunkBit(dev, blk, c);
4539                                 bi->pagesInUse++;
4540
4541                                 in = yaffs_FindOrCreateObjectByNumber(dev,
4542                                                                       tags.
4543                                                                       objectId,
4544                                                                       YAFFS_OBJECT_TYPE_FILE);
4545                                 /* PutChunkIntoFile checks for a clash (two data chunks with
4546                                  * the same chunkId).
4547                                  */
4548                                 yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,
4549                                                        1);
4550                                 endpos =
4551                                     (tags.chunkId - 1) * dev->nBytesPerChunk +
4552                                     tags.byteCount;
4553                                 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
4554                                     && in->variant.fileVariant.scannedFileSize <
4555                                     endpos) {
4556                                         in->variant.fileVariant.
4557                                             scannedFileSize = endpos;
4558                                         if (!dev->useHeaderFileSize) {
4559                                                 in->variant.fileVariant.
4560                                                     fileSize =
4561                                                     in->variant.fileVariant.
4562                                                     scannedFileSize;
4563                                         }
4564
4565                                 }
4566                                 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));   */
4567                         } else {
4568                                 /* chunkId == 0, so it is an ObjectHeader.
4569                                  * Thus, we read in the object header and make the object
4570                                  */
4571                                 yaffs_SetChunkBit(dev, blk, c);
4572                                 bi->pagesInUse++;
4573
4574                                 yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
4575                                                                 chunkData,
4576                                                                 NULL);
4577
4578                                 oh = (yaffs_ObjectHeader *) chunkData;
4579
4580                                 in = yaffs_FindObjectByNumber(dev,
4581                                                               tags.objectId);
4582                                 if (in && in->variantType != oh->type) {
4583                                         /* This should not happen, but somehow
4584                                          * Wev'e ended up with an objectId that has been reused but not yet 
4585                                          * deleted, and worse still it has changed type. Delete the old object.
4586                                          */
4587
4588                                         yaffs_DestroyObject(in);
4589
4590                                         in = 0;
4591                                 }
4592
4593                                 in = yaffs_FindOrCreateObjectByNumber(dev,
4594                                                                       tags.
4595                                                                       objectId,
4596                                                                       oh->type);
4597
4598                                 if (oh->shadowsObject > 0) {
4599                                         yaffs_HandleShadowedObject(dev,
4600                                                                    oh->
4601                                                                    shadowsObject,
4602                                                                    0);
4603                                 }
4604
4605                                 if (in->valid) {
4606                                         /* We have already filled this one. We have a duplicate and need to resolve it. */
4607
4608                                         unsigned existingSerial = in->serial;
4609                                         unsigned newSerial = tags.serialNumber;
4610
4611                                         if (dev->isYaffs2 ||
4612                                             ((existingSerial + 1) & 3) ==
4613                                             newSerial) {
4614                                                 /* Use new one - destroy the exisiting one */
4615                                                 yaffs_DeleteChunk(dev,
4616                                                                   in->chunkId,
4617                                                                   1, __LINE__);
4618                                                 in->valid = 0;
4619                                         } else {
4620                                                 /* Use existing - destroy this one. */
4621                                                 yaffs_DeleteChunk(dev, chunk, 1,
4622                                                                   __LINE__);
4623                                         }
4624                                 }
4625
4626                                 if (!in->valid &&
4627                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
4628                                      tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
4629                                         /* We only load some info, don't fiddle with directory structure */
4630                                         in->valid = 1;
4631                                         in->variantType = oh->type;
4632
4633                                         in->yst_mode = oh->yst_mode;
4634 #ifdef CONFIG_YAFFS_WINCE
4635                                         in->win_atime[0] = oh->win_atime[0];
4636                                         in->win_ctime[0] = oh->win_ctime[0];
4637                                         in->win_mtime[0] = oh->win_mtime[0];
4638                                         in->win_atime[1] = oh->win_atime[1];
4639                                         in->win_ctime[1] = oh->win_ctime[1];
4640                                         in->win_mtime[1] = oh->win_mtime[1];
4641 #else
4642                                         in->yst_uid = oh->yst_uid;
4643                                         in->yst_gid = oh->yst_gid;
4644                                         in->yst_atime = oh->yst_atime;
4645                                         in->yst_mtime = oh->yst_mtime;
4646                                         in->yst_ctime = oh->yst_ctime;
4647                                         in->yst_rdev = oh->yst_rdev;
4648 #endif
4649                                         in->chunkId = chunk;
4650
4651                                 } else if (!in->valid) {
4652                                         /* we need to load this info */
4653
4654                                         in->valid = 1;
4655                                         in->variantType = oh->type;
4656
4657                                         in->yst_mode = oh->yst_mode;
4658 #ifdef CONFIG_YAFFS_WINCE
4659                                         in->win_atime[0] = oh->win_atime[0];
4660                                         in->win_ctime[0] = oh->win_ctime[0];
4661                                         in->win_mtime[0] = oh->win_mtime[0];
4662                                         in->win_atime[1] = oh->win_atime[1];
4663                                         in->win_ctime[1] = oh->win_ctime[1];
4664                                         in->win_mtime[1] = oh->win_mtime[1];
4665 #else
4666                                         in->yst_uid = oh->yst_uid;
4667                                         in->yst_gid = oh->yst_gid;
4668                                         in->yst_atime = oh->yst_atime;
4669                                         in->yst_mtime = oh->yst_mtime;
4670                                         in->yst_ctime = oh->yst_ctime;
4671                                         in->yst_rdev = oh->yst_rdev;
4672 #endif
4673                                         in->chunkId = chunk;
4674
4675                                         yaffs_SetObjectName(in, oh->name);
4676                                         in->dirty = 0;
4677
4678                                         /* directory stuff...
4679                                          * hook up to parent
4680                                          */
4681
4682                                         parent =
4683                                             yaffs_FindOrCreateObjectByNumber
4684                                             (dev, oh->parentObjectId,
4685                                              YAFFS_OBJECT_TYPE_DIRECTORY);
4686                                         if (parent->variantType ==
4687                                             YAFFS_OBJECT_TYPE_UNKNOWN) {
4688                                                 /* Set up as a directory */
4689                                                 parent->variantType =
4690                                                     YAFFS_OBJECT_TYPE_DIRECTORY;
4691                                                 INIT_LIST_HEAD(&parent->variant.
4692                                                                directoryVariant.
4693                                                                children);
4694                                         } else if (parent->variantType !=
4695                                                    YAFFS_OBJECT_TYPE_DIRECTORY)
4696                                         {
4697                                                 /* Hoosterman, another problem....
4698                                                  * We're trying to use a non-directory as a directory
4699                                                  */
4700
4701                                                 T(YAFFS_TRACE_ERROR,
4702                                                   (TSTR
4703                                                    ("yaffs tragedy: attempting to use non-directory as"
4704                                                     " a directory in scan. Put in lost+found."
4705                                                     TENDSTR)));
4706                                                 parent = dev->lostNFoundDir;
4707                                         }
4708
4709                                         yaffs_AddObjectToDirectory(parent, in);
4710
4711                                         if (0 && (parent == dev->deletedDir ||
4712                                                   parent == dev->unlinkedDir)) {
4713                                                 in->deleted = 1;        /* If it is unlinked at start up then it wants deleting */
4714                                                 dev->nDeletedFiles++;
4715                                         }
4716                                         /* Note re hardlinks.
4717                                          * Since we might scan a hardlink before its equivalent object is scanned
4718                                          * we put them all in a list.
4719                                          * After scanning is complete, we should have all the objects, so we run through this
4720                                          * list and fix up all the chains.              
4721                                          */
4722
4723                                         switch (in->variantType) {
4724                                         case YAFFS_OBJECT_TYPE_UNKNOWN: 
4725                                                 /* Todo got a problem */
4726                                                 break;
4727                                         case YAFFS_OBJECT_TYPE_FILE:
4728                                                 if (dev->isYaffs2
4729                                                     && oh->isShrink) {
4730                                                         /* Prune back the shrunken chunks */
4731                                                         yaffs_PruneResizedChunks
4732                                                             (in, oh->fileSize);
4733                                                         /* Mark the block as having a shrinkHeader */
4734                                                         bi->hasShrinkHeader = 1;
4735                                                 }
4736
4737                                                 if (dev->useHeaderFileSize)
4738
4739                                                         in->variant.fileVariant.
4740                                                             fileSize =
4741                                                             oh->fileSize;
4742
4743                                                 break;
4744                                         case YAFFS_OBJECT_TYPE_HARDLINK:
4745                                                 in->variant.hardLinkVariant.
4746                                                     equivalentObjectId =
4747                                                     oh->equivalentObjectId;
4748                                                 in->hardLinks.next =
4749                                                     (struct list_head *)
4750                                                     hardList;
4751                                                 hardList = in;
4752                                                 break;
4753                                         case YAFFS_OBJECT_TYPE_DIRECTORY:
4754                                                 /* Do nothing */
4755                                                 break;
4756                                         case YAFFS_OBJECT_TYPE_SPECIAL:
4757                                                 /* Do nothing */
4758                                                 break;
4759                                         case YAFFS_OBJECT_TYPE_SYMLINK: 
4760                                                 in->variant.symLinkVariant.
4761                                                     alias =
4762                                                     yaffs_CloneString(oh->alias);
4763                                                 break;
4764                                         }
4765
4766                                         if (parent == dev->deletedDir) {
4767                                                 yaffs_DestroyObject(in);
4768                                                 bi->hasShrinkHeader = 1;
4769                                         }
4770                                 }
4771                         }
4772                 }
4773
4774                 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4775                         /* If we got this far while scanning, then the block is fully allocated.*/
4776                         state = YAFFS_BLOCK_STATE_FULL;
4777                 }
4778
4779                 bi->blockState = state;
4780
4781                 /* Now let's see if it was dirty */
4782                 if (bi->pagesInUse == 0 &&
4783                     !bi->hasShrinkHeader &&
4784                     bi->blockState == YAFFS_BLOCK_STATE_FULL) {
4785                         yaffs_BlockBecameDirty(dev, blk);
4786                 }
4787
4788         }
4789
4790         if (blockIndex) {
4791                 YFREE(blockIndex);
4792         }
4793         
4794         
4795         /* Ok, we've done all the scanning.
4796          * Fix up the hard link chains.
4797          * We should now have scanned all the objects, now it's time to add these 
4798          * hardlinks.
4799          */
4800
4801         yaffs_HardlinkFixup(dev,hardList);
4802
4803         /* Handle the unlinked files. Since they were left in an unlinked state we should
4804          * just delete them.
4805          */
4806         {
4807                 struct list_head *i;
4808                 struct list_head *n;
4809
4810                 yaffs_Object *l;
4811                 /* Soft delete all the unlinked files */
4812                 list_for_each_safe(i, n,
4813                                    &dev->unlinkedDir->variant.directoryVariant.
4814                                    children) {
4815                         if (i) {
4816                                 l = list_entry(i, yaffs_Object, siblings);
4817                                 yaffs_DestroyObject(l);
4818                         }
4819                 }
4820         }
4821
4822         yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
4823
4824         T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
4825
4826         return YAFFS_OK;
4827 }
4828
4829 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
4830 {
4831         __u8 *chunkData;
4832         yaffs_ObjectHeader *oh;
4833         yaffs_Device *dev = in->myDev;
4834         
4835         if(in->lazyLoaded){
4836                 in->lazyLoaded = 0;
4837                 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4838
4839                 yaffs_ReadChunkWithTagsFromNAND(dev,in->chunkId,chunkData,NULL);
4840                 oh = (yaffs_ObjectHeader *) chunkData;          
4841
4842                 in->yst_mode = oh->yst_mode;
4843 #ifdef CONFIG_YAFFS_WINCE
4844                 in->win_atime[0] = oh->win_atime[0];
4845                 in->win_ctime[0] = oh->win_ctime[0];
4846                 in->win_mtime[0] = oh->win_mtime[0];
4847                 in->win_atime[1] = oh->win_atime[1];
4848                 in->win_ctime[1] = oh->win_ctime[1];
4849                 in->win_mtime[1] = oh->win_mtime[1];
4850 #else
4851                 in->yst_uid = oh->yst_uid;
4852                 in->yst_gid = oh->yst_gid;
4853                 in->yst_atime = oh->yst_atime;
4854                 in->yst_mtime = oh->yst_mtime;
4855                 in->yst_ctime = oh->yst_ctime;
4856                 in->yst_rdev = oh->yst_rdev;
4857                 
4858 #endif
4859                 yaffs_SetObjectName(in, oh->name);
4860                 
4861                 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
4862                          in->variant.symLinkVariant.alias =
4863                                                     yaffs_CloneString(oh->alias);
4864                                                     
4865                 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
4866         }
4867 }
4868
4869 static int yaffs_ScanBackwards(yaffs_Device * dev)
4870 {
4871         yaffs_ExtendedTags tags;
4872         int blk;
4873         int blockIterator;
4874         int startIterator;
4875         int endIterator;
4876         int nBlocksToScan = 0;
4877
4878         int chunk;
4879         int c;
4880         int deleted;
4881         yaffs_BlockState state;
4882         yaffs_Object *hardList = NULL;
4883         yaffs_BlockInfo *bi;
4884         int sequenceNumber;
4885         yaffs_ObjectHeader *oh;
4886         yaffs_Object *in;
4887         yaffs_Object *parent;
4888         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
4889         int itsUnlinked;
4890         __u8 *chunkData;
4891         
4892         int fileSize;
4893         int isShrink;
4894         int equivalentObjectId;
4895         
4896
4897         yaffs_BlockIndex *blockIndex = NULL;
4898
4899         if (!dev->isYaffs2) {
4900                 T(YAFFS_TRACE_SCAN,
4901                   (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
4902                 return YAFFS_FAIL;
4903         }
4904
4905         T(YAFFS_TRACE_SCAN,
4906           (TSTR
4907            ("yaffs_ScanBackwards starts  intstartblk %d intendblk %d..."
4908             TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
4909
4910         chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4911
4912         dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
4913
4914         blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
4915
4916         /* Scan all the blocks to determine their state */
4917         for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
4918                 bi = yaffs_GetBlockInfo(dev, blk);
4919                 yaffs_ClearChunkBits(dev, blk);
4920                 bi->pagesInUse = 0;
4921                 bi->softDeletions = 0;
4922
4923                 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
4924
4925                 bi->blockState = state;
4926                 bi->sequenceNumber = sequenceNumber;
4927
4928                 T(YAFFS_TRACE_SCAN_DEBUG,
4929                   (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
4930                    state, sequenceNumber));
4931
4932                 if (state == YAFFS_BLOCK_STATE_DEAD) {
4933                         T(YAFFS_TRACE_BAD_BLOCKS,
4934                           (TSTR("block %d is bad" TENDSTR), blk));
4935                 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
4936                         T(YAFFS_TRACE_SCAN_DEBUG,
4937                           (TSTR("Block empty " TENDSTR)));
4938                         dev->nErasedBlocks++;
4939                         dev->nFreeChunks += dev->nChunksPerBlock;
4940                 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4941
4942                         /* Determine the highest sequence number */
4943                         if (dev->isYaffs2 &&
4944                             sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
4945                             sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
4946
4947                                 blockIndex[nBlocksToScan].seq = sequenceNumber;
4948                                 blockIndex[nBlocksToScan].block = blk;
4949
4950                                 nBlocksToScan++;
4951
4952                                 if (sequenceNumber >= dev->sequenceNumber) {
4953                                         dev->sequenceNumber = sequenceNumber;
4954                                 }
4955                         } else if (dev->isYaffs2) {
4956                                 /* TODO: Nasty sequence number! */
4957                                 T(YAFFS_TRACE_SCAN,
4958                                   (TSTR
4959                                    ("Block scanning block %d has bad sequence number %d"
4960                                     TENDSTR), blk, sequenceNumber));
4961
4962                         }
4963                 }
4964         }
4965
4966         /*
4967          * Sort the blocks
4968          * Dungy old bubble sort for now...
4969          */
4970         {
4971                 yaffs_BlockIndex temp;
4972                 int i;
4973                 int j;
4974
4975                 for (i = 0; i < nBlocksToScan; i++)
4976                         for (j = i + 1; j < nBlocksToScan; j++)
4977                                 if (blockIndex[i].seq > blockIndex[j].seq) {
4978                                         temp = blockIndex[j];
4979                                         blockIndex[j] = blockIndex[i];
4980                                         blockIndex[i] = temp;
4981                                 }
4982         }
4983
4984         /* Now scan the blocks looking at the data. */
4985         startIterator = 0;
4986         endIterator = nBlocksToScan - 1;
4987         T(YAFFS_TRACE_SCAN_DEBUG,
4988           (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
4989
4990         /* For each block.... backwards */
4991         for (blockIterator = endIterator; blockIterator >= startIterator;
4992              blockIterator--) {
4993
4994                 /* get the block to scan in the correct order */
4995                 blk = blockIndex[blockIterator].block;
4996
4997                 bi = yaffs_GetBlockInfo(dev, blk);
4998                 state = bi->blockState;
4999
5000                 deleted = 0;
5001
5002                 /* For each chunk in each block that needs scanning.... */
5003                 for (c = dev->nChunksPerBlock - 1; c >= 0 &&
5004                      (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
5005                       state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
5006                         /* Scan backwards... 
5007                          * Read the tags and decide what to do
5008                          */
5009                         chunk = blk * dev->nChunksPerBlock + c;
5010
5011                         yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5012                                                         &tags);
5013
5014                         /* Let's have a good look at this chunk... */
5015
5016                         if (!tags.chunkUsed) {
5017                                 // An unassigned chunk in the block
5018                                 // This means that either the block is empty or 
5019                                 // this is the one being allocated from
5020
5021                                 if (c == 0) {
5022                                         /* We're looking at the first chunk in the block so the block is unused */
5023                                         state = YAFFS_BLOCK_STATE_EMPTY;
5024                                         dev->nErasedBlocks++;
5025                                 } else {
5026                                         /* this is the block being allocated from */
5027                                         if (state ==
5028                                             YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5029                                                 T(YAFFS_TRACE_SCAN,
5030                                                   (TSTR
5031                                                    (" Allocating from %d %d"
5032                                                     TENDSTR), blk, c));
5033                                         }
5034                                         state = YAFFS_BLOCK_STATE_ALLOCATING;
5035                                         dev->allocationBlock = blk;
5036                                         dev->allocationPage = c;
5037                                         dev->allocationBlockFinder = blk;       
5038                                         /* Set it to here to encourage the allocator to 
5039                                          *  go forth from here.
5040                                          */
5041                                          
5042                                         /* Yaffs2 sanity check:
5043                                          * This should be the one with the highest sequence number
5044                                          */
5045                                         if (dev->isYaffs2
5046                                             && (dev->sequenceNumber !=
5047                                                 bi->sequenceNumber)) {
5048                                                 T(YAFFS_TRACE_ALWAYS,
5049                                                   (TSTR
5050                                                    ("yaffs: Allocation block %d was not highest sequence "
5051                                                     "id: block seq = %d, dev seq = %d"
5052                                                     TENDSTR), blk,
5053                                                    bi->sequenceNumber,
5054                                                    dev->sequenceNumber));
5055                                         }
5056                                 }
5057
5058                                 dev->nFreeChunks++;
5059                         } else if (tags.chunkId > 0) {
5060                                 /* chunkId > 0 so it is a data chunk... */
5061                                 unsigned int endpos;
5062
5063                                 __u32 chunkBase =
5064                                     (tags.chunkId - 1) * dev->nBytesPerChunk;
5065
5066                                 yaffs_SetChunkBit(dev, blk, c);
5067                                 bi->pagesInUse++;
5068
5069                                 in = yaffs_FindOrCreateObjectByNumber(dev,
5070                                                                       tags.
5071                                                                       objectId,
5072                                                                       YAFFS_OBJECT_TYPE_FILE);
5073                                 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
5074                                     && chunkBase <
5075                                     in->variant.fileVariant.shrinkSize) {
5076                                         /* This has not been invalidated by a resize */
5077                                         yaffs_PutChunkIntoFile(in, tags.chunkId,
5078                                                                chunk, -1);
5079
5080                                         /* File size is calculated by looking at the data chunks if we have not 
5081                                          * seen an object header yet. Stop this practice once we find an object header.
5082                                          */
5083                                         endpos =
5084                                             (tags.chunkId -
5085                                              1) * dev->nBytesPerChunk +
5086                                             tags.byteCount;
5087                                             
5088                                         if (!in->valid &&       /* have not got an object header yet */
5089                                             in->variant.fileVariant.
5090                                             scannedFileSize < endpos) {
5091                                                 in->variant.fileVariant.
5092                                                     scannedFileSize = endpos;
5093                                                 in->variant.fileVariant.
5094                                                     fileSize =
5095                                                     in->variant.fileVariant.
5096                                                     scannedFileSize;
5097                                         }
5098
5099                                 } else {
5100                                         /* This chunk has been invalidated by a resize, so delete */
5101                                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
5102
5103                                 }
5104                         } else {
5105                                 /* chunkId == 0, so it is an ObjectHeader.
5106                                  * Thus, we read in the object header and make the object
5107                                  */
5108                                 yaffs_SetChunkBit(dev, blk, c);
5109                                 bi->pagesInUse++;
5110
5111                                 oh = NULL;
5112                                 in = NULL;
5113
5114                                 if (tags.extraHeaderInfoAvailable) {
5115                                         in = yaffs_FindOrCreateObjectByNumber
5116                                             (dev, tags.objectId,
5117                                              tags.extraObjectType);
5118                                 }
5119
5120                                 if (!in ||
5121 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
5122                                     !in->valid ||
5123 #endif
5124                                     tags.extraShadows ||
5125                                     (!in->valid &&
5126                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
5127                                      tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
5128                                     ) {
5129
5130                                         /* If we don't have  valid info then we need to read the chunk
5131                                          * TODO In future we can probably defer reading the chunk and 
5132                                          * living with invalid data until needed.
5133                                          */
5134
5135                                         yaffs_ReadChunkWithTagsFromNAND(dev,
5136                                                                         chunk,
5137                                                                         chunkData,
5138                                                                         NULL);
5139
5140                                         oh = (yaffs_ObjectHeader *) chunkData;
5141
5142                                         if (!in)
5143                                                 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
5144
5145                                 }
5146
5147                                 if (!in) {
5148                                         /* TODO Hoosterman we have a problem! */
5149                                         T(YAFFS_TRACE_ERROR,
5150                                           (TSTR
5151                                            ("yaffs tragedy: Could not make object for object  %d  "
5152                                             "at chunk %d during scan"
5153                                             TENDSTR), tags.objectId, chunk));
5154
5155                                 }
5156
5157                                 if (in->valid) {
5158                                         /* We have already filled this one.
5159                                          * We have a duplicate that will be discarded, but 
5160                                          * we first have to suck out resize info if it is a file.
5161                                          */
5162
5163                                         if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) && 
5164                                              ((oh && 
5165                                                oh-> type == YAFFS_OBJECT_TYPE_FILE)||
5166                                               (tags.extraHeaderInfoAvailable  &&
5167                                                tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
5168                                             ) {
5169                                                 __u32 thisSize =
5170                                                     (oh) ? oh->fileSize : tags.
5171                                                     extraFileLength;
5172                                                 __u32 parentObjectId =
5173                                                     (oh) ? oh->
5174                                                     parentObjectId : tags.
5175                                                     extraParentObjectId;
5176                                                 unsigned isShrink =
5177                                                     (oh) ? oh->isShrink : tags.
5178                                                     extraIsShrinkHeader;
5179
5180                                                 /* If it is deleted (unlinked at start also means deleted)
5181                                                  * we treat the file size as being zeroed at this point.
5182                                                  */
5183                                                 if (parentObjectId ==
5184                                                     YAFFS_OBJECTID_DELETED
5185                                                     || parentObjectId ==
5186                                                     YAFFS_OBJECTID_UNLINKED) {
5187                                                         thisSize = 0;
5188                                                         isShrink = 1;
5189                                                 }
5190
5191                                                 if (isShrink &&
5192                                                     in->variant.fileVariant.
5193                                                     shrinkSize > thisSize) {
5194                                                         in->variant.fileVariant.
5195                                                             shrinkSize =
5196                                                             thisSize;
5197                                                 }
5198
5199                                                 if (isShrink) {
5200                                                         bi->hasShrinkHeader = 1;
5201                                                 }
5202
5203                                         }
5204                                         /* Use existing - destroy this one. */
5205                                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
5206
5207                                 }
5208
5209                                 if (!in->valid &&
5210                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
5211                                      tags.objectId ==
5212                                      YAFFS_OBJECTID_LOSTNFOUND)) {
5213                                         /* We only load some info, don't fiddle with directory structure */
5214                                         in->valid = 1;
5215                                         
5216                                         if(oh) {
5217                                                 in->variantType = oh->type;
5218
5219                                                 in->yst_mode = oh->yst_mode;
5220 #ifdef CONFIG_YAFFS_WINCE
5221                                                 in->win_atime[0] = oh->win_atime[0];
5222                                                 in->win_ctime[0] = oh->win_ctime[0];
5223                                                 in->win_mtime[0] = oh->win_mtime[0];
5224                                                 in->win_atime[1] = oh->win_atime[1];
5225                                                 in->win_ctime[1] = oh->win_ctime[1];
5226                                                 in->win_mtime[1] = oh->win_mtime[1];
5227 #else
5228                                                 in->yst_uid = oh->yst_uid;
5229                                                 in->yst_gid = oh->yst_gid;
5230                                                 in->yst_atime = oh->yst_atime;
5231                                                 in->yst_mtime = oh->yst_mtime;
5232                                                 in->yst_ctime = oh->yst_ctime;
5233                                                 in->yst_rdev = oh->yst_rdev;
5234                 
5235 #endif
5236                                         } else {
5237                                                 in->variantType = tags.extraObjectType;
5238                                                 in->lazyLoaded = 1;
5239                                         }
5240                                                 
5241                                         in->chunkId = chunk;
5242
5243                                 } else if (!in->valid) {
5244                                         /* we need to load this info */
5245
5246                                         in->valid = 1;
5247                                         in->chunkId = chunk;
5248                                         
5249                                         if(oh) {
5250                                                 in->variantType = oh->type;
5251
5252                                                 in->yst_mode = oh->yst_mode;
5253 #ifdef CONFIG_YAFFS_WINCE
5254                                                 in->win_atime[0] = oh->win_atime[0];
5255                                                 in->win_ctime[0] = oh->win_ctime[0];
5256                                                 in->win_mtime[0] = oh->win_mtime[0];
5257                                                 in->win_atime[1] = oh->win_atime[1];
5258                                                 in->win_ctime[1] = oh->win_ctime[1];
5259                                                 in->win_mtime[1] = oh->win_mtime[1];
5260 #else
5261                                                 in->yst_uid = oh->yst_uid;
5262                                                 in->yst_gid = oh->yst_gid;
5263                                                 in->yst_atime = oh->yst_atime;
5264                                                 in->yst_mtime = oh->yst_mtime;
5265                                                 in->yst_ctime = oh->yst_ctime;
5266                                                 in->yst_rdev = oh->yst_rdev;
5267 #endif
5268
5269                                                 if (oh->shadowsObject > 0) 
5270                                                         yaffs_HandleShadowedObject(dev,
5271                                                                            oh->
5272                                                                            shadowsObject,
5273                                                                            1);
5274                                         
5275
5276                                                 yaffs_SetObjectName(in, oh->name);
5277                                                 parent =
5278                                                     yaffs_FindOrCreateObjectByNumber
5279                                                         (dev, oh->parentObjectId,
5280                                                          YAFFS_OBJECT_TYPE_DIRECTORY);
5281
5282                                                  fileSize = oh->fileSize;
5283                                                  isShrink = oh->isShrink;
5284                                                  equivalentObjectId = oh->equivalentObjectId;
5285
5286                                         }
5287                                         else {
5288                                                 in->variantType = tags.extraObjectType;
5289                                                 parent =
5290                                                     yaffs_FindOrCreateObjectByNumber
5291                                                         (dev, tags.extraParentObjectId,
5292                                                          YAFFS_OBJECT_TYPE_DIRECTORY);
5293                                                  fileSize = tags.extraFileLength;
5294                                                  isShrink = tags.extraIsShrinkHeader;
5295                                                  equivalentObjectId = tags.extraEquivalentObjectId;
5296                                                 in->lazyLoaded = 1;
5297
5298                                         }
5299                                         in->dirty = 0;
5300
5301                                         /* directory stuff...
5302                                          * hook up to parent
5303                                          */
5304
5305                                         if (parent->variantType ==
5306                                             YAFFS_OBJECT_TYPE_UNKNOWN) {
5307                                                 /* Set up as a directory */
5308                                                 parent->variantType =
5309                                                     YAFFS_OBJECT_TYPE_DIRECTORY;
5310                                                 INIT_LIST_HEAD(&parent->variant.
5311                                                                directoryVariant.
5312                                                                children);
5313                                         } else if (parent->variantType !=
5314                                                    YAFFS_OBJECT_TYPE_DIRECTORY)
5315                                         {
5316                                                 /* Hoosterman, another problem....
5317                                                  * We're trying to use a non-directory as a directory
5318                                                  */
5319
5320                                                 T(YAFFS_TRACE_ERROR,
5321                                                   (TSTR
5322                                                    ("yaffs tragedy: attempting to use non-directory as"
5323                                                     " a directory in scan. Put in lost+found."
5324                                                     TENDSTR)));
5325                                                 parent = dev->lostNFoundDir;
5326                                         }
5327
5328                                         yaffs_AddObjectToDirectory(parent, in);
5329
5330                                         itsUnlinked = (parent == dev->deletedDir) ||
5331                                                       (parent == dev->unlinkedDir);
5332
5333                                         if (isShrink) {
5334                                                 /* Mark the block as having a shrinkHeader */
5335                                                 bi->hasShrinkHeader = 1;
5336                                         }
5337
5338                                         /* Note re hardlinks.
5339                                          * Since we might scan a hardlink before its equivalent object is scanned
5340                                          * we put them all in a list.
5341                                          * After scanning is complete, we should have all the objects, so we run
5342                                          * through this list and fix up all the chains.              
5343                                          */
5344
5345                                         switch (in->variantType) {
5346                                         case YAFFS_OBJECT_TYPE_UNKNOWN: 
5347                                                 /* Todo got a problem */
5348                                                 break;
5349                                         case YAFFS_OBJECT_TYPE_FILE:
5350
5351                                                 if (in->variant.fileVariant.
5352                                                     scannedFileSize < fileSize) {
5353                                                         /* This covers the case where the file size is greater
5354                                                          * than where the data is
5355                                                          * This will happen if the file is resized to be larger 
5356                                                          * than its current data extents.
5357                                                          */
5358                                                         in->variant.fileVariant.fileSize = fileSize;
5359                                                         in->variant.fileVariant.scannedFileSize =
5360                                                             in->variant.fileVariant.fileSize;
5361                                                 }
5362
5363                                                 if (isShrink &&
5364                                                     in->variant.fileVariant.shrinkSize > fileSize) {
5365                                                         in->variant.fileVariant.shrinkSize = fileSize;
5366                                                 }
5367
5368                                                 break;
5369                                         case YAFFS_OBJECT_TYPE_HARDLINK:
5370                                                 if(!itsUnlinked) {
5371                                                   in->variant.hardLinkVariant.equivalentObjectId =
5372                                                     equivalentObjectId;
5373                                                   in->hardLinks.next =
5374                                                     (struct list_head *) hardList;
5375                                                   hardList = in;
5376                                                 }
5377                                                 break;
5378                                         case YAFFS_OBJECT_TYPE_DIRECTORY:
5379                                                 /* Do nothing */
5380                                                 break;
5381                                         case YAFFS_OBJECT_TYPE_SPECIAL:
5382                                                 /* Do nothing */
5383                                                 break;
5384                                         case YAFFS_OBJECT_TYPE_SYMLINK:
5385                                                 if(oh)
5386                                                    in->variant.symLinkVariant.alias =
5387                                                     yaffs_CloneString(oh->
5388                                                                       alias);
5389                                                 break;
5390                                         }
5391
5392                                 }
5393                         }
5394                 }
5395
5396                 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5397                         /* If we got this far while scanning, then the block is fully allocated. */
5398                         state = YAFFS_BLOCK_STATE_FULL;
5399                 }
5400
5401                 bi->blockState = state;
5402
5403                 /* Now let's see if it was dirty */
5404                 if (bi->pagesInUse == 0 &&
5405                     !bi->hasShrinkHeader &&
5406                     bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5407                         yaffs_BlockBecameDirty(dev, blk);
5408                 }
5409
5410         }
5411
5412         if (blockIndex) {
5413                 YFREE(blockIndex);
5414         }
5415         /* Ok, we've done all the scanning.
5416          * Fix up the hard link chains.
5417          * We should now have scanned all the objects, now it's time to add these 
5418          * hardlinks.
5419          */
5420         yaffs_HardlinkFixup(dev,hardList);
5421         
5422         
5423         /*
5424         *  Sort out state of unlinked and deleted objects.
5425         */
5426         {
5427                 struct list_head *i;
5428                 struct list_head *n;
5429
5430                 yaffs_Object *l;
5431
5432                 /* Soft delete all the unlinked files */
5433                 list_for_each_safe(i, n,
5434                                    &dev->unlinkedDir->variant.directoryVariant.
5435                                    children) {
5436                         if (i) {
5437                                 l = list_entry(i, yaffs_Object, siblings);
5438                                 yaffs_DestroyObject(l);
5439                         }
5440                 }
5441
5442                 /* Soft delete all the deletedDir files */
5443                 list_for_each_safe(i, n,
5444                                    &dev->deletedDir->variant.directoryVariant.
5445                                    children) {
5446                         if (i) {
5447                                 l = list_entry(i, yaffs_Object, siblings);
5448                                 yaffs_DestroyObject(l);
5449
5450                         }
5451                 }
5452         }
5453
5454         yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5455
5456         T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
5457
5458         return YAFFS_OK;
5459 }
5460
5461 /*------------------------------  Directory Functions ----------------------------- */
5462
5463 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
5464 {
5465         yaffs_Device *dev = obj->myDev;
5466         
5467         if(dev && dev->removeObjectCallback)
5468                 dev->removeObjectCallback(obj);
5469            
5470         list_del_init(&obj->siblings);
5471         obj->parent = NULL;
5472 }
5473
5474
5475 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
5476                                        yaffs_Object * obj)
5477 {
5478
5479         if (!directory) {
5480                 T(YAFFS_TRACE_ALWAYS,
5481                   (TSTR
5482                    ("tragedy: Trying to add an object to a null pointer directory"
5483                     TENDSTR)));
5484                 YBUG();
5485         }
5486         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5487                 T(YAFFS_TRACE_ALWAYS,
5488                   (TSTR
5489                    ("tragedy: Trying to add an object to a non-directory"
5490                     TENDSTR)));
5491                 YBUG();
5492         }
5493
5494         if (obj->siblings.prev == NULL) {
5495                 /* Not initialised */
5496                 INIT_LIST_HEAD(&obj->siblings);
5497
5498         } else if (!list_empty(&obj->siblings)) {
5499                 /* If it is holed up somewhere else, un hook it */
5500                 yaffs_RemoveObjectFromDirectory(obj);
5501         }
5502         /* Now add it */
5503         list_add(&obj->siblings, &directory->variant.directoryVariant.children);
5504         obj->parent = directory;
5505
5506         if (directory == obj->myDev->unlinkedDir
5507             || directory == obj->myDev->deletedDir) {
5508                 obj->unlinked = 1;
5509                 obj->myDev->nUnlinkedFiles++;
5510                 obj->renameAllowed = 0;
5511         }
5512 }
5513
5514 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
5515                                      const YCHAR * name)
5516 {
5517         int sum;
5518
5519         struct list_head *i;
5520         YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
5521
5522         yaffs_Object *l;
5523
5524         if (!name) {
5525                 return NULL;
5526         }
5527
5528         if (!directory) {
5529                 T(YAFFS_TRACE_ALWAYS,
5530                   (TSTR
5531                    ("tragedy: yaffs_FindObjectByName: null pointer directory"
5532                     TENDSTR)));
5533                 YBUG();
5534         }
5535         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5536                 T(YAFFS_TRACE_ALWAYS,
5537                   (TSTR
5538                    ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5539                 YBUG();
5540         }
5541
5542         sum = yaffs_CalcNameSum(name);
5543
5544         list_for_each(i, &directory->variant.directoryVariant.children) {
5545                 if (i) {
5546                         l = list_entry(i, yaffs_Object, siblings);
5547                         
5548                         yaffs_CheckObjectDetailsLoaded(l);
5549
5550                         /* Special case for lost-n-found */
5551                         if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5552                                 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
5553                                         return l;
5554                                 }
5555                         } else if (yaffs_SumCompare(l->sum, sum) || l->chunkId <= 0)    
5556                         {
5557                                 /* LostnFound cunk called Objxxx
5558                                  * Do a real check
5559                                  */
5560                                 yaffs_GetObjectName(l, buffer,
5561                                                     YAFFS_MAX_NAME_LENGTH);
5562                                 if (yaffs_strcmp(name, buffer) == 0) {
5563                                         return l;
5564                                 }
5565
5566                         }
5567                 }
5568         }
5569
5570         return NULL;
5571 }
5572
5573
5574 #if 0
5575 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
5576                                    int (*fn) (yaffs_Object *))
5577 {
5578         struct list_head *i;
5579         yaffs_Object *l;
5580
5581         if (!theDir) {
5582                 T(YAFFS_TRACE_ALWAYS,
5583                   (TSTR
5584                    ("tragedy: yaffs_FindObjectByName: null pointer directory"
5585                     TENDSTR)));
5586                 YBUG();
5587         }
5588         if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5589                 T(YAFFS_TRACE_ALWAYS,
5590                   (TSTR
5591                    ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5592                 YBUG();
5593         }
5594
5595         list_for_each(i, &theDir->variant.directoryVariant.children) {
5596                 if (i) {
5597                         l = list_entry(i, yaffs_Object, siblings);
5598                         if (l && !fn(l)) {
5599                                 return YAFFS_FAIL;
5600                         }
5601                 }
5602         }
5603
5604         return YAFFS_OK;
5605
5606 }
5607 #endif
5608
5609 /* GetEquivalentObject dereferences any hard links to get to the
5610  * actual object.
5611  */
5612
5613 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
5614 {
5615         if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5616                 /* We want the object id of the equivalent object, not this one */
5617                 obj = obj->variant.hardLinkVariant.equivalentObject;
5618         }
5619         return obj;
5620
5621 }
5622
5623 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
5624 {
5625         memset(name, 0, buffSize * sizeof(YCHAR));
5626         
5627         yaffs_CheckObjectDetailsLoaded(obj);
5628
5629         if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5630                 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
5631         } else if (obj->chunkId <= 0) {
5632                 YCHAR locName[20];
5633                 /* make up a name */
5634                 yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX,
5635                               obj->objectId);
5636                 yaffs_strncpy(name, locName, buffSize - 1);
5637
5638         }
5639 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
5640         else if (obj->shortName[0]) {
5641                 yaffs_strcpy(name, obj->shortName);
5642         }
5643 #endif
5644         else {
5645                 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
5646
5647                 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
5648
5649                 memset(buffer, 0, obj->myDev->nBytesPerChunk);
5650
5651                 if (obj->chunkId >= 0) {
5652                         yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
5653                                                         obj->chunkId, buffer,
5654                                                         NULL);
5655                 }
5656                 yaffs_strncpy(name, oh->name, buffSize - 1);
5657
5658                 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
5659         }
5660
5661         return yaffs_strlen(name);
5662 }
5663
5664 int yaffs_GetObjectFileLength(yaffs_Object * obj)
5665 {
5666
5667         /* Dereference any hard linking */
5668         obj = yaffs_GetEquivalentObject(obj);
5669
5670         if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
5671                 return obj->variant.fileVariant.fileSize;
5672         }
5673         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
5674                 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5675         } else {
5676                 /* Only a directory should drop through to here */
5677                 return obj->myDev->nBytesPerChunk;
5678         }
5679 }
5680
5681 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
5682 {
5683         int count = 0;
5684         struct list_head *i;
5685
5686         if (!obj->unlinked) {
5687                 count++;        /* the object itself */
5688         }
5689         list_for_each(i, &obj->hardLinks) {
5690                 count++;        /* add the hard links; */
5691         }
5692         return count;
5693
5694 }
5695
5696 int yaffs_GetObjectInode(yaffs_Object * obj)
5697 {
5698         obj = yaffs_GetEquivalentObject(obj);
5699
5700         return obj->objectId;
5701 }
5702
5703 unsigned yaffs_GetObjectType(yaffs_Object * obj)
5704 {
5705         obj = yaffs_GetEquivalentObject(obj);
5706
5707         switch (obj->variantType) {
5708         case YAFFS_OBJECT_TYPE_FILE:
5709                 return DT_REG;
5710                 break;
5711         case YAFFS_OBJECT_TYPE_DIRECTORY:
5712                 return DT_DIR;
5713                 break;
5714         case YAFFS_OBJECT_TYPE_SYMLINK:
5715                 return DT_LNK;
5716                 break;
5717         case YAFFS_OBJECT_TYPE_HARDLINK:
5718                 return DT_REG;
5719                 break;
5720         case YAFFS_OBJECT_TYPE_SPECIAL:
5721                 if (S_ISFIFO(obj->yst_mode))
5722                         return DT_FIFO;
5723                 if (S_ISCHR(obj->yst_mode))
5724                         return DT_CHR;
5725                 if (S_ISBLK(obj->yst_mode))
5726                         return DT_BLK;
5727                 if (S_ISSOCK(obj->yst_mode))
5728                         return DT_SOCK;
5729         default:
5730                 return DT_REG;
5731                 break;
5732         }
5733 }
5734
5735 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
5736 {
5737         obj = yaffs_GetEquivalentObject(obj);
5738         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
5739                 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
5740         } else {
5741                 return yaffs_CloneString(_Y(""));
5742         }
5743 }
5744
5745 #ifndef CONFIG_YAFFS_WINCE
5746
5747 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
5748 {
5749         unsigned int valid = attr->ia_valid;
5750
5751         if (valid & ATTR_MODE)
5752                 obj->yst_mode = attr->ia_mode;
5753         if (valid & ATTR_UID)
5754                 obj->yst_uid = attr->ia_uid;
5755         if (valid & ATTR_GID)
5756                 obj->yst_gid = attr->ia_gid;
5757
5758         if (valid & ATTR_ATIME)
5759                 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
5760         if (valid & ATTR_CTIME)
5761                 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
5762         if (valid & ATTR_MTIME)
5763                 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
5764
5765         if (valid & ATTR_SIZE)
5766                 yaffs_ResizeFile(obj, attr->ia_size);
5767
5768         yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
5769
5770         return YAFFS_OK;
5771
5772 }
5773 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
5774 {
5775         unsigned int valid = 0;
5776
5777         attr->ia_mode = obj->yst_mode;
5778         valid |= ATTR_MODE;
5779         attr->ia_uid = obj->yst_uid;
5780         valid |= ATTR_UID;
5781         attr->ia_gid = obj->yst_gid;
5782         valid |= ATTR_GID;
5783
5784         Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
5785         valid |= ATTR_ATIME;
5786         Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
5787         valid |= ATTR_CTIME;
5788         Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
5789         valid |= ATTR_MTIME;
5790
5791         attr->ia_size = yaffs_GetFileSize(obj);
5792         valid |= ATTR_SIZE;
5793
5794         attr->ia_valid = valid;
5795
5796         return YAFFS_OK;
5797
5798 }
5799
5800 #endif
5801
5802 #if 0
5803 int yaffs_DumpObject(yaffs_Object * obj)
5804 {
5805         YCHAR name[257];
5806
5807         yaffs_GetObjectName(obj, name, 256);
5808
5809         T(YAFFS_TRACE_ALWAYS,
5810           (TSTR
5811            ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
5812             " chunk %d type %d size %d\n"
5813             TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
5814            obj->dirty, obj->valid, obj->serial, obj->sum, obj->chunkId,
5815            yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
5816
5817         return YAFFS_OK;
5818 }
5819 #endif
5820
5821 /*---------------------------- Initialisation code -------------------------------------- */
5822
5823 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
5824 {
5825
5826         /* Common functions, gotta have */
5827         if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
5828                 return 0;
5829
5830 #ifdef CONFIG_YAFFS_YAFFS2
5831
5832         /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
5833         if (dev->writeChunkWithTagsToNAND &&
5834             dev->readChunkWithTagsFromNAND &&
5835             !dev->writeChunkToNAND &&
5836             !dev->readChunkFromNAND &&
5837             dev->markNANDBlockBad && dev->queryNANDBlock)
5838                 return 1;
5839 #endif
5840
5841         /* Can use the "spare" style interface for yaffs1 */
5842         if (!dev->isYaffs2 &&
5843             !dev->writeChunkWithTagsToNAND &&
5844             !dev->readChunkWithTagsFromNAND &&
5845             dev->writeChunkToNAND &&
5846             dev->readChunkFromNAND &&
5847             !dev->markNANDBlockBad && !dev->queryNANDBlock)
5848                 return 1;
5849
5850         return 0;               /* bad */
5851 }
5852
5853
5854 static void yaffs_CreateInitialDirectories(yaffs_Device *dev)
5855 {
5856         /* Initialise the unlinked, deleted, root and lost and found directories */
5857         
5858         dev->lostNFoundDir = dev->rootDir =  NULL;
5859         dev->unlinkedDir = dev->deletedDir = NULL;
5860
5861         dev->unlinkedDir =
5862             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
5863         dev->deletedDir =
5864             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
5865
5866         dev->rootDir =
5867             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
5868                                       YAFFS_ROOT_MODE | S_IFDIR);
5869         dev->lostNFoundDir =
5870             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
5871                                       YAFFS_LOSTNFOUND_MODE | S_IFDIR);
5872         yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
5873 }
5874
5875 int yaffs_GutsInitialise(yaffs_Device * dev)
5876 {
5877         unsigned x;
5878         int bits;
5879         int extraBits;
5880
5881         T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
5882
5883         /* Check stuff that must be set */
5884
5885         if (!dev) {
5886                 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
5887                 return YAFFS_FAIL;
5888         }
5889
5890         dev->internalStartBlock = dev->startBlock;
5891         dev->internalEndBlock = dev->endBlock;
5892         dev->blockOffset = 0;
5893         dev->chunkOffset = 0;
5894         dev->nFreeChunks = 0;
5895
5896         if (dev->startBlock == 0) {
5897                 dev->internalStartBlock = dev->startBlock + 1;
5898                 dev->internalEndBlock = dev->endBlock + 1;
5899                 dev->blockOffset = 1;
5900                 dev->chunkOffset = dev->nChunksPerBlock;
5901         }
5902
5903         /* Check geometry parameters. */
5904
5905         if ((dev->isYaffs2 && dev->nBytesPerChunk < 1024) || 
5906             (!dev->isYaffs2 && dev->nBytesPerChunk != 512) || 
5907              dev->nChunksPerBlock < 2 || 
5908              dev->nReservedBlocks < 2 || 
5909              dev->internalStartBlock <= 0 || 
5910              dev->internalEndBlock <= 0 || 
5911              dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2)      // otherwise it is too small
5912             ) {
5913                 T(YAFFS_TRACE_ALWAYS,
5914                   (TSTR
5915                    ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s "
5916                     TENDSTR), dev->nBytesPerChunk, dev->isYaffs2 ? "2" : ""));
5917                 return YAFFS_FAIL;
5918         }
5919
5920         if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
5921                 T(YAFFS_TRACE_ALWAYS,
5922                   (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
5923                 return YAFFS_FAIL;
5924         }
5925
5926         /* Got the right mix of functions? */
5927         if (!yaffs_CheckDevFunctions(dev)) {
5928                 /* Function missing */
5929                 T(YAFFS_TRACE_ALWAYS,
5930                   (TSTR
5931                    ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
5932
5933                 return YAFFS_FAIL;
5934         }
5935
5936         /* This is really a compilation check. */
5937         if (!yaffs_CheckStructures()) {
5938                 T(YAFFS_TRACE_ALWAYS,
5939                   (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
5940                 return YAFFS_FAIL;
5941         }
5942
5943         if (dev->isMounted) {
5944                 T(YAFFS_TRACE_ALWAYS,
5945                   (TSTR("yaffs: device already mounted\n" TENDSTR)));
5946                 return YAFFS_FAIL;
5947         }
5948
5949         /* Finished with most checks. One or two more checks happen later on too. */
5950
5951         dev->isMounted = 1;
5952
5953
5954
5955         /* OK now calculate a few things for the device
5956          * Calculate chunkGroupBits.
5957          * We need to find the next power of 2 > than internalEndBlock
5958          */
5959
5960         x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
5961
5962         for (bits = extraBits = 0; x > 1; bits++) {
5963                 if (x & 1)
5964                         extraBits++;
5965                 x >>= 1;
5966         }
5967
5968         if (extraBits > 0)
5969                 bits++;
5970         
5971         /* Set up tnode width if wide tnodes are enabled. */
5972         if(!dev->wideTnodesDisabled){
5973                 /* bits must be even so that we end up with 32-bit words */
5974                 if(bits & 1)
5975                         bits++;
5976                 if(bits < 16)
5977                         dev->tnodeWidth = 16;
5978                 else
5979                         dev->tnodeWidth = bits;
5980         }
5981         else
5982                 dev->tnodeWidth = 16;
5983  
5984         dev->tnodeMask = (1<<dev->tnodeWidth)-1;
5985                 
5986         /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
5987          * so if the bitwidth of the
5988          * chunk range we're using is greater than 16 we need
5989          * to figure out chunk shift and chunkGroupSize
5990          */
5991                  
5992         if (bits <= dev->tnodeWidth)
5993                 dev->chunkGroupBits = 0;
5994         else
5995                 dev->chunkGroupBits = bits - dev->tnodeWidth;
5996                 
5997
5998         dev->chunkGroupSize = 1 << dev->chunkGroupBits;
5999
6000         if (dev->nChunksPerBlock < dev->chunkGroupSize) {
6001                 /* We have a problem because the soft delete won't work if
6002                  * the chunk group size > chunks per block.
6003                  * This can be remedied by using larger "virtual blocks".
6004                  */
6005                 T(YAFFS_TRACE_ALWAYS,
6006                   (TSTR("yaffs: chunk group too large\n" TENDSTR)));
6007
6008                 return YAFFS_FAIL;
6009         }
6010
6011         /* OK, we've finished verifying the device, lets continue with initialisation */
6012
6013         /* More device initialisation */
6014         dev->garbageCollections = 0;
6015         dev->passiveGarbageCollections = 0;
6016         dev->currentDirtyChecker = 0;
6017         dev->bufferedBlock = -1;
6018         dev->doingBufferedBlockRewrite = 0;
6019         dev->nDeletedFiles = 0;
6020         dev->nBackgroundDeletions = 0;
6021         dev->nUnlinkedFiles = 0;
6022         dev->eccFixed = 0;
6023         dev->eccUnfixed = 0;
6024         dev->tagsEccFixed = 0;
6025         dev->tagsEccUnfixed = 0;
6026         dev->nErasureFailures = 0;
6027         dev->nErasedBlocks = 0;
6028         dev->isDoingGC = 0;
6029
6030         /* Initialise temporary buffers and caches. */
6031         {
6032                 int i;
6033                 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
6034                         dev->tempBuffer[i].line = 0;    /* not in use */
6035                         dev->tempBuffer[i].buffer =
6036                             YMALLOC(dev->nBytesPerChunk);
6037                 }
6038         }
6039         
6040         if (dev->nShortOpCaches > 0) {
6041                 int i;
6042
6043                 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
6044                         dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
6045                 }
6046
6047                 dev->srCache =
6048                     YMALLOC(dev->nShortOpCaches * sizeof(yaffs_ChunkCache));
6049
6050                 for (i = 0; i < dev->nShortOpCaches; i++) {
6051                         dev->srCache[i].object = NULL;
6052                         dev->srCache[i].lastUse = 0;
6053                         dev->srCache[i].dirty = 0;
6054                         dev->srCache[i].data = YMALLOC(dev->nBytesPerChunk);
6055                 }
6056                 dev->srLastUse = 0;
6057         }
6058
6059         dev->cacheHits = 0;
6060         
6061         dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
6062
6063         if (dev->isYaffs2) {
6064                 dev->useHeaderFileSize = 1;
6065         }
6066
6067         yaffs_InitialiseBlocks(dev);
6068         yaffs_InitialiseTnodes(dev);
6069         yaffs_InitialiseObjects(dev);
6070
6071         yaffs_CreateInitialDirectories(dev);
6072
6073
6074         /* Now scan the flash. */
6075         if (dev->isYaffs2) {
6076                 if(yaffs_CheckpointRestore(dev)) {
6077                         T(YAFFS_TRACE_ALWAYS,
6078                           (TSTR("yaffs: restored from checkpoint" TENDSTR)));
6079                 } else {
6080
6081                         /* Clean up the mess caused by an aborted checkpoint load 
6082                          * and scan backwards. 
6083                          */
6084                         yaffs_DeinitialiseBlocks(dev);
6085                         yaffs_DeinitialiseTnodes(dev);
6086                         yaffs_DeinitialiseObjects(dev);
6087                         yaffs_InitialiseBlocks(dev);
6088                         yaffs_InitialiseTnodes(dev);
6089                         yaffs_InitialiseObjects(dev);
6090                         yaffs_CreateInitialDirectories(dev);
6091
6092                         yaffs_ScanBackwards(dev);
6093                 }
6094         }else
6095                 yaffs_Scan(dev);
6096
6097         /* Zero out stats */
6098         dev->nPageReads = 0;
6099         dev->nPageWrites = 0;
6100         dev->nBlockErasures = 0;
6101         dev->nGCCopies = 0;
6102         dev->nRetriedWrites = 0;
6103
6104         dev->nRetiredBlocks = 0;
6105
6106         yaffs_VerifyFreeChunks(dev);
6107
6108         T(YAFFS_TRACE_TRACING,
6109           (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
6110         return YAFFS_OK;
6111
6112 }
6113
6114 void yaffs_Deinitialise(yaffs_Device * dev)
6115 {
6116         if (dev->isMounted) {
6117                 int i;
6118
6119                 yaffs_DeinitialiseBlocks(dev);
6120                 yaffs_DeinitialiseTnodes(dev);
6121                 yaffs_DeinitialiseObjects(dev);
6122                 if (dev->nShortOpCaches > 0) {
6123
6124                         for (i = 0; i < dev->nShortOpCaches; i++) {
6125                                 YFREE(dev->srCache[i].data);
6126                         }
6127
6128                         YFREE(dev->srCache);
6129                 }
6130
6131                 YFREE(dev->gcCleanupList);
6132
6133                 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
6134                         YFREE(dev->tempBuffer[i].buffer);
6135                 }
6136
6137                 dev->isMounted = 0;
6138         }
6139
6140 }
6141
6142 static int yaffs_CountFreeChunks(yaffs_Device * dev)
6143 {
6144         int nFree;
6145         int b;
6146
6147         yaffs_BlockInfo *blk;
6148
6149         for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
6150              b++) {
6151                 blk = yaffs_GetBlockInfo(dev, b);
6152
6153                 switch (blk->blockState) {
6154                 case YAFFS_BLOCK_STATE_EMPTY:
6155                 case YAFFS_BLOCK_STATE_ALLOCATING:
6156                 case YAFFS_BLOCK_STATE_COLLECTING:
6157                 case YAFFS_BLOCK_STATE_FULL:
6158                         nFree +=
6159                             (dev->nChunksPerBlock - blk->pagesInUse +
6160                              blk->softDeletions);
6161                         break;
6162                 default:
6163                         break;
6164                 }
6165
6166         }
6167
6168         return nFree;
6169 }
6170
6171 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
6172 {
6173         /* This is what we report to the outside world */
6174
6175         int nFree;
6176         int nDirtyCacheChunks;
6177
6178 #if 1
6179         nFree = dev->nFreeChunks;
6180 #else
6181         nFree = yaffs_CountFreeChunks(dev);
6182 #endif
6183
6184         nFree += dev->nDeletedFiles;
6185         
6186         /* Now count the number of dirty chunks in the cache and subtract those */
6187
6188         {
6189                 int i;
6190                 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
6191                         if (dev->srCache[i].dirty)
6192                                 nDirtyCacheChunks++;
6193                 }
6194         }
6195
6196         nFree -= nDirtyCacheChunks;
6197
6198         nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
6199
6200         if (nFree < 0)
6201                 nFree = 0;
6202
6203         return nFree;
6204
6205 }
6206
6207 static int yaffs_freeVerificationFailures;
6208
6209 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
6210 {
6211         int counted = yaffs_CountFreeChunks(dev);
6212
6213         int difference = dev->nFreeChunks - counted;
6214
6215         if (difference) {
6216                 T(YAFFS_TRACE_ALWAYS,
6217                   (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
6218                    dev->nFreeChunks, counted, difference));
6219                 yaffs_freeVerificationFailures++;
6220         }
6221 }
6222
6223 /*---------------------------------------- YAFFS test code ----------------------*/
6224
6225 #define yaffs_CheckStruct(structure,syze, name) \
6226            if(sizeof(structure) != syze) \
6227                { \
6228                  T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
6229                  name,syze,sizeof(structure))); \
6230                  return YAFFS_FAIL; \
6231                 }
6232
6233 static int yaffs_CheckStructures(void)
6234 {
6235 /*      yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags") */
6236 /*      yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion") */
6237 /*      yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare") */
6238 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
6239         yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode")
6240 #endif
6241             yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader")
6242
6243             return YAFFS_OK;
6244 }