Fix problem introduced my mv over fix
[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.19 2005-09-20 05:08:50 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         
1751         /* Set up dynamic blockinfo stuff. */
1752         dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8;
1753         dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
1754         if (dev->blockInfo && dev->chunkBits) {
1755                 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
1756                 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
1757                 return YAFFS_OK;
1758         }
1759
1760         return YAFFS_FAIL;
1761
1762 }
1763
1764 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
1765 {
1766         YFREE(dev->blockInfo);
1767         dev->blockInfo = NULL;
1768         YFREE(dev->chunkBits);
1769         dev->chunkBits = NULL;
1770 }
1771
1772 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
1773                                             yaffs_BlockInfo * bi)
1774 {
1775         int i;
1776         __u32 seq;
1777         yaffs_BlockInfo *b;
1778
1779         if (!dev->isYaffs2)
1780                 return 1;       /* disqualification only applies to yaffs2. */
1781
1782         if (!bi->hasShrinkHeader)
1783                 return 1;       /* can gc */
1784
1785         /* Find the oldest dirty sequence number if we don't know it and save it
1786          * so we don't have to keep recomputing it.
1787          */
1788         if (!dev->oldestDirtySequence) {
1789                 seq = dev->sequenceNumber;
1790
1791                 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
1792                      i++) {
1793                         b = yaffs_GetBlockInfo(dev, i);
1794                         if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
1795                             (b->pagesInUse - b->softDeletions) <
1796                             dev->nChunksPerBlock && b->sequenceNumber < seq) {
1797                                 seq = b->sequenceNumber;
1798                         }
1799                 }
1800                 dev->oldestDirtySequence = seq;
1801         }
1802
1803         /* Can't do gc of this block if there are any blocks older than this one that have
1804          * discarded pages.
1805          */
1806         return (bi->sequenceNumber <= dev->oldestDirtySequence);
1807
1808         return 1;
1809
1810 }
1811
1812 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
1813  * for garbage collection.
1814  */
1815
1816 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
1817                                                int aggressive)
1818 {
1819
1820         int b = dev->currentDirtyChecker;
1821
1822         int i;
1823         int iterations;
1824         int dirtiest = -1;
1825         int pagesInUse;
1826         yaffs_BlockInfo *bi;
1827         static int nonAggressiveSkip = 0;
1828
1829         /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
1830          * search harder.
1831          * else (we're doing a leasurely gc), then we only bother to do this if the
1832          * block has only a few pages in use.
1833          */
1834
1835         nonAggressiveSkip--;
1836
1837         if (!aggressive && (nonAggressiveSkip > 0)) {
1838                 return -1;
1839         }
1840
1841         pagesInUse =
1842             (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
1843
1844         if (aggressive) {
1845                 iterations =
1846                     dev->internalEndBlock - dev->internalStartBlock + 1;
1847         } else {
1848                 iterations =
1849                     dev->internalEndBlock - dev->internalStartBlock + 1;
1850                 iterations = iterations / 16;
1851                 if (iterations > 200) {
1852                         iterations = 200;
1853                 }
1854         }
1855
1856         for (i = 0; i <= iterations && pagesInUse > 0; i++) {
1857                 b++;
1858                 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
1859                         b = dev->internalStartBlock;
1860                 }
1861
1862                 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
1863                         T(YAFFS_TRACE_ERROR,
1864                           (TSTR("**>> Block %d is not valid" TENDSTR), b));
1865                         YBUG();
1866                 }
1867
1868                 bi = yaffs_GetBlockInfo(dev, b);
1869
1870                 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
1871                     (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
1872                     yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
1873                         dirtiest = b;
1874                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
1875                 }
1876         }
1877
1878         dev->currentDirtyChecker = b;
1879
1880         if (dirtiest > 0) {
1881                 T(YAFFS_TRACE_GC,
1882                   (TSTR("GC Selected block %d with %d free" TENDSTR), dirtiest,
1883                    dev->nChunksPerBlock - pagesInUse));
1884         }
1885
1886         dev->oldestDirtySequence = 0;
1887
1888         if (dirtiest > 0) {
1889                 nonAggressiveSkip = 4;
1890         }
1891
1892         return dirtiest;
1893 }
1894
1895 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
1896 {
1897         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
1898
1899         int erasedOk = 0;
1900
1901         /* If the block is still healthy erase it and mark as clean.
1902          * If the block has had a data failure, then retire it.
1903          */
1904         bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
1905
1906         if (!bi->needsRetiring) {
1907                 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
1908                 if (!erasedOk) {
1909                         dev->nErasureFailures++;
1910                         T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1911                           (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
1912                 }
1913         }
1914
1915         if (erasedOk && (yaffs_traceMask & YAFFS_TRACE_ERASE)) {
1916                 int i;
1917                 for (i = 0; i < dev->nChunksPerBlock; i++) {
1918                         if (!yaffs_CheckChunkErased
1919                             (dev, blockNo * dev->nChunksPerBlock + i)) {
1920                                 T(YAFFS_TRACE_ERROR,
1921                                   (TSTR
1922                                    (">>Block %d erasure supposedly OK, but chunk %d not erased"
1923                                     TENDSTR), blockNo, i));
1924                         }
1925                 }
1926         }
1927
1928         if (erasedOk) {
1929                 /* Clean it up... */
1930                 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
1931                 dev->nErasedBlocks++;
1932                 bi->pagesInUse = 0;
1933                 bi->softDeletions = 0;
1934                 bi->hasShrinkHeader = 0;
1935                 yaffs_ClearChunkBits(dev, blockNo);
1936
1937                 T(YAFFS_TRACE_ERASE,
1938                   (TSTR("Erased block %d" TENDSTR), blockNo));
1939         } else {
1940                 dev->nFreeChunks -= dev->nChunksPerBlock;       /* We lost a block of free space */
1941
1942                 yaffs_RetireBlock(dev, blockNo);
1943                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1944                   (TSTR("**>> Block %d retired" TENDSTR), blockNo));
1945         }
1946 }
1947
1948 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
1949 {
1950         int i;
1951
1952         yaffs_BlockInfo *bi;
1953
1954         if (dev->nErasedBlocks < 1) {
1955                 /* Hoosterman we've got a problem.
1956                  * Can't get space to gc
1957                  */
1958                 T(YAFFS_TRACE_ERROR,
1959                   (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
1960
1961                 return -1;
1962         }
1963         
1964         /* Find an empty block. */
1965
1966         for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
1967                 dev->allocationBlockFinder++;
1968                 if (dev->allocationBlockFinder < dev->internalStartBlock
1969                     || dev->allocationBlockFinder > dev->internalEndBlock) {
1970                         dev->allocationBlockFinder = dev->internalStartBlock;
1971                 }
1972
1973                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
1974
1975                 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
1976                         bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
1977                         dev->sequenceNumber++;
1978                         bi->sequenceNumber = dev->sequenceNumber;
1979                         dev->nErasedBlocks--;
1980                         T(YAFFS_TRACE_ALLOCATE,
1981                           (TSTR("Allocated block %d, seq  %d, %d left" TENDSTR),
1982                            dev->allocationBlockFinder, dev->sequenceNumber,
1983                            dev->nErasedBlocks));
1984                         return dev->allocationBlockFinder;
1985                 }
1986         }
1987
1988         T(YAFFS_TRACE_ALWAYS,
1989           (TSTR
1990            ("yaffs tragedy: no more eraased blocks, but there should have been %d"
1991             TENDSTR), dev->nErasedBlocks));
1992
1993         return -1;
1994 }
1995
1996
1997
1998 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
1999 {
2000         int reservedChunks = (dev->nReservedBlocks * dev->nChunksPerBlock);
2001         return (dev->nFreeChunks > reservedChunks);
2002 }
2003
2004 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve)
2005 {
2006         int retVal;
2007         yaffs_BlockInfo *bi;
2008
2009         if (dev->allocationBlock < 0) {
2010                 /* Get next block to allocate off */
2011                 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2012                 dev->allocationPage = 0;
2013         }
2014
2015         if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2016                 /* Not enough space to allocate unless we're allowed to use the reserve. */
2017                 return -1;
2018         }
2019
2020         if (dev->nErasedBlocks < dev->nReservedBlocks
2021             && dev->allocationPage == 0) {
2022                 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2023         }
2024
2025         /* Next page please.... */
2026         if (dev->allocationBlock >= 0) {
2027                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2028
2029                 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2030                     dev->allocationPage;
2031                 bi->pagesInUse++;
2032                 yaffs_SetChunkBit(dev, dev->allocationBlock,
2033                                   dev->allocationPage);
2034
2035                 dev->allocationPage++;
2036
2037                 dev->nFreeChunks--;
2038
2039                 /* If the block is full set the state to full */
2040                 if (dev->allocationPage >= dev->nChunksPerBlock) {
2041                         bi->blockState = YAFFS_BLOCK_STATE_FULL;
2042                         dev->allocationBlock = -1;
2043                 }
2044
2045                 return retVal;
2046         }
2047         
2048         T(YAFFS_TRACE_ERROR,
2049           (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2050
2051         return -1;
2052 }
2053
2054 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2055 {
2056         int n;
2057
2058         n = dev->nErasedBlocks * dev->nChunksPerBlock;
2059
2060         if (dev->allocationBlock > 0) {
2061                 n += (dev->nChunksPerBlock - dev->allocationPage);
2062         }
2063
2064         return n;
2065
2066 }
2067
2068 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2069 {
2070         int oldChunk;
2071         int newChunk;
2072         int chunkInBlock;
2073         int markNAND;
2074         int retVal = YAFFS_OK;
2075         int cleanups = 0;
2076         int i;
2077
2078         int chunksBefore = yaffs_GetErasedChunks(dev);
2079         int chunksAfter;
2080
2081         yaffs_ExtendedTags tags;
2082
2083         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2084
2085         yaffs_Object *object;
2086
2087         bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2088
2089         T(YAFFS_TRACE_TRACING,
2090           (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2091            bi->pagesInUse, bi->hasShrinkHeader));
2092
2093         /*yaffs_VerifyFreeChunks(dev); */
2094
2095         bi->hasShrinkHeader = 0;        /* clear the flag so that the block can erase */
2096
2097         /* Take off the number of soft deleted entries because
2098          * they're going to get really deleted during GC.
2099          */
2100         dev->nFreeChunks -= bi->softDeletions;
2101
2102         dev->isDoingGC = 1;
2103
2104         if (!yaffs_StillSomeChunkBits(dev, block)) {
2105                 T(YAFFS_TRACE_TRACING,
2106                   (TSTR
2107                    ("Collecting block %d that has no chunks in use" TENDSTR),
2108                    block));
2109                 yaffs_BlockBecameDirty(dev, block);
2110         } else {
2111
2112                 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2113
2114                 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
2115                      chunkInBlock < dev->nChunksPerBlock
2116                      && yaffs_StillSomeChunkBits(dev, block);
2117                      chunkInBlock++, oldChunk++) {
2118                         if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
2119
2120                                 /* This page is in use and might need to be copied off */
2121
2122                                 markNAND = 1;
2123
2124                                 yaffs_InitialiseTags(&tags);
2125
2126                                 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2127                                                                 buffer, &tags);
2128
2129                                 object =
2130                                     yaffs_FindObjectByNumber(dev,
2131                                                              tags.objectId);
2132
2133                                 T(YAFFS_TRACE_GC_DETAIL,
2134                                   (TSTR
2135                                    ("Collecting page %d, %d %d %d " TENDSTR),
2136                                    chunkInBlock, tags.objectId, tags.chunkId,
2137                                    tags.byteCount));
2138
2139                                 if (!object) {
2140                                         T(YAFFS_TRACE_ERROR,
2141                                           (TSTR
2142                                            ("page %d in gc has no object "
2143                                             TENDSTR), oldChunk));
2144                                 }
2145
2146                                 if (object && object->deleted
2147                                     && tags.chunkId != 0) {
2148                                         /* Data chunk in a deleted file, throw it away
2149                                          * It's a soft deleted data chunk,
2150                                          * No need to copy this, just forget about it and 
2151                                          * fix up the object.
2152                                          */
2153
2154                                         object->nDataChunks--;
2155
2156                                         if (object->nDataChunks <= 0) {
2157                                                 /* remeber to clean up the object */
2158                                                 dev->gcCleanupList[cleanups] =
2159                                                     tags.objectId;
2160                                                 cleanups++;
2161                                         }
2162                                         markNAND = 0;
2163                                 } else if (0
2164                                            /* Todo object && object->deleted && object->nDataChunks == 0 */
2165                                            ) {
2166                                         /* Deleted object header with no data chunks.
2167                                          * Can be discarded and the file deleted.
2168                                          */
2169                                         object->chunkId = 0;
2170                                         yaffs_FreeTnode(object->myDev,
2171                                                         object->variant.
2172                                                         fileVariant.top);
2173                                         object->variant.fileVariant.top = NULL;
2174                                         yaffs_DoGenericObjectDeletion(object);
2175
2176                                 } else if (object) {
2177                                         /* It's either a data chunk in a live file or
2178                                          * an ObjectHeader, so we're interested in it.
2179                                          * NB Need to keep the ObjectHeaders of deleted files
2180                                          * until the whole file has been deleted off
2181                                          */
2182                                         tags.serialNumber++;
2183
2184                                         dev->nGCCopies++;
2185
2186                                         if (tags.chunkId == 0) {
2187                                                 /* It is an object Id,
2188                                                  * We need to nuke the shrinkheader flags first
2189                                                  * We no longer want the shrinkHeader flag since its work is done
2190                                                  * and if it is left in place it will mess up scanning.
2191                                                  * Also, clear out any shadowing stuff
2192                                                  */
2193
2194                                                 yaffs_ObjectHeader *oh;
2195                                                 oh = (yaffs_ObjectHeader *)buffer;
2196                                                 oh->isShrink = 0;
2197                                                 oh->shadowsObject = -1;
2198                                                 tags.extraShadows = 0;
2199                                                 tags.extraIsShrinkHeader = 0;
2200                                         }
2201
2202                                         newChunk =
2203                                             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
2204
2205                                         if (newChunk < 0) {
2206                                                 retVal = YAFFS_FAIL;
2207                                         } else {
2208
2209                                                 /* Ok, now fix up the Tnodes etc. */
2210
2211                                                 if (tags.chunkId == 0) {
2212                                                         /* It's a header */
2213                                                         object->chunkId =  newChunk;
2214                                                         object->serial =   tags.serialNumber;
2215                                                 } else {
2216                                                         /* It's a data chunk */
2217                                                         yaffs_PutChunkIntoFile
2218                                                             (object,
2219                                                              tags.chunkId,
2220                                                              newChunk, 0);
2221                                                 }
2222                                         }
2223                                 }
2224
2225                                 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
2226
2227                         }
2228                 }
2229
2230                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2231
2232
2233                 /* Do any required cleanups */
2234                 for (i = 0; i < cleanups; i++) {
2235                         /* Time to delete the file too */
2236                         object =
2237                             yaffs_FindObjectByNumber(dev,
2238                                                      dev->gcCleanupList[i]);
2239                         if (object) {
2240                                 yaffs_FreeTnode(dev,
2241                                                 object->variant.fileVariant.
2242                                                 top);
2243                                 object->variant.fileVariant.top = NULL;
2244                                 T(YAFFS_TRACE_GC,
2245                                   (TSTR
2246                                    ("yaffs: About to finally delete object %d"
2247                                     TENDSTR), object->objectId));
2248                                 yaffs_DoGenericObjectDeletion(object);
2249                         }
2250
2251                 }
2252
2253         }
2254
2255         if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
2256                 T(YAFFS_TRACE_GC,
2257                   (TSTR
2258                    ("gc did not increase free chunks before %d after %d"
2259                     TENDSTR), chunksBefore, chunksAfter));
2260         }
2261
2262         dev->isDoingGC = 0;
2263
2264         return YAFFS_OK;
2265 }
2266
2267 /* New garbage collector
2268  * If we're very low on erased blocks then we do aggressive garbage collection
2269  * otherwise we do "leasurely" garbage collection.
2270  * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2271  * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2272  *
2273  * The idea is to help clear out space in a more spread-out manner.
2274  * Dunno if it really does anything useful.
2275  */
2276 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
2277 {
2278         int block;
2279         int aggressive;
2280         int gcOk = YAFFS_OK;
2281         int maxTries = 0;
2282
2283         if (dev->isDoingGC) {
2284                 /* Bail out so we don't get recursive gc */
2285                 return YAFFS_OK;
2286         }
2287         
2288         /* This loop should pass the first time.
2289          * We'll only see looping here if the erase of the collected block fails.
2290          */
2291
2292         do {
2293                 maxTries++;
2294                 if (dev->nErasedBlocks < dev->nReservedBlocks) {
2295                         /* We need a block soon...*/
2296                         aggressive = 1;
2297                 } else {
2298                         /* We're in no hurry */
2299                         aggressive = 0;
2300                 }
2301
2302                 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
2303
2304                 if (block > 0) {
2305                         dev->garbageCollections++;
2306                         if (!aggressive) {
2307                                 dev->passiveGarbageCollections++;
2308                         }
2309
2310                         T(YAFFS_TRACE_GC,
2311                           (TSTR
2312                            ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
2313                            dev->nErasedBlocks, aggressive));
2314
2315                         gcOk = yaffs_GarbageCollectBlock(dev, block);
2316                 }
2317
2318                 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
2319                         T(YAFFS_TRACE_GC,
2320                           (TSTR
2321                            ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
2322                             TENDSTR), dev->nErasedBlocks, maxTries, block));
2323                 }
2324         } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
2325                  && (maxTries < 2));
2326
2327         return aggressive ? gcOk : YAFFS_OK;
2328 }
2329
2330 /*-------------------------  TAGS --------------------------------*/
2331
2332 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
2333                            int chunkInObject)
2334 {
2335         return (tags->chunkId == chunkInObject &&
2336                 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
2337
2338 }
2339
2340
2341 /*-------------------- Data file manipulation -----------------*/
2342
2343 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
2344                                  yaffs_ExtendedTags * tags)
2345 {
2346         /*Get the Tnode, then get the level 0 offset chunk offset */
2347         yaffs_Tnode *tn;
2348         int theChunk = -1;
2349         yaffs_ExtendedTags localTags;
2350         int retVal = -1;
2351
2352         yaffs_Device *dev = in->myDev;
2353
2354         if (!tags) {
2355                 /* Passed a NULL, so use our own tags space */
2356                 tags = &localTags;
2357         }
2358
2359         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2360
2361         if (tn) {
2362                 theChunk =
2363                     tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << 
2364                                 dev->chunkGroupBits;
2365
2366                 retVal =
2367                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2368                                            chunkInInode);
2369         }
2370         return retVal;
2371 }
2372
2373 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
2374                                           yaffs_ExtendedTags * tags)
2375 {
2376         /* Get the Tnode, then get the level 0 offset chunk offset */
2377         yaffs_Tnode *tn;
2378         int theChunk = -1;
2379         yaffs_ExtendedTags localTags;
2380
2381         yaffs_Device *dev = in->myDev;
2382         int retVal = -1;
2383
2384         if (!tags) {
2385                 /* Passed a NULL, so use our own tags space */
2386                 tags = &localTags;
2387         }
2388
2389         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2390
2391         if (tn) {
2392
2393                 theChunk =
2394                     tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] << dev->
2395                     chunkGroupBits;
2396
2397                 retVal =
2398                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2399                                            chunkInInode);
2400
2401                 /* Delete the entry in the filestructure (if found) */
2402                 if (retVal != -1) {
2403                         tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] = 0;
2404                 }
2405         } else {
2406                 /*T(("No level 0 found for %d\n", chunkInInode)); */
2407         }
2408
2409         if (retVal == -1) {
2410                 /* T(("Could not find %d to delete\n",chunkInInode)); */
2411         }
2412         return retVal;
2413 }
2414
2415 #ifdef YAFFS_PARANOID
2416
2417 static int yaffs_CheckFileSanity(yaffs_Object * in)
2418 {
2419         int chunk;
2420         int nChunks;
2421         int fSize;
2422         int failed = 0;
2423         int objId;
2424         yaffs_Tnode *tn;
2425         yaffs_Tags localTags;
2426         yaffs_Tags *tags = &localTags;
2427         int theChunk;
2428         int chunkDeleted;
2429
2430         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2431                 /* T(("Object not a file\n")); */
2432                 return YAFFS_FAIL;
2433         }
2434
2435         objId = in->objectId;
2436         fSize = in->variant.fileVariant.fileSize;
2437         nChunks =
2438             (fSize + in->myDev->nBytesPerChunk - 1) / in->myDev->nBytesPerChunk;
2439
2440         for (chunk = 1; chunk <= nChunks; chunk++) {
2441                 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
2442                                            chunk);
2443
2444                 if (tn) {
2445
2446                         theChunk =
2447                             tn->level0[chunk & YAFFS_TNODES_LEVEL0_MASK] << in->
2448                             myDev->chunkGroupBits;
2449
2450                         if (yaffs_CheckChunkBits
2451                             (dev, theChunk / dev->nChunksPerBlock,
2452                              theChunk % dev->nChunksPerBlock)) {
2453
2454                                 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
2455                                                             tags,
2456                                                             &chunkDeleted);
2457                                 if (yaffs_TagsMatch
2458                                     (tags, in->objectId, chunk, chunkDeleted)) {
2459                                         /* found it; */
2460
2461                                 }
2462                         } else {
2463
2464                                 failed = 1;
2465                         }
2466
2467                 } else {
2468                         /* T(("No level 0 found for %d\n", chunk)); */
2469                 }
2470         }
2471
2472         return failed ? YAFFS_FAIL : YAFFS_OK;
2473 }
2474
2475 #endif
2476
2477 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
2478                                   int chunkInNAND, int inScan)
2479 {
2480         /* NB inScan is zero unless scanning. 
2481          * For forward scanning, inScan is > 0; 
2482          * for backward scanning inScan is < 0
2483          */
2484          
2485         yaffs_Tnode *tn;
2486         yaffs_Device *dev = in->myDev;
2487         int existingChunk;
2488         yaffs_ExtendedTags existingTags;
2489         yaffs_ExtendedTags newTags;
2490         unsigned existingSerial, newSerial;
2491
2492         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2493                 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2494                  * If it is not during Scanning then something went wrong!
2495                  */
2496                 if (!inScan) {
2497                         T(YAFFS_TRACE_ERROR,
2498                           (TSTR
2499                            ("yaffs tragedy:attempt to put data chunk into a non-file"
2500                             TENDSTR)));
2501                         YBUG();
2502                 }
2503
2504                 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
2505                 return YAFFS_OK;
2506         }
2507
2508         tn = yaffs_AddOrFindLevel0Tnode(dev, &in->variant.fileVariant,
2509                                         chunkInInode);
2510         if (!tn) {
2511                 return YAFFS_FAIL;
2512         }
2513
2514         existingChunk = tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK];
2515
2516         if (inScan != 0) {
2517                 /* If we're scanning then we need to test for duplicates
2518                  * NB This does not need to be efficient since it should only ever 
2519                  * happen when the power fails during a write, then only one
2520                  * chunk should ever be affected.
2521                  *
2522                  * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2523                  * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2524                  */
2525
2526                 if (existingChunk != 0) {
2527                         /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
2528                          *    thus we have to do a FindChunkInFile to get the real chunk id.
2529                          *
2530                          * We have a duplicate now we need to decide which one to use:
2531                          *
2532                          * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2533                          * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2534                          * YAFFS1: Get both sets of tags and compare serial numbers.
2535                          */
2536
2537                         if (inScan > 0) {
2538                                 /* Only do this for forward scanning */
2539                                 yaffs_ReadChunkWithTagsFromNAND(dev,
2540                                                                 chunkInNAND,
2541                                                                 NULL, &newTags);
2542
2543                                 /* Do a proper find */
2544                                 existingChunk =
2545                                     yaffs_FindChunkInFile(in, chunkInInode,
2546                                                           &existingTags);
2547                         }
2548
2549                         if (existingChunk <= 0) {
2550                                 /*Hoosterman - how did this happen? */
2551
2552                                 T(YAFFS_TRACE_ERROR,
2553                                   (TSTR
2554                                    ("yaffs tragedy: existing chunk < 0 in scan"
2555                                     TENDSTR)));
2556
2557                         }
2558
2559                         /* NB The deleted flags should be false, otherwise the chunks will 
2560                          * not be loaded during a scan
2561                          */
2562
2563                         newSerial = newTags.serialNumber;
2564                         existingSerial = existingTags.serialNumber;
2565
2566                         if ((inScan > 0) &&
2567                             (in->myDev->isYaffs2 ||
2568                              existingChunk <= 0 ||
2569                              ((existingSerial + 1) & 3) == newSerial)) {
2570                                 /* Forward scanning.                            
2571                                  * Use new
2572                                  * Delete the old one and drop through to update the tnode
2573                                  */
2574                                 yaffs_DeleteChunk(dev, existingChunk, 1,
2575                                                   __LINE__);
2576                         } else {
2577                                 /* Backward scanning or we want to use the existing one
2578                                  * Use existing.
2579                                  * Delete the new one and return early so that the tnode isn't changed
2580                                  */
2581                                 yaffs_DeleteChunk(dev, chunkInNAND, 1,
2582                                                   __LINE__);
2583                                 return YAFFS_OK;
2584                         }
2585                 }
2586
2587         }
2588
2589         if (existingChunk == 0) {
2590                 in->nDataChunks++;
2591         }
2592
2593         tn->level0[chunkInInode & YAFFS_TNODES_LEVEL0_MASK] =
2594             (chunkInNAND >> dev->chunkGroupBits);
2595
2596         return YAFFS_OK;
2597 }
2598
2599 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
2600                                          __u8 * buffer)
2601 {
2602         int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
2603
2604         if (chunkInNAND >= 0) {
2605                 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
2606                                                        buffer, NULL);
2607         } else {
2608                 T(YAFFS_TRACE_NANDACCESS,
2609                   (TSTR("Chunk %d not found zero instead" TENDSTR),
2610                    chunkInNAND));
2611                 /* get sane (zero) data if you read a hole */
2612                 memset(buffer, 0, in->myDev->nBytesPerChunk);   
2613                 return 0;
2614         }
2615
2616 }
2617
2618 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
2619 {
2620         int block;
2621         int page;
2622         yaffs_ExtendedTags tags;
2623         yaffs_BlockInfo *bi;
2624
2625         if (chunkId <= 0)
2626                 return;
2627
2628         dev->nDeletions++;
2629         block = chunkId / dev->nChunksPerBlock;
2630         page = chunkId % dev->nChunksPerBlock;
2631
2632         bi = yaffs_GetBlockInfo(dev, block);
2633
2634         T(YAFFS_TRACE_DELETION,
2635           (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
2636
2637         if (markNAND &&
2638             bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
2639
2640 #ifdef CONFIG_MTD_NAND_VERIFY_WRITE
2641
2642                 /* Read data before write, to ensure correct ecc 
2643                  * if we're using MTD verification under Linux
2644                  */
2645                 yaffs_ReadChunkFromNAND(dev, chunkId, NULL, &spare, 0);
2646 #endif
2647
2648                 yaffs_InitialiseTags(&tags);
2649
2650                 tags.chunkDeleted = 1;
2651
2652                 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
2653                 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
2654         } else {
2655                 dev->nUnmarkedDeletions++;
2656         }
2657
2658         /* Pull out of the management area.
2659          * If the whole block became dirty, this will kick off an erasure.
2660          */
2661         if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2662             bi->blockState == YAFFS_BLOCK_STATE_FULL ||
2663             bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2664             bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2665                 dev->nFreeChunks++;
2666
2667                 yaffs_ClearChunkBit(dev, block, page);
2668
2669                 bi->pagesInUse--;
2670
2671                 if (bi->pagesInUse == 0 &&
2672                     !bi->hasShrinkHeader &&
2673                     bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
2674                     bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2675                         yaffs_BlockBecameDirty(dev, block);
2676                 }
2677
2678         } else {
2679                 /* T(("Bad news deleting chunk %d\n",chunkId)); */
2680         }
2681
2682 }
2683
2684 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
2685                                         const __u8 * buffer, int nBytes,
2686                                         int useReserve)
2687 {
2688         /* Find old chunk Need to do this to get serial number
2689          * Write new one and patch into tree.
2690          * Invalidate old tags.
2691          */
2692
2693         int prevChunkId;
2694         yaffs_ExtendedTags prevTags;
2695
2696         int newChunkId;
2697         yaffs_ExtendedTags newTags;
2698
2699         yaffs_Device *dev = in->myDev;
2700
2701         yaffs_CheckGarbageCollection(dev);
2702
2703         /* Get the previous chunk at this location in the file if it exists */
2704         prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
2705
2706         /* Set up new tags */
2707         yaffs_InitialiseTags(&newTags);
2708
2709         newTags.chunkId = chunkInInode;
2710         newTags.objectId = in->objectId;
2711         newTags.serialNumber =
2712             (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2713         newTags.byteCount = nBytes;
2714
2715         newChunkId =
2716             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2717                                               useReserve);
2718
2719         if (newChunkId >= 0) {
2720                 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
2721
2722                 if (prevChunkId >= 0) {
2723                         yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
2724
2725                 }
2726
2727                 yaffs_CheckFileSanity(in);
2728         }
2729         return newChunkId;
2730
2731 }
2732
2733 /* UpdateObjectHeader updates the header on NAND for an object.
2734  * If name is not NULL, then that new name is used.
2735  */
2736 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
2737                              int isShrink, int shadows)
2738 {
2739
2740         yaffs_BlockInfo *bi;
2741
2742         yaffs_Device *dev = in->myDev;
2743
2744         int prevChunkId;
2745         int retVal = 0;
2746
2747         int newChunkId;
2748         yaffs_ExtendedTags newTags;
2749
2750         __u8 *buffer = NULL;
2751         YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
2752
2753         yaffs_ObjectHeader *oh = NULL;
2754
2755         if (!in->fake || force) {
2756
2757                 yaffs_CheckGarbageCollection(dev);
2758
2759                 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
2760                 oh = (yaffs_ObjectHeader *) buffer;
2761
2762                 prevChunkId = in->chunkId;
2763
2764                 if (prevChunkId >= 0) {
2765                         yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
2766                                                         buffer, NULL);
2767                         memcpy(oldName, oh->name, sizeof(oh->name));
2768                 }
2769
2770                 memset(buffer, 0xFF, dev->nBytesPerChunk);
2771
2772                 oh->type = in->variantType;
2773                 oh->yst_mode = in->yst_mode;
2774                 oh->shadowsObject = shadows;
2775
2776 #ifdef CONFIG_YAFFS_WINCE
2777                 oh->win_atime[0] = in->win_atime[0];
2778                 oh->win_ctime[0] = in->win_ctime[0];
2779                 oh->win_mtime[0] = in->win_mtime[0];
2780                 oh->win_atime[1] = in->win_atime[1];
2781                 oh->win_ctime[1] = in->win_ctime[1];
2782                 oh->win_mtime[1] = in->win_mtime[1];
2783 #else
2784                 oh->yst_uid = in->yst_uid;
2785                 oh->yst_gid = in->yst_gid;
2786                 oh->yst_atime = in->yst_atime;
2787                 oh->yst_mtime = in->yst_mtime;
2788                 oh->yst_ctime = in->yst_ctime;
2789                 oh->yst_rdev = in->yst_rdev;
2790 #endif
2791                 if (in->parent) {
2792                         oh->parentObjectId = in->parent->objectId;
2793                 } else {
2794                         oh->parentObjectId = 0;
2795                 }
2796
2797                 if (name && *name) {
2798                         memset(oh->name, 0, sizeof(oh->name));
2799                         yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
2800                 } else if (prevChunkId) {
2801                         memcpy(oh->name, oldName, sizeof(oh->name));
2802                 } else {
2803                         memset(oh->name, 0, sizeof(oh->name));
2804                 }
2805
2806                 oh->isShrink = isShrink;
2807
2808                 switch (in->variantType) {
2809                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2810                         /* Should not happen */
2811                         break;
2812                 case YAFFS_OBJECT_TYPE_FILE:
2813                         oh->fileSize =
2814                             (oh->parentObjectId == YAFFS_OBJECTID_DELETED
2815                              || oh->parentObjectId ==
2816                              YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
2817                             fileVariant.fileSize;
2818                         break;
2819                 case YAFFS_OBJECT_TYPE_HARDLINK:
2820                         oh->equivalentObjectId =
2821                             in->variant.hardLinkVariant.equivalentObjectId;
2822                         break;
2823                 case YAFFS_OBJECT_TYPE_SPECIAL:
2824                         /* Do nothing */
2825                         break;
2826                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2827                         /* Do nothing */
2828                         break;
2829                 case YAFFS_OBJECT_TYPE_SYMLINK:
2830                         yaffs_strncpy(oh->alias,
2831                                       in->variant.symLinkVariant.alias,
2832                                       YAFFS_MAX_ALIAS_LENGTH);
2833                         oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
2834                         break;
2835                 }
2836
2837                 /* Tags */
2838                 yaffs_InitialiseTags(&newTags);
2839                 in->serial++;
2840                 newTags.chunkId = 0;
2841                 newTags.objectId = in->objectId;
2842                 newTags.serialNumber = in->serial;
2843
2844                 /* Add extra info for file header */
2845
2846                 newTags.extraHeaderInfoAvailable = 1;
2847                 newTags.extraParentObjectId = oh->parentObjectId;
2848                 newTags.extraFileLength = oh->fileSize;
2849                 newTags.extraIsShrinkHeader = oh->isShrink;
2850                 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
2851                 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
2852                 newTags.extraObjectType = in->variantType;
2853
2854                 /* Create new chunk in NAND */
2855                 newChunkId =
2856                     yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2857                                                       (prevChunkId >= 0) ? 1 : 0);
2858
2859                 if (newChunkId >= 0) {
2860
2861                         in->chunkId = newChunkId;
2862
2863                         if (prevChunkId >= 0) {
2864                                 yaffs_DeleteChunk(dev, prevChunkId, 1,
2865                                                   __LINE__);
2866                         }
2867
2868                         in->dirty = 0;
2869
2870                         /* If this was a shrink, then mark the block that the chunk lives on */
2871                         if (isShrink) {
2872                                 bi = yaffs_GetBlockInfo(in->myDev,
2873                                                         newChunkId /in->myDev-> nChunksPerBlock);
2874                                 bi->hasShrinkHeader = 1;
2875                         }
2876
2877                 }
2878
2879                 retVal = newChunkId;
2880
2881         }
2882
2883         if (buffer)
2884                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2885
2886         return retVal;
2887 }
2888
2889 /*------------------------ Short Operations Cache ----------------------------------------
2890  *   In many situations where there is no high level buffering (eg WinCE) a lot of
2891  *   reads might be short sequential reads, and a lot of writes may be short 
2892  *   sequential writes. eg. scanning/writing a jpeg file.
2893  *   In these cases, a short read/write cache can provide a huge perfomance benefit 
2894  *   with dumb-as-a-rock code.
2895  *   In Linux, the page cache provides read buffering aand the short op cache provides write 
2896  *   buffering.
2897  *
2898  *   There are a limited number (~10) of cache chunks per device so that we don't
2899  *   need a very intelligent search.
2900  */
2901
2902 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
2903 {
2904         yaffs_Device *dev = obj->myDev;
2905         int lowest = -99;       /* Stop compiler whining. */
2906         int i;
2907         yaffs_ChunkCache *cache;
2908         int chunkWritten = 0;
2909         int nCaches = obj->myDev->nShortOpCaches;
2910
2911         if (nCaches > 0) {
2912                 do {
2913                         cache = NULL;
2914
2915                         /* Find the dirty cache for this object with the lowest chunk id. */
2916                         for (i = 0; i < nCaches; i++) {
2917                                 if (dev->srCache[i].object == obj &&
2918                                     dev->srCache[i].dirty) {
2919                                         if (!cache
2920                                             || dev->srCache[i].chunkId <
2921                                             lowest) {
2922                                                 cache = &dev->srCache[i];
2923                                                 lowest = cache->chunkId;
2924                                         }
2925                                 }
2926                         }
2927
2928                         if (cache && !cache->locked) {
2929                                 /* Write it out and free it up */
2930
2931                                 chunkWritten =
2932                                     yaffs_WriteChunkDataToObject(cache->object,
2933                                                                  cache->chunkId,
2934                                                                  cache->data,
2935                                                                  cache->nBytes,
2936                                                                  1);
2937                                 cache->dirty = 0;
2938                                 cache->object = NULL;
2939                         }
2940
2941                 } while (cache && chunkWritten > 0);
2942
2943                 if (cache) {
2944                         /* Hoosterman, disk full while writing cache out. */
2945                         T(YAFFS_TRACE_ERROR,
2946                           (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
2947
2948                 }
2949         }
2950
2951 }
2952
2953 /* Grab us a cache chunk for use.
2954  * First look for an empty one. 
2955  * Then look for the least recently used non-dirty one.
2956  * Then look for the least recently used dirty one...., flush and look again.
2957  */
2958 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
2959 {
2960         int i;
2961         int usage;
2962         int theOne;
2963
2964         if (dev->nShortOpCaches > 0) {
2965                 for (i = 0; i < dev->nShortOpCaches; i++) {
2966                         if (!dev->srCache[i].object) 
2967                                 return &dev->srCache[i];
2968                 }
2969
2970                 return NULL;
2971
2972                 theOne = -1;
2973                 usage = 0;      /* just to stop the compiler grizzling */
2974
2975                 for (i = 0; i < dev->nShortOpCaches; i++) {
2976                         if (!dev->srCache[i].dirty &&
2977                             ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
2978                              theOne < 0)) {
2979                                 usage = dev->srCache[i].lastUse;
2980                                 theOne = i;
2981                         }
2982                 }
2983
2984
2985                 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
2986         } else {
2987                 return NULL;
2988         }
2989
2990 }
2991
2992 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
2993 {
2994         yaffs_ChunkCache *cache;
2995         yaffs_Object *theObj;
2996         int usage;
2997         int i;
2998         int pushout;
2999
3000         if (dev->nShortOpCaches > 0) {
3001                 /* Try find a non-dirty one... */
3002
3003                 cache = yaffs_GrabChunkCacheWorker(dev);
3004
3005                 if (!cache) {
3006                         /* They were all dirty, find the last recently used object and flush
3007                          * its cache, then  find again.
3008                          * NB what's here is not very accurate, we actually flush the object
3009                          * the last recently used page.
3010                          */
3011
3012                         /* With locking we can't assume we can use entry zero */
3013
3014                         theObj = NULL;
3015                         usage = -1;
3016                         cache = NULL;
3017                         pushout = -1;
3018
3019                         for (i = 0; i < dev->nShortOpCaches; i++) {
3020                                 if (dev->srCache[i].object &&
3021                                     !dev->srCache[i].locked &&
3022                                     (dev->srCache[i].lastUse < usage || !cache))
3023                                 {
3024                                         usage = dev->srCache[i].lastUse;
3025                                         theObj = dev->srCache[i].object;
3026                                         cache = &dev->srCache[i];
3027                                         pushout = i;
3028                                 }
3029                         }
3030
3031                         if (!cache || cache->dirty) {
3032                                 /* Flush and try again */
3033                                 yaffs_FlushFilesChunkCache(theObj);
3034                                 cache = yaffs_GrabChunkCacheWorker(dev);
3035                         }
3036
3037                 }
3038                 return cache;
3039         } else
3040                 return NULL;
3041
3042 }
3043
3044 /* Find a cached chunk */
3045 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
3046                                               int chunkId)
3047 {
3048         yaffs_Device *dev = obj->myDev;
3049         int i;
3050         if (dev->nShortOpCaches > 0) {
3051                 for (i = 0; i < dev->nShortOpCaches; i++) {
3052                         if (dev->srCache[i].object == obj &&
3053                             dev->srCache[i].chunkId == chunkId) {
3054                                 dev->cacheHits++;
3055
3056                                 return &dev->srCache[i];
3057                         }
3058                 }
3059         }
3060         return NULL;
3061 }
3062
3063 /* Mark the chunk for the least recently used algorithym */
3064 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
3065                                 int isAWrite)
3066 {
3067
3068         if (dev->nShortOpCaches > 0) {
3069                 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
3070                         /* Reset the cache usages */
3071                         int i;
3072                         for (i = 1; i < dev->nShortOpCaches; i++) {
3073                                 dev->srCache[i].lastUse = 0;
3074                         }
3075                         dev->srLastUse = 0;
3076                 }
3077
3078                 dev->srLastUse++;
3079
3080                 cache->lastUse = dev->srLastUse;
3081
3082                 if (isAWrite) {
3083                         cache->dirty = 1;
3084                 }
3085         }
3086 }
3087
3088 /* Invalidate a single cache page.
3089  * Do this when a whole page gets written,
3090  * ie the short cache for this page is no longer valid.
3091  */
3092 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
3093 {
3094         if (object->myDev->nShortOpCaches > 0) {
3095                 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
3096
3097                 if (cache) {
3098                         cache->object = NULL;
3099                 }
3100         }
3101 }
3102
3103 /* Invalidate all the cache pages associated with this object
3104  * Do this whenever ther file is deleted or resized.
3105  */
3106 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
3107 {
3108         int i;
3109         yaffs_Device *dev = in->myDev;
3110
3111         if (dev->nShortOpCaches > 0) {
3112                 /* Invalidate it. */
3113                 for (i = 0; i < dev->nShortOpCaches; i++) {
3114                         if (dev->srCache[i].object == in) {
3115                                 dev->srCache[i].object = NULL;
3116                         }
3117                 }
3118         }
3119 }
3120
3121 /*--------------------- File read/write ------------------------
3122  * Read and write have very similar structures.
3123  * In general the read/write has three parts to it
3124  * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3125  * Some complete chunks
3126  * An incomplete chunk to end off with
3127  *
3128  * Curve-balls: the first chunk might also be the last chunk.
3129  */
3130
3131 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, __u32 offset,
3132                            int nBytes)
3133 {
3134
3135         int chunk;
3136         int start;
3137         int nToCopy;
3138         int n = nBytes;
3139         int nDone = 0;
3140         yaffs_ChunkCache *cache;
3141
3142         yaffs_Device *dev;
3143
3144         dev = in->myDev;
3145
3146         while (n > 0) {
3147                 chunk = offset / dev->nBytesPerChunk + 1;   /* The first chunk is 1 */
3148                 start = offset % dev->nBytesPerChunk;
3149
3150                 /* OK now check for the curveball where the start and end are in
3151                  * the same chunk.      
3152                  */
3153                 if ((start + n) < dev->nBytesPerChunk) {
3154                         nToCopy = n;
3155                 } else {
3156                         nToCopy = dev->nBytesPerChunk - start;
3157                 }
3158
3159                 cache = yaffs_FindChunkCache(in, chunk);
3160
3161                 /* If the chunk is already in the cache or it is less than a whole chunk
3162                  * then use the cache (if there is caching)
3163                  * else bypass the cache.
3164                  */
3165                 if (cache || nToCopy != dev->nBytesPerChunk) {
3166                         if (dev->nShortOpCaches > 0) {
3167
3168                                 /* If we can't find the data in the cache, then load it up. */
3169
3170                                 if (!cache) {
3171                                         cache = yaffs_GrabChunkCache(in->myDev);
3172                                         cache->object = in;
3173                                         cache->chunkId = chunk;
3174                                         cache->dirty = 0;
3175                                         cache->locked = 0;
3176                                         yaffs_ReadChunkDataFromObject(in, chunk,
3177                                                                       cache->
3178                                                                       data);
3179                                         cache->nBytes = 0;
3180                                 }
3181
3182                                 yaffs_UseChunkCache(dev, cache, 0);
3183
3184                                 cache->locked = 1;
3185
3186 #ifdef CONFIG_YAFFS_WINCE
3187                                 yfsd_UnlockYAFFS(TRUE);
3188 #endif
3189                                 memcpy(buffer, &cache->data[start], nToCopy);
3190
3191 #ifdef CONFIG_YAFFS_WINCE
3192                                 yfsd_LockYAFFS(TRUE);
3193 #endif
3194                                 cache->locked = 0;
3195                         } else {
3196                                 /* Read into the local buffer then copy..*/
3197
3198                                 __u8 *localBuffer =
3199                                     yaffs_GetTempBuffer(dev, __LINE__);
3200                                 yaffs_ReadChunkDataFromObject(in, chunk,
3201                                                               localBuffer);
3202 #ifdef CONFIG_YAFFS_WINCE
3203                                 yfsd_UnlockYAFFS(TRUE);
3204 #endif
3205                                 memcpy(buffer, &localBuffer[start], nToCopy);
3206
3207 #ifdef CONFIG_YAFFS_WINCE
3208                                 yfsd_LockYAFFS(TRUE);
3209 #endif
3210                                 yaffs_ReleaseTempBuffer(dev, localBuffer,
3211                                                         __LINE__);
3212                         }
3213
3214                 } else {
3215 #ifdef CONFIG_YAFFS_WINCE
3216                         __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3217
3218                         /* Under WinCE can't do direct transfer. Need to use a local buffer.
3219                          * This is because we otherwise screw up WinCE's memory mapper
3220                          */
3221                         yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
3222
3223 #ifdef CONFIG_YAFFS_WINCE
3224                         yfsd_UnlockYAFFS(TRUE);
3225 #endif
3226                         memcpy(buffer, localBuffer, dev->nBytesPerChunk);
3227
3228 #ifdef CONFIG_YAFFS_WINCE
3229                         yfsd_LockYAFFS(TRUE);
3230                         yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3231 #endif
3232
3233 #else
3234                         /* A full chunk. Read directly into the supplied buffer. */
3235                         yaffs_ReadChunkDataFromObject(in, chunk, buffer);
3236 #endif
3237                 }
3238
3239                 n -= nToCopy;
3240                 offset += nToCopy;
3241                 buffer += nToCopy;
3242                 nDone += nToCopy;
3243
3244         }
3245
3246         return nDone;
3247 }
3248
3249 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, __u32 offset,
3250                           int nBytes, int writeThrough)
3251 {
3252
3253         int chunk;
3254         int start;
3255         int nToCopy;
3256         int n = nBytes;
3257         int nDone = 0;
3258         int nToWriteBack;
3259         int startOfWrite = offset;
3260         int chunkWritten = 0;
3261         int nBytesRead;
3262
3263         yaffs_Device *dev;
3264
3265         dev = in->myDev;
3266
3267         while (n > 0 && chunkWritten >= 0) {
3268                 chunk = offset / dev->nBytesPerChunk + 1;
3269                 start = offset % dev->nBytesPerChunk;
3270
3271                 /* OK now check for the curveball where the start and end are in
3272                  * the same chunk.
3273                  */
3274
3275                 if ((start + n) < dev->nBytesPerChunk) {
3276                         nToCopy = n;
3277
3278                         /* Now folks, to calculate how many bytes to write back....
3279                          * If we're overwriting and not writing to then end of file then
3280                          * we need to write back as much as was there before.
3281                          */
3282
3283                         nBytesRead =
3284                             in->variant.fileVariant.fileSize -
3285                             ((chunk - 1) * dev->nBytesPerChunk);
3286
3287                         if (nBytesRead > dev->nBytesPerChunk) {
3288                                 nBytesRead = dev->nBytesPerChunk;
3289                         }
3290
3291                         nToWriteBack =
3292                             (nBytesRead >
3293                              (start + n)) ? nBytesRead : (start + n);
3294
3295                 } else {
3296                         nToCopy = dev->nBytesPerChunk - start;
3297                         nToWriteBack = dev->nBytesPerChunk;
3298                 }
3299
3300                 if (nToCopy != dev->nBytesPerChunk) {
3301                         /* An incomplete start or end chunk (or maybe both start and end chunk) */
3302                         if (dev->nShortOpCaches > 0) {
3303                                 yaffs_ChunkCache *cache;
3304                                 /* If we can't find the data in the cache, then load the cache */
3305                                 cache = yaffs_FindChunkCache(in, chunk);
3306                                 if (!cache
3307                                     && yaffs_CheckSpaceForAllocation(in->
3308                                                                      myDev)) {
3309                                         cache = yaffs_GrabChunkCache(in->myDev);
3310                                         cache->object = in;
3311                                         cache->chunkId = chunk;
3312                                         cache->dirty = 0;
3313                                         cache->locked = 0;
3314                                         yaffs_ReadChunkDataFromObject(in, chunk,
3315                                                                       cache->
3316                                                                       data);
3317                                 }
3318
3319                                 if (cache) {
3320                                         yaffs_UseChunkCache(dev, cache, 1);
3321                                         cache->locked = 1;
3322 #ifdef CONFIG_YAFFS_WINCE
3323                                         yfsd_UnlockYAFFS(TRUE);
3324 #endif
3325
3326                                         memcpy(&cache->data[start], buffer,
3327                                                nToCopy);
3328
3329 #ifdef CONFIG_YAFFS_WINCE
3330                                         yfsd_LockYAFFS(TRUE);
3331 #endif
3332                                         cache->locked = 0;
3333                                         cache->nBytes = nToWriteBack;
3334
3335                                         if (writeThrough) {
3336                                                 chunkWritten =
3337                                                     yaffs_WriteChunkDataToObject
3338                                                     (cache->object,
3339                                                      cache->chunkId,
3340                                                      cache->data, cache->nBytes,
3341                                                      1);
3342                                                 cache->dirty = 0;
3343                                         }
3344
3345                                 } else {
3346                                         chunkWritten = -1;      /* fail the write */
3347                                 }
3348                         } else {
3349                                 /* An incomplete start or end chunk (or maybe both start and end chunk)
3350                                  * Read into the local buffer then copy, then copy over and write back.
3351                                  */
3352
3353                                 __u8 *localBuffer =
3354                                     yaffs_GetTempBuffer(dev, __LINE__);
3355
3356                                 yaffs_ReadChunkDataFromObject(in, chunk,
3357                                                               localBuffer);
3358
3359 #ifdef CONFIG_YAFFS_WINCE
3360                                 yfsd_UnlockYAFFS(TRUE);
3361 #endif
3362
3363                                 memcpy(&localBuffer[start], buffer, nToCopy);
3364
3365 #ifdef CONFIG_YAFFS_WINCE
3366                                 yfsd_LockYAFFS(TRUE);
3367 #endif
3368                                 chunkWritten =
3369                                     yaffs_WriteChunkDataToObject(in, chunk,
3370                                                                  localBuffer,
3371                                                                  nToWriteBack,
3372                                                                  0);
3373
3374                                 yaffs_ReleaseTempBuffer(dev, localBuffer,
3375                                                         __LINE__);
3376
3377                         }
3378
3379                 } else {
3380
3381 #ifdef CONFIG_YAFFS_WINCE
3382                         /* Under WinCE can't do direct transfer. Need to use a local buffer.
3383                          * This is because we otherwise screw up WinCE's memory mapper
3384                          */
3385                         __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3386 #ifdef CONFIG_YAFFS_WINCE
3387                         yfsd_UnlockYAFFS(TRUE);
3388 #endif
3389                         memcpy(localBuffer, buffer, dev->nBytesPerChunk);
3390 #ifdef CONFIG_YAFFS_WINCE
3391                         yfsd_LockYAFFS(TRUE);
3392 #endif
3393                         chunkWritten =
3394                             yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
3395                                                          dev->nBytesPerChunk,
3396                                                          0);
3397                         yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3398 #else
3399                         /* A full chunk. Write directly from the supplied buffer. */
3400                         chunkWritten =
3401                             yaffs_WriteChunkDataToObject(in, chunk, buffer,
3402                                                          dev->nBytesPerChunk,
3403                                                          0);
3404 #endif
3405                         /* Since we've overwritten the cached data, we better invalidate it. */
3406                         yaffs_InvalidateChunkCache(in, chunk);
3407                 }
3408
3409                 if (chunkWritten >= 0) {
3410                         n -= nToCopy;
3411                         offset += nToCopy;
3412                         buffer += nToCopy;
3413                         nDone += nToCopy;
3414                 }
3415
3416         }
3417
3418         /* Update file object */
3419
3420         if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
3421                 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
3422         }
3423
3424         in->dirty = 1;
3425
3426         return nDone;
3427 }
3428
3429
3430 /* ---------------------- File resizing stuff ------------------ */
3431
3432 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
3433 {
3434
3435         yaffs_Device *dev = in->myDev;
3436         int oldFileSize = in->variant.fileVariant.fileSize;
3437
3438         int lastDel = 1 + (oldFileSize - 1) / dev->nBytesPerChunk;
3439
3440         int startDel = 1 + (newSize + dev->nBytesPerChunk - 1) /
3441             dev->nBytesPerChunk;
3442         int i;
3443         int chunkId;
3444
3445         /* Delete backwards so that we don't end up with holes if
3446          * power is lost part-way through the operation.
3447          */
3448         for (i = lastDel; i >= startDel; i--) {
3449                 /* NB this could be optimised somewhat,
3450                  * eg. could retrieve the tags and write them without
3451                  * using yaffs_DeleteChunk
3452                  */
3453
3454                 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
3455                 if (chunkId > 0) {
3456                         if (chunkId <
3457                             (dev->internalStartBlock * dev->nChunksPerBlock)
3458                             || chunkId >=
3459                             ((dev->internalEndBlock +
3460                               1) * dev->nChunksPerBlock)) {
3461                                 T(YAFFS_TRACE_ALWAYS,
3462                                   (TSTR("Found daft chunkId %d for %d" TENDSTR),
3463                                    chunkId, i));
3464                         } else {
3465                                 in->nDataChunks--;
3466                                 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
3467                         }
3468                 }
3469         }
3470
3471 }
3472
3473 int yaffs_ResizeFile(yaffs_Object * in, int newSize)
3474 {
3475
3476         int oldFileSize = in->variant.fileVariant.fileSize;
3477         int sizeOfPartialChunk;
3478         yaffs_Device *dev = in->myDev;
3479
3480         sizeOfPartialChunk = newSize % dev->nBytesPerChunk;
3481
3482         yaffs_FlushFilesChunkCache(in);
3483         yaffs_InvalidateWholeChunkCache(in);
3484
3485         yaffs_CheckGarbageCollection(dev);
3486
3487         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3488                 return yaffs_GetFileSize(in);
3489         }
3490
3491         if (newSize == oldFileSize) {
3492                 return oldFileSize;
3493         }
3494
3495         if (newSize < oldFileSize) {
3496
3497                 yaffs_PruneResizedChunks(in, newSize);
3498
3499                 if (sizeOfPartialChunk != 0) {
3500                         int lastChunk = 1 + newSize / dev->nBytesPerChunk;
3501                         __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3502
3503                         /* Got to read and rewrite the last chunk with its new size and zero pad */
3504                         yaffs_ReadChunkDataFromObject(in, lastChunk,
3505                                                       localBuffer);
3506
3507                         memset(localBuffer + sizeOfPartialChunk, 0,
3508                                dev->nBytesPerChunk - sizeOfPartialChunk);
3509
3510                         yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
3511                                                      sizeOfPartialChunk, 1);
3512
3513                         yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3514                 }
3515
3516                 in->variant.fileVariant.fileSize = newSize;
3517
3518                 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
3519         }
3520         /* Write a new object header.
3521          * show we've shrunk the file, if need be
3522          * Do this only if the file is not in the deleted directories.
3523          */
3524         if (in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
3525             in->parent->objectId != YAFFS_OBJECTID_DELETED) {
3526                 yaffs_UpdateObjectHeader(in, NULL, 0,
3527                                          (newSize < oldFileSize) ? 1 : 0, 0);
3528         }
3529
3530         return newSize;
3531 }
3532
3533 loff_t yaffs_GetFileSize(yaffs_Object * obj)
3534 {
3535         obj = yaffs_GetEquivalentObject(obj);
3536
3537         switch (obj->variantType) {
3538         case YAFFS_OBJECT_TYPE_FILE:
3539                 return obj->variant.fileVariant.fileSize;
3540         case YAFFS_OBJECT_TYPE_SYMLINK:
3541                 return yaffs_strlen(obj->variant.symLinkVariant.alias);
3542         default:
3543                 return 0;
3544         }
3545 }
3546
3547
3548
3549 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
3550 {
3551         int retVal;
3552         if (in->dirty) {
3553                 yaffs_FlushFilesChunkCache(in);
3554                 if (updateTime) {
3555 #ifdef CONFIG_YAFFS_WINCE
3556                         yfsd_WinFileTimeNow(in->win_mtime);
3557 #else
3558
3559                         in->yst_mtime = Y_CURRENT_TIME;
3560
3561 #endif
3562                 }
3563
3564                 retVal =
3565                     (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
3566                      0) ? YAFFS_OK : YAFFS_FAIL;
3567         } else {
3568                 retVal = YAFFS_OK;
3569         }
3570
3571         return retVal;
3572
3573 }
3574
3575 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
3576 {
3577
3578         /* First off, invalidate the file's data in the cache, without flushing. */
3579         yaffs_InvalidateWholeChunkCache(in);
3580
3581         if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
3582                 /* Move to the unlinked directory so we have a record that it was deleted. */
3583                 yaffs_ChangeObjectName(in, in->myDev->deletedDir, NULL, 0, 0);
3584
3585         }
3586
3587         yaffs_RemoveObjectFromDirectory(in);
3588         yaffs_DeleteChunk(in->myDev, in->chunkId, 1, __LINE__);
3589         in->chunkId = -1;
3590
3591         yaffs_FreeObject(in);
3592         return YAFFS_OK;
3593
3594 }
3595
3596 /* yaffs_DeleteFile deletes the whole file data
3597  * and the inode associated with the file.
3598  * It does not delete the links associated with the file.
3599  */
3600 static int yaffs_UnlinkFile(yaffs_Object * in)
3601 {
3602
3603         int retVal;
3604         int immediateDeletion = 0;
3605
3606         if (1) {
3607 #ifdef __KERNEL__
3608                 if (!in->myInode) {
3609                         immediateDeletion = 1;
3610
3611                 }
3612 #else
3613                 if (in->inUse <= 0) {
3614                         immediateDeletion = 1;
3615
3616                 }
3617 #endif
3618                 if (immediateDeletion) {
3619                         retVal =
3620                             yaffs_ChangeObjectName(in, in->myDev->deletedDir,
3621                                                    NULL, 0, 0);
3622                         T(YAFFS_TRACE_TRACING,
3623                           (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
3624                            in->objectId));
3625                         in->deleted = 1;
3626                         in->myDev->nDeletedFiles++;
3627                         if (0 && in->myDev->isYaffs2) {
3628                                 yaffs_ResizeFile(in, 0);
3629                         }
3630                         yaffs_SoftDeleteFile(in);
3631                 } else {
3632                         retVal =
3633                             yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
3634                                                    NULL, 0, 0);
3635                 }
3636
3637         }
3638         return retVal;
3639 }
3640
3641 int yaffs_DeleteFile(yaffs_Object * in)
3642 {
3643         int retVal = YAFFS_OK;
3644
3645         if (in->nDataChunks > 0) {
3646                 /* Use soft deletion if there is data in the file */
3647                 if (!in->unlinked) {
3648                         retVal = yaffs_UnlinkFile(in);
3649                 }
3650                 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
3651                         in->deleted = 1;
3652                         in->myDev->nDeletedFiles++;
3653                         yaffs_SoftDeleteFile(in);
3654                 }
3655                 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
3656         } else {
3657                 /* The file has no data chunks so we toss it immediately */
3658                 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
3659                 in->variant.fileVariant.top = NULL;
3660                 yaffs_DoGenericObjectDeletion(in);
3661
3662                 return YAFFS_OK;
3663         }
3664 }
3665
3666 static int yaffs_DeleteDirectory(yaffs_Object * in)
3667 {
3668         /* First check that the directory is empty. */
3669         if (list_empty(&in->variant.directoryVariant.children)) {
3670                 return yaffs_DoGenericObjectDeletion(in);
3671         }
3672
3673         return YAFFS_FAIL;
3674
3675 }
3676
3677 static int yaffs_DeleteSymLink(yaffs_Object * in)
3678 {
3679         YFREE(in->variant.symLinkVariant.alias);
3680
3681         return yaffs_DoGenericObjectDeletion(in);
3682 }
3683
3684 static int yaffs_DeleteHardLink(yaffs_Object * in)
3685 {
3686         /* remove this hardlink from the list assocaited with the equivalent
3687          * object
3688          */
3689         list_del(&in->hardLinks);
3690         return yaffs_DoGenericObjectDeletion(in);
3691 }
3692
3693 static void yaffs_DestroyObject(yaffs_Object * obj)
3694 {
3695         switch (obj->variantType) {
3696         case YAFFS_OBJECT_TYPE_FILE:
3697                 yaffs_DeleteFile(obj);
3698                 break;
3699         case YAFFS_OBJECT_TYPE_DIRECTORY:
3700                 yaffs_DeleteDirectory(obj);
3701                 break;
3702         case YAFFS_OBJECT_TYPE_SYMLINK:
3703                 yaffs_DeleteSymLink(obj);
3704                 break;
3705         case YAFFS_OBJECT_TYPE_HARDLINK:
3706                 yaffs_DeleteHardLink(obj);
3707                 break;
3708         case YAFFS_OBJECT_TYPE_SPECIAL:
3709                 yaffs_DoGenericObjectDeletion(obj);
3710                 break;
3711         case YAFFS_OBJECT_TYPE_UNKNOWN:
3712                 break;          /* should not happen. */
3713         }
3714 }
3715
3716 static int yaffs_UnlinkWorker(yaffs_Object * obj)
3717 {
3718
3719         if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
3720                 return yaffs_DeleteHardLink(obj);
3721         } else if (!list_empty(&obj->hardLinks)) {
3722                 /* Curve ball: We're unlinking an object that has a hardlink.
3723                  *
3724                  * This problem arises because we are not strictly following
3725                  * The Linux link/inode model.
3726                  *
3727                  * We can't really delete the object.
3728                  * Instead, we do the following:
3729                  * - Select a hardlink.
3730                  * - Unhook it from the hard links
3731                  * - Unhook it from its parent directory (so that the rename can work)
3732                  * - Rename the object to the hardlink's name.
3733                  * - Delete the hardlink
3734                  */
3735
3736                 yaffs_Object *hl;
3737                 int retVal;
3738                 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
3739
3740                 hl = list_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
3741
3742                 list_del_init(&hl->hardLinks);
3743                 list_del_init(&hl->siblings);
3744
3745                 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
3746
3747                 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
3748
3749                 if (retVal == YAFFS_OK) {
3750                         retVal = yaffs_DoGenericObjectDeletion(hl);
3751                 }
3752                 return retVal;
3753
3754         } else {
3755                 switch (obj->variantType) {
3756                 case YAFFS_OBJECT_TYPE_FILE:
3757                         return yaffs_UnlinkFile(obj);
3758                         break;
3759                 case YAFFS_OBJECT_TYPE_DIRECTORY:
3760                         return yaffs_DeleteDirectory(obj);
3761                         break;
3762                 case YAFFS_OBJECT_TYPE_SYMLINK:
3763                         return yaffs_DeleteSymLink(obj);
3764                         break;
3765                 case YAFFS_OBJECT_TYPE_SPECIAL:
3766                         return yaffs_DoGenericObjectDeletion(obj);
3767                         break;
3768                 case YAFFS_OBJECT_TYPE_HARDLINK:
3769                 case YAFFS_OBJECT_TYPE_UNKNOWN:
3770                 default:
3771                         return YAFFS_FAIL;
3772                 }
3773         }
3774 }
3775
3776
3777 static int yaffs_UnlinkObject( yaffs_Object *obj)
3778 {
3779
3780         if (obj && obj->unlinkAllowed) {
3781                 return yaffs_UnlinkWorker(obj);
3782         }
3783
3784         return YAFFS_FAIL;
3785
3786 }
3787 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
3788 {
3789         yaffs_Object *obj;
3790
3791         obj = yaffs_FindObjectByName(dir, name);
3792         return yaffs_UnlinkObject(obj);
3793 }
3794
3795 /*----------------------- Initialisation Scanning ---------------------- */
3796
3797 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
3798                                        int backwardScanning)
3799 {
3800         yaffs_Object *obj;
3801
3802         if (!backwardScanning) {
3803                 /* Handle YAFFS1 forward scanning case
3804                  * For YAFFS1 we always do the deletion
3805                  */
3806
3807         } else {
3808                 /* Handle YAFFS2 case (backward scanning)
3809                  * If the shadowed object exists then ignore.
3810                  */
3811                 if (yaffs_FindObjectByNumber(dev, objId)) {
3812                         return;
3813                 }
3814         }
3815
3816         /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
3817          * We put it in unlinked dir to be cleaned up after the scanning
3818          */
3819         obj =
3820             yaffs_FindOrCreateObjectByNumber(dev, objId,
3821                                              YAFFS_OBJECT_TYPE_FILE);
3822         yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
3823         obj->variant.fileVariant.shrinkSize = 0;
3824         obj->valid = 1;         /* So that we don't read any other info for this file */
3825
3826 }
3827
3828 typedef struct {
3829         int seq;
3830         int block;
3831 } yaffs_BlockIndex;
3832
3833 static int yaffs_Scan(yaffs_Device * dev)
3834 {
3835         yaffs_ExtendedTags tags;
3836         int blk;
3837         int blockIterator;
3838         int startIterator;
3839         int endIterator;
3840         int nBlocksToScan = 0;
3841
3842         int chunk;
3843         int c;
3844         int deleted;
3845         yaffs_BlockState state;
3846         yaffs_Object *hardList = NULL;
3847         yaffs_Object *hl;
3848         yaffs_BlockInfo *bi;
3849         int sequenceNumber;
3850         yaffs_ObjectHeader *oh;
3851         yaffs_Object *in;
3852         yaffs_Object *parent;
3853         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
3854
3855         __u8 *chunkData;
3856
3857         yaffs_BlockIndex *blockIndex = NULL;
3858
3859         T(YAFFS_TRACE_SCAN,
3860           (TSTR("yaffs_Scan starts  intstartblk %d intendblk %d..." TENDSTR),
3861            dev->internalStartBlock, dev->internalEndBlock));
3862
3863         chunkData = yaffs_GetTempBuffer(dev, __LINE__);
3864
3865         dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
3866
3867         if (dev->isYaffs2) {
3868                 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
3869         }
3870
3871         /* Scan all the blocks to determine their state */
3872         for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
3873                 bi = yaffs_GetBlockInfo(dev, blk);
3874                 yaffs_ClearChunkBits(dev, blk);
3875                 bi->pagesInUse = 0;
3876                 bi->softDeletions = 0;
3877
3878                 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
3879
3880                 bi->blockState = state;
3881                 bi->sequenceNumber = sequenceNumber;
3882
3883                 T(YAFFS_TRACE_SCAN_DEBUG,
3884                   (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
3885                    state, sequenceNumber));
3886
3887                 if (state == YAFFS_BLOCK_STATE_DEAD) {
3888                         T(YAFFS_TRACE_BAD_BLOCKS,
3889                           (TSTR("block %d is bad" TENDSTR), blk));
3890                 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
3891                         T(YAFFS_TRACE_SCAN_DEBUG,
3892                           (TSTR("Block empty " TENDSTR)));
3893                         dev->nErasedBlocks++;
3894                         dev->nFreeChunks += dev->nChunksPerBlock;
3895                 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3896
3897                         /* Determine the highest sequence number */
3898                         if (dev->isYaffs2 &&
3899                             sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
3900                             sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
3901
3902                                 blockIndex[nBlocksToScan].seq = sequenceNumber;
3903                                 blockIndex[nBlocksToScan].block = blk;
3904
3905                                 nBlocksToScan++;
3906
3907                                 if (sequenceNumber >= dev->sequenceNumber) {
3908                                         dev->sequenceNumber = sequenceNumber;
3909                                 }
3910                         } else if (dev->isYaffs2) {
3911                                 /* TODO: Nasty sequence number! */
3912                                 T(YAFFS_TRACE_SCAN,
3913                                   (TSTR
3914                                    ("Block scanning block %d has bad sequence number %d"
3915                                     TENDSTR), blk, sequenceNumber));
3916
3917                         }
3918                 }
3919         }
3920
3921         /* Sort the blocks
3922          * Dungy old bubble sort for now...
3923          */
3924         if (dev->isYaffs2) {
3925                 yaffs_BlockIndex temp;
3926                 int i;
3927                 int j;
3928
3929                 for (i = 0; i < nBlocksToScan; i++)
3930                         for (j = i + 1; j < nBlocksToScan; j++)
3931                                 if (blockIndex[i].seq > blockIndex[j].seq) {
3932                                         temp = blockIndex[j];
3933                                         blockIndex[j] = blockIndex[i];
3934                                         blockIndex[i] = temp;
3935                                 }
3936         }
3937
3938         /* Now scan the blocks looking at the data. */
3939         if (dev->isYaffs2) {
3940                 startIterator = 0;
3941                 endIterator = nBlocksToScan - 1;
3942                 T(YAFFS_TRACE_SCAN_DEBUG,
3943                   (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
3944         } else {
3945                 startIterator = dev->internalStartBlock;
3946                 endIterator = dev->internalEndBlock;
3947         }
3948
3949         /* For each block.... */
3950         for (blockIterator = startIterator; blockIterator <= endIterator;
3951              blockIterator++) {
3952
3953                 if (dev->isYaffs2) {
3954                         /* get the block to scan in the correct order */
3955                         blk = blockIndex[blockIterator].block;
3956                 } else {
3957                         blk = blockIterator;
3958                 }
3959
3960                 bi = yaffs_GetBlockInfo(dev, blk);
3961                 state = bi->blockState;
3962
3963                 deleted = 0;
3964
3965                 /* For each chunk in each block that needs scanning....*/
3966                 for (c = 0; c < dev->nChunksPerBlock &&
3967                      state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
3968                         /* Read the tags and decide what to do */
3969                         chunk = blk * dev->nChunksPerBlock + c;
3970
3971                         yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
3972                                                         &tags);
3973
3974                         /* Let's have a good look at this chunk... */
3975
3976                         if (!dev->isYaffs2 && tags.chunkDeleted) {
3977                                 /* YAFFS1 only...
3978                                  * A deleted chunk
3979                                  */
3980                                 deleted++;
3981                                 dev->nFreeChunks++;
3982                                 /*T((" %d %d deleted\n",blk,c)); */
3983                         } else if (!tags.chunkUsed) {
3984                                 /* An unassigned chunk in the block
3985                                  * This means that either the block is empty or 
3986                                  * this is the one being allocated from
3987                                  */
3988
3989                                 if (c == 0) {
3990                                         /* We're looking at the first chunk in the block so the block is unused */
3991                                         state = YAFFS_BLOCK_STATE_EMPTY;
3992                                         dev->nErasedBlocks++;
3993                                 } else {
3994                                         /* this is the block being allocated from */
3995                                         T(YAFFS_TRACE_SCAN,
3996                                           (TSTR
3997                                            (" Allocating from %d %d" TENDSTR),
3998                                            blk, c));
3999                                         state = YAFFS_BLOCK_STATE_ALLOCATING;
4000                                         dev->allocationBlock = blk;
4001                                         dev->allocationPage = c;
4002                                         dev->allocationBlockFinder = blk;       
4003                                         /* Set it to here to encourage the allocator to go forth from here. */
4004                                         
4005                                         /* Yaffs2 sanity check:
4006                                          * This should be the one with the highest sequence number
4007                                          */
4008                                         if (dev->isYaffs2
4009                                             && (dev->sequenceNumber !=
4010                                                 bi->sequenceNumber)) {
4011                                                 T(YAFFS_TRACE_ALWAYS,
4012                                                   (TSTR
4013                                                    ("yaffs: Allocation block %d was not highest sequence id:"
4014                                                     " block seq = %d, dev seq = %d"
4015                                                     TENDSTR), blk,bi->sequenceNumber,dev->sequenceNumber));
4016                                         }
4017                                 }
4018
4019                                 dev->nFreeChunks += (dev->nChunksPerBlock - c);
4020                         } else if (tags.chunkId > 0) {
4021                                 /* chunkId > 0 so it is a data chunk... */
4022                                 unsigned int endpos;
4023
4024                                 yaffs_SetChunkBit(dev, blk, c);
4025                                 bi->pagesInUse++;
4026
4027                                 in = yaffs_FindOrCreateObjectByNumber(dev,
4028                                                                       tags.
4029                                                                       objectId,
4030                                                                       YAFFS_OBJECT_TYPE_FILE);
4031                                 /* PutChunkIntoFile checks for a clash (two data chunks with
4032                                  * the same chunkId).
4033                                  */
4034                                 yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,
4035                                                        1);
4036                                 endpos =
4037                                     (tags.chunkId - 1) * dev->nBytesPerChunk +
4038                                     tags.byteCount;
4039                                 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
4040                                     && in->variant.fileVariant.scannedFileSize <
4041                                     endpos) {
4042                                         in->variant.fileVariant.
4043                                             scannedFileSize = endpos;
4044                                         if (!dev->useHeaderFileSize) {
4045                                                 in->variant.fileVariant.
4046                                                     fileSize =
4047                                                     in->variant.fileVariant.
4048                                                     scannedFileSize;
4049                                         }
4050
4051                                 }
4052                                 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));   */
4053                         } else {
4054                                 /* chunkId == 0, so it is an ObjectHeader.
4055                                  * Thus, we read in the object header and make the object
4056                                  */
4057                                 yaffs_SetChunkBit(dev, blk, c);
4058                                 bi->pagesInUse++;
4059
4060                                 yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
4061                                                                 chunkData,
4062                                                                 NULL);
4063
4064                                 oh = (yaffs_ObjectHeader *) chunkData;
4065
4066                                 in = yaffs_FindObjectByNumber(dev,
4067                                                               tags.objectId);
4068                                 if (in && in->variantType != oh->type) {
4069                                         /* This should not happen, but somehow
4070                                          * Wev'e ended up with an objectId that has been reused but not yet 
4071                                          * deleted, and worse still it has changed type. Delete the old object.
4072                                          */
4073
4074                                         yaffs_DestroyObject(in);
4075
4076                                         in = 0;
4077                                 }
4078
4079                                 in = yaffs_FindOrCreateObjectByNumber(dev,
4080                                                                       tags.
4081                                                                       objectId,
4082                                                                       oh->type);
4083
4084                                 if (oh->shadowsObject > 0) {
4085                                         yaffs_HandleShadowedObject(dev,
4086                                                                    oh->
4087                                                                    shadowsObject,
4088                                                                    0);
4089                                 }
4090
4091                                 if (in->valid) {
4092                                         /* We have already filled this one. We have a duplicate and need to resolve it. */
4093
4094                                         unsigned existingSerial = in->serial;
4095                                         unsigned newSerial = tags.serialNumber;
4096
4097                                         if (dev->isYaffs2 ||
4098                                             ((existingSerial + 1) & 3) ==
4099                                             newSerial) {
4100                                                 /* Use new one - destroy the exisiting one */
4101                                                 yaffs_DeleteChunk(dev,
4102                                                                   in->chunkId,
4103                                                                   1, __LINE__);
4104                                                 in->valid = 0;
4105                                         } else {
4106                                                 /* Use existing - destroy this one. */
4107                                                 yaffs_DeleteChunk(dev, chunk, 1,
4108                                                                   __LINE__);
4109                                         }
4110                                 }
4111
4112                                 if (!in->valid &&
4113                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
4114                                      tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
4115                                         /* We only load some info, don't fiddle with directory structure */
4116                                         in->valid = 1;
4117                                         in->variantType = oh->type;
4118
4119                                         in->yst_mode = oh->yst_mode;
4120 #ifdef CONFIG_YAFFS_WINCE
4121                                         in->win_atime[0] = oh->win_atime[0];
4122                                         in->win_ctime[0] = oh->win_ctime[0];
4123                                         in->win_mtime[0] = oh->win_mtime[0];
4124                                         in->win_atime[1] = oh->win_atime[1];
4125                                         in->win_ctime[1] = oh->win_ctime[1];
4126                                         in->win_mtime[1] = oh->win_mtime[1];
4127 #else
4128                                         in->yst_uid = oh->yst_uid;
4129                                         in->yst_gid = oh->yst_gid;
4130                                         in->yst_atime = oh->yst_atime;
4131                                         in->yst_mtime = oh->yst_mtime;
4132                                         in->yst_ctime = oh->yst_ctime;
4133                                         in->yst_rdev = oh->yst_rdev;
4134 #endif
4135                                         in->chunkId = chunk;
4136
4137                                 } else if (!in->valid) {
4138                                         /* we need to load this info */
4139
4140                                         in->valid = 1;
4141                                         in->variantType = oh->type;
4142
4143                                         in->yst_mode = oh->yst_mode;
4144 #ifdef CONFIG_YAFFS_WINCE
4145                                         in->win_atime[0] = oh->win_atime[0];
4146                                         in->win_ctime[0] = oh->win_ctime[0];
4147                                         in->win_mtime[0] = oh->win_mtime[0];
4148                                         in->win_atime[1] = oh->win_atime[1];
4149                                         in->win_ctime[1] = oh->win_ctime[1];
4150                                         in->win_mtime[1] = oh->win_mtime[1];
4151 #else
4152                                         in->yst_uid = oh->yst_uid;
4153                                         in->yst_gid = oh->yst_gid;
4154                                         in->yst_atime = oh->yst_atime;
4155                                         in->yst_mtime = oh->yst_mtime;
4156                                         in->yst_ctime = oh->yst_ctime;
4157                                         in->yst_rdev = oh->yst_rdev;
4158 #endif
4159                                         in->chunkId = chunk;
4160
4161                                         yaffs_SetObjectName(in, oh->name);
4162                                         in->dirty = 0;
4163
4164                                         /* directory stuff...
4165                                          * hook up to parent
4166                                          */
4167
4168                                         parent =
4169                                             yaffs_FindOrCreateObjectByNumber
4170                                             (dev, oh->parentObjectId,
4171                                              YAFFS_OBJECT_TYPE_DIRECTORY);
4172                                         if (parent->variantType ==
4173                                             YAFFS_OBJECT_TYPE_UNKNOWN) {
4174                                                 /* Set up as a directory */
4175                                                 parent->variantType =
4176                                                     YAFFS_OBJECT_TYPE_DIRECTORY;
4177                                                 INIT_LIST_HEAD(&parent->variant.
4178                                                                directoryVariant.
4179                                                                children);
4180                                         } else if (parent->variantType !=
4181                                                    YAFFS_OBJECT_TYPE_DIRECTORY)
4182                                         {
4183                                                 /* Hoosterman, another problem....
4184                                                  * We're trying to use a non-directory as a directory
4185                                                  */
4186
4187                                                 T(YAFFS_TRACE_ERROR,
4188                                                   (TSTR
4189                                                    ("yaffs tragedy: attempting to use non-directory as"
4190                                                     " a directory in scan. Put in lost+found."
4191                                                     TENDSTR)));
4192                                                 parent = dev->lostNFoundDir;
4193                                         }
4194
4195                                         yaffs_AddObjectToDirectory(parent, in);
4196
4197                                         if (0 && (parent == dev->deletedDir ||
4198                                                   parent == dev->unlinkedDir)) {
4199                                                 in->deleted = 1;        /* If it is unlinked at start up then it wants deleting */
4200                                                 dev->nDeletedFiles++;
4201                                         }
4202                                         /* Note re hardlinks.
4203                                          * Since we might scan a hardlink before its equivalent object is scanned
4204                                          * we put them all in a list.
4205                                          * After scanning is complete, we should have all the objects, so we run through this
4206                                          * list and fix up all the chains.              
4207                                          */
4208
4209                                         switch (in->variantType) {
4210                                         case YAFFS_OBJECT_TYPE_UNKNOWN: 
4211                                                 /* Todo got a problem */
4212                                                 break;
4213                                         case YAFFS_OBJECT_TYPE_FILE:
4214                                                 if (dev->isYaffs2
4215                                                     && oh->isShrink) {
4216                                                         /* Prune back the shrunken chunks */
4217                                                         yaffs_PruneResizedChunks
4218                                                             (in, oh->fileSize);
4219                                                         /* Mark the block as having a shrinkHeader */
4220                                                         bi->hasShrinkHeader = 1;
4221                                                 }
4222
4223                                                 if (dev->useHeaderFileSize)
4224
4225                                                         in->variant.fileVariant.
4226                                                             fileSize =
4227                                                             oh->fileSize;
4228
4229                                                 break;
4230                                         case YAFFS_OBJECT_TYPE_HARDLINK:
4231                                                 in->variant.hardLinkVariant.
4232                                                     equivalentObjectId =
4233                                                     oh->equivalentObjectId;
4234                                                 in->hardLinks.next =
4235                                                     (struct list_head *)
4236                                                     hardList;
4237                                                 hardList = in;
4238                                                 break;
4239                                         case YAFFS_OBJECT_TYPE_DIRECTORY:
4240                                                 /* Do nothing */
4241                                                 break;
4242                                         case YAFFS_OBJECT_TYPE_SPECIAL:
4243                                                 /* Do nothing */
4244                                                 break;
4245                                         case YAFFS_OBJECT_TYPE_SYMLINK: 
4246                                                 in->variant.symLinkVariant.
4247                                                     alias =
4248                                                     yaffs_CloneString(oh->alias);
4249                                                 break;
4250                                         }
4251
4252                                         if (parent == dev->deletedDir) {
4253                                                 yaffs_DestroyObject(in);
4254                                                 bi->hasShrinkHeader = 1;
4255                                         }
4256                                 }
4257                         }
4258                 }
4259
4260                 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4261                         /* If we got this far while scanning, then the block is fully allocated.*/
4262                         state = YAFFS_BLOCK_STATE_FULL;
4263                 }
4264
4265                 bi->blockState = state;
4266
4267                 /* Now let's see if it was dirty */
4268                 if (bi->pagesInUse == 0 &&
4269                     !bi->hasShrinkHeader &&
4270                     bi->blockState == YAFFS_BLOCK_STATE_FULL) {
4271                         yaffs_BlockBecameDirty(dev, blk);
4272                 }
4273
4274         }
4275
4276         if (blockIndex) {
4277                 YFREE(blockIndex);
4278         }
4279         
4280         /* Ok, we've done all the scanning.
4281          * Fix up the hard link chains.
4282          * We should now have scanned all the objects, now it's time to add these 
4283          * hardlinks.
4284          */
4285         while (hardList) {
4286                 hl = hardList;
4287                 hardList = (yaffs_Object *) (hardList->hardLinks.next);
4288
4289                 in = yaffs_FindObjectByNumber(dev,
4290                                               hl->variant.hardLinkVariant.
4291                                               equivalentObjectId);
4292
4293                 if (in) {
4294                         /* Add the hardlink pointers */
4295                         hl->variant.hardLinkVariant.equivalentObject = in;
4296                         list_add(&hl->hardLinks, &in->hardLinks);
4297                 } else {
4298                         /* Todo Need to report/handle this better.
4299                          * Got a problem... hardlink to a non-existant object
4300                          */
4301                         hl->variant.hardLinkVariant.equivalentObject = NULL;
4302                         INIT_LIST_HEAD(&hl->hardLinks);
4303
4304                 }
4305
4306         }
4307
4308         /* Handle the unlinked files. Since they were left in an unlinked state we should
4309          * just delete them.
4310          */
4311         {
4312                 struct list_head *i;
4313                 struct list_head *n;
4314
4315                 yaffs_Object *l;
4316                 /* Soft delete all the unlinked files */
4317                 list_for_each_safe(i, n,
4318                                    &dev->unlinkedDir->variant.directoryVariant.
4319                                    children) {
4320                         if (i) {
4321                                 l = list_entry(i, yaffs_Object, siblings);
4322                                 yaffs_DestroyObject(l);
4323                         }
4324                 }
4325         }
4326
4327         yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
4328
4329         T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
4330
4331         return YAFFS_OK;
4332 }
4333
4334 static int yaffs_ScanBackwards(yaffs_Device * dev)
4335 {
4336         yaffs_ExtendedTags tags;
4337         int blk;
4338         int blockIterator;
4339         int startIterator;
4340         int endIterator;
4341         int nBlocksToScan = 0;
4342
4343         int chunk;
4344         int c;
4345         int deleted;
4346         yaffs_BlockState state;
4347         yaffs_Object *hardList = NULL;
4348         yaffs_Object *hl;
4349         yaffs_BlockInfo *bi;
4350         int sequenceNumber;
4351         yaffs_ObjectHeader *oh;
4352         yaffs_Object *in;
4353         yaffs_Object *parent;
4354         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
4355
4356         __u8 *chunkData;
4357
4358         yaffs_BlockIndex *blockIndex = NULL;
4359
4360         if (!dev->isYaffs2) {
4361                 T(YAFFS_TRACE_SCAN,
4362                   (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
4363                 return YAFFS_FAIL;
4364         }
4365
4366         T(YAFFS_TRACE_SCAN,
4367           (TSTR
4368            ("yaffs_ScanBackwards starts  intstartblk %d intendblk %d..."
4369             TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
4370
4371         chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4372
4373         dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
4374
4375         blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
4376
4377         /* Scan all the blocks to determine their state */
4378         for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
4379                 bi = yaffs_GetBlockInfo(dev, blk);
4380                 yaffs_ClearChunkBits(dev, blk);
4381                 bi->pagesInUse = 0;
4382                 bi->softDeletions = 0;
4383
4384                 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
4385
4386                 bi->blockState = state;
4387                 bi->sequenceNumber = sequenceNumber;
4388
4389                 T(YAFFS_TRACE_SCAN_DEBUG,
4390                   (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
4391                    state, sequenceNumber));
4392
4393                 if (state == YAFFS_BLOCK_STATE_DEAD) {
4394                         T(YAFFS_TRACE_BAD_BLOCKS,
4395                           (TSTR("block %d is bad" TENDSTR), blk));
4396                 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
4397                         T(YAFFS_TRACE_SCAN_DEBUG,
4398                           (TSTR("Block empty " TENDSTR)));
4399                         dev->nErasedBlocks++;
4400                         dev->nFreeChunks += dev->nChunksPerBlock;
4401                 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4402
4403                         /* Determine the highest sequence number */
4404                         if (dev->isYaffs2 &&
4405                             sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
4406                             sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
4407
4408                                 blockIndex[nBlocksToScan].seq = sequenceNumber;
4409                                 blockIndex[nBlocksToScan].block = blk;
4410
4411                                 nBlocksToScan++;
4412
4413                                 if (sequenceNumber >= dev->sequenceNumber) {
4414                                         dev->sequenceNumber = sequenceNumber;
4415                                 }
4416                         } else if (dev->isYaffs2) {
4417                                 /* TODO: Nasty sequence number! */
4418                                 T(YAFFS_TRACE_SCAN,
4419                                   (TSTR
4420                                    ("Block scanning block %d has bad sequence number %d"
4421                                     TENDSTR), blk, sequenceNumber));
4422
4423                         }
4424                 }
4425         }
4426
4427         /*
4428          * Sort the blocks
4429          * Dungy old bubble sort for now...
4430          */
4431         {
4432                 yaffs_BlockIndex temp;
4433                 int i;
4434                 int j;
4435
4436                 for (i = 0; i < nBlocksToScan; i++)
4437                         for (j = i + 1; j < nBlocksToScan; j++)
4438                                 if (blockIndex[i].seq > blockIndex[j].seq) {
4439                                         temp = blockIndex[j];
4440                                         blockIndex[j] = blockIndex[i];
4441                                         blockIndex[i] = temp;
4442                                 }
4443         }
4444
4445         /* Now scan the blocks looking at the data. */
4446         startIterator = 0;
4447         endIterator = nBlocksToScan - 1;
4448         T(YAFFS_TRACE_SCAN_DEBUG,
4449           (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
4450
4451         /* For each block.... backwards */
4452         for (blockIterator = endIterator; blockIterator >= startIterator;
4453              blockIterator--) {
4454
4455                 /* get the block to scan in the correct order */
4456                 blk = blockIndex[blockIterator].block;
4457
4458                 bi = yaffs_GetBlockInfo(dev, blk);
4459                 state = bi->blockState;
4460
4461                 deleted = 0;
4462
4463                 /* For each chunk in each block that needs scanning.... */
4464                 for (c = dev->nChunksPerBlock - 1; c >= 0 &&
4465                      (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
4466                       state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
4467                         /* Scan backwards... 
4468                          * Read the tags and decide what to do
4469                          */
4470                         chunk = blk * dev->nChunksPerBlock + c;
4471
4472                         yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
4473                                                         &tags);
4474
4475                         /* Let's have a good look at this chunk... */
4476
4477                         if (!tags.chunkUsed) {
4478                                 // An unassigned chunk in the block
4479                                 // This means that either the block is empty or 
4480                                 // this is the one being allocated from
4481
4482                                 if (c == 0) {
4483                                         /* We're looking at the first chunk in the block so the block is unused */
4484                                         state = YAFFS_BLOCK_STATE_EMPTY;
4485                                         dev->nErasedBlocks++;
4486                                 } else {
4487                                         /* this is the block being allocated from */
4488                                         if (state ==
4489                                             YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4490                                                 T(YAFFS_TRACE_SCAN,
4491                                                   (TSTR
4492                                                    (" Allocating from %d %d"
4493                                                     TENDSTR), blk, c));
4494                                         }
4495                                         state = YAFFS_BLOCK_STATE_ALLOCATING;
4496                                         dev->allocationBlock = blk;
4497                                         dev->allocationPage = c;
4498                                         dev->allocationBlockFinder = blk;       
4499                                         /* Set it to here to encourage the allocator to 
4500                                          *  go forth from here.
4501                                          */
4502                                          
4503                                         /* Yaffs2 sanity check:
4504                                          * This should be the one with the highest sequence number
4505                                          */
4506                                         if (dev->isYaffs2
4507                                             && (dev->sequenceNumber !=
4508                                                 bi->sequenceNumber)) {
4509                                                 T(YAFFS_TRACE_ALWAYS,
4510                                                   (TSTR
4511                                                    ("yaffs: Allocation block %d was not highest sequence "
4512                                                     "id: block seq = %d, dev seq = %d"
4513                                                     TENDSTR), blk,
4514                                                    bi->sequenceNumber,
4515                                                    dev->sequenceNumber));
4516                                         }
4517                                 }
4518
4519                                 dev->nFreeChunks++;
4520                         } else if (tags.chunkId > 0) {
4521                                 /* chunkId > 0 so it is a data chunk... */
4522                                 unsigned int endpos;
4523
4524                                 __u32 chunkBase =
4525                                     (tags.chunkId - 1) * dev->nBytesPerChunk;
4526
4527                                 yaffs_SetChunkBit(dev, blk, c);
4528                                 bi->pagesInUse++;
4529
4530                                 in = yaffs_FindOrCreateObjectByNumber(dev,
4531                                                                       tags.
4532                                                                       objectId,
4533                                                                       YAFFS_OBJECT_TYPE_FILE);
4534                                 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
4535                                     && chunkBase <
4536                                     in->variant.fileVariant.shrinkSize) {
4537                                         /* This has not been invalidated by a resize */
4538                                         yaffs_PutChunkIntoFile(in, tags.chunkId,
4539                                                                chunk, -1);
4540
4541                                         /* File size is calculated by looking at the data chunks if we have not 
4542                                          * seen an object header yet. Stop this practice once we find an object header.
4543                                          */
4544                                         endpos =
4545                                             (tags.chunkId -
4546                                              1) * dev->nBytesPerChunk +
4547                                             tags.byteCount;
4548                                             
4549                                         if (!in->valid &&       /* have not got an object header yet */
4550                                             in->variant.fileVariant.
4551                                             scannedFileSize < endpos) {
4552                                                 in->variant.fileVariant.
4553                                                     scannedFileSize = endpos;
4554                                                 in->variant.fileVariant.
4555                                                     fileSize =
4556                                                     in->variant.fileVariant.
4557                                                     scannedFileSize;
4558                                         }
4559
4560                                 } else {
4561                                         /* This chunk has been invalidated by a resize, so delete */
4562                                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
4563
4564                                 }
4565                         } else {
4566                                 /* chunkId == 0, so it is an ObjectHeader.
4567                                  * Thus, we read in the object header and make the object
4568                                  */
4569                                 yaffs_SetChunkBit(dev, blk, c);
4570                                 bi->pagesInUse++;
4571
4572                                 oh = NULL;
4573                                 in = NULL;
4574
4575                                 if (tags.extraHeaderInfoAvailable) {
4576                                         in = yaffs_FindOrCreateObjectByNumber
4577                                             (dev, tags.objectId,
4578                                              tags.extraObjectType);
4579                                 }
4580
4581                                 if (!in || !in->valid) {
4582
4583                                         /* If we don't have  valid info then we need to read the chunk
4584                                          * TODO In future we can probably defer reading the chunk and 
4585                                          * living with invalid data until needed.
4586                                          */
4587
4588                                         yaffs_ReadChunkWithTagsFromNAND(dev,
4589                                                                         chunk,
4590                                                                         chunkData,
4591                                                                         NULL);
4592
4593                                         oh = (yaffs_ObjectHeader *) chunkData;
4594
4595                                         if (!in)
4596                                                 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
4597
4598                                 }
4599
4600                                 if (!in) {
4601                                         /* TODO Hoosterman we have a problem! */
4602                                         T(YAFFS_TRACE_ERROR,
4603                                           (TSTR
4604                                            ("yaffs tragedy: Could not make object for object  %d  "
4605                                             "at chunk %d during scan"
4606                                             TENDSTR), tags.objectId, chunk));
4607
4608                                 }
4609
4610                                 if (in->valid) {
4611                                         /* We have already filled this one.
4612                                          * We have a duplicate that will be discarded, but 
4613                                          * we first have to suck out resize info if it is a file.
4614                                          */
4615
4616                                         if ((in->variantType ==
4617                                              YAFFS_OBJECT_TYPE_FILE) && ((oh
4618                                                                           &&
4619                                                                           oh->
4620                                                                           type
4621                                                                           ==
4622                                                                           YAFFS_OBJECT_TYPE_FILE)
4623                                                                          ||
4624                                                                          (tags.
4625                                                                           extraHeaderInfoAvailable
4626                                                                           &&
4627                                                                           tags.
4628                                                                           extraObjectType
4629                                                                           ==
4630                                                                           YAFFS_OBJECT_TYPE_FILE))
4631                                             ) {
4632                                                 __u32 thisSize =
4633                                                     (oh) ? oh->fileSize : tags.
4634                                                     extraFileLength;
4635                                                 __u32 parentObjectId =
4636                                                     (oh) ? oh->
4637                                                     parentObjectId : tags.
4638                                                     extraParentObjectId;
4639                                                 unsigned isShrink =
4640                                                     (oh) ? oh->isShrink : tags.
4641                                                     extraIsShrinkHeader;
4642
4643                                                 /* If it is deleted (unlinked at start also means deleted)
4644                                                  * we treat the file size as being zeroed at this point.
4645                                                  */
4646                                                 if (parentObjectId ==
4647                                                     YAFFS_OBJECTID_DELETED
4648                                                     || parentObjectId ==
4649                                                     YAFFS_OBJECTID_UNLINKED) {
4650                                                         thisSize = 0;
4651                                                         isShrink = 1;
4652                                                 }
4653
4654                                                 if (isShrink &&
4655                                                     in->variant.fileVariant.
4656                                                     shrinkSize > thisSize) {
4657                                                         in->variant.fileVariant.
4658                                                             shrinkSize =
4659                                                             thisSize;
4660                                                 }
4661
4662                                                 if (isShrink) {
4663                                                         bi->hasShrinkHeader = 1;
4664                                                 }
4665
4666                                         }
4667                                         /* Use existing - destroy this one. */
4668                                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
4669
4670                                 }
4671
4672                                 if (!in->valid &&
4673                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
4674                                      tags.objectId ==
4675                                      YAFFS_OBJECTID_LOSTNFOUND)) {
4676                                         /* We only load some info, don't fiddle with directory structure */
4677                                         in->valid = 1;
4678                                         in->variantType = oh->type;
4679
4680                                         in->yst_mode = oh->yst_mode;
4681 #ifdef CONFIG_YAFFS_WINCE
4682                                         in->win_atime[0] = oh->win_atime[0];
4683                                         in->win_ctime[0] = oh->win_ctime[0];
4684                                         in->win_mtime[0] = oh->win_mtime[0];
4685                                         in->win_atime[1] = oh->win_atime[1];
4686                                         in->win_ctime[1] = oh->win_ctime[1];
4687                                         in->win_mtime[1] = oh->win_mtime[1];
4688 #else
4689                                         in->yst_uid = oh->yst_uid;
4690                                         in->yst_gid = oh->yst_gid;
4691                                         in->yst_atime = oh->yst_atime;
4692                                         in->yst_mtime = oh->yst_mtime;
4693                                         in->yst_ctime = oh->yst_ctime;
4694                                         in->yst_rdev = oh->yst_rdev;
4695 #endif
4696                                         in->chunkId = chunk;
4697
4698                                 } else if (!in->valid) {
4699                                         /* we need to load this info */
4700
4701                                         in->valid = 1;
4702                                         in->variantType = oh->type;
4703
4704                                         in->yst_mode = oh->yst_mode;
4705 #ifdef CONFIG_YAFFS_WINCE
4706                                         in->win_atime[0] = oh->win_atime[0];
4707                                         in->win_ctime[0] = oh->win_ctime[0];
4708                                         in->win_mtime[0] = oh->win_mtime[0];
4709                                         in->win_atime[1] = oh->win_atime[1];
4710                                         in->win_ctime[1] = oh->win_ctime[1];
4711                                         in->win_mtime[1] = oh->win_mtime[1];
4712 #else
4713                                         in->yst_uid = oh->yst_uid;
4714                                         in->yst_gid = oh->yst_gid;
4715                                         in->yst_atime = oh->yst_atime;
4716                                         in->yst_mtime = oh->yst_mtime;
4717                                         in->yst_ctime = oh->yst_ctime;
4718                                         in->yst_rdev = oh->yst_rdev;
4719 #endif
4720                                         in->chunkId = chunk;
4721
4722                                         if (oh->shadowsObject > 0) {
4723                                                 yaffs_HandleShadowedObject(dev,
4724                                                                            oh->
4725                                                                            shadowsObject,
4726                                                                            1);
4727                                         }
4728
4729                                         yaffs_SetObjectName(in, oh->name);
4730                                         in->dirty = 0;
4731
4732                                         /* directory stuff...
4733                                          * hook up to parent
4734                                          */
4735
4736                                         parent =
4737                                             yaffs_FindOrCreateObjectByNumber
4738                                             (dev, oh->parentObjectId,
4739                                              YAFFS_OBJECT_TYPE_DIRECTORY);
4740                                         if (parent->variantType ==
4741                                             YAFFS_OBJECT_TYPE_UNKNOWN) {
4742                                                 /* Set up as a directory */
4743                                                 parent->variantType =
4744                                                     YAFFS_OBJECT_TYPE_DIRECTORY;
4745                                                 INIT_LIST_HEAD(&parent->variant.
4746                                                                directoryVariant.
4747                                                                children);
4748                                         } else if (parent->variantType !=
4749                                                    YAFFS_OBJECT_TYPE_DIRECTORY)
4750                                         {
4751                                                 /* Hoosterman, another problem....
4752                                                  * We're trying to use a non-directory as a directory
4753                                                  */
4754
4755                                                 T(YAFFS_TRACE_ERROR,
4756                                                   (TSTR
4757                                                    ("yaffs tragedy: attempting to use non-directory as"
4758                                                     " a directory in scan. Put in lost+found."
4759                                                     TENDSTR)));
4760                                                 parent = dev->lostNFoundDir;
4761                                         }
4762
4763                                         yaffs_AddObjectToDirectory(parent, in);
4764
4765                                         if ((parent == dev->deletedDir ||
4766                                              parent == dev->unlinkedDir)) {
4767                                              /* If it is unlinked at start up then it wants deleting */
4768                                                 in->deleted = 1;
4769                                         }
4770
4771                                         if (oh->isShrink) {
4772                                                 /* Mark the block as having a shrinkHeader */
4773                                                 bi->hasShrinkHeader = 1;
4774                                         }
4775
4776                                         /* Note re hardlinks.
4777                                          * Since we might scan a hardlink before its equivalent object is scanned
4778                                          * we put them all in a list.
4779                                          * After scanning is complete, we should have all the objects, so we run
4780                                          * through this list and fix up all the chains.              
4781                                          */
4782
4783                                         switch (in->variantType) {
4784                                         case YAFFS_OBJECT_TYPE_UNKNOWN: 
4785                                                 /* Todo got a problem */
4786                                                 break;
4787                                         case YAFFS_OBJECT_TYPE_FILE:
4788
4789                                                 if (in->variant.fileVariant.
4790                                                     scannedFileSize <
4791                                                     oh->fileSize) {
4792                                                         /* This covers the case where the file size is greater
4793                                                          * than where the data is
4794                                                          * This will happen if the file is resized to be larger 
4795                                                          * than its current data extents.
4796                                                          */
4797                                                         in->variant.fileVariant.fileSize =
4798                                                             oh->fileSize;
4799                                                         in->variant.fileVariant.scannedFileSize =
4800                                                             in->variant.fileVariant.fileSize;
4801                                                 }
4802
4803                                                 if (oh->isShrink &&
4804                                                     in->variant.fileVariant.shrinkSize > 
4805                                                     oh->fileSize) {
4806                                                         in->variant.fileVariant.shrinkSize =
4807                                                             oh->fileSize;
4808                                                 }
4809
4810                                                 break;
4811                                         case YAFFS_OBJECT_TYPE_HARDLINK:
4812                                                 in->variant.hardLinkVariant.equivalentObjectId =
4813                                                     oh->equivalentObjectId;
4814                                                 in->hardLinks.next =
4815                                                     (struct list_head *) hardList;
4816                                                 hardList = in;
4817                                                 break;
4818                                         case YAFFS_OBJECT_TYPE_DIRECTORY:
4819                                                 /* Do nothing */
4820                                                 break;
4821                                         case YAFFS_OBJECT_TYPE_SPECIAL:
4822                                                 /* Do nothing */
4823                                                 break;
4824                                         case YAFFS_OBJECT_TYPE_SYMLINK:
4825                                                 in->variant.symLinkVariant.
4826                                                     alias =
4827                                                     yaffs_CloneString(oh->
4828                                                                       alias);
4829                                                 break;
4830                                         }
4831
4832                                 }
4833                         }
4834                 }
4835
4836                 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4837                         /* If we got this far while scanning, then the block is fully allocated. */
4838                         state = YAFFS_BLOCK_STATE_FULL;
4839                 }
4840
4841                 bi->blockState = state;
4842
4843                 /* Now let's see if it was dirty */
4844                 if (bi->pagesInUse == 0 &&
4845                     !bi->hasShrinkHeader &&
4846                     bi->blockState == YAFFS_BLOCK_STATE_FULL) {
4847                         yaffs_BlockBecameDirty(dev, blk);
4848                 }
4849
4850         }
4851
4852         if (blockIndex) {
4853                 YFREE(blockIndex);
4854         }
4855         /* Ok, we've done all the scanning.
4856          * Fix up the hard link chains.
4857          * We should now have scanned all the objects, now it's time to add these 
4858          * hardlinks.
4859          */
4860         while (hardList) {
4861                 hl = hardList;
4862                 hardList = (yaffs_Object *) (hardList->hardLinks.next);
4863
4864                 in = yaffs_FindObjectByNumber(dev,
4865                                               hl->variant.hardLinkVariant.
4866                                               equivalentObjectId);
4867
4868                 if (in) {
4869                         /* Add the hardlink pointers */
4870                         hl->variant.hardLinkVariant.equivalentObject = in;
4871                         list_add(&hl->hardLinks, &in->hardLinks);
4872                 } else {
4873                         /* Todo Need to report/handle this better.
4874                          * Got a problem... hardlink to a non-existant object
4875                          */
4876                         hl->variant.hardLinkVariant.equivalentObject = NULL;
4877                         INIT_LIST_HEAD(&hl->hardLinks);
4878
4879                 }
4880
4881         }
4882
4883         {
4884                 struct list_head *i;
4885                 struct list_head *n;
4886
4887                 yaffs_Object *l;
4888
4889                 /* Soft delete all the unlinked files */
4890                 list_for_each_safe(i, n,
4891                                    &dev->unlinkedDir->variant.directoryVariant.
4892                                    children) {
4893                         if (i) {
4894                                 l = list_entry(i, yaffs_Object, siblings);
4895                                 yaffs_DestroyObject(l);
4896                         }
4897                 }
4898
4899                 /* Soft delete all the deletedDir files */
4900                 list_for_each_safe(i, n,
4901                                    &dev->deletedDir->variant.directoryVariant.
4902                                    children) {
4903                         if (i) {
4904                                 l = list_entry(i, yaffs_Object, siblings);
4905                                 yaffs_DestroyObject(l);
4906
4907                         }
4908                 }
4909         }
4910
4911         yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
4912
4913         T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
4914
4915         return YAFFS_OK;
4916 }
4917
4918 /*------------------------------  Directory Functions ----------------------------- */
4919
4920 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
4921 {
4922         yaffs_Device *dev = obj->myDev;
4923         
4924         if(dev && dev->removeObjectCallback)
4925                 dev->removeObjectCallback(obj);
4926            
4927         list_del_init(&obj->siblings);
4928         obj->parent = NULL;
4929 }
4930
4931
4932 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
4933                                        yaffs_Object * obj)
4934 {
4935
4936         if (!directory) {
4937                 T(YAFFS_TRACE_ALWAYS,
4938                   (TSTR
4939                    ("tragedy: Trying to add an object to a null pointer directory"
4940                     TENDSTR)));
4941                 YBUG();
4942         }
4943         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4944                 T(YAFFS_TRACE_ALWAYS,
4945                   (TSTR
4946                    ("tragedy: Trying to add an object to a non-directory"
4947                     TENDSTR)));
4948                 YBUG();
4949         }
4950
4951         if (obj->siblings.prev == NULL) {
4952                 /* Not initialised */
4953                 INIT_LIST_HEAD(&obj->siblings);
4954
4955         } else if (!list_empty(&obj->siblings)) {
4956                 /* If it is holed up somewhere else, un hook it */
4957                 yaffs_RemoveObjectFromDirectory(obj);
4958         }
4959         /* Now add it */
4960         list_add(&obj->siblings, &directory->variant.directoryVariant.children);
4961         obj->parent = directory;
4962
4963         if (directory == obj->myDev->unlinkedDir
4964             || directory == obj->myDev->deletedDir) {
4965                 obj->unlinked = 1;
4966                 obj->myDev->nUnlinkedFiles++;
4967                 obj->renameAllowed = 0;
4968         }
4969 }
4970
4971 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
4972                                      const YCHAR * name)
4973 {
4974         int sum;
4975
4976         struct list_head *i;
4977         YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
4978
4979         yaffs_Object *l;
4980
4981         if (!name) {
4982                 return NULL;
4983         }
4984
4985         if (!directory) {
4986                 T(YAFFS_TRACE_ALWAYS,
4987                   (TSTR
4988                    ("tragedy: yaffs_FindObjectByName: null pointer directory"
4989                     TENDSTR)));
4990                 YBUG();
4991         }
4992         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4993                 T(YAFFS_TRACE_ALWAYS,
4994                   (TSTR
4995                    ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
4996                 YBUG();
4997         }
4998
4999         sum = yaffs_CalcNameSum(name);
5000
5001         list_for_each(i, &directory->variant.directoryVariant.children) {
5002                 if (i) {
5003                         l = list_entry(i, yaffs_Object, siblings);
5004
5005                         /* Special case for lost-n-found */
5006                         if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5007                                 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
5008                                         return l;
5009                                 }
5010                         } else if (yaffs_SumCompare(l->sum, sum) || l->chunkId <= 0)    
5011                         {
5012                                 /* LostnFound cunk called Objxxx
5013                                  * Do a real check
5014                                  */
5015                                 yaffs_GetObjectName(l, buffer,
5016                                                     YAFFS_MAX_NAME_LENGTH);
5017                                 if (yaffs_strcmp(name, buffer) == 0) {
5018                                         return l;
5019                                 }
5020
5021                         }
5022                 }
5023         }
5024
5025         return NULL;
5026 }
5027
5028
5029 #if 0
5030 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
5031                                    int (*fn) (yaffs_Object *))
5032 {
5033         struct list_head *i;
5034         yaffs_Object *l;
5035
5036         if (!theDir) {
5037                 T(YAFFS_TRACE_ALWAYS,
5038                   (TSTR
5039                    ("tragedy: yaffs_FindObjectByName: null pointer directory"
5040                     TENDSTR)));
5041                 YBUG();
5042         }
5043         if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5044                 T(YAFFS_TRACE_ALWAYS,
5045                   (TSTR
5046                    ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5047                 YBUG();
5048         }
5049
5050         list_for_each(i, &theDir->variant.directoryVariant.children) {
5051                 if (i) {
5052                         l = list_entry(i, yaffs_Object, siblings);
5053                         if (l && !fn(l)) {
5054                                 return YAFFS_FAIL;
5055                         }
5056                 }
5057         }
5058
5059         return YAFFS_OK;
5060
5061 }
5062 #endif
5063
5064 /* GetEquivalentObject dereferences any hard links to get to the
5065  * actual object.
5066  */
5067
5068 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
5069 {
5070         if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5071                 /* We want the object id of the equivalent object, not this one */
5072                 obj = obj->variant.hardLinkVariant.equivalentObject;
5073         }
5074         return obj;
5075
5076 }
5077
5078 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
5079 {
5080         memset(name, 0, buffSize * sizeof(YCHAR));
5081
5082         if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5083                 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
5084         } else if (obj->chunkId <= 0) {
5085                 YCHAR locName[20];
5086                 /* make up a name */
5087                 yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX,
5088                               obj->objectId);
5089                 yaffs_strncpy(name, locName, buffSize - 1);
5090
5091         }
5092 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
5093         else if (obj->shortName[0]) {
5094                 yaffs_strcpy(name, obj->shortName);
5095         }
5096 #endif
5097         else {
5098                 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
5099
5100                 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
5101
5102                 memset(buffer, 0, obj->myDev->nBytesPerChunk);
5103
5104                 if (obj->chunkId >= 0) {
5105                         yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
5106                                                         obj->chunkId, buffer,
5107                                                         NULL);
5108                 }
5109                 yaffs_strncpy(name, oh->name, buffSize - 1);
5110
5111                 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
5112         }
5113
5114         return yaffs_strlen(name);
5115 }
5116
5117 int yaffs_GetObjectFileLength(yaffs_Object * obj)
5118 {
5119
5120         /* Dereference any hard linking */
5121         obj = yaffs_GetEquivalentObject(obj);
5122
5123         if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
5124                 return obj->variant.fileVariant.fileSize;
5125         }
5126         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
5127                 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5128         } else {
5129                 /* Only a directory should drop through to here */
5130                 return obj->myDev->nBytesPerChunk;
5131         }
5132 }
5133
5134 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
5135 {
5136         int count = 0;
5137         struct list_head *i;
5138
5139         if (!obj->unlinked) {
5140                 count++;        /* the object itself */
5141         }
5142         list_for_each(i, &obj->hardLinks) {
5143                 count++;        /* add the hard links; */
5144         }
5145         return count;
5146
5147 }
5148
5149 int yaffs_GetObjectInode(yaffs_Object * obj)
5150 {
5151         obj = yaffs_GetEquivalentObject(obj);
5152
5153         return obj->objectId;
5154 }
5155
5156 unsigned yaffs_GetObjectType(yaffs_Object * obj)
5157 {
5158         obj = yaffs_GetEquivalentObject(obj);
5159
5160         switch (obj->variantType) {
5161         case YAFFS_OBJECT_TYPE_FILE:
5162                 return DT_REG;
5163                 break;
5164         case YAFFS_OBJECT_TYPE_DIRECTORY:
5165                 return DT_DIR;
5166                 break;
5167         case YAFFS_OBJECT_TYPE_SYMLINK:
5168                 return DT_LNK;
5169                 break;
5170         case YAFFS_OBJECT_TYPE_HARDLINK:
5171                 return DT_REG;
5172                 break;
5173         case YAFFS_OBJECT_TYPE_SPECIAL:
5174                 if (S_ISFIFO(obj->yst_mode))
5175                         return DT_FIFO;
5176                 if (S_ISCHR(obj->yst_mode))
5177                         return DT_CHR;
5178                 if (S_ISBLK(obj->yst_mode))
5179                         return DT_BLK;
5180                 if (S_ISSOCK(obj->yst_mode))
5181                         return DT_SOCK;
5182         default:
5183                 return DT_REG;
5184                 break;
5185         }
5186 }
5187
5188 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
5189 {
5190         obj = yaffs_GetEquivalentObject(obj);
5191         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
5192                 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
5193         } else {
5194                 return yaffs_CloneString(_Y(""));
5195         }
5196 }
5197
5198 #ifndef CONFIG_YAFFS_WINCE
5199
5200 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
5201 {
5202         unsigned int valid = attr->ia_valid;
5203
5204         if (valid & ATTR_MODE)
5205                 obj->yst_mode = attr->ia_mode;
5206         if (valid & ATTR_UID)
5207                 obj->yst_uid = attr->ia_uid;
5208         if (valid & ATTR_GID)
5209                 obj->yst_gid = attr->ia_gid;
5210
5211         if (valid & ATTR_ATIME)
5212                 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
5213         if (valid & ATTR_CTIME)
5214                 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
5215         if (valid & ATTR_MTIME)
5216                 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
5217
5218         if (valid & ATTR_SIZE)
5219                 yaffs_ResizeFile(obj, attr->ia_size);
5220
5221         yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
5222
5223         return YAFFS_OK;
5224
5225 }
5226 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
5227 {
5228         unsigned int valid = 0;
5229
5230         attr->ia_mode = obj->yst_mode;
5231         valid |= ATTR_MODE;
5232         attr->ia_uid = obj->yst_uid;
5233         valid |= ATTR_UID;
5234         attr->ia_gid = obj->yst_gid;
5235         valid |= ATTR_GID;
5236
5237         Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
5238         valid |= ATTR_ATIME;
5239         Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
5240         valid |= ATTR_CTIME;
5241         Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
5242         valid |= ATTR_MTIME;
5243
5244         attr->ia_size = yaffs_GetFileSize(obj);
5245         valid |= ATTR_SIZE;
5246
5247         attr->ia_valid = valid;
5248
5249         return YAFFS_OK;
5250
5251 }
5252
5253 #endif
5254
5255 #if 0
5256 int yaffs_DumpObject(yaffs_Object * obj)
5257 {
5258         YCHAR name[257];
5259
5260         yaffs_GetObjectName(obj, name, 256);
5261
5262         T(YAFFS_TRACE_ALWAYS,
5263           (TSTR
5264            ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
5265             " chunk %d type %d size %d\n"
5266             TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
5267            obj->dirty, obj->valid, obj->serial, obj->sum, obj->chunkId,
5268            yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
5269
5270         return YAFFS_OK;
5271 }
5272 #endif
5273
5274 /*---------------------------- Initialisation code -------------------------------------- */
5275
5276 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
5277 {
5278
5279         /* Common functions, gotta have */
5280         if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
5281                 return 0;
5282
5283 #ifdef CONFIG_YAFFS_YAFFS2
5284
5285         /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
5286         if (dev->writeChunkWithTagsToNAND &&
5287             dev->readChunkWithTagsFromNAND &&
5288             !dev->writeChunkToNAND &&
5289             !dev->readChunkFromNAND &&
5290             dev->markNANDBlockBad && dev->queryNANDBlock)
5291                 return 1;
5292 #endif
5293
5294         /* Can use the "spare" style interface for yaffs1 */
5295         if (!dev->isYaffs2 &&
5296             !dev->writeChunkWithTagsToNAND &&
5297             !dev->readChunkWithTagsFromNAND &&
5298             dev->writeChunkToNAND &&
5299             dev->readChunkFromNAND &&
5300             !dev->markNANDBlockBad && !dev->queryNANDBlock)
5301                 return 1;
5302
5303         return 0;               /* bad */
5304 }
5305
5306 int yaffs_GutsInitialise(yaffs_Device * dev)
5307 {
5308         unsigned x;
5309         int bits;
5310         int extraBits;
5311         int nBlocks;
5312
5313         T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
5314
5315         /* Check stuff that must be set */
5316
5317         if (!dev) {
5318                 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
5319                 return YAFFS_FAIL;
5320         }
5321
5322         dev->internalStartBlock = dev->startBlock;
5323         dev->internalEndBlock = dev->endBlock;
5324         dev->blockOffset = 0;
5325         dev->chunkOffset = 0;
5326         dev->nFreeChunks = 0;
5327
5328         if (dev->startBlock == 0) {
5329                 dev->internalStartBlock = dev->startBlock + 1;
5330                 dev->internalEndBlock = dev->endBlock + 1;
5331                 dev->blockOffset = 1;
5332                 dev->chunkOffset = dev->nChunksPerBlock;
5333         }
5334
5335         /* Check geometry parameters. */
5336
5337         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
5338             ) {
5339                 T(YAFFS_TRACE_ALWAYS,
5340                   (TSTR
5341                    ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s "
5342                     TENDSTR), dev->nBytesPerChunk, dev->isYaffs2 ? "2" : ""));
5343                 return YAFFS_FAIL;
5344         }
5345
5346         if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
5347                 T(YAFFS_TRACE_ALWAYS,
5348                   (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
5349                 return YAFFS_FAIL;
5350         }
5351
5352         /* Got the right mix of functions? */
5353         if (!yaffs_CheckDevFunctions(dev)) {
5354                 /* Function missing */
5355                 T(YAFFS_TRACE_ALWAYS,
5356                   (TSTR
5357                    ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
5358
5359                 return YAFFS_FAIL;
5360         }
5361
5362         /* This is really a compilation check. */
5363         if (!yaffs_CheckStructures()) {
5364                 T(YAFFS_TRACE_ALWAYS,
5365                   (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
5366                 return YAFFS_FAIL;
5367         }
5368
5369         if (dev->isMounted) {
5370                 T(YAFFS_TRACE_ALWAYS,
5371                   (TSTR("yaffs: device already mounted\n" TENDSTR)));
5372                 return YAFFS_FAIL;
5373         }
5374
5375         /* Finished with most checks. One or two more checks happen later on too. */
5376
5377         dev->isMounted = 1;
5378
5379         nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5380
5381         /* OK now calculate a few things for the device
5382          * Calculate chunkGroupBits.
5383          * We need to find the next power of 2 > than internalEndBlock
5384          */
5385
5386         x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
5387
5388         for (bits = extraBits = 0; x > 1; bits++) {
5389                 if (x & 1)
5390                         extraBits++;
5391                 x >>= 1;
5392         }
5393
5394         if (extraBits > 0)
5395                 bits++;
5396
5397         /* Level0 Tnodes are 16 bits, so if the bitwidth of the
5398          * chunk range we're using is greater than 16 we need
5399          * to figure out chunk shift and chunkGroupSize
5400          */
5401         if (bits <= 16) {
5402                 dev->chunkGroupBits = 0;
5403         } else {
5404                 dev->chunkGroupBits = bits - 16;
5405         }
5406
5407         dev->chunkGroupSize = 1 << dev->chunkGroupBits;
5408
5409         if (dev->nChunksPerBlock < dev->chunkGroupSize) {
5410                 /* We have a problem because the soft delete won't work if
5411                  * the chunk group size > chunks per block.
5412                  * This can be remedied by using larger "virtual blocks".
5413                  */
5414                 T(YAFFS_TRACE_ALWAYS,
5415                   (TSTR("yaffs: chunk group too large\n" TENDSTR)));
5416
5417                 return YAFFS_FAIL;
5418         }
5419
5420         /* OK, we've finished verifying the device, lets continue with initialisation */
5421
5422         /* More device initialisation */
5423         dev->garbageCollections = 0;
5424         dev->passiveGarbageCollections = 0;
5425         dev->currentDirtyChecker = 0;
5426         dev->bufferedBlock = -1;
5427         dev->doingBufferedBlockRewrite = 0;
5428         dev->nDeletedFiles = 0;
5429         dev->nBackgroundDeletions = 0;
5430         dev->nUnlinkedFiles = 0;
5431         dev->eccFixed = 0;
5432         dev->eccUnfixed = 0;
5433         dev->tagsEccFixed = 0;
5434         dev->tagsEccUnfixed = 0;
5435         dev->nErasureFailures = 0;
5436         dev->nErasedBlocks = 0;
5437         dev->isDoingGC = 0;
5438
5439         /* Initialise temporary buffers */
5440         {
5441                 int i;
5442                 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
5443                         dev->tempBuffer[i].line = 0;    /* not in use */
5444                         dev->tempBuffer[i].buffer =
5445                             YMALLOC(dev->nBytesPerChunk);
5446                 }
5447         }
5448
5449         yaffs_InitialiseBlocks(dev, nBlocks);
5450
5451         yaffs_InitialiseTnodes(dev);
5452
5453         yaffs_InitialiseObjects(dev);
5454
5455         dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
5456
5457         if (dev->nShortOpCaches > 0) {
5458                 int i;
5459
5460                 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
5461                         dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
5462                 }
5463
5464                 dev->srCache =
5465                     YMALLOC(dev->nShortOpCaches * sizeof(yaffs_ChunkCache));
5466
5467                 for (i = 0; i < dev->nShortOpCaches; i++) {
5468                         dev->srCache[i].object = NULL;
5469                         dev->srCache[i].lastUse = 0;
5470                         dev->srCache[i].dirty = 0;
5471                         dev->srCache[i].data = YMALLOC(dev->nBytesPerChunk);
5472                 }
5473                 dev->srLastUse = 0;
5474         }
5475
5476         dev->cacheHits = 0;
5477
5478         /* Initialise the unlinked, root and lost and found directories */
5479         dev->lostNFoundDir = dev->rootDir =  NULL;
5480         dev->unlinkedDir = dev->deletedDir = NULL;
5481
5482         dev->unlinkedDir =
5483             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
5484         dev->deletedDir =
5485             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
5486
5487         dev->rootDir =
5488             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
5489                                       YAFFS_ROOT_MODE | S_IFDIR);
5490         dev->lostNFoundDir =
5491             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
5492                                       YAFFS_LOSTNFOUND_MODE | S_IFDIR);
5493         yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
5494
5495         if (dev->isYaffs2) {
5496                 dev->useHeaderFileSize = 1;
5497         }
5498
5499         /* Now scan the flash.   */
5500         if (dev->isYaffs2)
5501                 yaffs_ScanBackwards(dev);
5502         else
5503                 yaffs_Scan(dev);
5504
5505         /* Zero out stats */
5506         dev->nPageReads = 0;
5507         dev->nPageWrites = 0;
5508         dev->nBlockErasures = 0;
5509         dev->nGCCopies = 0;
5510         dev->nRetriedWrites = 0;
5511
5512         dev->nRetiredBlocks = 0;
5513
5514         yaffs_VerifyFreeChunks(dev);
5515
5516         T(YAFFS_TRACE_ALWAYS,
5517           (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
5518         return YAFFS_OK;
5519
5520 }
5521
5522 void yaffs_Deinitialise(yaffs_Device * dev)
5523 {
5524         if (dev->isMounted) {
5525                 int i;
5526
5527                 yaffs_DeinitialiseBlocks(dev);
5528                 yaffs_DeinitialiseTnodes(dev);
5529                 yaffs_DeinitialiseObjects(dev);
5530                 if (dev->nShortOpCaches > 0) {
5531
5532                         for (i = 0; i < dev->nShortOpCaches; i++) {
5533                                 YFREE(dev->srCache[i].data);
5534                         }
5535
5536                         YFREE(dev->srCache);
5537                 }
5538
5539                 YFREE(dev->gcCleanupList);
5540
5541                 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
5542                         YFREE(dev->tempBuffer[i].buffer);
5543                 }
5544
5545                 dev->isMounted = 0;
5546         }
5547
5548 }
5549
5550 static int yaffs_CountFreeChunks(yaffs_Device * dev)
5551 {
5552         int nFree;
5553         int b;
5554
5555         yaffs_BlockInfo *blk;
5556
5557         for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
5558              b++) {
5559                 blk = yaffs_GetBlockInfo(dev, b);
5560
5561                 switch (blk->blockState) {
5562                 case YAFFS_BLOCK_STATE_EMPTY:
5563                 case YAFFS_BLOCK_STATE_ALLOCATING:
5564                 case YAFFS_BLOCK_STATE_COLLECTING:
5565                 case YAFFS_BLOCK_STATE_FULL:
5566                         nFree +=
5567                             (dev->nChunksPerBlock - blk->pagesInUse +
5568                              blk->softDeletions);
5569                         break;
5570                 default:
5571                         break;
5572                 }
5573
5574         }
5575
5576         return nFree;
5577 }
5578
5579 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
5580 {
5581         /* This is what we report to the outside world */
5582
5583         int nFree;
5584         int nDirtyCacheChunks;
5585
5586 #if 1
5587         nFree = dev->nFreeChunks;
5588 #else
5589         nFree = yaffs_CountFreeChunks(dev);
5590 #endif
5591
5592         /* Now count the number of dirty chunks in the cache and subtract those */
5593
5594         {
5595                 int i;
5596                 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
5597                         if (dev->srCache[i].dirty)
5598                                 nDirtyCacheChunks++;
5599                 }
5600         }
5601
5602         nFree -= nDirtyCacheChunks;
5603
5604         nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
5605
5606         if (nFree < 0)
5607                 nFree = 0;
5608
5609         return nFree;
5610
5611 }
5612
5613 static int yaffs_freeVerificationFailures;
5614
5615 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
5616 {
5617         int counted = yaffs_CountFreeChunks(dev);
5618
5619         int difference = dev->nFreeChunks - counted;
5620
5621         if (difference) {
5622                 T(YAFFS_TRACE_ALWAYS,
5623                   (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
5624                    dev->nFreeChunks, counted, difference));
5625                 yaffs_freeVerificationFailures++;
5626         }
5627 }
5628
5629 /*---------------------------------------- YAFFS test code ----------------------*/
5630
5631 #define yaffs_CheckStruct(structure,syze, name) \
5632            if(sizeof(structure) != syze) \
5633                { \
5634                  T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
5635                  name,syze,sizeof(structure))); \
5636                  return YAFFS_FAIL; \
5637                 }
5638
5639 static int yaffs_CheckStructures(void)
5640 {
5641 /*      yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags") */
5642 /*      yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion") */
5643 /*      yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare") */
5644 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
5645         yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode")
5646 #endif
5647             yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader")
5648
5649             return YAFFS_OK;
5650 }