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