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