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