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