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