94ed16c4d4ba7741fc533dee8a06a72285a6439c
[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.35 2006-06-05 04:10:49 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                         T(YAFFS_TRACE_CHECKPOINT,(TSTR("Read object %d parent %d type %d" TENDSTR),
3572                                 cp.objectId,cp.parentId,cp.variantType));
3573                         obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
3574                         if(obj) {
3575                                 yaffs_CheckpointObjectToObject(obj,&cp);
3576                                 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
3577                                         ok = yaffs_ReadCheckpointTnodes(obj);
3578                                 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
3579                                         obj->hardLinks.next =
3580                                                     (struct list_head *)
3581                                                     hardList;
3582                                         hardList = obj;
3583                                 }
3584                            
3585                         }
3586                 }
3587         }
3588         
3589         if(ok)
3590                 yaffs_HardlinkFixup(dev,hardList);
3591         
3592         return ok ? 1 : 0;
3593 }
3594
3595 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
3596 {
3597
3598         int ok;
3599         
3600         ok = yaffs_CheckpointOpen(dev,1);
3601         
3602         if(ok)
3603                 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
3604         if(ok)
3605                 ok = yaffs_WriteCheckpointDevice(dev);
3606         if(ok)
3607                 ok = yaffs_WriteCheckpointObjects(dev);
3608         if(ok)
3609                 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
3610                 
3611         if(!yaffs_CheckpointClose(dev))
3612                  ok = 0;
3613                  
3614         if(ok)
3615                 dev->isCheckpointed = 1;
3616          else 
3617                 dev->isCheckpointed = 0;
3618
3619         return dev->isCheckpointed;
3620 }
3621
3622 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
3623 {
3624         int ok;
3625         
3626         ok = yaffs_CheckpointOpen(dev,0); /* open for read */
3627         
3628         if(ok)
3629                 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
3630         if(ok)
3631                 ok = yaffs_ReadCheckpointDevice(dev);
3632         if(ok)
3633                 ok = yaffs_ReadCheckpointObjects(dev);
3634         if(ok)
3635                 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
3636                 
3637
3638
3639         if(!yaffs_CheckpointClose(dev))
3640                 ok = 0;
3641
3642         if(ok)
3643                 dev->isCheckpointed = 1;
3644          else 
3645                 dev->isCheckpointed = 0;
3646
3647         return ok ? 1 : 0;
3648
3649 }
3650
3651 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
3652 {
3653         if(dev->isCheckpointed || 
3654            dev->blocksInCheckpoint > 0){
3655                 dev->isCheckpointed = 0;
3656                 yaffs_CheckpointInvalidateStream(dev);
3657                 if(dev->superBlock && dev->markSuperBlockDirty)
3658                         dev->markSuperBlockDirty(dev->superBlock);
3659         }
3660 }
3661
3662
3663 int yaffs_CheckpointSave(yaffs_Device *dev)
3664 {
3665         T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3666
3667         if(!dev->isCheckpointed)
3668                 yaffs_WriteCheckpointData(dev);
3669         
3670         T(YAFFS_TRACE_CHECKPOINT,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3671
3672         return dev->isCheckpointed;
3673 }
3674
3675 int yaffs_CheckpointRestore(yaffs_Device *dev)
3676 {
3677         int retval;
3678         T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3679         
3680         retval = yaffs_ReadCheckpointData(dev);
3681
3682         T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
3683         
3684         return retval;
3685 }
3686
3687 /*--------------------- File read/write ------------------------
3688  * Read and write have very similar structures.
3689  * In general the read/write has three parts to it
3690  * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3691  * Some complete chunks
3692  * An incomplete chunk to end off with
3693  *
3694  * Curve-balls: the first chunk might also be the last chunk.
3695  */
3696
3697 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, __u32 offset,
3698                            int nBytes)
3699 {
3700
3701         int chunk;
3702         int start;
3703         int nToCopy;
3704         int n = nBytes;
3705         int nDone = 0;
3706         yaffs_ChunkCache *cache;
3707
3708         yaffs_Device *dev;
3709
3710         dev = in->myDev;
3711
3712         while (n > 0) {
3713                 chunk = offset / dev->nBytesPerChunk + 1;   /* The first chunk is 1 */
3714                 start = offset % dev->nBytesPerChunk;
3715
3716                 /* OK now check for the curveball where the start and end are in
3717                  * the same chunk.      
3718                  */
3719                 if ((start + n) < dev->nBytesPerChunk) {
3720                         nToCopy = n;
3721                 } else {
3722                         nToCopy = dev->nBytesPerChunk - start;
3723                 }
3724
3725                 cache = yaffs_FindChunkCache(in, chunk);
3726
3727                 /* If the chunk is already in the cache or it is less than a whole chunk
3728                  * then use the cache (if there is caching)
3729                  * else bypass the cache.
3730                  */
3731                 if (cache || nToCopy != dev->nBytesPerChunk) {
3732                         if (dev->nShortOpCaches > 0) {
3733
3734                                 /* If we can't find the data in the cache, then load it up. */
3735
3736                                 if (!cache) {
3737                                         cache = yaffs_GrabChunkCache(in->myDev);
3738                                         cache->object = in;
3739                                         cache->chunkId = chunk;
3740                                         cache->dirty = 0;
3741                                         cache->locked = 0;
3742                                         yaffs_ReadChunkDataFromObject(in, chunk,
3743                                                                       cache->
3744                                                                       data);
3745                                         cache->nBytes = 0;
3746                                 }
3747
3748                                 yaffs_UseChunkCache(dev, cache, 0);
3749
3750                                 cache->locked = 1;
3751
3752 #ifdef CONFIG_YAFFS_WINCE
3753                                 yfsd_UnlockYAFFS(TRUE);
3754 #endif
3755                                 memcpy(buffer, &cache->data[start], nToCopy);
3756
3757 #ifdef CONFIG_YAFFS_WINCE
3758                                 yfsd_LockYAFFS(TRUE);
3759 #endif
3760                                 cache->locked = 0;
3761                         } else {
3762                                 /* Read into the local buffer then copy..*/
3763
3764                                 __u8 *localBuffer =
3765                                     yaffs_GetTempBuffer(dev, __LINE__);
3766                                 yaffs_ReadChunkDataFromObject(in, chunk,
3767                                                               localBuffer);
3768 #ifdef CONFIG_YAFFS_WINCE
3769                                 yfsd_UnlockYAFFS(TRUE);
3770 #endif
3771                                 memcpy(buffer, &localBuffer[start], nToCopy);
3772
3773 #ifdef CONFIG_YAFFS_WINCE
3774                                 yfsd_LockYAFFS(TRUE);
3775 #endif
3776                                 yaffs_ReleaseTempBuffer(dev, localBuffer,
3777                                                         __LINE__);
3778                         }
3779
3780                 } else {
3781 #ifdef CONFIG_YAFFS_WINCE
3782                         __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3783
3784                         /* Under WinCE can't do direct transfer. Need to use a local buffer.
3785                          * This is because we otherwise screw up WinCE's memory mapper
3786                          */
3787                         yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
3788
3789 #ifdef CONFIG_YAFFS_WINCE
3790                         yfsd_UnlockYAFFS(TRUE);
3791 #endif
3792                         memcpy(buffer, localBuffer, dev->nBytesPerChunk);
3793
3794 #ifdef CONFIG_YAFFS_WINCE
3795                         yfsd_LockYAFFS(TRUE);
3796                         yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3797 #endif
3798
3799 #else
3800                         /* A full chunk. Read directly into the supplied buffer. */
3801                         yaffs_ReadChunkDataFromObject(in, chunk, buffer);
3802 #endif
3803                 }
3804
3805                 n -= nToCopy;
3806                 offset += nToCopy;
3807                 buffer += nToCopy;
3808                 nDone += nToCopy;
3809
3810         }
3811
3812         return nDone;
3813 }
3814
3815 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, __u32 offset,
3816                           int nBytes, int writeThrough)
3817 {
3818
3819         int chunk;
3820         int start;
3821         int nToCopy;
3822         int n = nBytes;
3823         int nDone = 0;
3824         int nToWriteBack;
3825         int startOfWrite = offset;
3826         int chunkWritten = 0;
3827         int nBytesRead;
3828
3829         yaffs_Device *dev;
3830
3831         dev = in->myDev;
3832
3833         while (n > 0 && chunkWritten >= 0) {
3834                 chunk = offset / dev->nBytesPerChunk + 1;
3835                 start = offset % dev->nBytesPerChunk;
3836
3837                 /* OK now check for the curveball where the start and end are in
3838                  * the same chunk.
3839                  */
3840
3841                 if ((start + n) < dev->nBytesPerChunk) {
3842                         nToCopy = n;
3843
3844                         /* Now folks, to calculate how many bytes to write back....
3845                          * If we're overwriting and not writing to then end of file then
3846                          * we need to write back as much as was there before.
3847                          */
3848
3849                         nBytesRead =
3850                             in->variant.fileVariant.fileSize -
3851                             ((chunk - 1) * dev->nBytesPerChunk);
3852
3853                         if (nBytesRead > dev->nBytesPerChunk) {
3854                                 nBytesRead = dev->nBytesPerChunk;
3855                         }
3856
3857                         nToWriteBack =
3858                             (nBytesRead >
3859                              (start + n)) ? nBytesRead : (start + n);
3860
3861                 } else {
3862                         nToCopy = dev->nBytesPerChunk - start;
3863                         nToWriteBack = dev->nBytesPerChunk;
3864                 }
3865
3866                 if (nToCopy != dev->nBytesPerChunk) {
3867                         /* An incomplete start or end chunk (or maybe both start and end chunk) */
3868                         if (dev->nShortOpCaches > 0) {
3869                                 yaffs_ChunkCache *cache;
3870                                 /* If we can't find the data in the cache, then load the cache */
3871                                 cache = yaffs_FindChunkCache(in, chunk);
3872                                 
3873                                 if (!cache
3874                                     && yaffs_CheckSpaceForAllocation(in->
3875                                                                      myDev)) {
3876                                         cache = yaffs_GrabChunkCache(in->myDev);
3877                                         cache->object = in;
3878                                         cache->chunkId = chunk;
3879                                         cache->dirty = 0;
3880                                         cache->locked = 0;
3881                                         yaffs_ReadChunkDataFromObject(in, chunk,
3882                                                                       cache->
3883                                                                       data);
3884                                 }
3885                                 else if(cache && 
3886                                         !cache->dirty &&
3887                                         !yaffs_CheckSpaceForAllocation(in->myDev)){
3888                                         /* Drop the cache if it was a read cache item and
3889                                          * no space check has been made for it.
3890                                          */ 
3891                                          cache = NULL;
3892                                 }
3893
3894                                 if (cache) {
3895                                         yaffs_UseChunkCache(dev, cache, 1);
3896                                         cache->locked = 1;
3897 #ifdef CONFIG_YAFFS_WINCE
3898                                         yfsd_UnlockYAFFS(TRUE);
3899 #endif
3900
3901                                         memcpy(&cache->data[start], buffer,
3902                                                nToCopy);
3903
3904 #ifdef CONFIG_YAFFS_WINCE
3905                                         yfsd_LockYAFFS(TRUE);
3906 #endif
3907                                         cache->locked = 0;
3908                                         cache->nBytes = nToWriteBack;
3909
3910                                         if (writeThrough) {
3911                                                 chunkWritten =
3912                                                     yaffs_WriteChunkDataToObject
3913                                                     (cache->object,
3914                                                      cache->chunkId,
3915                                                      cache->data, cache->nBytes,
3916                                                      1);
3917                                                 cache->dirty = 0;
3918                                         }
3919
3920                                 } else {
3921                                         chunkWritten = -1;      /* fail the write */
3922                                 }
3923                         } else {
3924                                 /* An incomplete start or end chunk (or maybe both start and end chunk)
3925                                  * Read into the local buffer then copy, then copy over and write back.
3926                                  */
3927
3928                                 __u8 *localBuffer =
3929                                     yaffs_GetTempBuffer(dev, __LINE__);
3930
3931                                 yaffs_ReadChunkDataFromObject(in, chunk,
3932                                                               localBuffer);
3933
3934 #ifdef CONFIG_YAFFS_WINCE
3935                                 yfsd_UnlockYAFFS(TRUE);
3936 #endif
3937
3938                                 memcpy(&localBuffer[start], buffer, nToCopy);
3939
3940 #ifdef CONFIG_YAFFS_WINCE
3941                                 yfsd_LockYAFFS(TRUE);
3942 #endif
3943                                 chunkWritten =
3944                                     yaffs_WriteChunkDataToObject(in, chunk,
3945                                                                  localBuffer,
3946                                                                  nToWriteBack,
3947                                                                  0);
3948
3949                                 yaffs_ReleaseTempBuffer(dev, localBuffer,
3950                                                         __LINE__);
3951
3952                         }
3953
3954                 } else {
3955
3956 #ifdef CONFIG_YAFFS_WINCE
3957                         /* Under WinCE can't do direct transfer. Need to use a local buffer.
3958                          * This is because we otherwise screw up WinCE's memory mapper
3959                          */
3960                         __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3961 #ifdef CONFIG_YAFFS_WINCE
3962                         yfsd_UnlockYAFFS(TRUE);
3963 #endif
3964                         memcpy(localBuffer, buffer, dev->nBytesPerChunk);
3965 #ifdef CONFIG_YAFFS_WINCE
3966                         yfsd_LockYAFFS(TRUE);
3967 #endif
3968                         chunkWritten =
3969                             yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
3970                                                          dev->nBytesPerChunk,
3971                                                          0);
3972                         yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3973 #else
3974                         /* A full chunk. Write directly from the supplied buffer. */
3975                         chunkWritten =
3976                             yaffs_WriteChunkDataToObject(in, chunk, buffer,
3977                                                          dev->nBytesPerChunk,
3978                                                          0);
3979 #endif
3980                         /* Since we've overwritten the cached data, we better invalidate it. */
3981                         yaffs_InvalidateChunkCache(in, chunk);
3982                 }
3983
3984                 if (chunkWritten >= 0) {
3985                         n -= nToCopy;
3986                         offset += nToCopy;
3987                         buffer += nToCopy;
3988                         nDone += nToCopy;
3989                 }
3990
3991         }
3992
3993         /* Update file object */
3994
3995         if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
3996                 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
3997         }
3998
3999         in->dirty = 1;
4000
4001         return nDone;
4002 }
4003
4004
4005 /* ---------------------- File resizing stuff ------------------ */
4006
4007 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
4008 {
4009
4010         yaffs_Device *dev = in->myDev;
4011         int oldFileSize = in->variant.fileVariant.fileSize;
4012
4013         int lastDel = 1 + (oldFileSize - 1) / dev->nBytesPerChunk;
4014
4015         int startDel = 1 + (newSize + dev->nBytesPerChunk - 1) /
4016             dev->nBytesPerChunk;
4017         int i;
4018         int chunkId;
4019
4020         /* Delete backwards so that we don't end up with holes if
4021          * power is lost part-way through the operation.
4022          */
4023         for (i = lastDel; i >= startDel; i--) {
4024                 /* NB this could be optimised somewhat,
4025                  * eg. could retrieve the tags and write them without
4026                  * using yaffs_DeleteChunk
4027                  */
4028
4029                 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
4030                 if (chunkId > 0) {
4031                         if (chunkId <
4032                             (dev->internalStartBlock * dev->nChunksPerBlock)
4033                             || chunkId >=
4034                             ((dev->internalEndBlock +
4035                               1) * dev->nChunksPerBlock)) {
4036                                 T(YAFFS_TRACE_ALWAYS,
4037                                   (TSTR("Found daft chunkId %d for %d" TENDSTR),
4038                                    chunkId, i));
4039                         } else {
4040                                 in->nDataChunks--;
4041                                 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
4042                         }
4043                 }
4044         }
4045
4046 }
4047
4048 int yaffs_ResizeFile(yaffs_Object * in, int newSize)
4049 {
4050
4051         int oldFileSize = in->variant.fileVariant.fileSize;
4052         int sizeOfPartialChunk;
4053         yaffs_Device *dev = in->myDev;
4054
4055         sizeOfPartialChunk = newSize % dev->nBytesPerChunk;
4056
4057         yaffs_FlushFilesChunkCache(in);
4058         yaffs_InvalidateWholeChunkCache(in);
4059
4060         yaffs_CheckGarbageCollection(dev);
4061
4062         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
4063                 return yaffs_GetFileSize(in);
4064         }
4065
4066         if (newSize == oldFileSize) {
4067                 return oldFileSize;
4068         }
4069
4070         if (newSize < oldFileSize) {
4071
4072                 yaffs_PruneResizedChunks(in, newSize);
4073
4074                 if (sizeOfPartialChunk != 0) {
4075                         int lastChunk = 1 + newSize / dev->nBytesPerChunk;
4076                         __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4077
4078                         /* Got to read and rewrite the last chunk with its new size and zero pad */
4079                         yaffs_ReadChunkDataFromObject(in, lastChunk,
4080                                                       localBuffer);
4081
4082                         memset(localBuffer + sizeOfPartialChunk, 0,
4083                                dev->nBytesPerChunk - sizeOfPartialChunk);
4084
4085                         yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
4086                                                      sizeOfPartialChunk, 1);
4087
4088                         yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4089                 }
4090
4091                 in->variant.fileVariant.fileSize = newSize;
4092
4093                 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
4094         }
4095         /* Write a new object header.
4096          * show we've shrunk the file, if need be
4097          * Do this only if the file is not in the deleted directories.
4098          */
4099         if (in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
4100             in->parent->objectId != YAFFS_OBJECTID_DELETED) {
4101                 yaffs_UpdateObjectHeader(in, NULL, 0,
4102                                          (newSize < oldFileSize) ? 1 : 0, 0);
4103         }
4104
4105         return newSize;
4106 }
4107
4108 loff_t yaffs_GetFileSize(yaffs_Object * obj)
4109 {
4110         obj = yaffs_GetEquivalentObject(obj);
4111
4112         switch (obj->variantType) {
4113         case YAFFS_OBJECT_TYPE_FILE:
4114                 return obj->variant.fileVariant.fileSize;
4115         case YAFFS_OBJECT_TYPE_SYMLINK:
4116                 return yaffs_strlen(obj->variant.symLinkVariant.alias);
4117         default:
4118                 return 0;
4119         }
4120 }
4121
4122
4123
4124 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
4125 {
4126         int retVal;
4127         if (in->dirty) {
4128                 yaffs_FlushFilesChunkCache(in);
4129                 if (updateTime) {
4130 #ifdef CONFIG_YAFFS_WINCE
4131                         yfsd_WinFileTimeNow(in->win_mtime);
4132 #else
4133
4134                         in->yst_mtime = Y_CURRENT_TIME;
4135
4136 #endif
4137                 }
4138
4139                 retVal =
4140                     (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
4141                      0) ? YAFFS_OK : YAFFS_FAIL;
4142         } else {
4143                 retVal = YAFFS_OK;
4144         }
4145
4146         return retVal;
4147
4148 }
4149
4150 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
4151 {
4152
4153         /* First off, invalidate the file's data in the cache, without flushing. */
4154         yaffs_InvalidateWholeChunkCache(in);
4155
4156         if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
4157                 /* Move to the unlinked directory so we have a record that it was deleted. */
4158                 yaffs_ChangeObjectName(in, in->myDev->deletedDir, NULL, 0, 0);
4159
4160         }
4161
4162         yaffs_RemoveObjectFromDirectory(in);
4163         yaffs_DeleteChunk(in->myDev, in->chunkId, 1, __LINE__);
4164         in->chunkId = -1;
4165
4166         yaffs_FreeObject(in);
4167         return YAFFS_OK;
4168
4169 }
4170
4171 /* yaffs_DeleteFile deletes the whole file data
4172  * and the inode associated with the file.
4173  * It does not delete the links associated with the file.
4174  */
4175 static int yaffs_UnlinkFile(yaffs_Object * in)
4176 {
4177
4178         int retVal;
4179         int immediateDeletion = 0;
4180
4181         if (1) {
4182 #ifdef __KERNEL__
4183                 if (!in->myInode) {
4184                         immediateDeletion = 1;
4185
4186                 }
4187 #else
4188                 if (in->inUse <= 0) {
4189                         immediateDeletion = 1;
4190
4191                 }
4192 #endif
4193                 if (immediateDeletion) {
4194                         retVal =
4195                             yaffs_ChangeObjectName(in, in->myDev->deletedDir,
4196                                                    NULL, 0, 0);
4197                         T(YAFFS_TRACE_TRACING,
4198                           (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
4199                            in->objectId));
4200                         in->deleted = 1;
4201                         in->myDev->nDeletedFiles++;
4202                         if (0 && in->myDev->isYaffs2) {
4203                                 yaffs_ResizeFile(in, 0);
4204                         }
4205                         yaffs_SoftDeleteFile(in);
4206                 } else {
4207                         retVal =
4208                             yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
4209                                                    NULL, 0, 0);
4210                 }
4211
4212         }
4213         return retVal;
4214 }
4215
4216 int yaffs_DeleteFile(yaffs_Object * in)
4217 {
4218         int retVal = YAFFS_OK;
4219
4220         if (in->nDataChunks > 0) {
4221                 /* Use soft deletion if there is data in the file */
4222                 if (!in->unlinked) {
4223                         retVal = yaffs_UnlinkFile(in);
4224                 }
4225                 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
4226                         in->deleted = 1;
4227                         in->myDev->nDeletedFiles++;
4228                         yaffs_SoftDeleteFile(in);
4229                 }
4230                 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
4231         } else {
4232                 /* The file has no data chunks so we toss it immediately */
4233                 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
4234                 in->variant.fileVariant.top = NULL;
4235                 yaffs_DoGenericObjectDeletion(in);
4236
4237                 return YAFFS_OK;
4238         }
4239 }
4240
4241 static int yaffs_DeleteDirectory(yaffs_Object * in)
4242 {
4243         /* First check that the directory is empty. */
4244         if (list_empty(&in->variant.directoryVariant.children)) {
4245                 return yaffs_DoGenericObjectDeletion(in);
4246         }
4247
4248         return YAFFS_FAIL;
4249
4250 }
4251
4252 static int yaffs_DeleteSymLink(yaffs_Object * in)
4253 {
4254         YFREE(in->variant.symLinkVariant.alias);
4255
4256         return yaffs_DoGenericObjectDeletion(in);
4257 }
4258
4259 static int yaffs_DeleteHardLink(yaffs_Object * in)
4260 {
4261         /* remove this hardlink from the list assocaited with the equivalent
4262          * object
4263          */
4264         list_del(&in->hardLinks);
4265         return yaffs_DoGenericObjectDeletion(in);
4266 }
4267
4268 static void yaffs_DestroyObject(yaffs_Object * obj)
4269 {
4270         switch (obj->variantType) {
4271         case YAFFS_OBJECT_TYPE_FILE:
4272                 yaffs_DeleteFile(obj);
4273                 break;
4274         case YAFFS_OBJECT_TYPE_DIRECTORY:
4275                 yaffs_DeleteDirectory(obj);
4276                 break;
4277         case YAFFS_OBJECT_TYPE_SYMLINK:
4278                 yaffs_DeleteSymLink(obj);
4279                 break;
4280         case YAFFS_OBJECT_TYPE_HARDLINK:
4281                 yaffs_DeleteHardLink(obj);
4282                 break;
4283         case YAFFS_OBJECT_TYPE_SPECIAL:
4284                 yaffs_DoGenericObjectDeletion(obj);
4285                 break;
4286         case YAFFS_OBJECT_TYPE_UNKNOWN:
4287                 break;          /* should not happen. */
4288         }
4289 }
4290
4291 static int yaffs_UnlinkWorker(yaffs_Object * obj)
4292 {
4293
4294         if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4295                 return yaffs_DeleteHardLink(obj);
4296         } else if (!list_empty(&obj->hardLinks)) {
4297                 /* Curve ball: We're unlinking an object that has a hardlink.
4298                  *
4299                  * This problem arises because we are not strictly following
4300                  * The Linux link/inode model.
4301                  *
4302                  * We can't really delete the object.
4303                  * Instead, we do the following:
4304                  * - Select a hardlink.
4305                  * - Unhook it from the hard links
4306                  * - Unhook it from its parent directory (so that the rename can work)
4307                  * - Rename the object to the hardlink's name.
4308                  * - Delete the hardlink
4309                  */
4310
4311                 yaffs_Object *hl;
4312                 int retVal;
4313                 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
4314
4315                 hl = list_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
4316
4317                 list_del_init(&hl->hardLinks);
4318                 list_del_init(&hl->siblings);
4319
4320                 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
4321
4322                 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
4323
4324                 if (retVal == YAFFS_OK) {
4325                         retVal = yaffs_DoGenericObjectDeletion(hl);
4326                 }
4327                 return retVal;
4328
4329         } else {
4330                 switch (obj->variantType) {
4331                 case YAFFS_OBJECT_TYPE_FILE:
4332                         return yaffs_UnlinkFile(obj);
4333                         break;
4334                 case YAFFS_OBJECT_TYPE_DIRECTORY:
4335                         return yaffs_DeleteDirectory(obj);
4336                         break;
4337                 case YAFFS_OBJECT_TYPE_SYMLINK:
4338                         return yaffs_DeleteSymLink(obj);
4339                         break;
4340                 case YAFFS_OBJECT_TYPE_SPECIAL:
4341                         return yaffs_DoGenericObjectDeletion(obj);
4342                         break;
4343                 case YAFFS_OBJECT_TYPE_HARDLINK:
4344                 case YAFFS_OBJECT_TYPE_UNKNOWN:
4345                 default:
4346                         return YAFFS_FAIL;
4347                 }
4348         }
4349 }
4350
4351
4352 static int yaffs_UnlinkObject( yaffs_Object *obj)
4353 {
4354
4355         if (obj && obj->unlinkAllowed) {
4356                 return yaffs_UnlinkWorker(obj);
4357         }
4358
4359         return YAFFS_FAIL;
4360
4361 }
4362 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
4363 {
4364         yaffs_Object *obj;
4365
4366         obj = yaffs_FindObjectByName(dir, name);
4367         return yaffs_UnlinkObject(obj);
4368 }
4369
4370 /*----------------------- Initialisation Scanning ---------------------- */
4371
4372 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
4373                                        int backwardScanning)
4374 {
4375         yaffs_Object *obj;
4376
4377         if (!backwardScanning) {
4378                 /* Handle YAFFS1 forward scanning case
4379                  * For YAFFS1 we always do the deletion
4380                  */
4381
4382         } else {
4383                 /* Handle YAFFS2 case (backward scanning)
4384                  * If the shadowed object exists then ignore.
4385                  */
4386                 if (yaffs_FindObjectByNumber(dev, objId)) {
4387                         return;
4388                 }
4389         }
4390
4391         /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
4392          * We put it in unlinked dir to be cleaned up after the scanning
4393          */
4394         obj =
4395             yaffs_FindOrCreateObjectByNumber(dev, objId,
4396                                              YAFFS_OBJECT_TYPE_FILE);
4397         yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
4398         obj->variant.fileVariant.shrinkSize = 0;
4399         obj->valid = 1;         /* So that we don't read any other info for this file */
4400
4401 }
4402
4403 typedef struct {
4404         int seq;
4405         int block;
4406 } yaffs_BlockIndex;
4407
4408
4409 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
4410 {
4411         yaffs_Object *hl;
4412         yaffs_Object *in;
4413         
4414         while (hardList) {
4415                 hl = hardList;
4416                 hardList = (yaffs_Object *) (hardList->hardLinks.next);
4417
4418                 in = yaffs_FindObjectByNumber(dev,
4419                                               hl->variant.hardLinkVariant.
4420                                               equivalentObjectId);
4421
4422                 if (in) {
4423                         /* Add the hardlink pointers */
4424                         hl->variant.hardLinkVariant.equivalentObject = in;
4425                         list_add(&hl->hardLinks, &in->hardLinks);
4426                 } else {
4427                         /* Todo Need to report/handle this better.
4428                          * Got a problem... hardlink to a non-existant object
4429                          */
4430                         hl->variant.hardLinkVariant.equivalentObject = NULL;
4431                         INIT_LIST_HEAD(&hl->hardLinks);
4432
4433                 }
4434
4435         }
4436
4437 }
4438
4439
4440
4441
4442
4443 static int ybicmp(const void *a, const void *b){
4444     register int aseq = ((yaffs_BlockIndex *)a)->seq;
4445     register int bseq = ((yaffs_BlockIndex *)b)->seq;
4446     register int ablock = ((yaffs_BlockIndex *)a)->block;
4447     register int bblock = ((yaffs_BlockIndex *)b)->block;
4448     if( aseq == bseq )
4449         return ablock - bblock;
4450     else
4451         return aseq - bseq;
4452
4453 }
4454
4455 static int yaffs_Scan(yaffs_Device * dev)
4456 {
4457         yaffs_ExtendedTags tags;
4458         int blk;
4459         int blockIterator;
4460         int startIterator;
4461         int endIterator;
4462         int nBlocksToScan = 0;
4463
4464         int chunk;
4465         int c;
4466         int deleted;
4467         yaffs_BlockState state;
4468         yaffs_Object *hardList = NULL;
4469         yaffs_Object *hl;
4470         yaffs_BlockInfo *bi;
4471         int sequenceNumber;
4472         yaffs_ObjectHeader *oh;
4473         yaffs_Object *in;
4474         yaffs_Object *parent;
4475         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
4476
4477         __u8 *chunkData;
4478
4479         yaffs_BlockIndex *blockIndex = NULL;
4480
4481         if (dev->isYaffs2) {
4482                 T(YAFFS_TRACE_SCAN,
4483                   (TSTR("yaffs_Scan is not for YAFFS2!" TENDSTR)));
4484                 return YAFFS_FAIL;
4485         }
4486         
4487         //TODO  Throw all the yaffs2 stuuf out of yaffs_Scan since it is only for yaffs1 format.
4488         
4489         T(YAFFS_TRACE_SCAN,
4490           (TSTR("yaffs_Scan starts  intstartblk %d intendblk %d..." TENDSTR),
4491            dev->internalStartBlock, dev->internalEndBlock));
4492
4493         chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4494
4495         dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
4496
4497         if (dev->isYaffs2) {
4498                 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
4499         }
4500
4501         /* Scan all the blocks to determine their state */
4502         for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
4503                 bi = yaffs_GetBlockInfo(dev, blk);
4504                 yaffs_ClearChunkBits(dev, blk);
4505                 bi->pagesInUse = 0;
4506                 bi->softDeletions = 0;
4507
4508                 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
4509
4510                 bi->blockState = state;
4511                 bi->sequenceNumber = sequenceNumber;
4512
4513                 T(YAFFS_TRACE_SCAN_DEBUG,
4514                   (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
4515                    state, sequenceNumber));
4516
4517                 if (state == YAFFS_BLOCK_STATE_DEAD) {
4518                         T(YAFFS_TRACE_BAD_BLOCKS,
4519                           (TSTR("block %d is bad" TENDSTR), blk));
4520                 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
4521                         T(YAFFS_TRACE_SCAN_DEBUG,
4522                           (TSTR("Block empty " TENDSTR)));
4523                         dev->nErasedBlocks++;
4524                         dev->nFreeChunks += dev->nChunksPerBlock;
4525                 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4526
4527                         /* Determine the highest sequence number */
4528                         if (dev->isYaffs2 &&
4529                             sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
4530                             sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
4531
4532                                 blockIndex[nBlocksToScan].seq = sequenceNumber;
4533                                 blockIndex[nBlocksToScan].block = blk;
4534
4535                                 nBlocksToScan++;
4536
4537                                 if (sequenceNumber >= dev->sequenceNumber) {
4538                                         dev->sequenceNumber = sequenceNumber;
4539                                 }
4540                         } else if (dev->isYaffs2) {
4541                                 /* TODO: Nasty sequence number! */
4542                                 T(YAFFS_TRACE_SCAN,
4543                                   (TSTR
4544                                    ("Block scanning block %d has bad sequence number %d"
4545                                     TENDSTR), blk, sequenceNumber));
4546
4547                         }
4548                 }
4549         }
4550
4551         /* Sort the blocks
4552          * Dungy old bubble sort for now...
4553          */
4554         if (dev->isYaffs2) {
4555                 yaffs_BlockIndex temp;
4556                 int i;
4557                 int j;
4558
4559                 for (i = 0; i < nBlocksToScan; i++)
4560                         for (j = i + 1; j < nBlocksToScan; j++)
4561                                 if (blockIndex[i].seq > blockIndex[j].seq) {
4562                                         temp = blockIndex[j];
4563                                         blockIndex[j] = blockIndex[i];
4564                                         blockIndex[i] = temp;
4565                                 }
4566         }
4567
4568         /* Now scan the blocks looking at the data. */
4569         if (dev->isYaffs2) {
4570                 startIterator = 0;
4571                 endIterator = nBlocksToScan - 1;
4572                 T(YAFFS_TRACE_SCAN_DEBUG,
4573                   (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
4574         } else {
4575                 startIterator = dev->internalStartBlock;
4576                 endIterator = dev->internalEndBlock;
4577         }
4578
4579         /* For each block.... */
4580         for (blockIterator = startIterator; blockIterator <= endIterator;
4581              blockIterator++) {
4582
4583                 if (dev->isYaffs2) {
4584                         /* get the block to scan in the correct order */
4585                         blk = blockIndex[blockIterator].block;
4586                 } else {
4587                         blk = blockIterator;
4588                 }
4589
4590                 bi = yaffs_GetBlockInfo(dev, blk);
4591                 state = bi->blockState;
4592
4593                 deleted = 0;
4594
4595                 /* For each chunk in each block that needs scanning....*/
4596                 for (c = 0; c < dev->nChunksPerBlock &&
4597                      state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
4598                         /* Read the tags and decide what to do */
4599                         chunk = blk * dev->nChunksPerBlock + c;
4600
4601                         yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
4602                                                         &tags);
4603
4604                         /* Let's have a good look at this chunk... */
4605
4606                         if (!dev->isYaffs2 && tags.chunkDeleted) {
4607                                 /* YAFFS1 only...
4608                                  * A deleted chunk
4609                                  */
4610                                 deleted++;
4611                                 dev->nFreeChunks++;
4612                                 /*T((" %d %d deleted\n",blk,c)); */
4613                         } else if (!tags.chunkUsed) {
4614                                 /* An unassigned chunk in the block
4615                                  * This means that either the block is empty or 
4616                                  * this is the one being allocated from
4617                                  */
4618
4619                                 if (c == 0) {
4620                                         /* We're looking at the first chunk in the block so the block is unused */
4621                                         state = YAFFS_BLOCK_STATE_EMPTY;
4622                                         dev->nErasedBlocks++;
4623                                 } else {
4624                                         /* this is the block being allocated from */
4625                                         T(YAFFS_TRACE_SCAN,
4626                                           (TSTR
4627                                            (" Allocating from %d %d" TENDSTR),
4628                                            blk, c));
4629                                         state = YAFFS_BLOCK_STATE_ALLOCATING;
4630                                         dev->allocationBlock = blk;
4631                                         dev->allocationPage = c;
4632                                         dev->allocationBlockFinder = blk;       
4633                                         /* Set it to here to encourage the allocator to go forth from here. */
4634                                         
4635                                         /* Yaffs2 sanity check:
4636                                          * This should be the one with the highest sequence number
4637                                          */
4638                                         if (dev->isYaffs2
4639                                             && (dev->sequenceNumber !=
4640                                                 bi->sequenceNumber)) {
4641                                                 T(YAFFS_TRACE_ALWAYS,
4642                                                   (TSTR
4643                                                    ("yaffs: Allocation block %d was not highest sequence id:"
4644                                                     " block seq = %d, dev seq = %d"
4645                                                     TENDSTR), blk,bi->sequenceNumber,dev->sequenceNumber));
4646                                         }
4647                                 }
4648
4649                                 dev->nFreeChunks += (dev->nChunksPerBlock - c);
4650                         } else if (tags.chunkId > 0) {
4651                                 /* chunkId > 0 so it is a data chunk... */
4652                                 unsigned int endpos;
4653
4654                                 yaffs_SetChunkBit(dev, blk, c);
4655                                 bi->pagesInUse++;
4656
4657                                 in = yaffs_FindOrCreateObjectByNumber(dev,
4658                                                                       tags.
4659                                                                       objectId,
4660                                                                       YAFFS_OBJECT_TYPE_FILE);
4661                                 /* PutChunkIntoFile checks for a clash (two data chunks with
4662                                  * the same chunkId).
4663                                  */
4664                                 yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,
4665                                                        1);
4666                                 endpos =
4667                                     (tags.chunkId - 1) * dev->nBytesPerChunk +
4668                                     tags.byteCount;
4669                                 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
4670                                     && in->variant.fileVariant.scannedFileSize <
4671                                     endpos) {
4672                                         in->variant.fileVariant.
4673                                             scannedFileSize = endpos;
4674                                         if (!dev->useHeaderFileSize) {
4675                                                 in->variant.fileVariant.
4676                                                     fileSize =
4677                                                     in->variant.fileVariant.
4678                                                     scannedFileSize;
4679                                         }
4680
4681                                 }
4682                                 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));   */
4683                         } else {
4684                                 /* chunkId == 0, so it is an ObjectHeader.
4685                                  * Thus, we read in the object header and make the object
4686                                  */
4687                                 yaffs_SetChunkBit(dev, blk, c);
4688                                 bi->pagesInUse++;
4689
4690                                 yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
4691                                                                 chunkData,
4692                                                                 NULL);
4693
4694                                 oh = (yaffs_ObjectHeader *) chunkData;
4695
4696                                 in = yaffs_FindObjectByNumber(dev,
4697                                                               tags.objectId);
4698                                 if (in && in->variantType != oh->type) {
4699                                         /* This should not happen, but somehow
4700                                          * Wev'e ended up with an objectId that has been reused but not yet 
4701                                          * deleted, and worse still it has changed type. Delete the old object.
4702                                          */
4703
4704                                         yaffs_DestroyObject(in);
4705
4706                                         in = 0;
4707                                 }
4708
4709                                 in = yaffs_FindOrCreateObjectByNumber(dev,
4710                                                                       tags.
4711                                                                       objectId,
4712                                                                       oh->type);
4713
4714                                 if (oh->shadowsObject > 0) {
4715                                         yaffs_HandleShadowedObject(dev,
4716                                                                    oh->
4717                                                                    shadowsObject,
4718                                                                    0);
4719                                 }
4720
4721                                 if (in->valid) {
4722                                         /* We have already filled this one. We have a duplicate and need to resolve it. */
4723
4724                                         unsigned existingSerial = in->serial;
4725                                         unsigned newSerial = tags.serialNumber;
4726
4727                                         if (dev->isYaffs2 ||
4728                                             ((existingSerial + 1) & 3) ==
4729                                             newSerial) {
4730                                                 /* Use new one - destroy the exisiting one */
4731                                                 yaffs_DeleteChunk(dev,
4732                                                                   in->chunkId,
4733                                                                   1, __LINE__);
4734                                                 in->valid = 0;
4735                                         } else {
4736                                                 /* Use existing - destroy this one. */
4737                                                 yaffs_DeleteChunk(dev, chunk, 1,
4738                                                                   __LINE__);
4739                                         }
4740                                 }
4741
4742                                 if (!in->valid &&
4743                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
4744                                      tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
4745                                         /* We only load some info, don't fiddle with directory structure */
4746                                         in->valid = 1;
4747                                         in->variantType = oh->type;
4748
4749                                         in->yst_mode = oh->yst_mode;
4750 #ifdef CONFIG_YAFFS_WINCE
4751                                         in->win_atime[0] = oh->win_atime[0];
4752                                         in->win_ctime[0] = oh->win_ctime[0];
4753                                         in->win_mtime[0] = oh->win_mtime[0];
4754                                         in->win_atime[1] = oh->win_atime[1];
4755                                         in->win_ctime[1] = oh->win_ctime[1];
4756                                         in->win_mtime[1] = oh->win_mtime[1];
4757 #else
4758                                         in->yst_uid = oh->yst_uid;
4759                                         in->yst_gid = oh->yst_gid;
4760                                         in->yst_atime = oh->yst_atime;
4761                                         in->yst_mtime = oh->yst_mtime;
4762                                         in->yst_ctime = oh->yst_ctime;
4763                                         in->yst_rdev = oh->yst_rdev;
4764 #endif
4765                                         in->chunkId = chunk;
4766
4767                                 } else if (!in->valid) {
4768                                         /* we need to load this info */
4769
4770                                         in->valid = 1;
4771                                         in->variantType = oh->type;
4772
4773                                         in->yst_mode = oh->yst_mode;
4774 #ifdef CONFIG_YAFFS_WINCE
4775                                         in->win_atime[0] = oh->win_atime[0];
4776                                         in->win_ctime[0] = oh->win_ctime[0];
4777                                         in->win_mtime[0] = oh->win_mtime[0];
4778                                         in->win_atime[1] = oh->win_atime[1];
4779                                         in->win_ctime[1] = oh->win_ctime[1];
4780                                         in->win_mtime[1] = oh->win_mtime[1];
4781 #else
4782                                         in->yst_uid = oh->yst_uid;
4783                                         in->yst_gid = oh->yst_gid;
4784                                         in->yst_atime = oh->yst_atime;
4785                                         in->yst_mtime = oh->yst_mtime;
4786                                         in->yst_ctime = oh->yst_ctime;
4787                                         in->yst_rdev = oh->yst_rdev;
4788 #endif
4789                                         in->chunkId = chunk;
4790
4791                                         yaffs_SetObjectName(in, oh->name);
4792                                         in->dirty = 0;
4793
4794                                         /* directory stuff...
4795                                          * hook up to parent
4796                                          */
4797
4798                                         parent =
4799                                             yaffs_FindOrCreateObjectByNumber
4800                                             (dev, oh->parentObjectId,
4801                                              YAFFS_OBJECT_TYPE_DIRECTORY);
4802                                         if (parent->variantType ==
4803                                             YAFFS_OBJECT_TYPE_UNKNOWN) {
4804                                                 /* Set up as a directory */
4805                                                 parent->variantType =
4806                                                     YAFFS_OBJECT_TYPE_DIRECTORY;
4807                                                 INIT_LIST_HEAD(&parent->variant.
4808                                                                directoryVariant.
4809                                                                children);
4810                                         } else if (parent->variantType !=
4811                                                    YAFFS_OBJECT_TYPE_DIRECTORY)
4812                                         {
4813                                                 /* Hoosterman, another problem....
4814                                                  * We're trying to use a non-directory as a directory
4815                                                  */
4816
4817                                                 T(YAFFS_TRACE_ERROR,
4818                                                   (TSTR
4819                                                    ("yaffs tragedy: attempting to use non-directory as"
4820                                                     " a directory in scan. Put in lost+found."
4821                                                     TENDSTR)));
4822                                                 parent = dev->lostNFoundDir;
4823                                         }
4824
4825                                         yaffs_AddObjectToDirectory(parent, in);
4826
4827                                         if (0 && (parent == dev->deletedDir ||
4828                                                   parent == dev->unlinkedDir)) {
4829                                                 in->deleted = 1;        /* If it is unlinked at start up then it wants deleting */
4830                                                 dev->nDeletedFiles++;
4831                                         }
4832                                         /* Note re hardlinks.
4833                                          * Since we might scan a hardlink before its equivalent object is scanned
4834                                          * we put them all in a list.
4835                                          * After scanning is complete, we should have all the objects, so we run through this
4836                                          * list and fix up all the chains.              
4837                                          */
4838
4839                                         switch (in->variantType) {
4840                                         case YAFFS_OBJECT_TYPE_UNKNOWN: 
4841                                                 /* Todo got a problem */
4842                                                 break;
4843                                         case YAFFS_OBJECT_TYPE_FILE:
4844                                                 if (dev->isYaffs2
4845                                                     && oh->isShrink) {
4846                                                         /* Prune back the shrunken chunks */
4847                                                         yaffs_PruneResizedChunks
4848                                                             (in, oh->fileSize);
4849                                                         /* Mark the block as having a shrinkHeader */
4850                                                         bi->hasShrinkHeader = 1;
4851                                                 }
4852
4853                                                 if (dev->useHeaderFileSize)
4854
4855                                                         in->variant.fileVariant.
4856                                                             fileSize =
4857                                                             oh->fileSize;
4858
4859                                                 break;
4860                                         case YAFFS_OBJECT_TYPE_HARDLINK:
4861                                                 in->variant.hardLinkVariant.
4862                                                     equivalentObjectId =
4863                                                     oh->equivalentObjectId;
4864                                                 in->hardLinks.next =
4865                                                     (struct list_head *)
4866                                                     hardList;
4867                                                 hardList = in;
4868                                                 break;
4869                                         case YAFFS_OBJECT_TYPE_DIRECTORY:
4870                                                 /* Do nothing */
4871                                                 break;
4872                                         case YAFFS_OBJECT_TYPE_SPECIAL:
4873                                                 /* Do nothing */
4874                                                 break;
4875                                         case YAFFS_OBJECT_TYPE_SYMLINK: 
4876                                                 in->variant.symLinkVariant.
4877                                                     alias =
4878                                                     yaffs_CloneString(oh->alias);
4879                                                 break;
4880                                         }
4881
4882                                         if (parent == dev->deletedDir) {
4883                                                 yaffs_DestroyObject(in);
4884                                                 bi->hasShrinkHeader = 1;
4885                                         }
4886                                 }
4887                         }
4888                 }
4889
4890                 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4891                         /* If we got this far while scanning, then the block is fully allocated.*/
4892                         state = YAFFS_BLOCK_STATE_FULL;
4893                 }
4894
4895                 bi->blockState = state;
4896
4897                 /* Now let's see if it was dirty */
4898                 if (bi->pagesInUse == 0 &&
4899                     !bi->hasShrinkHeader &&
4900                     bi->blockState == YAFFS_BLOCK_STATE_FULL) {
4901                         yaffs_BlockBecameDirty(dev, blk);
4902                 }
4903
4904         }
4905
4906         if (blockIndex) {
4907                 YFREE(blockIndex);
4908         }
4909         
4910         
4911         /* Ok, we've done all the scanning.
4912          * Fix up the hard link chains.
4913          * We should now have scanned all the objects, now it's time to add these 
4914          * hardlinks.
4915          */
4916
4917         yaffs_HardlinkFixup(dev,hardList);
4918
4919         /* Handle the unlinked files. Since they were left in an unlinked state we should
4920          * just delete them.
4921          */
4922         {
4923                 struct list_head *i;
4924                 struct list_head *n;
4925
4926                 yaffs_Object *l;
4927                 /* Soft delete all the unlinked files */
4928                 list_for_each_safe(i, n,
4929                                    &dev->unlinkedDir->variant.directoryVariant.
4930                                    children) {
4931                         if (i) {
4932                                 l = list_entry(i, yaffs_Object, siblings);
4933                                 yaffs_DestroyObject(l);
4934                         }
4935                 }
4936         }
4937
4938         yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
4939
4940         T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
4941
4942         return YAFFS_OK;
4943 }
4944
4945 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
4946 {
4947         __u8 *chunkData;
4948         yaffs_ObjectHeader *oh;
4949         yaffs_Device *dev = in->myDev;
4950         
4951         if(in->lazyLoaded){
4952                 in->lazyLoaded = 0;
4953                 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4954
4955                 yaffs_ReadChunkWithTagsFromNAND(dev,in->chunkId,chunkData,NULL);
4956                 oh = (yaffs_ObjectHeader *) chunkData;          
4957
4958                 in->yst_mode = oh->yst_mode;
4959 #ifdef CONFIG_YAFFS_WINCE
4960                 in->win_atime[0] = oh->win_atime[0];
4961                 in->win_ctime[0] = oh->win_ctime[0];
4962                 in->win_mtime[0] = oh->win_mtime[0];
4963                 in->win_atime[1] = oh->win_atime[1];
4964                 in->win_ctime[1] = oh->win_ctime[1];
4965                 in->win_mtime[1] = oh->win_mtime[1];
4966 #else
4967                 in->yst_uid = oh->yst_uid;
4968                 in->yst_gid = oh->yst_gid;
4969                 in->yst_atime = oh->yst_atime;
4970                 in->yst_mtime = oh->yst_mtime;
4971                 in->yst_ctime = oh->yst_ctime;
4972                 in->yst_rdev = oh->yst_rdev;
4973                 
4974 #endif
4975                 yaffs_SetObjectName(in, oh->name);
4976                 
4977                 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
4978                          in->variant.symLinkVariant.alias =
4979                                                     yaffs_CloneString(oh->alias);
4980                                                     
4981                 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
4982         }
4983 }
4984
4985 static int yaffs_ScanBackwards(yaffs_Device * dev)
4986 {
4987         yaffs_ExtendedTags tags;
4988         int blk;
4989         int blockIterator;
4990         int startIterator;
4991         int endIterator;
4992         int nBlocksToScan = 0;
4993
4994         int chunk;
4995         int c;
4996         int deleted;
4997         yaffs_BlockState state;
4998         yaffs_Object *hardList = NULL;
4999         yaffs_BlockInfo *bi;
5000         int sequenceNumber;
5001         yaffs_ObjectHeader *oh;
5002         yaffs_Object *in;
5003         yaffs_Object *parent;
5004         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5005         int itsUnlinked;
5006         __u8 *chunkData;
5007         
5008         int fileSize;
5009         int isShrink;
5010         int equivalentObjectId;
5011         
5012
5013         yaffs_BlockIndex *blockIndex = NULL;
5014         int altBlockIndex = 0;
5015
5016         if (!dev->isYaffs2) {
5017                 T(YAFFS_TRACE_SCAN,
5018                   (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
5019                 return YAFFS_FAIL;
5020         }
5021
5022         T(YAFFS_TRACE_SCAN,
5023           (TSTR
5024            ("yaffs_ScanBackwards starts  intstartblk %d intendblk %d..."
5025             TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
5026
5027
5028         dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5029
5030         blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
5031         
5032         if(!blockIndex) {
5033                 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
5034                 altBlockIndex = 1;
5035         }
5036         
5037         if(!blockIndex) {
5038                 T(YAFFS_TRACE_SCAN,
5039                   (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
5040                 return YAFFS_FAIL;
5041         }
5042         
5043         chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5044
5045         /* Scan all the blocks to determine their state */
5046         for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5047                 bi = yaffs_GetBlockInfo(dev, blk);
5048                 yaffs_ClearChunkBits(dev, blk);
5049                 bi->pagesInUse = 0;
5050                 bi->softDeletions = 0;
5051
5052                 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5053
5054                 bi->blockState = state;
5055                 bi->sequenceNumber = sequenceNumber;
5056
5057                 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
5058                         bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
5059                         
5060                 T(YAFFS_TRACE_SCAN_DEBUG,
5061                   (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5062                    state, sequenceNumber));
5063
5064                 
5065                 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
5066                         /* todo .. fix free space ? */
5067                         
5068                 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
5069                         T(YAFFS_TRACE_BAD_BLOCKS,
5070                           (TSTR("block %d is bad" TENDSTR), blk));
5071                 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5072                         T(YAFFS_TRACE_SCAN_DEBUG,
5073                           (TSTR("Block empty " TENDSTR)));
5074                         dev->nErasedBlocks++;
5075                         dev->nFreeChunks += dev->nChunksPerBlock;
5076                 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5077
5078                         /* Determine the highest sequence number */
5079                         if (dev->isYaffs2 &&
5080                             sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
5081                             sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
5082
5083                                 blockIndex[nBlocksToScan].seq = sequenceNumber;
5084                                 blockIndex[nBlocksToScan].block = blk;
5085
5086                                 nBlocksToScan++;
5087
5088                                 if (sequenceNumber >= dev->sequenceNumber) {
5089                                         dev->sequenceNumber = sequenceNumber;
5090                                 }
5091                         } else if (dev->isYaffs2) {
5092                                 /* TODO: Nasty sequence number! */
5093                                 T(YAFFS_TRACE_SCAN,
5094                                   (TSTR
5095                                    ("Block scanning block %d has bad sequence number %d"
5096                                     TENDSTR), blk, sequenceNumber));
5097
5098                         }
5099                 }
5100         }
5101
5102         T(YAFFS_TRACE_SCAN,
5103         (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
5104
5105
5106
5107         YYIELD();
5108
5109         /* Sort the blocks */
5110 #ifndef CONFIG_YAFFS_USE_OWN_SORT
5111         {
5112                 /* Use qsort now. */
5113                 qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
5114         }
5115 #else
5116         {
5117                 /* Dungy old bubble sort... */
5118                 
5119                 yaffs_BlockIndex temp;
5120                 int i;
5121                 int j;
5122
5123                 for (i = 0; i < nBlocksToScan; i++)
5124                         for (j = i + 1; j < nBlocksToScan; j++)
5125                                 if (blockIndex[i].seq > blockIndex[j].seq) {
5126                                         temp = blockIndex[j];
5127                                         blockIndex[j] = blockIndex[i];
5128                                         blockIndex[i] = temp;
5129                                 }
5130         }
5131 #endif
5132
5133         YYIELD();
5134
5135         T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
5136
5137         /* Now scan the blocks looking at the data. */
5138         startIterator = 0;
5139         endIterator = nBlocksToScan - 1;
5140         T(YAFFS_TRACE_SCAN_DEBUG,
5141           (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
5142
5143         /* For each block.... backwards */
5144         for (blockIterator = endIterator; blockIterator >= startIterator;
5145              blockIterator--) {
5146                 /* Cooperative multitasking! This loop can run for so
5147                    long that watchdog timers expire. */
5148                 YYIELD();
5149
5150                 /* get the block to scan in the correct order */
5151                 blk = blockIndex[blockIterator].block;
5152
5153                 bi = yaffs_GetBlockInfo(dev, blk);
5154                 state = bi->blockState;
5155
5156                 deleted = 0;
5157
5158                 /* For each chunk in each block that needs scanning.... */
5159                 for (c = dev->nChunksPerBlock - 1; c >= 0 &&
5160                      (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
5161                       state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
5162                         /* Scan backwards... 
5163                          * Read the tags and decide what to do
5164                          */
5165                         chunk = blk * dev->nChunksPerBlock + c;
5166
5167                         yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5168                                                         &tags);
5169
5170                         /* Let's have a good look at this chunk... */
5171
5172                         if (!tags.chunkUsed) {
5173                                 // An unassigned chunk in the block
5174                                 // This means that either the block is empty or 
5175                                 // this is the one being allocated from
5176
5177                                 if (c == 0) {
5178                                         /* We're looking at the first chunk in the block so the block is unused */
5179                                         state = YAFFS_BLOCK_STATE_EMPTY;
5180                                         dev->nErasedBlocks++;
5181                                 } else {
5182                                         /* this is the block being allocated from */
5183                                         if (state ==
5184                                             YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5185                                                 T(YAFFS_TRACE_SCAN,
5186                                                   (TSTR
5187                                                    (" Allocating from %d %d"
5188                                                     TENDSTR), blk, c));
5189                                         }
5190                                         state = YAFFS_BLOCK_STATE_ALLOCATING;
5191                                         dev->allocationBlock = blk;
5192                                         dev->allocationPage = c;
5193                                         dev->allocationBlockFinder = blk;       
5194                                         /* Set it to here to encourage the allocator to 
5195                                          *  go forth from here.
5196                                          */
5197                                          
5198                                         /* Yaffs2 sanity check:
5199                                          * This should be the one with the highest sequence number
5200                                          */
5201                                         if (dev->isYaffs2
5202                                             && (dev->sequenceNumber !=
5203                                                 bi->sequenceNumber)) {
5204                                                 T(YAFFS_TRACE_ALWAYS,
5205                                                   (TSTR
5206                                                    ("yaffs: Allocation block %d was not highest sequence "
5207                                                     "id: block seq = %d, dev seq = %d"
5208                                                     TENDSTR), blk,
5209                                                    bi->sequenceNumber,
5210                                                    dev->sequenceNumber));
5211                                         }
5212                                 }
5213
5214                                 dev->nFreeChunks++;
5215                         } else if (tags.chunkId > 0) {
5216                                 /* chunkId > 0 so it is a data chunk... */
5217                                 unsigned int endpos;
5218
5219                                 __u32 chunkBase =
5220                                     (tags.chunkId - 1) * dev->nBytesPerChunk;
5221
5222                                 yaffs_SetChunkBit(dev, blk, c);
5223                                 bi->pagesInUse++;
5224
5225                                 in = yaffs_FindOrCreateObjectByNumber(dev,
5226                                                                       tags.
5227                                                                       objectId,
5228                                                                       YAFFS_OBJECT_TYPE_FILE);
5229                                 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
5230                                     && chunkBase <
5231                                     in->variant.fileVariant.shrinkSize) {
5232                                         /* This has not been invalidated by a resize */
5233                                         yaffs_PutChunkIntoFile(in, tags.chunkId,
5234                                                                chunk, -1);
5235
5236                                         /* File size is calculated by looking at the data chunks if we have not 
5237                                          * seen an object header yet. Stop this practice once we find an object header.
5238                                          */
5239                                         endpos =
5240                                             (tags.chunkId -
5241                                              1) * dev->nBytesPerChunk +
5242                                             tags.byteCount;
5243                                             
5244                                         if (!in->valid &&       /* have not got an object header yet */
5245                                             in->variant.fileVariant.
5246                                             scannedFileSize < endpos) {
5247                                                 in->variant.fileVariant.
5248                                                     scannedFileSize = endpos;
5249                                                 in->variant.fileVariant.
5250                                                     fileSize =
5251                                                     in->variant.fileVariant.
5252                                                     scannedFileSize;
5253                                         }
5254
5255                                 } else {
5256                                         /* This chunk has been invalidated by a resize, so delete */
5257                                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
5258
5259                                 }
5260                         } else {
5261                                 /* chunkId == 0, so it is an ObjectHeader.
5262                                  * Thus, we read in the object header and make the object
5263                                  */
5264                                 yaffs_SetChunkBit(dev, blk, c);
5265                                 bi->pagesInUse++;
5266
5267                                 oh = NULL;
5268                                 in = NULL;
5269
5270                                 if (tags.extraHeaderInfoAvailable) {
5271                                         in = yaffs_FindOrCreateObjectByNumber
5272                                             (dev, tags.objectId,
5273                                              tags.extraObjectType);
5274                                 }
5275
5276                                 if (!in ||
5277 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
5278                                     !in->valid ||
5279 #endif
5280                                     tags.extraShadows ||
5281                                     (!in->valid &&
5282                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
5283                                      tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
5284                                     ) {
5285
5286                                         /* If we don't have  valid info then we need to read the chunk
5287                                          * TODO In future we can probably defer reading the chunk and 
5288                                          * living with invalid data until needed.
5289                                          */
5290
5291                                         yaffs_ReadChunkWithTagsFromNAND(dev,
5292                                                                         chunk,
5293                                                                         chunkData,
5294                                                                         NULL);
5295
5296                                         oh = (yaffs_ObjectHeader *) chunkData;
5297
5298                                         if (!in)
5299                                                 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
5300
5301                                 }
5302
5303                                 if (!in) {
5304                                         /* TODO Hoosterman we have a problem! */
5305                                         T(YAFFS_TRACE_ERROR,
5306                                           (TSTR
5307                                            ("yaffs tragedy: Could not make object for object  %d  "
5308                                             "at chunk %d during scan"
5309                                             TENDSTR), tags.objectId, chunk));
5310
5311                                 }
5312
5313                                 if (in->valid) {
5314                                         /* We have already filled this one.
5315                                          * We have a duplicate that will be discarded, but 
5316                                          * we first have to suck out resize info if it is a file.
5317                                          */
5318
5319                                         if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) && 
5320                                              ((oh && 
5321                                                oh-> type == YAFFS_OBJECT_TYPE_FILE)||
5322                                               (tags.extraHeaderInfoAvailable  &&
5323                                                tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
5324                                             ) {
5325                                                 __u32 thisSize =
5326                                                     (oh) ? oh->fileSize : tags.
5327                                                     extraFileLength;
5328                                                 __u32 parentObjectId =
5329                                                     (oh) ? oh->
5330                                                     parentObjectId : tags.
5331                                                     extraParentObjectId;
5332                                                 unsigned isShrink =
5333                                                     (oh) ? oh->isShrink : tags.
5334                                                     extraIsShrinkHeader;
5335
5336                                                 /* If it is deleted (unlinked at start also means deleted)
5337                                                  * we treat the file size as being zeroed at this point.
5338                                                  */
5339                                                 if (parentObjectId ==
5340                                                     YAFFS_OBJECTID_DELETED
5341                                                     || parentObjectId ==
5342                                                     YAFFS_OBJECTID_UNLINKED) {
5343                                                         thisSize = 0;
5344                                                         isShrink = 1;
5345                                                 }
5346
5347                                                 if (isShrink &&
5348                                                     in->variant.fileVariant.
5349                                                     shrinkSize > thisSize) {
5350                                                         in->variant.fileVariant.
5351                                                             shrinkSize =
5352                                                             thisSize;
5353                                                 }
5354
5355                                                 if (isShrink) {
5356                                                         bi->hasShrinkHeader = 1;
5357                                                 }
5358
5359                                         }
5360                                         /* Use existing - destroy this one. */
5361                                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
5362
5363                                 }
5364
5365                                 if (!in->valid &&
5366                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
5367                                      tags.objectId ==
5368                                      YAFFS_OBJECTID_LOSTNFOUND)) {
5369                                         /* We only load some info, don't fiddle with directory structure */
5370                                         in->valid = 1;
5371                                         
5372                                         if(oh) {
5373                                                 in->variantType = oh->type;
5374
5375                                                 in->yst_mode = oh->yst_mode;
5376 #ifdef CONFIG_YAFFS_WINCE
5377                                                 in->win_atime[0] = oh->win_atime[0];
5378                                                 in->win_ctime[0] = oh->win_ctime[0];
5379                                                 in->win_mtime[0] = oh->win_mtime[0];
5380                                                 in->win_atime[1] = oh->win_atime[1];
5381                                                 in->win_ctime[1] = oh->win_ctime[1];
5382                                                 in->win_mtime[1] = oh->win_mtime[1];
5383 #else
5384                                                 in->yst_uid = oh->yst_uid;
5385                                                 in->yst_gid = oh->yst_gid;
5386                                                 in->yst_atime = oh->yst_atime;
5387                                                 in->yst_mtime = oh->yst_mtime;
5388                                                 in->yst_ctime = oh->yst_ctime;
5389                                                 in->yst_rdev = oh->yst_rdev;
5390                 
5391 #endif
5392                                         } else {
5393                                                 in->variantType = tags.extraObjectType;
5394                                                 in->lazyLoaded = 1;
5395                                         }
5396                                                 
5397                                         in->chunkId = chunk;
5398
5399                                 } else if (!in->valid) {
5400                                         /* we need to load this info */
5401
5402                                         in->valid = 1;
5403                                         in->chunkId = chunk;
5404                                         
5405                                         if(oh) {
5406                                                 in->variantType = oh->type;
5407
5408                                                 in->yst_mode = oh->yst_mode;
5409 #ifdef CONFIG_YAFFS_WINCE
5410                                                 in->win_atime[0] = oh->win_atime[0];
5411                                                 in->win_ctime[0] = oh->win_ctime[0];
5412                                                 in->win_mtime[0] = oh->win_mtime[0];
5413                                                 in->win_atime[1] = oh->win_atime[1];
5414                                                 in->win_ctime[1] = oh->win_ctime[1];
5415                                                 in->win_mtime[1] = oh->win_mtime[1];
5416 #else
5417                                                 in->yst_uid = oh->yst_uid;
5418                                                 in->yst_gid = oh->yst_gid;
5419                                                 in->yst_atime = oh->yst_atime;
5420                                                 in->yst_mtime = oh->yst_mtime;
5421                                                 in->yst_ctime = oh->yst_ctime;
5422                                                 in->yst_rdev = oh->yst_rdev;
5423 #endif
5424
5425                                                 if (oh->shadowsObject > 0) 
5426                                                         yaffs_HandleShadowedObject(dev,
5427                                                                            oh->
5428                                                                            shadowsObject,
5429                                                                            1);
5430                                         
5431
5432                                                 yaffs_SetObjectName(in, oh->name);
5433                                                 parent =
5434                                                     yaffs_FindOrCreateObjectByNumber
5435                                                         (dev, oh->parentObjectId,
5436                                                          YAFFS_OBJECT_TYPE_DIRECTORY);
5437
5438                                                  fileSize = oh->fileSize;
5439                                                  isShrink = oh->isShrink;
5440                                                  equivalentObjectId = oh->equivalentObjectId;
5441
5442                                         }
5443                                         else {
5444                                                 in->variantType = tags.extraObjectType;
5445                                                 parent =
5446                                                     yaffs_FindOrCreateObjectByNumber
5447                                                         (dev, tags.extraParentObjectId,
5448                                                          YAFFS_OBJECT_TYPE_DIRECTORY);
5449                                                  fileSize = tags.extraFileLength;
5450                                                  isShrink = tags.extraIsShrinkHeader;
5451                                                  equivalentObjectId = tags.extraEquivalentObjectId;
5452                                                 in->lazyLoaded = 1;
5453
5454                                         }
5455                                         in->dirty = 0;
5456
5457                                         /* directory stuff...
5458                                          * hook up to parent
5459                                          */
5460
5461                                         if (parent->variantType ==
5462                                             YAFFS_OBJECT_TYPE_UNKNOWN) {
5463                                                 /* Set up as a directory */
5464                                                 parent->variantType =
5465                                                     YAFFS_OBJECT_TYPE_DIRECTORY;
5466                                                 INIT_LIST_HEAD(&parent->variant.
5467                                                                directoryVariant.
5468                                                                children);
5469                                         } else if (parent->variantType !=
5470                                                    YAFFS_OBJECT_TYPE_DIRECTORY)
5471                                         {
5472                                                 /* Hoosterman, another problem....
5473                                                  * We're trying to use a non-directory as a directory
5474                                                  */
5475
5476                                                 T(YAFFS_TRACE_ERROR,
5477                                                   (TSTR
5478                                                    ("yaffs tragedy: attempting to use non-directory as"
5479                                                     " a directory in scan. Put in lost+found."
5480                                                     TENDSTR)));
5481                                                 parent = dev->lostNFoundDir;
5482                                         }
5483
5484                                         yaffs_AddObjectToDirectory(parent, in);
5485
5486                                         itsUnlinked = (parent == dev->deletedDir) ||
5487                                                       (parent == dev->unlinkedDir);
5488
5489                                         if (isShrink) {
5490                                                 /* Mark the block as having a shrinkHeader */
5491                                                 bi->hasShrinkHeader = 1;
5492                                         }
5493
5494                                         /* Note re hardlinks.
5495                                          * Since we might scan a hardlink before its equivalent object is scanned
5496                                          * we put them all in a list.
5497                                          * After scanning is complete, we should have all the objects, so we run
5498                                          * through this list and fix up all the chains.              
5499                                          */
5500
5501                                         switch (in->variantType) {
5502                                         case YAFFS_OBJECT_TYPE_UNKNOWN: 
5503                                                 /* Todo got a problem */
5504                                                 break;
5505                                         case YAFFS_OBJECT_TYPE_FILE:
5506
5507                                                 if (in->variant.fileVariant.
5508                                                     scannedFileSize < fileSize) {
5509                                                         /* This covers the case where the file size is greater
5510                                                          * than where the data is
5511                                                          * This will happen if the file is resized to be larger 
5512                                                          * than its current data extents.
5513                                                          */
5514                                                         in->variant.fileVariant.fileSize = fileSize;
5515                                                         in->variant.fileVariant.scannedFileSize =
5516                                                             in->variant.fileVariant.fileSize;
5517                                                 }
5518
5519                                                 if (isShrink &&
5520                                                     in->variant.fileVariant.shrinkSize > fileSize) {
5521                                                         in->variant.fileVariant.shrinkSize = fileSize;
5522                                                 }
5523
5524                                                 break;
5525                                         case YAFFS_OBJECT_TYPE_HARDLINK:
5526                                                 if(!itsUnlinked) {
5527                                                   in->variant.hardLinkVariant.equivalentObjectId =
5528                                                     equivalentObjectId;
5529                                                   in->hardLinks.next =
5530                                                     (struct list_head *) hardList;
5531                                                   hardList = in;
5532                                                 }
5533                                                 break;
5534                                         case YAFFS_OBJECT_TYPE_DIRECTORY:
5535                                                 /* Do nothing */
5536                                                 break;
5537                                         case YAFFS_OBJECT_TYPE_SPECIAL:
5538                                                 /* Do nothing */
5539                                                 break;
5540                                         case YAFFS_OBJECT_TYPE_SYMLINK:
5541                                                 if(oh)
5542                                                    in->variant.symLinkVariant.alias =
5543                                                     yaffs_CloneString(oh->
5544                                                                       alias);
5545                                                 break;
5546                                         }
5547
5548                                 }
5549                         }
5550                 }
5551
5552                 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5553                         /* If we got this far while scanning, then the block is fully allocated. */
5554                         state = YAFFS_BLOCK_STATE_FULL;
5555                 }
5556
5557                 bi->blockState = state;
5558
5559                 /* Now let's see if it was dirty */
5560                 if (bi->pagesInUse == 0 &&
5561                     !bi->hasShrinkHeader &&
5562                     bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5563                         yaffs_BlockBecameDirty(dev, blk);
5564                 }
5565
5566         }
5567
5568         if (altBlockIndex) 
5569                 YFREE_ALT(blockIndex);
5570         else
5571                 YFREE(blockIndex);
5572         
5573         /* Ok, we've done all the scanning.
5574          * Fix up the hard link chains.
5575          * We should now have scanned all the objects, now it's time to add these 
5576          * hardlinks.
5577          */
5578         yaffs_HardlinkFixup(dev,hardList);
5579         
5580         
5581         /*
5582         *  Sort out state of unlinked and deleted objects.
5583         */
5584         {
5585                 struct list_head *i;
5586                 struct list_head *n;
5587
5588                 yaffs_Object *l;
5589
5590                 /* Soft delete all the unlinked files */
5591                 list_for_each_safe(i, n,
5592                                    &dev->unlinkedDir->variant.directoryVariant.
5593                                    children) {
5594                         if (i) {
5595                                 l = list_entry(i, yaffs_Object, siblings);
5596                                 yaffs_DestroyObject(l);
5597                         }
5598                 }
5599
5600                 /* Soft delete all the deletedDir files */
5601                 list_for_each_safe(i, n,
5602                                    &dev->deletedDir->variant.directoryVariant.
5603                                    children) {
5604                         if (i) {
5605                                 l = list_entry(i, yaffs_Object, siblings);
5606                                 yaffs_DestroyObject(l);
5607
5608                         }
5609                 }
5610         }
5611
5612         yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5613
5614         T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
5615
5616         return YAFFS_OK;
5617 }
5618
5619 /*------------------------------  Directory Functions ----------------------------- */
5620
5621 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
5622 {
5623         yaffs_Device *dev = obj->myDev;
5624         
5625         if(dev && dev->removeObjectCallback)
5626                 dev->removeObjectCallback(obj);
5627            
5628         list_del_init(&obj->siblings);
5629         obj->parent = NULL;
5630 }
5631
5632
5633 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
5634                                        yaffs_Object * obj)
5635 {
5636
5637         if (!directory) {
5638                 T(YAFFS_TRACE_ALWAYS,
5639                   (TSTR
5640                    ("tragedy: Trying to add an object to a null pointer directory"
5641                     TENDSTR)));
5642                 YBUG();
5643         }
5644         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5645                 T(YAFFS_TRACE_ALWAYS,
5646                   (TSTR
5647                    ("tragedy: Trying to add an object to a non-directory"
5648                     TENDSTR)));
5649                 YBUG();
5650         }
5651
5652         if (obj->siblings.prev == NULL) {
5653                 /* Not initialised */
5654                 INIT_LIST_HEAD(&obj->siblings);
5655
5656         } else if (!list_empty(&obj->siblings)) {
5657                 /* If it is holed up somewhere else, un hook it */
5658                 yaffs_RemoveObjectFromDirectory(obj);
5659         }
5660         /* Now add it */
5661         list_add(&obj->siblings, &directory->variant.directoryVariant.children);
5662         obj->parent = directory;
5663
5664         if (directory == obj->myDev->unlinkedDir
5665             || directory == obj->myDev->deletedDir) {
5666                 obj->unlinked = 1;
5667                 obj->myDev->nUnlinkedFiles++;
5668                 obj->renameAllowed = 0;
5669         }
5670 }
5671
5672 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
5673                                      const YCHAR * name)
5674 {
5675         int sum;
5676
5677         struct list_head *i;
5678         YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
5679
5680         yaffs_Object *l;
5681
5682         if (!name) {
5683                 return NULL;
5684         }
5685
5686         if (!directory) {
5687                 T(YAFFS_TRACE_ALWAYS,
5688                   (TSTR
5689                    ("tragedy: yaffs_FindObjectByName: null pointer directory"
5690                     TENDSTR)));
5691                 YBUG();
5692         }
5693         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5694                 T(YAFFS_TRACE_ALWAYS,
5695                   (TSTR
5696                    ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5697                 YBUG();
5698         }
5699
5700         sum = yaffs_CalcNameSum(name);
5701
5702         list_for_each(i, &directory->variant.directoryVariant.children) {
5703                 if (i) {
5704                         l = list_entry(i, yaffs_Object, siblings);
5705                         
5706                         yaffs_CheckObjectDetailsLoaded(l);
5707
5708                         /* Special case for lost-n-found */
5709                         if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5710                                 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
5711                                         return l;
5712                                 }
5713                         } else if (yaffs_SumCompare(l->sum, sum) || l->chunkId <= 0)    
5714                         {
5715                                 /* LostnFound cunk called Objxxx
5716                                  * Do a real check
5717                                  */
5718                                 yaffs_GetObjectName(l, buffer,
5719                                                     YAFFS_MAX_NAME_LENGTH);
5720                                 if (yaffs_strcmp(name, buffer) == 0) {
5721                                         return l;
5722                                 }
5723
5724                         }
5725                 }
5726         }
5727
5728         return NULL;
5729 }
5730
5731
5732 #if 0
5733 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
5734                                    int (*fn) (yaffs_Object *))
5735 {
5736         struct list_head *i;
5737         yaffs_Object *l;
5738
5739         if (!theDir) {
5740                 T(YAFFS_TRACE_ALWAYS,
5741                   (TSTR
5742                    ("tragedy: yaffs_FindObjectByName: null pointer directory"
5743                     TENDSTR)));
5744                 YBUG();
5745         }
5746         if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5747                 T(YAFFS_TRACE_ALWAYS,
5748                   (TSTR
5749                    ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5750                 YBUG();
5751         }
5752
5753         list_for_each(i, &theDir->variant.directoryVariant.children) {
5754                 if (i) {
5755                         l = list_entry(i, yaffs_Object, siblings);
5756                         if (l && !fn(l)) {
5757                                 return YAFFS_FAIL;
5758                         }
5759                 }
5760         }
5761
5762         return YAFFS_OK;
5763
5764 }
5765 #endif
5766
5767 /* GetEquivalentObject dereferences any hard links to get to the
5768  * actual object.
5769  */
5770
5771 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
5772 {
5773         if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5774                 /* We want the object id of the equivalent object, not this one */
5775                 obj = obj->variant.hardLinkVariant.equivalentObject;
5776         }
5777         return obj;
5778
5779 }
5780
5781 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
5782 {
5783         memset(name, 0, buffSize * sizeof(YCHAR));
5784         
5785         yaffs_CheckObjectDetailsLoaded(obj);
5786
5787         if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5788                 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
5789         } else if (obj->chunkId <= 0) {
5790                 YCHAR locName[20];
5791                 /* make up a name */
5792                 yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX,
5793                               obj->objectId);
5794                 yaffs_strncpy(name, locName, buffSize - 1);
5795
5796         }
5797 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
5798         else if (obj->shortName[0]) {
5799                 yaffs_strcpy(name, obj->shortName);
5800         }
5801 #endif
5802         else {
5803                 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
5804
5805                 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
5806
5807                 memset(buffer, 0, obj->myDev->nBytesPerChunk);
5808
5809                 if (obj->chunkId >= 0) {
5810                         yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
5811                                                         obj->chunkId, buffer,
5812                                                         NULL);
5813                 }
5814                 yaffs_strncpy(name, oh->name, buffSize - 1);
5815
5816                 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
5817         }
5818
5819         return yaffs_strlen(name);
5820 }
5821
5822 int yaffs_GetObjectFileLength(yaffs_Object * obj)
5823 {
5824
5825         /* Dereference any hard linking */
5826         obj = yaffs_GetEquivalentObject(obj);
5827
5828         if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
5829                 return obj->variant.fileVariant.fileSize;
5830         }
5831         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
5832                 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5833         } else {
5834                 /* Only a directory should drop through to here */
5835                 return obj->myDev->nBytesPerChunk;
5836         }
5837 }
5838
5839 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
5840 {
5841         int count = 0;
5842         struct list_head *i;
5843
5844         if (!obj->unlinked) {
5845                 count++;        /* the object itself */
5846         }
5847         list_for_each(i, &obj->hardLinks) {
5848                 count++;        /* add the hard links; */
5849         }
5850         return count;
5851
5852 }
5853
5854 int yaffs_GetObjectInode(yaffs_Object * obj)
5855 {
5856         obj = yaffs_GetEquivalentObject(obj);
5857
5858         return obj->objectId;
5859 }
5860
5861 unsigned yaffs_GetObjectType(yaffs_Object * obj)
5862 {
5863         obj = yaffs_GetEquivalentObject(obj);
5864
5865         switch (obj->variantType) {
5866         case YAFFS_OBJECT_TYPE_FILE:
5867                 return DT_REG;
5868                 break;
5869         case YAFFS_OBJECT_TYPE_DIRECTORY:
5870                 return DT_DIR;
5871                 break;
5872         case YAFFS_OBJECT_TYPE_SYMLINK:
5873                 return DT_LNK;
5874                 break;
5875         case YAFFS_OBJECT_TYPE_HARDLINK:
5876                 return DT_REG;
5877                 break;
5878         case YAFFS_OBJECT_TYPE_SPECIAL:
5879                 if (S_ISFIFO(obj->yst_mode))
5880                         return DT_FIFO;
5881                 if (S_ISCHR(obj->yst_mode))
5882                         return DT_CHR;
5883                 if (S_ISBLK(obj->yst_mode))
5884                         return DT_BLK;
5885                 if (S_ISSOCK(obj->yst_mode))
5886                         return DT_SOCK;
5887         default:
5888                 return DT_REG;
5889                 break;
5890         }
5891 }
5892
5893 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
5894 {
5895         obj = yaffs_GetEquivalentObject(obj);
5896         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
5897                 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
5898         } else {
5899                 return yaffs_CloneString(_Y(""));
5900         }
5901 }
5902
5903 #ifndef CONFIG_YAFFS_WINCE
5904
5905 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
5906 {
5907         unsigned int valid = attr->ia_valid;
5908
5909         if (valid & ATTR_MODE)
5910                 obj->yst_mode = attr->ia_mode;
5911         if (valid & ATTR_UID)
5912                 obj->yst_uid = attr->ia_uid;
5913         if (valid & ATTR_GID)
5914                 obj->yst_gid = attr->ia_gid;
5915
5916         if (valid & ATTR_ATIME)
5917                 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
5918         if (valid & ATTR_CTIME)
5919                 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
5920         if (valid & ATTR_MTIME)
5921                 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
5922
5923         if (valid & ATTR_SIZE)
5924                 yaffs_ResizeFile(obj, attr->ia_size);
5925
5926         yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
5927
5928         return YAFFS_OK;
5929
5930 }
5931 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
5932 {
5933         unsigned int valid = 0;
5934
5935         attr->ia_mode = obj->yst_mode;
5936         valid |= ATTR_MODE;
5937         attr->ia_uid = obj->yst_uid;
5938         valid |= ATTR_UID;
5939         attr->ia_gid = obj->yst_gid;
5940         valid |= ATTR_GID;
5941
5942         Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
5943         valid |= ATTR_ATIME;
5944         Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
5945         valid |= ATTR_CTIME;
5946         Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
5947         valid |= ATTR_MTIME;
5948
5949         attr->ia_size = yaffs_GetFileSize(obj);
5950         valid |= ATTR_SIZE;
5951
5952         attr->ia_valid = valid;
5953
5954         return YAFFS_OK;
5955
5956 }
5957
5958 #endif
5959
5960 #if 0
5961 int yaffs_DumpObject(yaffs_Object * obj)
5962 {
5963         YCHAR name[257];
5964
5965         yaffs_GetObjectName(obj, name, 256);
5966
5967         T(YAFFS_TRACE_ALWAYS,
5968           (TSTR
5969            ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
5970             " chunk %d type %d size %d\n"
5971             TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
5972            obj->dirty, obj->valid, obj->serial, obj->sum, obj->chunkId,
5973            yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
5974
5975         return YAFFS_OK;
5976 }
5977 #endif
5978
5979 /*---------------------------- Initialisation code -------------------------------------- */
5980
5981 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
5982 {
5983
5984         /* Common functions, gotta have */
5985         if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
5986                 return 0;
5987
5988 #ifdef CONFIG_YAFFS_YAFFS2
5989
5990         /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
5991         if (dev->writeChunkWithTagsToNAND &&
5992             dev->readChunkWithTagsFromNAND &&
5993             !dev->writeChunkToNAND &&
5994             !dev->readChunkFromNAND &&
5995             dev->markNANDBlockBad && dev->queryNANDBlock)
5996                 return 1;
5997 #endif
5998
5999         /* Can use the "spare" style interface for yaffs1 */
6000         if (!dev->isYaffs2 &&
6001             !dev->writeChunkWithTagsToNAND &&
6002             !dev->readChunkWithTagsFromNAND &&
6003             dev->writeChunkToNAND &&
6004             dev->readChunkFromNAND &&
6005             !dev->markNANDBlockBad && !dev->queryNANDBlock)
6006                 return 1;
6007
6008         return 0;               /* bad */
6009 }
6010
6011
6012 static void yaffs_CreateInitialDirectories(yaffs_Device *dev)
6013 {
6014         /* Initialise the unlinked, deleted, root and lost and found directories */
6015         
6016         dev->lostNFoundDir = dev->rootDir =  NULL;
6017         dev->unlinkedDir = dev->deletedDir = NULL;
6018
6019         dev->unlinkedDir =
6020             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
6021         dev->deletedDir =
6022             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
6023
6024         dev->rootDir =
6025             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
6026                                       YAFFS_ROOT_MODE | S_IFDIR);
6027         dev->lostNFoundDir =
6028             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
6029                                       YAFFS_LOSTNFOUND_MODE | S_IFDIR);
6030         yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
6031 }
6032
6033 int yaffs_GutsInitialise(yaffs_Device * dev)
6034 {
6035         unsigned x;
6036         int bits;
6037         int extraBits;
6038
6039         T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
6040
6041         /* Check stuff that must be set */
6042
6043         if (!dev) {
6044                 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
6045                 return YAFFS_FAIL;
6046         }
6047
6048         dev->internalStartBlock = dev->startBlock;
6049         dev->internalEndBlock = dev->endBlock;
6050         dev->blockOffset = 0;
6051         dev->chunkOffset = 0;
6052         dev->nFreeChunks = 0;
6053
6054         if (dev->startBlock == 0) {
6055                 dev->internalStartBlock = dev->startBlock + 1;
6056                 dev->internalEndBlock = dev->endBlock + 1;
6057                 dev->blockOffset = 1;
6058                 dev->chunkOffset = dev->nChunksPerBlock;
6059         }
6060
6061         /* Check geometry parameters. */
6062
6063         if ((dev->isYaffs2 && dev->nBytesPerChunk < 1024) || 
6064             (!dev->isYaffs2 && dev->nBytesPerChunk != 512) || 
6065              dev->nChunksPerBlock < 2 || 
6066              dev->nReservedBlocks < 2 || 
6067              dev->internalStartBlock <= 0 || 
6068              dev->internalEndBlock <= 0 || 
6069              dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2)      // otherwise it is too small
6070             ) {
6071                 T(YAFFS_TRACE_ALWAYS,
6072                   (TSTR
6073                    ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s "
6074                     TENDSTR), dev->nBytesPerChunk, dev->isYaffs2 ? "2" : ""));
6075                 return YAFFS_FAIL;
6076         }
6077
6078         if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
6079                 T(YAFFS_TRACE_ALWAYS,
6080                   (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
6081                 return YAFFS_FAIL;
6082         }
6083
6084         /* Got the right mix of functions? */
6085         if (!yaffs_CheckDevFunctions(dev)) {
6086                 /* Function missing */
6087                 T(YAFFS_TRACE_ALWAYS,
6088                   (TSTR
6089                    ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
6090
6091                 return YAFFS_FAIL;
6092         }
6093
6094         /* This is really a compilation check. */
6095         if (!yaffs_CheckStructures()) {
6096                 T(YAFFS_TRACE_ALWAYS,
6097                   (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
6098                 return YAFFS_FAIL;
6099         }
6100
6101         if (dev->isMounted) {
6102                 T(YAFFS_TRACE_ALWAYS,
6103                   (TSTR("yaffs: device already mounted\n" TENDSTR)));
6104                 return YAFFS_FAIL;
6105         }
6106
6107         /* Finished with most checks. One or two more checks happen later on too. */
6108
6109         dev->isMounted = 1;
6110
6111
6112
6113         /* OK now calculate a few things for the device
6114          * Calculate chunkGroupBits.
6115          * We need to find the next power of 2 > than internalEndBlock
6116          */
6117
6118         x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
6119
6120         for (bits = extraBits = 0; x > 1; bits++) {
6121                 if (x & 1)
6122                         extraBits++;
6123                 x >>= 1;
6124         }
6125
6126         if (extraBits > 0)
6127                 bits++;
6128         
6129         /* Set up tnode width if wide tnodes are enabled. */
6130         if(!dev->wideTnodesDisabled){
6131                 /* bits must be even so that we end up with 32-bit words */
6132                 if(bits & 1)
6133                         bits++;
6134                 if(bits < 16)
6135                         dev->tnodeWidth = 16;
6136                 else
6137                         dev->tnodeWidth = bits;
6138         }
6139         else
6140                 dev->tnodeWidth = 16;
6141  
6142         dev->tnodeMask = (1<<dev->tnodeWidth)-1;
6143                 
6144         /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
6145          * so if the bitwidth of the
6146          * chunk range we're using is greater than 16 we need
6147          * to figure out chunk shift and chunkGroupSize
6148          */
6149                  
6150         if (bits <= dev->tnodeWidth)
6151                 dev->chunkGroupBits = 0;
6152         else
6153                 dev->chunkGroupBits = bits - dev->tnodeWidth;
6154                 
6155
6156         dev->chunkGroupSize = 1 << dev->chunkGroupBits;
6157
6158         if (dev->nChunksPerBlock < dev->chunkGroupSize) {
6159                 /* We have a problem because the soft delete won't work if
6160                  * the chunk group size > chunks per block.
6161                  * This can be remedied by using larger "virtual blocks".
6162                  */
6163                 T(YAFFS_TRACE_ALWAYS,
6164                   (TSTR("yaffs: chunk group too large\n" TENDSTR)));
6165
6166                 return YAFFS_FAIL;
6167         }
6168
6169         /* OK, we've finished verifying the device, lets continue with initialisation */
6170
6171         /* More device initialisation */
6172         dev->garbageCollections = 0;
6173         dev->passiveGarbageCollections = 0;
6174         dev->currentDirtyChecker = 0;
6175         dev->bufferedBlock = -1;
6176         dev->doingBufferedBlockRewrite = 0;
6177         dev->nDeletedFiles = 0;
6178         dev->nBackgroundDeletions = 0;
6179         dev->nUnlinkedFiles = 0;
6180         dev->eccFixed = 0;
6181         dev->eccUnfixed = 0;
6182         dev->tagsEccFixed = 0;
6183         dev->tagsEccUnfixed = 0;
6184         dev->nErasureFailures = 0;
6185         dev->nErasedBlocks = 0;
6186         dev->isDoingGC = 0;
6187
6188         /* Initialise temporary buffers and caches. */
6189         {
6190                 int i;
6191                 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
6192                         dev->tempBuffer[i].line = 0;    /* not in use */
6193                         dev->tempBuffer[i].buffer =
6194                             YMALLOC_DMA(dev->nBytesPerChunk);
6195                 }
6196         }
6197         
6198         if (dev->nShortOpCaches > 0) {
6199                 int i;
6200
6201                 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
6202                         dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
6203                 }
6204
6205                 dev->srCache =
6206                     YMALLOC(dev->nShortOpCaches * sizeof(yaffs_ChunkCache));
6207
6208                 for (i = 0; i < dev->nShortOpCaches; i++) {
6209                         dev->srCache[i].object = NULL;
6210                         dev->srCache[i].lastUse = 0;
6211                         dev->srCache[i].dirty = 0;
6212                         dev->srCache[i].data = YMALLOC_DMA(dev->nBytesPerChunk);
6213                 }
6214                 dev->srLastUse = 0;
6215         }
6216
6217         dev->cacheHits = 0;
6218         
6219         dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
6220
6221         if (dev->isYaffs2) {
6222                 dev->useHeaderFileSize = 1;
6223         }
6224
6225         yaffs_InitialiseBlocks(dev);
6226         yaffs_InitialiseTnodes(dev);
6227         yaffs_InitialiseObjects(dev);
6228
6229         yaffs_CreateInitialDirectories(dev);
6230
6231
6232         /* Now scan the flash. */
6233         if (dev->isYaffs2) {
6234                 if(yaffs_CheckpointRestore(dev)) {
6235                         T(YAFFS_TRACE_ALWAYS,
6236                           (TSTR("yaffs: restored from checkpoint" TENDSTR)));
6237                 } else {
6238
6239                         /* Clean up the mess caused by an aborted checkpoint load 
6240                          * and scan backwards. 
6241                          */
6242                         yaffs_DeinitialiseBlocks(dev);
6243                         yaffs_DeinitialiseTnodes(dev);
6244                         yaffs_DeinitialiseObjects(dev);
6245                         yaffs_InitialiseBlocks(dev);
6246                         yaffs_InitialiseTnodes(dev);
6247                         yaffs_InitialiseObjects(dev);
6248                         yaffs_CreateInitialDirectories(dev);
6249
6250                         yaffs_ScanBackwards(dev);
6251                 }
6252         }else
6253                 yaffs_Scan(dev);
6254
6255         /* Zero out stats */
6256         dev->nPageReads = 0;
6257         dev->nPageWrites = 0;
6258         dev->nBlockErasures = 0;
6259         dev->nGCCopies = 0;
6260         dev->nRetriedWrites = 0;
6261
6262         dev->nRetiredBlocks = 0;
6263
6264         yaffs_VerifyFreeChunks(dev);
6265
6266         T(YAFFS_TRACE_TRACING,
6267           (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
6268         return YAFFS_OK;
6269
6270 }
6271
6272 void yaffs_Deinitialise(yaffs_Device * dev)
6273 {
6274         if (dev->isMounted) {
6275                 int i;
6276
6277                 yaffs_DeinitialiseBlocks(dev);
6278                 yaffs_DeinitialiseTnodes(dev);
6279                 yaffs_DeinitialiseObjects(dev);
6280                 if (dev->nShortOpCaches > 0) {
6281
6282                         for (i = 0; i < dev->nShortOpCaches; i++) {
6283                                 YFREE(dev->srCache[i].data);
6284                         }
6285
6286                         YFREE(dev->srCache);
6287                 }
6288
6289                 YFREE(dev->gcCleanupList);
6290
6291                 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
6292                         YFREE(dev->tempBuffer[i].buffer);
6293                 }
6294
6295                 dev->isMounted = 0;
6296         }
6297
6298 }
6299
6300 static int yaffs_CountFreeChunks(yaffs_Device * dev)
6301 {
6302         int nFree;
6303         int b;
6304
6305         yaffs_BlockInfo *blk;
6306
6307         for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
6308              b++) {
6309                 blk = yaffs_GetBlockInfo(dev, b);
6310
6311                 switch (blk->blockState) {
6312                 case YAFFS_BLOCK_STATE_EMPTY:
6313                 case YAFFS_BLOCK_STATE_ALLOCATING:
6314                 case YAFFS_BLOCK_STATE_COLLECTING:
6315                 case YAFFS_BLOCK_STATE_FULL:
6316                         nFree +=
6317                             (dev->nChunksPerBlock - blk->pagesInUse +
6318                              blk->softDeletions);
6319                         break;
6320                 default:
6321                         break;
6322                 }
6323
6324         }
6325
6326         return nFree;
6327 }
6328
6329 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
6330 {
6331         /* This is what we report to the outside world */
6332
6333         int nFree;
6334         int nDirtyCacheChunks;
6335         int blocksForCheckpoint;
6336
6337 #if 1
6338         nFree = dev->nFreeChunks;
6339 #else
6340         nFree = yaffs_CountFreeChunks(dev);
6341 #endif
6342
6343         nFree += dev->nDeletedFiles;
6344         
6345         /* Now count the number of dirty chunks in the cache and subtract those */
6346
6347         {
6348                 int i;
6349                 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
6350                         if (dev->srCache[i].dirty)
6351                                 nDirtyCacheChunks++;
6352                 }
6353         }
6354
6355         nFree -= nDirtyCacheChunks;
6356
6357         nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
6358         
6359         /* Now we figure out how much to reserve for the checkpoint and report that... */
6360         blocksForCheckpoint = dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
6361         if(blocksForCheckpoint < 0)
6362                 blocksForCheckpoint = 0;
6363                 
6364         nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
6365
6366         if (nFree < 0)
6367                 nFree = 0;
6368
6369         return nFree;
6370
6371 }
6372
6373 static int yaffs_freeVerificationFailures;
6374
6375 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
6376 {
6377         int counted = yaffs_CountFreeChunks(dev);
6378
6379         int difference = dev->nFreeChunks - counted;
6380
6381         if (difference) {
6382                 T(YAFFS_TRACE_ALWAYS,
6383                   (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
6384                    dev->nFreeChunks, counted, difference));
6385                 yaffs_freeVerificationFailures++;
6386         }
6387 }
6388
6389 /*---------------------------------------- YAFFS test code ----------------------*/
6390
6391 #define yaffs_CheckStruct(structure,syze, name) \
6392            if(sizeof(structure) != syze) \
6393                { \
6394                  T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
6395                  name,syze,sizeof(structure))); \
6396                  return YAFFS_FAIL; \
6397                 }
6398
6399 static int yaffs_CheckStructures(void)
6400 {
6401 /*      yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags") */
6402 /*      yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion") */
6403 /*      yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare") */
6404 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
6405         yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode")
6406 #endif
6407             yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader")
6408
6409             return YAFFS_OK;
6410 }