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