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