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