1f36cea86dd0ec7b0908299a7f444545e23c192c
[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.23 2005-11-07 07:19:34 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                 yaffs_InitialiseTags(&tags);
2664
2665                 tags.chunkDeleted = 1;
2666
2667                 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
2668                 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
2669         } else {
2670                 dev->nUnmarkedDeletions++;
2671         }
2672
2673         /* Pull out of the management area.
2674          * If the whole block became dirty, this will kick off an erasure.
2675          */
2676         if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2677             bi->blockState == YAFFS_BLOCK_STATE_FULL ||
2678             bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2679             bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2680                 dev->nFreeChunks++;
2681
2682                 yaffs_ClearChunkBit(dev, block, page);
2683
2684                 bi->pagesInUse--;
2685
2686                 if (bi->pagesInUse == 0 &&
2687                     !bi->hasShrinkHeader &&
2688                     bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
2689                     bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2690                         yaffs_BlockBecameDirty(dev, block);
2691                 }
2692
2693         } else {
2694                 /* T(("Bad news deleting chunk %d\n",chunkId)); */
2695         }
2696
2697 }
2698
2699 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
2700                                         const __u8 * buffer, int nBytes,
2701                                         int useReserve)
2702 {
2703         /* Find old chunk Need to do this to get serial number
2704          * Write new one and patch into tree.
2705          * Invalidate old tags.
2706          */
2707
2708         int prevChunkId;
2709         yaffs_ExtendedTags prevTags;
2710
2711         int newChunkId;
2712         yaffs_ExtendedTags newTags;
2713
2714         yaffs_Device *dev = in->myDev;
2715
2716         yaffs_CheckGarbageCollection(dev);
2717
2718         /* Get the previous chunk at this location in the file if it exists */
2719         prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
2720
2721         /* Set up new tags */
2722         yaffs_InitialiseTags(&newTags);
2723
2724         newTags.chunkId = chunkInInode;
2725         newTags.objectId = in->objectId;
2726         newTags.serialNumber =
2727             (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2728         newTags.byteCount = nBytes;
2729
2730         newChunkId =
2731             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2732                                               useReserve);
2733
2734         if (newChunkId >= 0) {
2735                 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
2736
2737                 if (prevChunkId >= 0) {
2738                         yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
2739
2740                 }
2741
2742                 yaffs_CheckFileSanity(in);
2743         }
2744         return newChunkId;
2745
2746 }
2747
2748 /* UpdateObjectHeader updates the header on NAND for an object.
2749  * If name is not NULL, then that new name is used.
2750  */
2751 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
2752                              int isShrink, int shadows)
2753 {
2754
2755         yaffs_BlockInfo *bi;
2756
2757         yaffs_Device *dev = in->myDev;
2758
2759         int prevChunkId;
2760         int retVal = 0;
2761
2762         int newChunkId;
2763         yaffs_ExtendedTags newTags;
2764
2765         __u8 *buffer = NULL;
2766         YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
2767
2768         yaffs_ObjectHeader *oh = NULL;
2769
2770         if (!in->fake || force) {
2771
2772                 yaffs_CheckGarbageCollection(dev);
2773
2774                 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
2775                 oh = (yaffs_ObjectHeader *) buffer;
2776
2777                 prevChunkId = in->chunkId;
2778
2779                 if (prevChunkId >= 0) {
2780                         yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
2781                                                         buffer, NULL);
2782                         memcpy(oldName, oh->name, sizeof(oh->name));
2783                 }
2784
2785                 memset(buffer, 0xFF, dev->nBytesPerChunk);
2786
2787                 oh->type = in->variantType;
2788                 oh->yst_mode = in->yst_mode;
2789                 oh->shadowsObject = shadows;
2790
2791 #ifdef CONFIG_YAFFS_WINCE
2792                 oh->win_atime[0] = in->win_atime[0];
2793                 oh->win_ctime[0] = in->win_ctime[0];
2794                 oh->win_mtime[0] = in->win_mtime[0];
2795                 oh->win_atime[1] = in->win_atime[1];
2796                 oh->win_ctime[1] = in->win_ctime[1];
2797                 oh->win_mtime[1] = in->win_mtime[1];
2798 #else
2799                 oh->yst_uid = in->yst_uid;
2800                 oh->yst_gid = in->yst_gid;
2801                 oh->yst_atime = in->yst_atime;
2802                 oh->yst_mtime = in->yst_mtime;
2803                 oh->yst_ctime = in->yst_ctime;
2804                 oh->yst_rdev = in->yst_rdev;
2805 #endif
2806                 if (in->parent) {
2807                         oh->parentObjectId = in->parent->objectId;
2808                 } else {
2809                         oh->parentObjectId = 0;
2810                 }
2811
2812                 if (name && *name) {
2813                         memset(oh->name, 0, sizeof(oh->name));
2814                         yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
2815                 } else if (prevChunkId) {
2816                         memcpy(oh->name, oldName, sizeof(oh->name));
2817                 } else {
2818                         memset(oh->name, 0, sizeof(oh->name));
2819                 }
2820
2821                 oh->isShrink = isShrink;
2822
2823                 switch (in->variantType) {
2824                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2825                         /* Should not happen */
2826                         break;
2827                 case YAFFS_OBJECT_TYPE_FILE:
2828                         oh->fileSize =
2829                             (oh->parentObjectId == YAFFS_OBJECTID_DELETED
2830                              || oh->parentObjectId ==
2831                              YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
2832                             fileVariant.fileSize;
2833                         break;
2834                 case YAFFS_OBJECT_TYPE_HARDLINK:
2835                         oh->equivalentObjectId =
2836                             in->variant.hardLinkVariant.equivalentObjectId;
2837                         break;
2838                 case YAFFS_OBJECT_TYPE_SPECIAL:
2839                         /* Do nothing */
2840                         break;
2841                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2842                         /* Do nothing */
2843                         break;
2844                 case YAFFS_OBJECT_TYPE_SYMLINK:
2845                         yaffs_strncpy(oh->alias,
2846                                       in->variant.symLinkVariant.alias,
2847                                       YAFFS_MAX_ALIAS_LENGTH);
2848                         oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
2849                         break;
2850                 }
2851
2852                 /* Tags */
2853                 yaffs_InitialiseTags(&newTags);
2854                 in->serial++;
2855                 newTags.chunkId = 0;
2856                 newTags.objectId = in->objectId;
2857                 newTags.serialNumber = in->serial;
2858
2859                 /* Add extra info for file header */
2860
2861                 newTags.extraHeaderInfoAvailable = 1;
2862                 newTags.extraParentObjectId = oh->parentObjectId;
2863                 newTags.extraFileLength = oh->fileSize;
2864                 newTags.extraIsShrinkHeader = oh->isShrink;
2865                 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
2866                 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
2867                 newTags.extraObjectType = in->variantType;
2868
2869                 /* Create new chunk in NAND */
2870                 newChunkId =
2871                     yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2872                                                       (prevChunkId >= 0) ? 1 : 0);
2873
2874                 if (newChunkId >= 0) {
2875
2876                         in->chunkId = newChunkId;
2877
2878                         if (prevChunkId >= 0) {
2879                                 yaffs_DeleteChunk(dev, prevChunkId, 1,
2880                                                   __LINE__);
2881                         }
2882
2883                         in->dirty = 0;
2884
2885                         /* If this was a shrink, then mark the block that the chunk lives on */
2886                         if (isShrink) {
2887                                 bi = yaffs_GetBlockInfo(in->myDev,
2888                                                         newChunkId /in->myDev-> nChunksPerBlock);
2889                                 bi->hasShrinkHeader = 1;
2890                         }
2891
2892                 }
2893
2894                 retVal = newChunkId;
2895
2896         }
2897
2898         if (buffer)
2899                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2900
2901         return retVal;
2902 }
2903
2904 /*------------------------ Short Operations Cache ----------------------------------------
2905  *   In many situations where there is no high level buffering (eg WinCE) a lot of
2906  *   reads might be short sequential reads, and a lot of writes may be short 
2907  *   sequential writes. eg. scanning/writing a jpeg file.
2908  *   In these cases, a short read/write cache can provide a huge perfomance benefit 
2909  *   with dumb-as-a-rock code.
2910  *   In Linux, the page cache provides read buffering aand the short op cache provides write 
2911  *   buffering.
2912  *
2913  *   There are a limited number (~10) of cache chunks per device so that we don't
2914  *   need a very intelligent search.
2915  */
2916
2917 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
2918 {
2919         yaffs_Device *dev = obj->myDev;
2920         int lowest = -99;       /* Stop compiler whining. */
2921         int i;
2922         yaffs_ChunkCache *cache;
2923         int chunkWritten = 0;
2924         int nCaches = obj->myDev->nShortOpCaches;
2925
2926         if (nCaches > 0) {
2927                 do {
2928                         cache = NULL;
2929
2930                         /* Find the dirty cache for this object with the lowest chunk id. */
2931                         for (i = 0; i < nCaches; i++) {
2932                                 if (dev->srCache[i].object == obj &&
2933                                     dev->srCache[i].dirty) {
2934                                         if (!cache
2935                                             || dev->srCache[i].chunkId <
2936                                             lowest) {
2937                                                 cache = &dev->srCache[i];
2938                                                 lowest = cache->chunkId;
2939                                         }
2940                                 }
2941                         }
2942
2943                         if (cache && !cache->locked) {
2944                                 /* Write it out and free it up */
2945
2946                                 chunkWritten =
2947                                     yaffs_WriteChunkDataToObject(cache->object,
2948                                                                  cache->chunkId,
2949                                                                  cache->data,
2950                                                                  cache->nBytes,
2951                                                                  1);
2952                                 cache->dirty = 0;
2953                                 cache->object = NULL;
2954                         }
2955
2956                 } while (cache && chunkWritten > 0);
2957
2958                 if (cache) {
2959                         /* Hoosterman, disk full while writing cache out. */
2960                         T(YAFFS_TRACE_ERROR,
2961                           (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
2962
2963                 }
2964         }
2965
2966 }
2967
2968 /* Grab us a cache chunk for use.
2969  * First look for an empty one. 
2970  * Then look for the least recently used non-dirty one.
2971  * Then look for the least recently used dirty one...., flush and look again.
2972  */
2973 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
2974 {
2975         int i;
2976         int usage;
2977         int theOne;
2978
2979         if (dev->nShortOpCaches > 0) {
2980                 for (i = 0; i < dev->nShortOpCaches; i++) {
2981                         if (!dev->srCache[i].object) 
2982                                 return &dev->srCache[i];
2983                 }
2984
2985                 return NULL;
2986
2987                 theOne = -1;
2988                 usage = 0;      /* just to stop the compiler grizzling */
2989
2990                 for (i = 0; i < dev->nShortOpCaches; i++) {
2991                         if (!dev->srCache[i].dirty &&
2992                             ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
2993                              theOne < 0)) {
2994                                 usage = dev->srCache[i].lastUse;
2995                                 theOne = i;
2996                         }
2997                 }
2998
2999
3000                 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3001         } else {
3002                 return NULL;
3003         }
3004
3005 }
3006
3007 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
3008 {
3009         yaffs_ChunkCache *cache;
3010         yaffs_Object *theObj;
3011         int usage;
3012         int i;
3013         int pushout;
3014
3015         if (dev->nShortOpCaches > 0) {
3016                 /* Try find a non-dirty one... */
3017
3018                 cache = yaffs_GrabChunkCacheWorker(dev);
3019
3020                 if (!cache) {
3021                         /* They were all dirty, find the last recently used object and flush
3022                          * its cache, then  find again.
3023                          * NB what's here is not very accurate, we actually flush the object
3024                          * the last recently used page.
3025                          */
3026
3027                         /* With locking we can't assume we can use entry zero */
3028
3029                         theObj = NULL;
3030                         usage = -1;
3031                         cache = NULL;
3032                         pushout = -1;
3033
3034                         for (i = 0; i < dev->nShortOpCaches; i++) {
3035                                 if (dev->srCache[i].object &&
3036                                     !dev->srCache[i].locked &&
3037                                     (dev->srCache[i].lastUse < usage || !cache))
3038                                 {
3039                                         usage = dev->srCache[i].lastUse;
3040                                         theObj = dev->srCache[i].object;
3041                                         cache = &dev->srCache[i];
3042                                         pushout = i;
3043                                 }
3044                         }
3045
3046                         if (!cache || cache->dirty) {
3047                                 /* Flush and try again */
3048                                 yaffs_FlushFilesChunkCache(theObj);
3049                                 cache = yaffs_GrabChunkCacheWorker(dev);
3050                         }
3051
3052                 }
3053                 return cache;
3054         } else
3055                 return NULL;
3056
3057 }
3058
3059 /* Find a cached chunk */
3060 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
3061                                               int chunkId)
3062 {
3063         yaffs_Device *dev = obj->myDev;
3064         int i;
3065         if (dev->nShortOpCaches > 0) {
3066                 for (i = 0; i < dev->nShortOpCaches; i++) {
3067                         if (dev->srCache[i].object == obj &&
3068                             dev->srCache[i].chunkId == chunkId) {
3069                                 dev->cacheHits++;
3070
3071                                 return &dev->srCache[i];
3072                         }
3073                 }
3074         }
3075         return NULL;
3076 }
3077
3078 /* Mark the chunk for the least recently used algorithym */
3079 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
3080                                 int isAWrite)
3081 {
3082
3083         if (dev->nShortOpCaches > 0) {
3084                 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
3085                         /* Reset the cache usages */
3086                         int i;
3087                         for (i = 1; i < dev->nShortOpCaches; i++) {
3088                                 dev->srCache[i].lastUse = 0;
3089                         }
3090                         dev->srLastUse = 0;
3091                 }
3092
3093                 dev->srLastUse++;
3094
3095                 cache->lastUse = dev->srLastUse;
3096
3097                 if (isAWrite) {
3098                         cache->dirty = 1;
3099                 }
3100         }
3101 }
3102
3103 /* Invalidate a single cache page.
3104  * Do this when a whole page gets written,
3105  * ie the short cache for this page is no longer valid.
3106  */
3107 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
3108 {
3109         if (object->myDev->nShortOpCaches > 0) {
3110                 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
3111
3112                 if (cache) {
3113                         cache->object = NULL;
3114                 }
3115         }
3116 }
3117
3118 /* Invalidate all the cache pages associated with this object
3119  * Do this whenever ther file is deleted or resized.
3120  */
3121 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
3122 {
3123         int i;
3124         yaffs_Device *dev = in->myDev;
3125
3126         if (dev->nShortOpCaches > 0) {
3127                 /* Invalidate it. */
3128                 for (i = 0; i < dev->nShortOpCaches; i++) {
3129                         if (dev->srCache[i].object == in) {
3130                                 dev->srCache[i].object = NULL;
3131                         }
3132                 }
3133         }
3134 }
3135
3136 /*--------------------- File read/write ------------------------
3137  * Read and write have very similar structures.
3138  * In general the read/write has three parts to it
3139  * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3140  * Some complete chunks
3141  * An incomplete chunk to end off with
3142  *
3143  * Curve-balls: the first chunk might also be the last chunk.
3144  */
3145
3146 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, __u32 offset,
3147                            int nBytes)
3148 {
3149
3150         int chunk;
3151         int start;
3152         int nToCopy;
3153         int n = nBytes;
3154         int nDone = 0;
3155         yaffs_ChunkCache *cache;
3156
3157         yaffs_Device *dev;
3158
3159         dev = in->myDev;
3160
3161         while (n > 0) {
3162                 chunk = offset / dev->nBytesPerChunk + 1;   /* The first chunk is 1 */
3163                 start = offset % dev->nBytesPerChunk;
3164
3165                 /* OK now check for the curveball where the start and end are in
3166                  * the same chunk.      
3167                  */
3168                 if ((start + n) < dev->nBytesPerChunk) {
3169                         nToCopy = n;
3170                 } else {
3171                         nToCopy = dev->nBytesPerChunk - start;
3172                 }
3173
3174                 cache = yaffs_FindChunkCache(in, chunk);
3175
3176                 /* If the chunk is already in the cache or it is less than a whole chunk
3177                  * then use the cache (if there is caching)
3178                  * else bypass the cache.
3179                  */
3180                 if (cache || nToCopy != dev->nBytesPerChunk) {
3181                         if (dev->nShortOpCaches > 0) {
3182
3183                                 /* If we can't find the data in the cache, then load it up. */
3184
3185                                 if (!cache) {
3186                                         cache = yaffs_GrabChunkCache(in->myDev);
3187                                         cache->object = in;
3188                                         cache->chunkId = chunk;
3189                                         cache->dirty = 0;
3190                                         cache->locked = 0;
3191                                         yaffs_ReadChunkDataFromObject(in, chunk,
3192                                                                       cache->
3193                                                                       data);
3194                                         cache->nBytes = 0;
3195                                 }
3196
3197                                 yaffs_UseChunkCache(dev, cache, 0);
3198
3199                                 cache->locked = 1;
3200
3201 #ifdef CONFIG_YAFFS_WINCE
3202                                 yfsd_UnlockYAFFS(TRUE);
3203 #endif
3204                                 memcpy(buffer, &cache->data[start], nToCopy);
3205
3206 #ifdef CONFIG_YAFFS_WINCE
3207                                 yfsd_LockYAFFS(TRUE);
3208 #endif
3209                                 cache->locked = 0;
3210                         } else {
3211                                 /* Read into the local buffer then copy..*/
3212
3213                                 __u8 *localBuffer =
3214                                     yaffs_GetTempBuffer(dev, __LINE__);
3215                                 yaffs_ReadChunkDataFromObject(in, chunk,
3216                                                               localBuffer);
3217 #ifdef CONFIG_YAFFS_WINCE
3218                                 yfsd_UnlockYAFFS(TRUE);
3219 #endif
3220                                 memcpy(buffer, &localBuffer[start], nToCopy);
3221
3222 #ifdef CONFIG_YAFFS_WINCE
3223                                 yfsd_LockYAFFS(TRUE);
3224 #endif
3225                                 yaffs_ReleaseTempBuffer(dev, localBuffer,
3226                                                         __LINE__);
3227                         }
3228
3229                 } else {
3230 #ifdef CONFIG_YAFFS_WINCE
3231                         __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3232
3233                         /* Under WinCE can't do direct transfer. Need to use a local buffer.
3234                          * This is because we otherwise screw up WinCE's memory mapper
3235                          */
3236                         yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
3237
3238 #ifdef CONFIG_YAFFS_WINCE
3239                         yfsd_UnlockYAFFS(TRUE);
3240 #endif
3241                         memcpy(buffer, localBuffer, dev->nBytesPerChunk);
3242
3243 #ifdef CONFIG_YAFFS_WINCE
3244                         yfsd_LockYAFFS(TRUE);
3245                         yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3246 #endif
3247
3248 #else
3249                         /* A full chunk. Read directly into the supplied buffer. */
3250                         yaffs_ReadChunkDataFromObject(in, chunk, buffer);
3251 #endif
3252                 }
3253
3254                 n -= nToCopy;
3255                 offset += nToCopy;
3256                 buffer += nToCopy;
3257                 nDone += nToCopy;
3258
3259         }
3260
3261         return nDone;
3262 }
3263
3264 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, __u32 offset,
3265                           int nBytes, int writeThrough)
3266 {
3267
3268         int chunk;
3269         int start;
3270         int nToCopy;
3271         int n = nBytes;
3272         int nDone = 0;
3273         int nToWriteBack;
3274         int startOfWrite = offset;
3275         int chunkWritten = 0;
3276         int nBytesRead;
3277
3278         yaffs_Device *dev;
3279
3280         dev = in->myDev;
3281
3282         while (n > 0 && chunkWritten >= 0) {
3283                 chunk = offset / dev->nBytesPerChunk + 1;
3284                 start = offset % dev->nBytesPerChunk;
3285
3286                 /* OK now check for the curveball where the start and end are in
3287                  * the same chunk.
3288                  */
3289
3290                 if ((start + n) < dev->nBytesPerChunk) {
3291                         nToCopy = n;
3292
3293                         /* Now folks, to calculate how many bytes to write back....
3294                          * If we're overwriting and not writing to then end of file then
3295                          * we need to write back as much as was there before.
3296                          */
3297
3298                         nBytesRead =
3299                             in->variant.fileVariant.fileSize -
3300                             ((chunk - 1) * dev->nBytesPerChunk);
3301
3302                         if (nBytesRead > dev->nBytesPerChunk) {
3303                                 nBytesRead = dev->nBytesPerChunk;
3304                         }
3305
3306                         nToWriteBack =
3307                             (nBytesRead >
3308                              (start + n)) ? nBytesRead : (start + n);
3309
3310                 } else {
3311                         nToCopy = dev->nBytesPerChunk - start;
3312                         nToWriteBack = dev->nBytesPerChunk;
3313                 }
3314
3315                 if (nToCopy != dev->nBytesPerChunk) {
3316                         /* An incomplete start or end chunk (or maybe both start and end chunk) */
3317                         if (dev->nShortOpCaches > 0) {
3318                                 yaffs_ChunkCache *cache;
3319                                 /* If we can't find the data in the cache, then load the cache */
3320                                 cache = yaffs_FindChunkCache(in, chunk);
3321                                 if (!cache
3322                                     && yaffs_CheckSpaceForAllocation(in->
3323                                                                      myDev)) {
3324                                         cache = yaffs_GrabChunkCache(in->myDev);
3325                                         cache->object = in;
3326                                         cache->chunkId = chunk;
3327                                         cache->dirty = 0;
3328                                         cache->locked = 0;
3329                                         yaffs_ReadChunkDataFromObject(in, chunk,
3330                                                                       cache->
3331                                                                       data);
3332                                 }
3333
3334                                 if (cache) {
3335                                         yaffs_UseChunkCache(dev, cache, 1);
3336                                         cache->locked = 1;
3337 #ifdef CONFIG_YAFFS_WINCE
3338                                         yfsd_UnlockYAFFS(TRUE);
3339 #endif
3340
3341                                         memcpy(&cache->data[start], buffer,
3342                                                nToCopy);
3343
3344 #ifdef CONFIG_YAFFS_WINCE
3345                                         yfsd_LockYAFFS(TRUE);
3346 #endif
3347                                         cache->locked = 0;
3348                                         cache->nBytes = nToWriteBack;
3349
3350                                         if (writeThrough) {
3351                                                 chunkWritten =
3352                                                     yaffs_WriteChunkDataToObject
3353                                                     (cache->object,
3354                                                      cache->chunkId,
3355                                                      cache->data, cache->nBytes,
3356                                                      1);
3357                                                 cache->dirty = 0;
3358                                         }
3359
3360                                 } else {
3361                                         chunkWritten = -1;      /* fail the write */
3362                                 }
3363                         } else {
3364                                 /* An incomplete start or end chunk (or maybe both start and end chunk)
3365                                  * Read into the local buffer then copy, then copy over and write back.
3366                                  */
3367
3368                                 __u8 *localBuffer =
3369                                     yaffs_GetTempBuffer(dev, __LINE__);
3370
3371                                 yaffs_ReadChunkDataFromObject(in, chunk,
3372                                                               localBuffer);
3373
3374 #ifdef CONFIG_YAFFS_WINCE
3375                                 yfsd_UnlockYAFFS(TRUE);
3376 #endif
3377
3378                                 memcpy(&localBuffer[start], buffer, nToCopy);
3379
3380 #ifdef CONFIG_YAFFS_WINCE
3381                                 yfsd_LockYAFFS(TRUE);
3382 #endif
3383                                 chunkWritten =
3384                                     yaffs_WriteChunkDataToObject(in, chunk,
3385                                                                  localBuffer,
3386                                                                  nToWriteBack,
3387                                                                  0);
3388
3389                                 yaffs_ReleaseTempBuffer(dev, localBuffer,
3390                                                         __LINE__);
3391
3392                         }
3393
3394                 } else {
3395
3396 #ifdef CONFIG_YAFFS_WINCE
3397                         /* Under WinCE can't do direct transfer. Need to use a local buffer.
3398                          * This is because we otherwise screw up WinCE's memory mapper
3399                          */
3400                         __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3401 #ifdef CONFIG_YAFFS_WINCE
3402                         yfsd_UnlockYAFFS(TRUE);
3403 #endif
3404                         memcpy(localBuffer, buffer, dev->nBytesPerChunk);
3405 #ifdef CONFIG_YAFFS_WINCE
3406                         yfsd_LockYAFFS(TRUE);
3407 #endif
3408                         chunkWritten =
3409                             yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
3410                                                          dev->nBytesPerChunk,
3411                                                          0);
3412                         yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3413 #else
3414                         /* A full chunk. Write directly from the supplied buffer. */
3415                         chunkWritten =
3416                             yaffs_WriteChunkDataToObject(in, chunk, buffer,
3417                                                          dev->nBytesPerChunk,
3418                                                          0);
3419 #endif
3420                         /* Since we've overwritten the cached data, we better invalidate it. */
3421                         yaffs_InvalidateChunkCache(in, chunk);
3422                 }
3423
3424                 if (chunkWritten >= 0) {
3425                         n -= nToCopy;
3426                         offset += nToCopy;
3427                         buffer += nToCopy;
3428                         nDone += nToCopy;
3429                 }
3430
3431         }
3432
3433         /* Update file object */
3434
3435         if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
3436                 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
3437         }
3438
3439         in->dirty = 1;
3440
3441         return nDone;
3442 }
3443
3444
3445 /* ---------------------- File resizing stuff ------------------ */
3446
3447 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
3448 {
3449
3450         yaffs_Device *dev = in->myDev;
3451         int oldFileSize = in->variant.fileVariant.fileSize;
3452
3453         int lastDel = 1 + (oldFileSize - 1) / dev->nBytesPerChunk;
3454
3455         int startDel = 1 + (newSize + dev->nBytesPerChunk - 1) /
3456             dev->nBytesPerChunk;
3457         int i;
3458         int chunkId;
3459
3460         /* Delete backwards so that we don't end up with holes if
3461          * power is lost part-way through the operation.
3462          */
3463         for (i = lastDel; i >= startDel; i--) {
3464                 /* NB this could be optimised somewhat,
3465                  * eg. could retrieve the tags and write them without
3466                  * using yaffs_DeleteChunk
3467                  */
3468
3469                 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
3470                 if (chunkId > 0) {
3471                         if (chunkId <
3472                             (dev->internalStartBlock * dev->nChunksPerBlock)
3473                             || chunkId >=
3474                             ((dev->internalEndBlock +
3475                               1) * dev->nChunksPerBlock)) {
3476                                 T(YAFFS_TRACE_ALWAYS,
3477                                   (TSTR("Found daft chunkId %d for %d" TENDSTR),
3478                                    chunkId, i));
3479                         } else {
3480                                 in->nDataChunks--;
3481                                 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
3482                         }
3483                 }
3484         }
3485
3486 }
3487
3488 int yaffs_ResizeFile(yaffs_Object * in, int newSize)
3489 {
3490
3491         int oldFileSize = in->variant.fileVariant.fileSize;
3492         int sizeOfPartialChunk;
3493         yaffs_Device *dev = in->myDev;
3494
3495         sizeOfPartialChunk = newSize % dev->nBytesPerChunk;
3496
3497         yaffs_FlushFilesChunkCache(in);
3498         yaffs_InvalidateWholeChunkCache(in);
3499
3500         yaffs_CheckGarbageCollection(dev);
3501
3502         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3503                 return yaffs_GetFileSize(in);
3504         }
3505
3506         if (newSize == oldFileSize) {
3507                 return oldFileSize;
3508         }
3509
3510         if (newSize < oldFileSize) {
3511
3512                 yaffs_PruneResizedChunks(in, newSize);
3513
3514                 if (sizeOfPartialChunk != 0) {
3515                         int lastChunk = 1 + newSize / dev->nBytesPerChunk;
3516                         __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3517
3518                         /* Got to read and rewrite the last chunk with its new size and zero pad */
3519                         yaffs_ReadChunkDataFromObject(in, lastChunk,
3520                                                       localBuffer);
3521
3522                         memset(localBuffer + sizeOfPartialChunk, 0,
3523                                dev->nBytesPerChunk - sizeOfPartialChunk);
3524
3525                         yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
3526                                                      sizeOfPartialChunk, 1);
3527
3528                         yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3529                 }
3530
3531                 in->variant.fileVariant.fileSize = newSize;
3532
3533                 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
3534         }
3535         /* Write a new object header.
3536          * show we've shrunk the file, if need be
3537          * Do this only if the file is not in the deleted directories.
3538          */
3539         if (in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
3540             in->parent->objectId != YAFFS_OBJECTID_DELETED) {
3541                 yaffs_UpdateObjectHeader(in, NULL, 0,
3542                                          (newSize < oldFileSize) ? 1 : 0, 0);
3543         }
3544
3545         return newSize;
3546 }
3547
3548 loff_t yaffs_GetFileSize(yaffs_Object * obj)
3549 {
3550         obj = yaffs_GetEquivalentObject(obj);
3551
3552         switch (obj->variantType) {
3553         case YAFFS_OBJECT_TYPE_FILE:
3554                 return obj->variant.fileVariant.fileSize;
3555         case YAFFS_OBJECT_TYPE_SYMLINK:
3556                 return yaffs_strlen(obj->variant.symLinkVariant.alias);
3557         default:
3558                 return 0;
3559         }
3560 }
3561
3562
3563
3564 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
3565 {
3566         int retVal;
3567         if (in->dirty) {
3568                 yaffs_FlushFilesChunkCache(in);
3569                 if (updateTime) {
3570 #ifdef CONFIG_YAFFS_WINCE
3571                         yfsd_WinFileTimeNow(in->win_mtime);
3572 #else
3573
3574                         in->yst_mtime = Y_CURRENT_TIME;
3575
3576 #endif
3577                 }
3578
3579                 retVal =
3580                     (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
3581                      0) ? YAFFS_OK : YAFFS_FAIL;
3582         } else {
3583                 retVal = YAFFS_OK;
3584         }
3585
3586         return retVal;
3587
3588 }
3589
3590 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
3591 {
3592
3593         /* First off, invalidate the file's data in the cache, without flushing. */
3594         yaffs_InvalidateWholeChunkCache(in);
3595
3596         if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
3597                 /* Move to the unlinked directory so we have a record that it was deleted. */
3598                 yaffs_ChangeObjectName(in, in->myDev->deletedDir, NULL, 0, 0);
3599
3600         }
3601
3602         yaffs_RemoveObjectFromDirectory(in);
3603         yaffs_DeleteChunk(in->myDev, in->chunkId, 1, __LINE__);
3604         in->chunkId = -1;
3605
3606         yaffs_FreeObject(in);
3607         return YAFFS_OK;
3608
3609 }
3610
3611 /* yaffs_DeleteFile deletes the whole file data
3612  * and the inode associated with the file.
3613  * It does not delete the links associated with the file.
3614  */
3615 static int yaffs_UnlinkFile(yaffs_Object * in)
3616 {
3617
3618         int retVal;
3619         int immediateDeletion = 0;
3620
3621         if (1) {
3622 #ifdef __KERNEL__
3623                 if (!in->myInode) {
3624                         immediateDeletion = 1;
3625
3626                 }
3627 #else
3628                 if (in->inUse <= 0) {
3629                         immediateDeletion = 1;
3630
3631                 }
3632 #endif
3633                 if (immediateDeletion) {
3634                         retVal =
3635                             yaffs_ChangeObjectName(in, in->myDev->deletedDir,
3636                                                    NULL, 0, 0);
3637                         T(YAFFS_TRACE_TRACING,
3638                           (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
3639                            in->objectId));
3640                         in->deleted = 1;
3641                         in->myDev->nDeletedFiles++;
3642                         if (0 && in->myDev->isYaffs2) {
3643                                 yaffs_ResizeFile(in, 0);
3644                         }
3645                         yaffs_SoftDeleteFile(in);
3646                 } else {
3647                         retVal =
3648                             yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
3649                                                    NULL, 0, 0);
3650                 }
3651
3652         }
3653         return retVal;
3654 }
3655
3656 int yaffs_DeleteFile(yaffs_Object * in)
3657 {
3658         int retVal = YAFFS_OK;
3659
3660         if (in->nDataChunks > 0) {
3661                 /* Use soft deletion if there is data in the file */
3662                 if (!in->unlinked) {
3663                         retVal = yaffs_UnlinkFile(in);
3664                 }
3665                 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
3666                         in->deleted = 1;
3667                         in->myDev->nDeletedFiles++;
3668                         yaffs_SoftDeleteFile(in);
3669                 }
3670                 return in->deleted ? YAFFS_OK : YAFFS_FAIL;
3671         } else {
3672                 /* The file has no data chunks so we toss it immediately */
3673                 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
3674                 in->variant.fileVariant.top = NULL;
3675                 yaffs_DoGenericObjectDeletion(in);
3676
3677                 return YAFFS_OK;
3678         }
3679 }
3680
3681 static int yaffs_DeleteDirectory(yaffs_Object * in)
3682 {
3683         /* First check that the directory is empty. */
3684         if (list_empty(&in->variant.directoryVariant.children)) {
3685                 return yaffs_DoGenericObjectDeletion(in);
3686         }
3687
3688         return YAFFS_FAIL;
3689
3690 }
3691
3692 static int yaffs_DeleteSymLink(yaffs_Object * in)
3693 {
3694         YFREE(in->variant.symLinkVariant.alias);
3695
3696         return yaffs_DoGenericObjectDeletion(in);
3697 }
3698
3699 static int yaffs_DeleteHardLink(yaffs_Object * in)
3700 {
3701         /* remove this hardlink from the list assocaited with the equivalent
3702          * object
3703          */
3704         list_del(&in->hardLinks);
3705         return yaffs_DoGenericObjectDeletion(in);
3706 }
3707
3708 static void yaffs_DestroyObject(yaffs_Object * obj)
3709 {
3710         switch (obj->variantType) {
3711         case YAFFS_OBJECT_TYPE_FILE:
3712                 yaffs_DeleteFile(obj);
3713                 break;
3714         case YAFFS_OBJECT_TYPE_DIRECTORY:
3715                 yaffs_DeleteDirectory(obj);
3716                 break;
3717         case YAFFS_OBJECT_TYPE_SYMLINK:
3718                 yaffs_DeleteSymLink(obj);
3719                 break;
3720         case YAFFS_OBJECT_TYPE_HARDLINK:
3721                 yaffs_DeleteHardLink(obj);
3722                 break;
3723         case YAFFS_OBJECT_TYPE_SPECIAL:
3724                 yaffs_DoGenericObjectDeletion(obj);
3725                 break;
3726         case YAFFS_OBJECT_TYPE_UNKNOWN:
3727                 break;          /* should not happen. */
3728         }
3729 }
3730
3731 static int yaffs_UnlinkWorker(yaffs_Object * obj)
3732 {
3733
3734         if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
3735                 return yaffs_DeleteHardLink(obj);
3736         } else if (!list_empty(&obj->hardLinks)) {
3737                 /* Curve ball: We're unlinking an object that has a hardlink.
3738                  *
3739                  * This problem arises because we are not strictly following
3740                  * The Linux link/inode model.
3741                  *
3742                  * We can't really delete the object.
3743                  * Instead, we do the following:
3744                  * - Select a hardlink.
3745                  * - Unhook it from the hard links
3746                  * - Unhook it from its parent directory (so that the rename can work)
3747                  * - Rename the object to the hardlink's name.
3748                  * - Delete the hardlink
3749                  */
3750
3751                 yaffs_Object *hl;
3752                 int retVal;
3753                 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
3754
3755                 hl = list_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
3756
3757                 list_del_init(&hl->hardLinks);
3758                 list_del_init(&hl->siblings);
3759
3760                 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
3761
3762                 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
3763
3764                 if (retVal == YAFFS_OK) {
3765                         retVal = yaffs_DoGenericObjectDeletion(hl);
3766                 }
3767                 return retVal;
3768
3769         } else {
3770                 switch (obj->variantType) {
3771                 case YAFFS_OBJECT_TYPE_FILE:
3772                         return yaffs_UnlinkFile(obj);
3773                         break;
3774                 case YAFFS_OBJECT_TYPE_DIRECTORY:
3775                         return yaffs_DeleteDirectory(obj);
3776                         break;
3777                 case YAFFS_OBJECT_TYPE_SYMLINK:
3778                         return yaffs_DeleteSymLink(obj);
3779                         break;
3780                 case YAFFS_OBJECT_TYPE_SPECIAL:
3781                         return yaffs_DoGenericObjectDeletion(obj);
3782                         break;
3783                 case YAFFS_OBJECT_TYPE_HARDLINK:
3784                 case YAFFS_OBJECT_TYPE_UNKNOWN:
3785                 default:
3786                         return YAFFS_FAIL;
3787                 }
3788         }
3789 }
3790
3791
3792 static int yaffs_UnlinkObject( yaffs_Object *obj)
3793 {
3794
3795         if (obj && obj->unlinkAllowed) {
3796                 return yaffs_UnlinkWorker(obj);
3797         }
3798
3799         return YAFFS_FAIL;
3800
3801 }
3802 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
3803 {
3804         yaffs_Object *obj;
3805
3806         obj = yaffs_FindObjectByName(dir, name);
3807         return yaffs_UnlinkObject(obj);
3808 }
3809
3810 /*----------------------- Initialisation Scanning ---------------------- */
3811
3812 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
3813                                        int backwardScanning)
3814 {
3815         yaffs_Object *obj;
3816
3817         if (!backwardScanning) {
3818                 /* Handle YAFFS1 forward scanning case
3819                  * For YAFFS1 we always do the deletion
3820                  */
3821
3822         } else {
3823                 /* Handle YAFFS2 case (backward scanning)
3824                  * If the shadowed object exists then ignore.
3825                  */
3826                 if (yaffs_FindObjectByNumber(dev, objId)) {
3827                         return;
3828                 }
3829         }
3830
3831         /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
3832          * We put it in unlinked dir to be cleaned up after the scanning
3833          */
3834         obj =
3835             yaffs_FindOrCreateObjectByNumber(dev, objId,
3836                                              YAFFS_OBJECT_TYPE_FILE);
3837         yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
3838         obj->variant.fileVariant.shrinkSize = 0;
3839         obj->valid = 1;         /* So that we don't read any other info for this file */
3840
3841 }
3842
3843 typedef struct {
3844         int seq;
3845         int block;
3846 } yaffs_BlockIndex;
3847
3848 static int yaffs_Scan(yaffs_Device * dev)
3849 {
3850         yaffs_ExtendedTags tags;
3851         int blk;
3852         int blockIterator;
3853         int startIterator;
3854         int endIterator;
3855         int nBlocksToScan = 0;
3856
3857         int chunk;
3858         int c;
3859         int deleted;
3860         yaffs_BlockState state;
3861         yaffs_Object *hardList = NULL;
3862         yaffs_Object *hl;
3863         yaffs_BlockInfo *bi;
3864         int sequenceNumber;
3865         yaffs_ObjectHeader *oh;
3866         yaffs_Object *in;
3867         yaffs_Object *parent;
3868         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
3869
3870         __u8 *chunkData;
3871
3872         yaffs_BlockIndex *blockIndex = NULL;
3873
3874         T(YAFFS_TRACE_SCAN,
3875           (TSTR("yaffs_Scan starts  intstartblk %d intendblk %d..." TENDSTR),
3876            dev->internalStartBlock, dev->internalEndBlock));
3877
3878         chunkData = yaffs_GetTempBuffer(dev, __LINE__);
3879
3880         dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
3881
3882         if (dev->isYaffs2) {
3883                 blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
3884         }
3885
3886         /* Scan all the blocks to determine their state */
3887         for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
3888                 bi = yaffs_GetBlockInfo(dev, blk);
3889                 yaffs_ClearChunkBits(dev, blk);
3890                 bi->pagesInUse = 0;
3891                 bi->softDeletions = 0;
3892
3893                 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
3894
3895                 bi->blockState = state;
3896                 bi->sequenceNumber = sequenceNumber;
3897
3898                 T(YAFFS_TRACE_SCAN_DEBUG,
3899                   (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
3900                    state, sequenceNumber));
3901
3902                 if (state == YAFFS_BLOCK_STATE_DEAD) {
3903                         T(YAFFS_TRACE_BAD_BLOCKS,
3904                           (TSTR("block %d is bad" TENDSTR), blk));
3905                 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
3906                         T(YAFFS_TRACE_SCAN_DEBUG,
3907                           (TSTR("Block empty " TENDSTR)));
3908                         dev->nErasedBlocks++;
3909                         dev->nFreeChunks += dev->nChunksPerBlock;
3910                 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3911
3912                         /* Determine the highest sequence number */
3913                         if (dev->isYaffs2 &&
3914                             sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
3915                             sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
3916
3917                                 blockIndex[nBlocksToScan].seq = sequenceNumber;
3918                                 blockIndex[nBlocksToScan].block = blk;
3919
3920                                 nBlocksToScan++;
3921
3922                                 if (sequenceNumber >= dev->sequenceNumber) {
3923                                         dev->sequenceNumber = sequenceNumber;
3924                                 }
3925                         } else if (dev->isYaffs2) {
3926                                 /* TODO: Nasty sequence number! */
3927                                 T(YAFFS_TRACE_SCAN,
3928                                   (TSTR
3929                                    ("Block scanning block %d has bad sequence number %d"
3930                                     TENDSTR), blk, sequenceNumber));
3931
3932                         }
3933                 }
3934         }
3935
3936         /* Sort the blocks
3937          * Dungy old bubble sort for now...
3938          */
3939         if (dev->isYaffs2) {
3940                 yaffs_BlockIndex temp;
3941                 int i;
3942                 int j;
3943
3944                 for (i = 0; i < nBlocksToScan; i++)
3945                         for (j = i + 1; j < nBlocksToScan; j++)
3946                                 if (blockIndex[i].seq > blockIndex[j].seq) {
3947                                         temp = blockIndex[j];
3948                                         blockIndex[j] = blockIndex[i];
3949                                         blockIndex[i] = temp;
3950                                 }
3951         }
3952
3953         /* Now scan the blocks looking at the data. */
3954         if (dev->isYaffs2) {
3955                 startIterator = 0;
3956                 endIterator = nBlocksToScan - 1;
3957                 T(YAFFS_TRACE_SCAN_DEBUG,
3958                   (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
3959         } else {
3960                 startIterator = dev->internalStartBlock;
3961                 endIterator = dev->internalEndBlock;
3962         }
3963
3964         /* For each block.... */
3965         for (blockIterator = startIterator; blockIterator <= endIterator;
3966              blockIterator++) {
3967
3968                 if (dev->isYaffs2) {
3969                         /* get the block to scan in the correct order */
3970                         blk = blockIndex[blockIterator].block;
3971                 } else {
3972                         blk = blockIterator;
3973                 }
3974
3975                 bi = yaffs_GetBlockInfo(dev, blk);
3976                 state = bi->blockState;
3977
3978                 deleted = 0;
3979
3980                 /* For each chunk in each block that needs scanning....*/
3981                 for (c = 0; c < dev->nChunksPerBlock &&
3982                      state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
3983                         /* Read the tags and decide what to do */
3984                         chunk = blk * dev->nChunksPerBlock + c;
3985
3986                         yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
3987                                                         &tags);
3988
3989                         /* Let's have a good look at this chunk... */
3990
3991                         if (!dev->isYaffs2 && tags.chunkDeleted) {
3992                                 /* YAFFS1 only...
3993                                  * A deleted chunk
3994                                  */
3995                                 deleted++;
3996                                 dev->nFreeChunks++;
3997                                 /*T((" %d %d deleted\n",blk,c)); */
3998                         } else if (!tags.chunkUsed) {
3999                                 /* An unassigned chunk in the block
4000                                  * This means that either the block is empty or 
4001                                  * this is the one being allocated from
4002                                  */
4003
4004                                 if (c == 0) {
4005                                         /* We're looking at the first chunk in the block so the block is unused */
4006                                         state = YAFFS_BLOCK_STATE_EMPTY;
4007                                         dev->nErasedBlocks++;
4008                                 } else {
4009                                         /* this is the block being allocated from */
4010                                         T(YAFFS_TRACE_SCAN,
4011                                           (TSTR
4012                                            (" Allocating from %d %d" TENDSTR),
4013                                            blk, c));
4014                                         state = YAFFS_BLOCK_STATE_ALLOCATING;
4015                                         dev->allocationBlock = blk;
4016                                         dev->allocationPage = c;
4017                                         dev->allocationBlockFinder = blk;       
4018                                         /* Set it to here to encourage the allocator to go forth from here. */
4019                                         
4020                                         /* Yaffs2 sanity check:
4021                                          * This should be the one with the highest sequence number
4022                                          */
4023                                         if (dev->isYaffs2
4024                                             && (dev->sequenceNumber !=
4025                                                 bi->sequenceNumber)) {
4026                                                 T(YAFFS_TRACE_ALWAYS,
4027                                                   (TSTR
4028                                                    ("yaffs: Allocation block %d was not highest sequence id:"
4029                                                     " block seq = %d, dev seq = %d"
4030                                                     TENDSTR), blk,bi->sequenceNumber,dev->sequenceNumber));
4031                                         }
4032                                 }
4033
4034                                 dev->nFreeChunks += (dev->nChunksPerBlock - c);
4035                         } else if (tags.chunkId > 0) {
4036                                 /* chunkId > 0 so it is a data chunk... */
4037                                 unsigned int endpos;
4038
4039                                 yaffs_SetChunkBit(dev, blk, c);
4040                                 bi->pagesInUse++;
4041
4042                                 in = yaffs_FindOrCreateObjectByNumber(dev,
4043                                                                       tags.
4044                                                                       objectId,
4045                                                                       YAFFS_OBJECT_TYPE_FILE);
4046                                 /* PutChunkIntoFile checks for a clash (two data chunks with
4047                                  * the same chunkId).
4048                                  */
4049                                 yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,
4050                                                        1);
4051                                 endpos =
4052                                     (tags.chunkId - 1) * dev->nBytesPerChunk +
4053                                     tags.byteCount;
4054                                 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
4055                                     && in->variant.fileVariant.scannedFileSize <
4056                                     endpos) {
4057                                         in->variant.fileVariant.
4058                                             scannedFileSize = endpos;
4059                                         if (!dev->useHeaderFileSize) {
4060                                                 in->variant.fileVariant.
4061                                                     fileSize =
4062                                                     in->variant.fileVariant.
4063                                                     scannedFileSize;
4064                                         }
4065
4066                                 }
4067                                 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));   */
4068                         } else {
4069                                 /* chunkId == 0, so it is an ObjectHeader.
4070                                  * Thus, we read in the object header and make the object
4071                                  */
4072                                 yaffs_SetChunkBit(dev, blk, c);
4073                                 bi->pagesInUse++;
4074
4075                                 yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
4076                                                                 chunkData,
4077                                                                 NULL);
4078
4079                                 oh = (yaffs_ObjectHeader *) chunkData;
4080
4081                                 in = yaffs_FindObjectByNumber(dev,
4082                                                               tags.objectId);
4083                                 if (in && in->variantType != oh->type) {
4084                                         /* This should not happen, but somehow
4085                                          * Wev'e ended up with an objectId that has been reused but not yet 
4086                                          * deleted, and worse still it has changed type. Delete the old object.
4087                                          */
4088
4089                                         yaffs_DestroyObject(in);
4090
4091                                         in = 0;
4092                                 }
4093
4094                                 in = yaffs_FindOrCreateObjectByNumber(dev,
4095                                                                       tags.
4096                                                                       objectId,
4097                                                                       oh->type);
4098
4099                                 if (oh->shadowsObject > 0) {
4100                                         yaffs_HandleShadowedObject(dev,
4101                                                                    oh->
4102                                                                    shadowsObject,
4103                                                                    0);
4104                                 }
4105
4106                                 if (in->valid) {
4107                                         /* We have already filled this one. We have a duplicate and need to resolve it. */
4108
4109                                         unsigned existingSerial = in->serial;
4110                                         unsigned newSerial = tags.serialNumber;
4111
4112                                         if (dev->isYaffs2 ||
4113                                             ((existingSerial + 1) & 3) ==
4114                                             newSerial) {
4115                                                 /* Use new one - destroy the exisiting one */
4116                                                 yaffs_DeleteChunk(dev,
4117                                                                   in->chunkId,
4118                                                                   1, __LINE__);
4119                                                 in->valid = 0;
4120                                         } else {
4121                                                 /* Use existing - destroy this one. */
4122                                                 yaffs_DeleteChunk(dev, chunk, 1,
4123                                                                   __LINE__);
4124                                         }
4125                                 }
4126
4127                                 if (!in->valid &&
4128                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
4129                                      tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
4130                                         /* We only load some info, don't fiddle with directory structure */
4131                                         in->valid = 1;
4132                                         in->variantType = oh->type;
4133
4134                                         in->yst_mode = oh->yst_mode;
4135 #ifdef CONFIG_YAFFS_WINCE
4136                                         in->win_atime[0] = oh->win_atime[0];
4137                                         in->win_ctime[0] = oh->win_ctime[0];
4138                                         in->win_mtime[0] = oh->win_mtime[0];
4139                                         in->win_atime[1] = oh->win_atime[1];
4140                                         in->win_ctime[1] = oh->win_ctime[1];
4141                                         in->win_mtime[1] = oh->win_mtime[1];
4142 #else
4143                                         in->yst_uid = oh->yst_uid;
4144                                         in->yst_gid = oh->yst_gid;
4145                                         in->yst_atime = oh->yst_atime;
4146                                         in->yst_mtime = oh->yst_mtime;
4147                                         in->yst_ctime = oh->yst_ctime;
4148                                         in->yst_rdev = oh->yst_rdev;
4149 #endif
4150                                         in->chunkId = chunk;
4151
4152                                 } else if (!in->valid) {
4153                                         /* we need to load this info */
4154
4155                                         in->valid = 1;
4156                                         in->variantType = oh->type;
4157
4158                                         in->yst_mode = oh->yst_mode;
4159 #ifdef CONFIG_YAFFS_WINCE
4160                                         in->win_atime[0] = oh->win_atime[0];
4161                                         in->win_ctime[0] = oh->win_ctime[0];
4162                                         in->win_mtime[0] = oh->win_mtime[0];
4163                                         in->win_atime[1] = oh->win_atime[1];
4164                                         in->win_ctime[1] = oh->win_ctime[1];
4165                                         in->win_mtime[1] = oh->win_mtime[1];
4166 #else
4167                                         in->yst_uid = oh->yst_uid;
4168                                         in->yst_gid = oh->yst_gid;
4169                                         in->yst_atime = oh->yst_atime;
4170                                         in->yst_mtime = oh->yst_mtime;
4171                                         in->yst_ctime = oh->yst_ctime;
4172                                         in->yst_rdev = oh->yst_rdev;
4173 #endif
4174                                         in->chunkId = chunk;
4175
4176                                         yaffs_SetObjectName(in, oh->name);
4177                                         in->dirty = 0;
4178
4179                                         /* directory stuff...
4180                                          * hook up to parent
4181                                          */
4182
4183                                         parent =
4184                                             yaffs_FindOrCreateObjectByNumber
4185                                             (dev, oh->parentObjectId,
4186                                              YAFFS_OBJECT_TYPE_DIRECTORY);
4187                                         if (parent->variantType ==
4188                                             YAFFS_OBJECT_TYPE_UNKNOWN) {
4189                                                 /* Set up as a directory */
4190                                                 parent->variantType =
4191                                                     YAFFS_OBJECT_TYPE_DIRECTORY;
4192                                                 INIT_LIST_HEAD(&parent->variant.
4193                                                                directoryVariant.
4194                                                                children);
4195                                         } else if (parent->variantType !=
4196                                                    YAFFS_OBJECT_TYPE_DIRECTORY)
4197                                         {
4198                                                 /* Hoosterman, another problem....
4199                                                  * We're trying to use a non-directory as a directory
4200                                                  */
4201
4202                                                 T(YAFFS_TRACE_ERROR,
4203                                                   (TSTR
4204                                                    ("yaffs tragedy: attempting to use non-directory as"
4205                                                     " a directory in scan. Put in lost+found."
4206                                                     TENDSTR)));
4207                                                 parent = dev->lostNFoundDir;
4208                                         }
4209
4210                                         yaffs_AddObjectToDirectory(parent, in);
4211
4212                                         if (0 && (parent == dev->deletedDir ||
4213                                                   parent == dev->unlinkedDir)) {
4214                                                 in->deleted = 1;        /* If it is unlinked at start up then it wants deleting */
4215                                                 dev->nDeletedFiles++;
4216                                         }
4217                                         /* Note re hardlinks.
4218                                          * Since we might scan a hardlink before its equivalent object is scanned
4219                                          * we put them all in a list.
4220                                          * After scanning is complete, we should have all the objects, so we run through this
4221                                          * list and fix up all the chains.              
4222                                          */
4223
4224                                         switch (in->variantType) {
4225                                         case YAFFS_OBJECT_TYPE_UNKNOWN: 
4226                                                 /* Todo got a problem */
4227                                                 break;
4228                                         case YAFFS_OBJECT_TYPE_FILE:
4229                                                 if (dev->isYaffs2
4230                                                     && oh->isShrink) {
4231                                                         /* Prune back the shrunken chunks */
4232                                                         yaffs_PruneResizedChunks
4233                                                             (in, oh->fileSize);
4234                                                         /* Mark the block as having a shrinkHeader */
4235                                                         bi->hasShrinkHeader = 1;
4236                                                 }
4237
4238                                                 if (dev->useHeaderFileSize)
4239
4240                                                         in->variant.fileVariant.
4241                                                             fileSize =
4242                                                             oh->fileSize;
4243
4244                                                 break;
4245                                         case YAFFS_OBJECT_TYPE_HARDLINK:
4246                                                 in->variant.hardLinkVariant.
4247                                                     equivalentObjectId =
4248                                                     oh->equivalentObjectId;
4249                                                 in->hardLinks.next =
4250                                                     (struct list_head *)
4251                                                     hardList;
4252                                                 hardList = in;
4253                                                 break;
4254                                         case YAFFS_OBJECT_TYPE_DIRECTORY:
4255                                                 /* Do nothing */
4256                                                 break;
4257                                         case YAFFS_OBJECT_TYPE_SPECIAL:
4258                                                 /* Do nothing */
4259                                                 break;
4260                                         case YAFFS_OBJECT_TYPE_SYMLINK: 
4261                                                 in->variant.symLinkVariant.
4262                                                     alias =
4263                                                     yaffs_CloneString(oh->alias);
4264                                                 break;
4265                                         }
4266
4267                                         if (parent == dev->deletedDir) {
4268                                                 yaffs_DestroyObject(in);
4269                                                 bi->hasShrinkHeader = 1;
4270                                         }
4271                                 }
4272                         }
4273                 }
4274
4275                 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4276                         /* If we got this far while scanning, then the block is fully allocated.*/
4277                         state = YAFFS_BLOCK_STATE_FULL;
4278                 }
4279
4280                 bi->blockState = state;
4281
4282                 /* Now let's see if it was dirty */
4283                 if (bi->pagesInUse == 0 &&
4284                     !bi->hasShrinkHeader &&
4285                     bi->blockState == YAFFS_BLOCK_STATE_FULL) {
4286                         yaffs_BlockBecameDirty(dev, blk);
4287                 }
4288
4289         }
4290
4291         if (blockIndex) {
4292                 YFREE(blockIndex);
4293         }
4294         
4295         /* Ok, we've done all the scanning.
4296          * Fix up the hard link chains.
4297          * We should now have scanned all the objects, now it's time to add these 
4298          * hardlinks.
4299          */
4300         while (hardList) {
4301                 hl = hardList;
4302                 hardList = (yaffs_Object *) (hardList->hardLinks.next);
4303
4304                 in = yaffs_FindObjectByNumber(dev,
4305                                               hl->variant.hardLinkVariant.
4306                                               equivalentObjectId);
4307
4308                 if (in) {
4309                         /* Add the hardlink pointers */
4310                         hl->variant.hardLinkVariant.equivalentObject = in;
4311                         list_add(&hl->hardLinks, &in->hardLinks);
4312                 } else {
4313                         /* Todo Need to report/handle this better.
4314                          * Got a problem... hardlink to a non-existant object
4315                          */
4316                         hl->variant.hardLinkVariant.equivalentObject = NULL;
4317                         INIT_LIST_HEAD(&hl->hardLinks);
4318
4319                 }
4320
4321         }
4322
4323         /* Handle the unlinked files. Since they were left in an unlinked state we should
4324          * just delete them.
4325          */
4326         {
4327                 struct list_head *i;
4328                 struct list_head *n;
4329
4330                 yaffs_Object *l;
4331                 /* Soft delete all the unlinked files */
4332                 list_for_each_safe(i, n,
4333                                    &dev->unlinkedDir->variant.directoryVariant.
4334                                    children) {
4335                         if (i) {
4336                                 l = list_entry(i, yaffs_Object, siblings);
4337                                 yaffs_DestroyObject(l);
4338                         }
4339                 }
4340         }
4341
4342         yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
4343
4344         T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
4345
4346         return YAFFS_OK;
4347 }
4348
4349 static int yaffs_ScanBackwards(yaffs_Device * dev)
4350 {
4351         yaffs_ExtendedTags tags;
4352         int blk;
4353         int blockIterator;
4354         int startIterator;
4355         int endIterator;
4356         int nBlocksToScan = 0;
4357
4358         int chunk;
4359         int c;
4360         int deleted;
4361         yaffs_BlockState state;
4362         yaffs_Object *hardList = NULL;
4363         yaffs_Object *hl;
4364         yaffs_BlockInfo *bi;
4365         int sequenceNumber;
4366         yaffs_ObjectHeader *oh;
4367         yaffs_Object *in;
4368         yaffs_Object *parent;
4369         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
4370
4371         __u8 *chunkData;
4372
4373         yaffs_BlockIndex *blockIndex = NULL;
4374
4375         if (!dev->isYaffs2) {
4376                 T(YAFFS_TRACE_SCAN,
4377                   (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
4378                 return YAFFS_FAIL;
4379         }
4380
4381         T(YAFFS_TRACE_SCAN,
4382           (TSTR
4383            ("yaffs_ScanBackwards starts  intstartblk %d intendblk %d..."
4384             TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
4385
4386         chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4387
4388         dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
4389
4390         blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
4391
4392         /* Scan all the blocks to determine their state */
4393         for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
4394                 bi = yaffs_GetBlockInfo(dev, blk);
4395                 yaffs_ClearChunkBits(dev, blk);
4396                 bi->pagesInUse = 0;
4397                 bi->softDeletions = 0;
4398
4399                 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
4400
4401                 bi->blockState = state;
4402                 bi->sequenceNumber = sequenceNumber;
4403
4404                 T(YAFFS_TRACE_SCAN_DEBUG,
4405                   (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
4406                    state, sequenceNumber));
4407
4408                 if (state == YAFFS_BLOCK_STATE_DEAD) {
4409                         T(YAFFS_TRACE_BAD_BLOCKS,
4410                           (TSTR("block %d is bad" TENDSTR), blk));
4411                 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
4412                         T(YAFFS_TRACE_SCAN_DEBUG,
4413                           (TSTR("Block empty " TENDSTR)));
4414                         dev->nErasedBlocks++;
4415                         dev->nFreeChunks += dev->nChunksPerBlock;
4416                 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4417
4418                         /* Determine the highest sequence number */
4419                         if (dev->isYaffs2 &&
4420                             sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
4421                             sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
4422
4423                                 blockIndex[nBlocksToScan].seq = sequenceNumber;
4424                                 blockIndex[nBlocksToScan].block = blk;
4425
4426                                 nBlocksToScan++;
4427
4428                                 if (sequenceNumber >= dev->sequenceNumber) {
4429                                         dev->sequenceNumber = sequenceNumber;
4430                                 }
4431                         } else if (dev->isYaffs2) {
4432                                 /* TODO: Nasty sequence number! */
4433                                 T(YAFFS_TRACE_SCAN,
4434                                   (TSTR
4435                                    ("Block scanning block %d has bad sequence number %d"
4436                                     TENDSTR), blk, sequenceNumber));
4437
4438                         }
4439                 }
4440         }
4441
4442         /*
4443          * Sort the blocks
4444          * Dungy old bubble sort for now...
4445          */
4446         {
4447                 yaffs_BlockIndex temp;
4448                 int i;
4449                 int j;
4450
4451                 for (i = 0; i < nBlocksToScan; i++)
4452                         for (j = i + 1; j < nBlocksToScan; j++)
4453                                 if (blockIndex[i].seq > blockIndex[j].seq) {
4454                                         temp = blockIndex[j];
4455                                         blockIndex[j] = blockIndex[i];
4456                                         blockIndex[i] = temp;
4457                                 }
4458         }
4459
4460         /* Now scan the blocks looking at the data. */
4461         startIterator = 0;
4462         endIterator = nBlocksToScan - 1;
4463         T(YAFFS_TRACE_SCAN_DEBUG,
4464           (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
4465
4466         /* For each block.... backwards */
4467         for (blockIterator = endIterator; blockIterator >= startIterator;
4468              blockIterator--) {
4469
4470                 /* get the block to scan in the correct order */
4471                 blk = blockIndex[blockIterator].block;
4472
4473                 bi = yaffs_GetBlockInfo(dev, blk);
4474                 state = bi->blockState;
4475
4476                 deleted = 0;
4477
4478                 /* For each chunk in each block that needs scanning.... */
4479                 for (c = dev->nChunksPerBlock - 1; c >= 0 &&
4480                      (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
4481                       state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
4482                         /* Scan backwards... 
4483                          * Read the tags and decide what to do
4484                          */
4485                         chunk = blk * dev->nChunksPerBlock + c;
4486
4487                         yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
4488                                                         &tags);
4489
4490                         /* Let's have a good look at this chunk... */
4491
4492                         if (!tags.chunkUsed) {
4493                                 // An unassigned chunk in the block
4494                                 // This means that either the block is empty or 
4495                                 // this is the one being allocated from
4496
4497                                 if (c == 0) {
4498                                         /* We're looking at the first chunk in the block so the block is unused */
4499                                         state = YAFFS_BLOCK_STATE_EMPTY;
4500                                         dev->nErasedBlocks++;
4501                                 } else {
4502                                         /* this is the block being allocated from */
4503                                         if (state ==
4504                                             YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4505                                                 T(YAFFS_TRACE_SCAN,
4506                                                   (TSTR
4507                                                    (" Allocating from %d %d"
4508                                                     TENDSTR), blk, c));
4509                                         }
4510                                         state = YAFFS_BLOCK_STATE_ALLOCATING;
4511                                         dev->allocationBlock = blk;
4512                                         dev->allocationPage = c;
4513                                         dev->allocationBlockFinder = blk;       
4514                                         /* Set it to here to encourage the allocator to 
4515                                          *  go forth from here.
4516                                          */
4517                                          
4518                                         /* Yaffs2 sanity check:
4519                                          * This should be the one with the highest sequence number
4520                                          */
4521                                         if (dev->isYaffs2
4522                                             && (dev->sequenceNumber !=
4523                                                 bi->sequenceNumber)) {
4524                                                 T(YAFFS_TRACE_ALWAYS,
4525                                                   (TSTR
4526                                                    ("yaffs: Allocation block %d was not highest sequence "
4527                                                     "id: block seq = %d, dev seq = %d"
4528                                                     TENDSTR), blk,
4529                                                    bi->sequenceNumber,
4530                                                    dev->sequenceNumber));
4531                                         }
4532                                 }
4533
4534                                 dev->nFreeChunks++;
4535                         } else if (tags.chunkId > 0) {
4536                                 /* chunkId > 0 so it is a data chunk... */
4537                                 unsigned int endpos;
4538
4539                                 __u32 chunkBase =
4540                                     (tags.chunkId - 1) * dev->nBytesPerChunk;
4541
4542                                 yaffs_SetChunkBit(dev, blk, c);
4543                                 bi->pagesInUse++;
4544
4545                                 in = yaffs_FindOrCreateObjectByNumber(dev,
4546                                                                       tags.
4547                                                                       objectId,
4548                                                                       YAFFS_OBJECT_TYPE_FILE);
4549                                 if (in->variantType == YAFFS_OBJECT_TYPE_FILE
4550                                     && chunkBase <
4551                                     in->variant.fileVariant.shrinkSize) {
4552                                         /* This has not been invalidated by a resize */
4553                                         yaffs_PutChunkIntoFile(in, tags.chunkId,
4554                                                                chunk, -1);
4555
4556                                         /* File size is calculated by looking at the data chunks if we have not 
4557                                          * seen an object header yet. Stop this practice once we find an object header.
4558                                          */
4559                                         endpos =
4560                                             (tags.chunkId -
4561                                              1) * dev->nBytesPerChunk +
4562                                             tags.byteCount;
4563                                             
4564                                         if (!in->valid &&       /* have not got an object header yet */
4565                                             in->variant.fileVariant.
4566                                             scannedFileSize < endpos) {
4567                                                 in->variant.fileVariant.
4568                                                     scannedFileSize = endpos;
4569                                                 in->variant.fileVariant.
4570                                                     fileSize =
4571                                                     in->variant.fileVariant.
4572                                                     scannedFileSize;
4573                                         }
4574
4575                                 } else {
4576                                         /* This chunk has been invalidated by a resize, so delete */
4577                                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
4578
4579                                 }
4580                         } else {
4581                                 /* chunkId == 0, so it is an ObjectHeader.
4582                                  * Thus, we read in the object header and make the object
4583                                  */
4584                                 yaffs_SetChunkBit(dev, blk, c);
4585                                 bi->pagesInUse++;
4586
4587                                 oh = NULL;
4588                                 in = NULL;
4589
4590                                 if (tags.extraHeaderInfoAvailable) {
4591                                         in = yaffs_FindOrCreateObjectByNumber
4592                                             (dev, tags.objectId,
4593                                              tags.extraObjectType);
4594                                 }
4595
4596                                 if (!in || !in->valid) {
4597
4598                                         /* If we don't have  valid info then we need to read the chunk
4599                                          * TODO In future we can probably defer reading the chunk and 
4600                                          * living with invalid data until needed.
4601                                          */
4602
4603                                         yaffs_ReadChunkWithTagsFromNAND(dev,
4604                                                                         chunk,
4605                                                                         chunkData,
4606                                                                         NULL);
4607
4608                                         oh = (yaffs_ObjectHeader *) chunkData;
4609
4610                                         if (!in)
4611                                                 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
4612
4613                                 }
4614
4615                                 if (!in) {
4616                                         /* TODO Hoosterman we have a problem! */
4617                                         T(YAFFS_TRACE_ERROR,
4618                                           (TSTR
4619                                            ("yaffs tragedy: Could not make object for object  %d  "
4620                                             "at chunk %d during scan"
4621                                             TENDSTR), tags.objectId, chunk));
4622
4623                                 }
4624
4625                                 if (in->valid) {
4626                                         /* We have already filled this one.
4627                                          * We have a duplicate that will be discarded, but 
4628                                          * we first have to suck out resize info if it is a file.
4629                                          */
4630
4631                                         if ((in->variantType ==
4632                                              YAFFS_OBJECT_TYPE_FILE) && ((oh
4633                                                                           &&
4634                                                                           oh->
4635                                                                           type
4636                                                                           ==
4637                                                                           YAFFS_OBJECT_TYPE_FILE)
4638                                                                          ||
4639                                                                          (tags.
4640                                                                           extraHeaderInfoAvailable
4641                                                                           &&
4642                                                                           tags.
4643                                                                           extraObjectType
4644                                                                           ==
4645                                                                           YAFFS_OBJECT_TYPE_FILE))
4646                                             ) {
4647                                                 __u32 thisSize =
4648                                                     (oh) ? oh->fileSize : tags.
4649                                                     extraFileLength;
4650                                                 __u32 parentObjectId =
4651                                                     (oh) ? oh->
4652                                                     parentObjectId : tags.
4653                                                     extraParentObjectId;
4654                                                 unsigned isShrink =
4655                                                     (oh) ? oh->isShrink : tags.
4656                                                     extraIsShrinkHeader;
4657
4658                                                 /* If it is deleted (unlinked at start also means deleted)
4659                                                  * we treat the file size as being zeroed at this point.
4660                                                  */
4661                                                 if (parentObjectId ==
4662                                                     YAFFS_OBJECTID_DELETED
4663                                                     || parentObjectId ==
4664                                                     YAFFS_OBJECTID_UNLINKED) {
4665                                                         thisSize = 0;
4666                                                         isShrink = 1;
4667                                                 }
4668
4669                                                 if (isShrink &&
4670                                                     in->variant.fileVariant.
4671                                                     shrinkSize > thisSize) {
4672                                                         in->variant.fileVariant.
4673                                                             shrinkSize =
4674                                                             thisSize;
4675                                                 }
4676
4677                                                 if (isShrink) {
4678                                                         bi->hasShrinkHeader = 1;
4679                                                 }
4680
4681                                         }
4682                                         /* Use existing - destroy this one. */
4683                                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
4684
4685                                 }
4686
4687                                 if (!in->valid &&
4688                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
4689                                      tags.objectId ==
4690                                      YAFFS_OBJECTID_LOSTNFOUND)) {
4691                                         /* We only load some info, don't fiddle with directory structure */
4692                                         in->valid = 1;
4693                                         in->variantType = oh->type;
4694
4695                                         in->yst_mode = oh->yst_mode;
4696 #ifdef CONFIG_YAFFS_WINCE
4697                                         in->win_atime[0] = oh->win_atime[0];
4698                                         in->win_ctime[0] = oh->win_ctime[0];
4699                                         in->win_mtime[0] = oh->win_mtime[0];
4700                                         in->win_atime[1] = oh->win_atime[1];
4701                                         in->win_ctime[1] = oh->win_ctime[1];
4702                                         in->win_mtime[1] = oh->win_mtime[1];
4703 #else
4704                                         in->yst_uid = oh->yst_uid;
4705                                         in->yst_gid = oh->yst_gid;
4706                                         in->yst_atime = oh->yst_atime;
4707                                         in->yst_mtime = oh->yst_mtime;
4708                                         in->yst_ctime = oh->yst_ctime;
4709                                         in->yst_rdev = oh->yst_rdev;
4710 #endif
4711                                         in->chunkId = chunk;
4712
4713                                 } else if (!in->valid) {
4714                                         /* we need to load this info */
4715
4716                                         in->valid = 1;
4717                                         in->variantType = oh->type;
4718
4719                                         in->yst_mode = oh->yst_mode;
4720 #ifdef CONFIG_YAFFS_WINCE
4721                                         in->win_atime[0] = oh->win_atime[0];
4722                                         in->win_ctime[0] = oh->win_ctime[0];
4723                                         in->win_mtime[0] = oh->win_mtime[0];
4724                                         in->win_atime[1] = oh->win_atime[1];
4725                                         in->win_ctime[1] = oh->win_ctime[1];
4726                                         in->win_mtime[1] = oh->win_mtime[1];
4727 #else
4728                                         in->yst_uid = oh->yst_uid;
4729                                         in->yst_gid = oh->yst_gid;
4730                                         in->yst_atime = oh->yst_atime;
4731                                         in->yst_mtime = oh->yst_mtime;
4732                                         in->yst_ctime = oh->yst_ctime;
4733                                         in->yst_rdev = oh->yst_rdev;
4734 #endif
4735                                         in->chunkId = chunk;
4736
4737                                         if (oh->shadowsObject > 0) {
4738                                                 yaffs_HandleShadowedObject(dev,
4739                                                                            oh->
4740                                                                            shadowsObject,
4741                                                                            1);
4742                                         }
4743
4744                                         yaffs_SetObjectName(in, oh->name);
4745                                         in->dirty = 0;
4746
4747                                         /* directory stuff...
4748                                          * hook up to parent
4749                                          */
4750
4751                                         parent =
4752                                             yaffs_FindOrCreateObjectByNumber
4753                                             (dev, oh->parentObjectId,
4754                                              YAFFS_OBJECT_TYPE_DIRECTORY);
4755                                         if (parent->variantType ==
4756                                             YAFFS_OBJECT_TYPE_UNKNOWN) {
4757                                                 /* Set up as a directory */
4758                                                 parent->variantType =
4759                                                     YAFFS_OBJECT_TYPE_DIRECTORY;
4760                                                 INIT_LIST_HEAD(&parent->variant.
4761                                                                directoryVariant.
4762                                                                children);
4763                                         } else if (parent->variantType !=
4764                                                    YAFFS_OBJECT_TYPE_DIRECTORY)
4765                                         {
4766                                                 /* Hoosterman, another problem....
4767                                                  * We're trying to use a non-directory as a directory
4768                                                  */
4769
4770                                                 T(YAFFS_TRACE_ERROR,
4771                                                   (TSTR
4772                                                    ("yaffs tragedy: attempting to use non-directory as"
4773                                                     " a directory in scan. Put in lost+found."
4774                                                     TENDSTR)));
4775                                                 parent = dev->lostNFoundDir;
4776                                         }
4777
4778                                         yaffs_AddObjectToDirectory(parent, in);
4779
4780                                         if ((parent == dev->deletedDir ||
4781                                              parent == dev->unlinkedDir)) {
4782                                              /* If it is unlinked at start up then it wants deleting */
4783                                                 in->deleted = 1;
4784                                         }
4785
4786                                         if (oh->isShrink) {
4787                                                 /* Mark the block as having a shrinkHeader */
4788                                                 bi->hasShrinkHeader = 1;
4789                                         }
4790
4791                                         /* Note re hardlinks.
4792                                          * Since we might scan a hardlink before its equivalent object is scanned
4793                                          * we put them all in a list.
4794                                          * After scanning is complete, we should have all the objects, so we run
4795                                          * through this list and fix up all the chains.              
4796                                          */
4797
4798                                         switch (in->variantType) {
4799                                         case YAFFS_OBJECT_TYPE_UNKNOWN: 
4800                                                 /* Todo got a problem */
4801                                                 break;
4802                                         case YAFFS_OBJECT_TYPE_FILE:
4803
4804                                                 if (in->variant.fileVariant.
4805                                                     scannedFileSize <
4806                                                     oh->fileSize) {
4807                                                         /* This covers the case where the file size is greater
4808                                                          * than where the data is
4809                                                          * This will happen if the file is resized to be larger 
4810                                                          * than its current data extents.
4811                                                          */
4812                                                         in->variant.fileVariant.fileSize =
4813                                                             oh->fileSize;
4814                                                         in->variant.fileVariant.scannedFileSize =
4815                                                             in->variant.fileVariant.fileSize;
4816                                                 }
4817
4818                                                 if (oh->isShrink &&
4819                                                     in->variant.fileVariant.shrinkSize > 
4820                                                     oh->fileSize) {
4821                                                         in->variant.fileVariant.shrinkSize =
4822                                                             oh->fileSize;
4823                                                 }
4824
4825                                                 break;
4826                                         case YAFFS_OBJECT_TYPE_HARDLINK:
4827                                                 in->variant.hardLinkVariant.equivalentObjectId =
4828                                                     oh->equivalentObjectId;
4829                                                 in->hardLinks.next =
4830                                                     (struct list_head *) hardList;
4831                                                 hardList = in;
4832                                                 break;
4833                                         case YAFFS_OBJECT_TYPE_DIRECTORY:
4834                                                 /* Do nothing */
4835                                                 break;
4836                                         case YAFFS_OBJECT_TYPE_SPECIAL:
4837                                                 /* Do nothing */
4838                                                 break;
4839                                         case YAFFS_OBJECT_TYPE_SYMLINK:
4840                                                 in->variant.symLinkVariant.
4841                                                     alias =
4842                                                     yaffs_CloneString(oh->
4843                                                                       alias);
4844                                                 break;
4845                                         }
4846
4847                                 }
4848                         }
4849                 }
4850
4851                 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
4852                         /* If we got this far while scanning, then the block is fully allocated. */
4853                         state = YAFFS_BLOCK_STATE_FULL;
4854                 }
4855
4856                 bi->blockState = state;
4857
4858                 /* Now let's see if it was dirty */
4859                 if (bi->pagesInUse == 0 &&
4860                     !bi->hasShrinkHeader &&
4861                     bi->blockState == YAFFS_BLOCK_STATE_FULL) {
4862                         yaffs_BlockBecameDirty(dev, blk);
4863                 }
4864
4865         }
4866
4867         if (blockIndex) {
4868                 YFREE(blockIndex);
4869         }
4870         /* Ok, we've done all the scanning.
4871          * Fix up the hard link chains.
4872          * We should now have scanned all the objects, now it's time to add these 
4873          * hardlinks.
4874          */
4875         while (hardList) {
4876                 hl = hardList;
4877                 hardList = (yaffs_Object *) (hardList->hardLinks.next);
4878
4879                 in = yaffs_FindObjectByNumber(dev,
4880                                               hl->variant.hardLinkVariant.
4881                                               equivalentObjectId);
4882
4883                 if (in) {
4884                         /* Add the hardlink pointers */
4885                         hl->variant.hardLinkVariant.equivalentObject = in;
4886                         list_add(&hl->hardLinks, &in->hardLinks);
4887                 } else {
4888                         /* Todo Need to report/handle this better.
4889                          * Got a problem... hardlink to a non-existant object
4890                          */
4891                         hl->variant.hardLinkVariant.equivalentObject = NULL;
4892                         INIT_LIST_HEAD(&hl->hardLinks);
4893
4894                 }
4895
4896         }
4897
4898         {
4899                 struct list_head *i;
4900                 struct list_head *n;
4901
4902                 yaffs_Object *l;
4903
4904                 /* Soft delete all the unlinked files */
4905                 list_for_each_safe(i, n,
4906                                    &dev->unlinkedDir->variant.directoryVariant.
4907                                    children) {
4908                         if (i) {
4909                                 l = list_entry(i, yaffs_Object, siblings);
4910                                 yaffs_DestroyObject(l);
4911                         }
4912                 }
4913
4914                 /* Soft delete all the deletedDir files */
4915                 list_for_each_safe(i, n,
4916                                    &dev->deletedDir->variant.directoryVariant.
4917                                    children) {
4918                         if (i) {
4919                                 l = list_entry(i, yaffs_Object, siblings);
4920                                 yaffs_DestroyObject(l);
4921
4922                         }
4923                 }
4924         }
4925
4926         yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
4927
4928         T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
4929
4930         return YAFFS_OK;
4931 }
4932
4933 /*------------------------------  Directory Functions ----------------------------- */
4934
4935 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
4936 {
4937         yaffs_Device *dev = obj->myDev;
4938         
4939         if(dev && dev->removeObjectCallback)
4940                 dev->removeObjectCallback(obj);
4941            
4942         list_del_init(&obj->siblings);
4943         obj->parent = NULL;
4944 }
4945
4946
4947 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
4948                                        yaffs_Object * obj)
4949 {
4950
4951         if (!directory) {
4952                 T(YAFFS_TRACE_ALWAYS,
4953                   (TSTR
4954                    ("tragedy: Trying to add an object to a null pointer directory"
4955                     TENDSTR)));
4956                 YBUG();
4957         }
4958         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4959                 T(YAFFS_TRACE_ALWAYS,
4960                   (TSTR
4961                    ("tragedy: Trying to add an object to a non-directory"
4962                     TENDSTR)));
4963                 YBUG();
4964         }
4965
4966         if (obj->siblings.prev == NULL) {
4967                 /* Not initialised */
4968                 INIT_LIST_HEAD(&obj->siblings);
4969
4970         } else if (!list_empty(&obj->siblings)) {
4971                 /* If it is holed up somewhere else, un hook it */
4972                 yaffs_RemoveObjectFromDirectory(obj);
4973         }
4974         /* Now add it */
4975         list_add(&obj->siblings, &directory->variant.directoryVariant.children);
4976         obj->parent = directory;
4977
4978         if (directory == obj->myDev->unlinkedDir
4979             || directory == obj->myDev->deletedDir) {
4980                 obj->unlinked = 1;
4981                 obj->myDev->nUnlinkedFiles++;
4982                 obj->renameAllowed = 0;
4983         }
4984 }
4985
4986 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
4987                                      const YCHAR * name)
4988 {
4989         int sum;
4990
4991         struct list_head *i;
4992         YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
4993
4994         yaffs_Object *l;
4995
4996         if (!name) {
4997                 return NULL;
4998         }
4999
5000         if (!directory) {
5001                 T(YAFFS_TRACE_ALWAYS,
5002                   (TSTR
5003                    ("tragedy: yaffs_FindObjectByName: null pointer directory"
5004                     TENDSTR)));
5005                 YBUG();
5006         }
5007         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5008                 T(YAFFS_TRACE_ALWAYS,
5009                   (TSTR
5010                    ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5011                 YBUG();
5012         }
5013
5014         sum = yaffs_CalcNameSum(name);
5015
5016         list_for_each(i, &directory->variant.directoryVariant.children) {
5017                 if (i) {
5018                         l = list_entry(i, yaffs_Object, siblings);
5019
5020                         /* Special case for lost-n-found */
5021                         if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5022                                 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
5023                                         return l;
5024                                 }
5025                         } else if (yaffs_SumCompare(l->sum, sum) || l->chunkId <= 0)    
5026                         {
5027                                 /* LostnFound cunk called Objxxx
5028                                  * Do a real check
5029                                  */
5030                                 yaffs_GetObjectName(l, buffer,
5031                                                     YAFFS_MAX_NAME_LENGTH);
5032                                 if (yaffs_strcmp(name, buffer) == 0) {
5033                                         return l;
5034                                 }
5035
5036                         }
5037                 }
5038         }
5039
5040         return NULL;
5041 }
5042
5043
5044 #if 0
5045 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
5046                                    int (*fn) (yaffs_Object *))
5047 {
5048         struct list_head *i;
5049         yaffs_Object *l;
5050
5051         if (!theDir) {
5052                 T(YAFFS_TRACE_ALWAYS,
5053                   (TSTR
5054                    ("tragedy: yaffs_FindObjectByName: null pointer directory"
5055                     TENDSTR)));
5056                 YBUG();
5057         }
5058         if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
5059                 T(YAFFS_TRACE_ALWAYS,
5060                   (TSTR
5061                    ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
5062                 YBUG();
5063         }
5064
5065         list_for_each(i, &theDir->variant.directoryVariant.children) {
5066                 if (i) {
5067                         l = list_entry(i, yaffs_Object, siblings);
5068                         if (l && !fn(l)) {
5069                                 return YAFFS_FAIL;
5070                         }
5071                 }
5072         }
5073
5074         return YAFFS_OK;
5075
5076 }
5077 #endif
5078
5079 /* GetEquivalentObject dereferences any hard links to get to the
5080  * actual object.
5081  */
5082
5083 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
5084 {
5085         if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5086                 /* We want the object id of the equivalent object, not this one */
5087                 obj = obj->variant.hardLinkVariant.equivalentObject;
5088         }
5089         return obj;
5090
5091 }
5092
5093 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
5094 {
5095         memset(name, 0, buffSize * sizeof(YCHAR));
5096
5097         if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
5098                 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
5099         } else if (obj->chunkId <= 0) {
5100                 YCHAR locName[20];
5101                 /* make up a name */
5102                 yaffs_sprintf(locName, _Y("%s%d"), YAFFS_LOSTNFOUND_PREFIX,
5103                               obj->objectId);
5104                 yaffs_strncpy(name, locName, buffSize - 1);
5105
5106         }
5107 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
5108         else if (obj->shortName[0]) {
5109                 yaffs_strcpy(name, obj->shortName);
5110         }
5111 #endif
5112         else {
5113                 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
5114
5115                 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
5116
5117                 memset(buffer, 0, obj->myDev->nBytesPerChunk);
5118
5119                 if (obj->chunkId >= 0) {
5120                         yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
5121                                                         obj->chunkId, buffer,
5122                                                         NULL);
5123                 }
5124                 yaffs_strncpy(name, oh->name, buffSize - 1);
5125
5126                 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
5127         }
5128
5129         return yaffs_strlen(name);
5130 }
5131
5132 int yaffs_GetObjectFileLength(yaffs_Object * obj)
5133 {
5134
5135         /* Dereference any hard linking */
5136         obj = yaffs_GetEquivalentObject(obj);
5137
5138         if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
5139                 return obj->variant.fileVariant.fileSize;
5140         }
5141         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
5142                 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5143         } else {
5144                 /* Only a directory should drop through to here */
5145                 return obj->myDev->nBytesPerChunk;
5146         }
5147 }
5148
5149 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
5150 {
5151         int count = 0;
5152         struct list_head *i;
5153
5154         if (!obj->unlinked) {
5155                 count++;        /* the object itself */
5156         }
5157         list_for_each(i, &obj->hardLinks) {
5158                 count++;        /* add the hard links; */
5159         }
5160         return count;
5161
5162 }
5163
5164 int yaffs_GetObjectInode(yaffs_Object * obj)
5165 {
5166         obj = yaffs_GetEquivalentObject(obj);
5167
5168         return obj->objectId;
5169 }
5170
5171 unsigned yaffs_GetObjectType(yaffs_Object * obj)
5172 {
5173         obj = yaffs_GetEquivalentObject(obj);
5174
5175         switch (obj->variantType) {
5176         case YAFFS_OBJECT_TYPE_FILE:
5177                 return DT_REG;
5178                 break;
5179         case YAFFS_OBJECT_TYPE_DIRECTORY:
5180                 return DT_DIR;
5181                 break;
5182         case YAFFS_OBJECT_TYPE_SYMLINK:
5183                 return DT_LNK;
5184                 break;
5185         case YAFFS_OBJECT_TYPE_HARDLINK:
5186                 return DT_REG;
5187                 break;
5188         case YAFFS_OBJECT_TYPE_SPECIAL:
5189                 if (S_ISFIFO(obj->yst_mode))
5190                         return DT_FIFO;
5191                 if (S_ISCHR(obj->yst_mode))
5192                         return DT_CHR;
5193                 if (S_ISBLK(obj->yst_mode))
5194                         return DT_BLK;
5195                 if (S_ISSOCK(obj->yst_mode))
5196                         return DT_SOCK;
5197         default:
5198                 return DT_REG;
5199                 break;
5200         }
5201 }
5202
5203 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
5204 {
5205         obj = yaffs_GetEquivalentObject(obj);
5206         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
5207                 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
5208         } else {
5209                 return yaffs_CloneString(_Y(""));
5210         }
5211 }
5212
5213 #ifndef CONFIG_YAFFS_WINCE
5214
5215 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
5216 {
5217         unsigned int valid = attr->ia_valid;
5218
5219         if (valid & ATTR_MODE)
5220                 obj->yst_mode = attr->ia_mode;
5221         if (valid & ATTR_UID)
5222                 obj->yst_uid = attr->ia_uid;
5223         if (valid & ATTR_GID)
5224                 obj->yst_gid = attr->ia_gid;
5225
5226         if (valid & ATTR_ATIME)
5227                 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
5228         if (valid & ATTR_CTIME)
5229                 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
5230         if (valid & ATTR_MTIME)
5231                 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
5232
5233         if (valid & ATTR_SIZE)
5234                 yaffs_ResizeFile(obj, attr->ia_size);
5235
5236         yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
5237
5238         return YAFFS_OK;
5239
5240 }
5241 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
5242 {
5243         unsigned int valid = 0;
5244
5245         attr->ia_mode = obj->yst_mode;
5246         valid |= ATTR_MODE;
5247         attr->ia_uid = obj->yst_uid;
5248         valid |= ATTR_UID;
5249         attr->ia_gid = obj->yst_gid;
5250         valid |= ATTR_GID;
5251
5252         Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
5253         valid |= ATTR_ATIME;
5254         Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
5255         valid |= ATTR_CTIME;
5256         Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
5257         valid |= ATTR_MTIME;
5258
5259         attr->ia_size = yaffs_GetFileSize(obj);
5260         valid |= ATTR_SIZE;
5261
5262         attr->ia_valid = valid;
5263
5264         return YAFFS_OK;
5265
5266 }
5267
5268 #endif
5269
5270 #if 0
5271 int yaffs_DumpObject(yaffs_Object * obj)
5272 {
5273         YCHAR name[257];
5274
5275         yaffs_GetObjectName(obj, name, 256);
5276
5277         T(YAFFS_TRACE_ALWAYS,
5278           (TSTR
5279            ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
5280             " chunk %d type %d size %d\n"
5281             TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
5282            obj->dirty, obj->valid, obj->serial, obj->sum, obj->chunkId,
5283            yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
5284
5285         return YAFFS_OK;
5286 }
5287 #endif
5288
5289 /*---------------------------- Initialisation code -------------------------------------- */
5290
5291 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
5292 {
5293
5294         /* Common functions, gotta have */
5295         if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
5296                 return 0;
5297
5298 #ifdef CONFIG_YAFFS_YAFFS2
5299
5300         /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
5301         if (dev->writeChunkWithTagsToNAND &&
5302             dev->readChunkWithTagsFromNAND &&
5303             !dev->writeChunkToNAND &&
5304             !dev->readChunkFromNAND &&
5305             dev->markNANDBlockBad && dev->queryNANDBlock)
5306                 return 1;
5307 #endif
5308
5309         /* Can use the "spare" style interface for yaffs1 */
5310         if (!dev->isYaffs2 &&
5311             !dev->writeChunkWithTagsToNAND &&
5312             !dev->readChunkWithTagsFromNAND &&
5313             dev->writeChunkToNAND &&
5314             dev->readChunkFromNAND &&
5315             !dev->markNANDBlockBad && !dev->queryNANDBlock)
5316                 return 1;
5317
5318         return 0;               /* bad */
5319 }
5320
5321 int yaffs_GutsInitialise(yaffs_Device * dev)
5322 {
5323         unsigned x;
5324         int bits;
5325         int extraBits;
5326         int nBlocks;
5327
5328         T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
5329
5330         /* Check stuff that must be set */
5331
5332         if (!dev) {
5333                 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
5334                 return YAFFS_FAIL;
5335         }
5336
5337         dev->internalStartBlock = dev->startBlock;
5338         dev->internalEndBlock = dev->endBlock;
5339         dev->blockOffset = 0;
5340         dev->chunkOffset = 0;
5341         dev->nFreeChunks = 0;
5342
5343         if (dev->startBlock == 0) {
5344                 dev->internalStartBlock = dev->startBlock + 1;
5345                 dev->internalEndBlock = dev->endBlock + 1;
5346                 dev->blockOffset = 1;
5347                 dev->chunkOffset = dev->nChunksPerBlock;
5348         }
5349
5350         /* Check geometry parameters. */
5351
5352         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
5353             ) {
5354                 T(YAFFS_TRACE_ALWAYS,
5355                   (TSTR
5356                    ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s "
5357                     TENDSTR), dev->nBytesPerChunk, dev->isYaffs2 ? "2" : ""));
5358                 return YAFFS_FAIL;
5359         }
5360
5361         if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
5362                 T(YAFFS_TRACE_ALWAYS,
5363                   (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
5364                 return YAFFS_FAIL;
5365         }
5366
5367         /* Got the right mix of functions? */
5368         if (!yaffs_CheckDevFunctions(dev)) {
5369                 /* Function missing */
5370                 T(YAFFS_TRACE_ALWAYS,
5371                   (TSTR
5372                    ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
5373
5374                 return YAFFS_FAIL;
5375         }
5376
5377         /* This is really a compilation check. */
5378         if (!yaffs_CheckStructures()) {
5379                 T(YAFFS_TRACE_ALWAYS,
5380                   (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
5381                 return YAFFS_FAIL;
5382         }
5383
5384         if (dev->isMounted) {
5385                 T(YAFFS_TRACE_ALWAYS,
5386                   (TSTR("yaffs: device already mounted\n" TENDSTR)));
5387                 return YAFFS_FAIL;
5388         }
5389
5390         /* Finished with most checks. One or two more checks happen later on too. */
5391
5392         dev->isMounted = 1;
5393
5394         nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
5395
5396         /* OK now calculate a few things for the device
5397          * Calculate chunkGroupBits.
5398          * We need to find the next power of 2 > than internalEndBlock
5399          */
5400
5401         x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
5402
5403         for (bits = extraBits = 0; x > 1; bits++) {
5404                 if (x & 1)
5405                         extraBits++;
5406                 x >>= 1;
5407         }
5408
5409         if (extraBits > 0)
5410                 bits++;
5411
5412         /* Level0 Tnodes are 16 bits, so if the bitwidth of the
5413          * chunk range we're using is greater than 16 we need
5414          * to figure out chunk shift and chunkGroupSize
5415          */
5416         if (bits <= 16) {
5417                 dev->chunkGroupBits = 0;
5418         } else {
5419                 dev->chunkGroupBits = bits - 16;
5420         }
5421
5422         dev->chunkGroupSize = 1 << dev->chunkGroupBits;
5423
5424         if (dev->nChunksPerBlock < dev->chunkGroupSize) {
5425                 /* We have a problem because the soft delete won't work if
5426                  * the chunk group size > chunks per block.
5427                  * This can be remedied by using larger "virtual blocks".
5428                  */
5429                 T(YAFFS_TRACE_ALWAYS,
5430                   (TSTR("yaffs: chunk group too large\n" TENDSTR)));
5431
5432                 return YAFFS_FAIL;
5433         }
5434
5435         /* OK, we've finished verifying the device, lets continue with initialisation */
5436
5437         /* More device initialisation */
5438         dev->garbageCollections = 0;
5439         dev->passiveGarbageCollections = 0;
5440         dev->currentDirtyChecker = 0;
5441         dev->bufferedBlock = -1;
5442         dev->doingBufferedBlockRewrite = 0;
5443         dev->nDeletedFiles = 0;
5444         dev->nBackgroundDeletions = 0;
5445         dev->nUnlinkedFiles = 0;
5446         dev->eccFixed = 0;
5447         dev->eccUnfixed = 0;
5448         dev->tagsEccFixed = 0;
5449         dev->tagsEccUnfixed = 0;
5450         dev->nErasureFailures = 0;
5451         dev->nErasedBlocks = 0;
5452         dev->isDoingGC = 0;
5453
5454         /* Initialise temporary buffers */
5455         {
5456                 int i;
5457                 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
5458                         dev->tempBuffer[i].line = 0;    /* not in use */
5459                         dev->tempBuffer[i].buffer =
5460                             YMALLOC(dev->nBytesPerChunk);
5461                 }
5462         }
5463
5464         yaffs_InitialiseBlocks(dev, nBlocks);
5465
5466         yaffs_InitialiseTnodes(dev);
5467
5468         yaffs_InitialiseObjects(dev);
5469
5470         dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
5471
5472         if (dev->nShortOpCaches > 0) {
5473                 int i;
5474
5475                 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
5476                         dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
5477                 }
5478
5479                 dev->srCache =
5480                     YMALLOC(dev->nShortOpCaches * sizeof(yaffs_ChunkCache));
5481
5482                 for (i = 0; i < dev->nShortOpCaches; i++) {
5483                         dev->srCache[i].object = NULL;
5484                         dev->srCache[i].lastUse = 0;
5485                         dev->srCache[i].dirty = 0;
5486                         dev->srCache[i].data = YMALLOC(dev->nBytesPerChunk);
5487                 }
5488                 dev->srLastUse = 0;
5489         }
5490
5491         dev->cacheHits = 0;
5492
5493         /* Initialise the unlinked, root and lost and found directories */
5494         dev->lostNFoundDir = dev->rootDir =  NULL;
5495         dev->unlinkedDir = dev->deletedDir = NULL;
5496
5497         dev->unlinkedDir =
5498             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
5499         dev->deletedDir =
5500             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
5501
5502         dev->rootDir =
5503             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
5504                                       YAFFS_ROOT_MODE | S_IFDIR);
5505         dev->lostNFoundDir =
5506             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
5507                                       YAFFS_LOSTNFOUND_MODE | S_IFDIR);
5508         yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
5509
5510         if (dev->isYaffs2) {
5511                 dev->useHeaderFileSize = 1;
5512         }
5513
5514         /* Now scan the flash.   */
5515         if (dev->isYaffs2)
5516                 yaffs_ScanBackwards(dev);
5517         else
5518                 yaffs_Scan(dev);
5519
5520         /* Zero out stats */
5521         dev->nPageReads = 0;
5522         dev->nPageWrites = 0;
5523         dev->nBlockErasures = 0;
5524         dev->nGCCopies = 0;
5525         dev->nRetriedWrites = 0;
5526
5527         dev->nRetiredBlocks = 0;
5528
5529         yaffs_VerifyFreeChunks(dev);
5530
5531         T(YAFFS_TRACE_TRACING,
5532           (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
5533         return YAFFS_OK;
5534
5535 }
5536
5537 void yaffs_Deinitialise(yaffs_Device * dev)
5538 {
5539         if (dev->isMounted) {
5540                 int i;
5541
5542                 yaffs_DeinitialiseBlocks(dev);
5543                 yaffs_DeinitialiseTnodes(dev);
5544                 yaffs_DeinitialiseObjects(dev);
5545                 if (dev->nShortOpCaches > 0) {
5546
5547                         for (i = 0; i < dev->nShortOpCaches; i++) {
5548                                 YFREE(dev->srCache[i].data);
5549                         }
5550
5551                         YFREE(dev->srCache);
5552                 }
5553
5554                 YFREE(dev->gcCleanupList);
5555
5556                 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
5557                         YFREE(dev->tempBuffer[i].buffer);
5558                 }
5559
5560                 dev->isMounted = 0;
5561         }
5562
5563 }
5564
5565 static int yaffs_CountFreeChunks(yaffs_Device * dev)
5566 {
5567         int nFree;
5568         int b;
5569
5570         yaffs_BlockInfo *blk;
5571
5572         for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
5573              b++) {
5574                 blk = yaffs_GetBlockInfo(dev, b);
5575
5576                 switch (blk->blockState) {
5577                 case YAFFS_BLOCK_STATE_EMPTY:
5578                 case YAFFS_BLOCK_STATE_ALLOCATING:
5579                 case YAFFS_BLOCK_STATE_COLLECTING:
5580                 case YAFFS_BLOCK_STATE_FULL:
5581                         nFree +=
5582                             (dev->nChunksPerBlock - blk->pagesInUse +
5583                              blk->softDeletions);
5584                         break;
5585                 default:
5586                         break;
5587                 }
5588
5589         }
5590
5591         return nFree;
5592 }
5593
5594 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
5595 {
5596         /* This is what we report to the outside world */
5597
5598         int nFree;
5599         int nDirtyCacheChunks;
5600
5601 #if 1
5602         nFree = dev->nFreeChunks;
5603 #else
5604         nFree = yaffs_CountFreeChunks(dev);
5605 #endif
5606
5607         /* Now count the number of dirty chunks in the cache and subtract those */
5608
5609         {
5610                 int i;
5611                 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
5612                         if (dev->srCache[i].dirty)
5613                                 nDirtyCacheChunks++;
5614                 }
5615         }
5616
5617         nFree -= nDirtyCacheChunks;
5618
5619         nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
5620
5621         if (nFree < 0)
5622                 nFree = 0;
5623
5624         return nFree;
5625
5626 }
5627
5628 static int yaffs_freeVerificationFailures;
5629
5630 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
5631 {
5632         int counted = yaffs_CountFreeChunks(dev);
5633
5634         int difference = dev->nFreeChunks - counted;
5635
5636         if (difference) {
5637                 T(YAFFS_TRACE_ALWAYS,
5638                   (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
5639                    dev->nFreeChunks, counted, difference));
5640                 yaffs_freeVerificationFailures++;
5641         }
5642 }
5643
5644 /*---------------------------------------- YAFFS test code ----------------------*/
5645
5646 #define yaffs_CheckStruct(structure,syze, name) \
5647            if(sizeof(structure) != syze) \
5648                { \
5649                  T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
5650                  name,syze,sizeof(structure))); \
5651                  return YAFFS_FAIL; \
5652                 }
5653
5654 static int yaffs_CheckStructures(void)
5655 {
5656 /*      yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags") */
5657 /*      yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion") */
5658 /*      yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare") */
5659 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
5660         yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode")
5661 #endif
5662             yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader")
5663
5664             return YAFFS_OK;
5665 }