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