Fix some checkpoint stuff, add qsort
[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.34 2006-05-21 09:39:12 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 #ifndef CONFIG_YAFFS_OWN_SORT
26 #include "yaffs_qsort.h"
27 #endif
28 #include "yaffs_nand.h"
29
30 #include "yaffs_checkptrw.h"
31
32 #include "yaffs_nand.h"
33
34
35 #ifdef CONFIG_YAFFS_WINCE
36 void yfsd_LockYAFFS(BOOL fsLockOnly);
37 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
38 #endif
39
40 #define YAFFS_PASSIVE_GC_CHUNKS 2
41
42 #include "yaffs_ecc.h"
43
44
45 /* Robustification (if it ever comes about...) */
46 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
47 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND);
48 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
49                                      const __u8 * data,
50                                      const yaffs_ExtendedTags * tags);
51 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
52                                     const yaffs_ExtendedTags * tags);
53
54 /* Other local prototypes */
55 static int yaffs_UnlinkObject( yaffs_Object *obj);
56
57 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
58
59 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
60                                              const __u8 * buffer,
61                                              yaffs_ExtendedTags * tags,
62                                              int useReserve);
63 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
64                                   int chunkInNAND, int inScan);
65
66 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
67                                            yaffs_ObjectType type);
68 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
69                                        yaffs_Object * obj);
70 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
71                                     int force, int isShrink, int shadows);
72 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
73 static int yaffs_CheckStructures(void);
74 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
75                               int chunkOffset, int *limit);
76 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
77
78 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
79
80 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo);
81 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
82                                     int lineNo);
83
84 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
85                                   int chunkInNAND);
86
87 static int yaffs_UnlinkWorker(yaffs_Object * obj);
88 static void yaffs_DestroyObject(yaffs_Object * obj);
89
90 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
91                            int chunkInObject);
92
93 loff_t yaffs_GetFileSize(yaffs_Object * obj);
94
95 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve);
96
97 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
98
99 #ifdef YAFFS_PARANOID
100 static int yaffs_CheckFileSanity(yaffs_Object * in);
101 #else
102 #define yaffs_CheckFileSanity(in)
103 #endif
104
105 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
106 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
107
108 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
109
110 /* 
111  * Temporary buffer manipulations.
112  */
113
114 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
115 {
116         int i, j;
117         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
118                 if (dev->tempBuffer[i].line == 0) {
119                         dev->tempBuffer[i].line = lineNo;
120                         if ((i + 1) > dev->maxTemp) {
121                                 dev->maxTemp = i + 1;
122                                 for (j = 0; j <= i; j++)
123                                         dev->tempBuffer[j].maxLine =
124                                             dev->tempBuffer[j].line;
125                         }
126
127                         return dev->tempBuffer[i].buffer;
128                 }
129         }
130
131         T(YAFFS_TRACE_BUFFERS,
132           (TSTR("Out of temp buffers at line %d, other held by lines:"),
133            lineNo));
134         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
135                 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
136         }
137         T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
138
139         /*
140          * If we got here then we have to allocate an unmanaged one
141          * This is not good.
142          */
143
144         dev->unmanagedTempAllocations++;
145         return YMALLOC(dev->nBytesPerChunk);
146
147 }
148
149 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
150                                     int lineNo)
151 {
152         int i;
153         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
154                 if (dev->tempBuffer[i].buffer == buffer) {
155                         dev->tempBuffer[i].line = 0;
156                         return;
157                 }
158         }
159
160         if (buffer) {
161                 /* assume it is an unmanaged one. */
162                 T(YAFFS_TRACE_BUFFERS,
163                   (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
164                    lineNo));
165                 YFREE(buffer);
166                 dev->unmanagedTempDeallocations++;
167         }
168
169 }
170
171 /*
172  * Determine if we have a managed buffer.
173  */
174 int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
175 {
176         int i;
177         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
178                 if (dev->tempBuffer[i].buffer == buffer)
179                         return 1;
180
181         }
182
183     for (i = 0; i < dev->nShortOpCaches; i++) {
184         if( dev->srCache[i].data == buffer )
185             return 1;
186
187     }
188
189     if (buffer == dev->checkpointBuffer)
190       return 1;
191
192     T(YAFFS_TRACE_ALWAYS,
193           (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
194     return 0;
195 }
196
197 /*
198  * Chunk bitmap manipulations
199  */
200
201 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
202 {
203         if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
204                 T(YAFFS_TRACE_ERROR,
205                   (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
206                    blk));
207                 YBUG();
208         }
209         return dev->chunkBits +
210             (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
211 }
212
213 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
214 {
215         __u8 *blkBits = yaffs_BlockBits(dev, blk);
216
217         memset(blkBits, 0, dev->chunkBitmapStride);
218 }
219
220 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
221 {
222         __u8 *blkBits = yaffs_BlockBits(dev, blk);
223
224         blkBits[chunk / 8] &= ~(1 << (chunk & 7));
225 }
226
227 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
228 {
229         __u8 *blkBits = yaffs_BlockBits(dev, blk);
230
231         blkBits[chunk / 8] |= (1 << (chunk & 7));
232 }
233
234 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
235 {
236         __u8 *blkBits = yaffs_BlockBits(dev, blk);
237         return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
238 }
239
240 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
241 {
242         __u8 *blkBits = yaffs_BlockBits(dev, blk);
243         int i;
244         for (i = 0; i < dev->chunkBitmapStride; i++) {
245                 if (*blkBits)
246                         return 1;
247                 blkBits++;
248         }
249         return 0;
250 }
251
252 /*
253  *  Simple hash function. Needs to have a reasonable spread
254  */
255  
256 static Y_INLINE int yaffs_HashFunction(int n)
257 {
258         n = abs(n);
259         return (n % YAFFS_NOBJECT_BUCKETS);
260 }
261
262 /*
263  * Access functions to useful fake objects
264  */
265  
266 yaffs_Object *yaffs_Root(yaffs_Device * dev)
267 {
268         return dev->rootDir;
269 }
270
271 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
272 {
273         return dev->lostNFoundDir;
274 }
275
276
277 /*
278  *  Erased NAND checking functions
279  */
280  
281 int yaffs_CheckFF(__u8 * buffer, int nBytes)
282 {
283         /* Horrible, slow implementation */
284         while (nBytes--) {
285                 if (*buffer != 0xFF)
286                         return 0;
287                 buffer++;
288         }
289         return 1;
290 }
291
292 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
293                                   int chunkInNAND)
294 {
295
296         int retval = YAFFS_OK;
297         __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
298         yaffs_ExtendedTags tags;
299
300         yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
301
302         if (!yaffs_CheckFF(data, dev->nBytesPerChunk) || tags.chunkUsed) {
303                 T(YAFFS_TRACE_NANDACCESS,
304                   (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
305                 retval = YAFFS_FAIL;
306         }
307
308         yaffs_ReleaseTempBuffer(dev, data, __LINE__);
309
310         return retval;
311
312 }
313
314 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
315                                              const __u8 * data,
316                                              yaffs_ExtendedTags * tags,
317                                              int useReserve)
318 {
319         int chunk;
320
321         int writeOk = 1;
322         int attempts = 0;
323         
324         yaffs_InvalidateCheckpoint(dev);
325
326         do {
327                 chunk = yaffs_AllocateChunk(dev, useReserve);
328
329                 if (chunk >= 0) {
330
331                         /* First check this chunk is erased... */
332 #ifndef CONFIG_YAFFS_DISABLE_CHUNK_ERASED_CHECK
333                         writeOk = yaffs_CheckChunkErased(dev, chunk);
334 #endif
335                         if (!writeOk) {
336                                 T(YAFFS_TRACE_ERROR,
337                                   (TSTR
338                                    ("**>> yaffs chunk %d was not erased"
339                                     TENDSTR), chunk));
340                         } else {
341                                 writeOk =
342                                     yaffs_WriteChunkWithTagsToNAND(dev, chunk,
343                                                                    data, tags);
344                         }
345                         attempts++;
346
347                         if (writeOk) {
348                                 /*
349                                  *  Copy the data into the robustification buffer.
350                                  *  NB We do this at the end to prevent duplicates in the case of a write error.
351                                  *  Todo
352                                  */
353                                 yaffs_HandleWriteChunkOk(dev, chunk, data,
354                                                          tags);
355                         } else {
356                                 yaffs_HandleWriteChunkError(dev, chunk);
357                         }
358                 }
359
360         } while (chunk >= 0 && !writeOk);
361
362         if (attempts > 1) {
363                 T(YAFFS_TRACE_ERROR,
364                   (TSTR("**>> yaffs write required %d attempts" TENDSTR),
365                    attempts));
366                 dev->nRetriedWrites += (attempts - 1);
367         }
368
369         return chunk;
370 }
371
372 /*
373  * Block retiring for handling a broken block.
374  */
375  
376 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
377 {
378
379         yaffs_InvalidateCheckpoint(dev);
380         
381         yaffs_MarkBlockBad(dev, blockInNAND);
382
383         yaffs_GetBlockInfo(dev, blockInNAND)->blockState =
384             YAFFS_BLOCK_STATE_DEAD;
385
386         dev->nRetiredBlocks++;
387 }
388
389 /*
390  * Functions for robustisizing TODO
391  *
392  */
393  
394 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
395                                      const __u8 * data,
396                                      const yaffs_ExtendedTags * tags)
397 {
398 }
399
400 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
401                                     const yaffs_ExtendedTags * tags)
402 {
403 }
404
405 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND)
406 {
407         int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
408
409         /* Mark the block for retirement */
410         yaffs_GetBlockInfo(dev, blockInNAND)->needsRetiring = 1;
411         /* Delete the chunk */
412         yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
413 }
414
415
416 /*---------------- Name handling functions ------------*/ 
417
418 static __u16 yaffs_CalcNameSum(const YCHAR * name)
419 {
420         __u16 sum = 0;
421         __u16 i = 1;
422
423         YUCHAR *bname = (YUCHAR *) name;
424         if (bname) {
425                 while ((*bname) && (i <= YAFFS_MAX_NAME_LENGTH)) {
426
427 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
428                         sum += yaffs_toupper(*bname) * i;
429 #else
430                         sum += (*bname) * i;
431 #endif
432                         i++;
433                         bname++;
434                 }
435         }
436         return sum;
437 }
438
439 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
440 {
441 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
442         if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
443                 yaffs_strcpy(obj->shortName, name);
444         } else {
445                 obj->shortName[0] = _Y('\0');
446         }
447 #endif
448         obj->sum = yaffs_CalcNameSum(name);
449 }
450
451 /*-------------------- TNODES -------------------
452
453  * List of spare tnodes
454  * The list is hooked together using the first pointer
455  * in the tnode.
456  */
457  
458 /* yaffs_CreateTnodes creates a bunch more tnodes and
459  * adds them to the tnode free list.
460  * Don't use this function directly
461  */
462
463 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
464 {
465         int i;
466         int tnodeSize;
467         yaffs_Tnode *newTnodes;
468         __u8 *mem;
469         yaffs_Tnode *curr;
470         yaffs_Tnode *next;
471         yaffs_TnodeList *tnl;
472
473         if (nTnodes < 1)
474                 return YAFFS_OK;
475                 
476         /* Calculate the tnode size in bytes for variable width tnode support.
477          * Must be a multiple of 32-bits  */
478         tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
479
480         /* make these things */
481
482         newTnodes = YMALLOC(nTnodes * tnodeSize);
483         mem = (__u8 *)newTnodes;
484
485         if (!newTnodes) {
486                 T(YAFFS_TRACE_ERROR,
487                   (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
488                 return YAFFS_FAIL;
489         }
490
491         /* Hook them into the free list */
492 #if 0
493         for (i = 0; i < nTnodes - 1; i++) {
494                 newTnodes[i].internal[0] = &newTnodes[i + 1];
495 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
496                 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
497 #endif
498         }
499
500         newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
501 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
502         newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
503 #endif
504         dev->freeTnodes = newTnodes;
505 #else
506         /* New hookup for wide tnodes */
507         for(i = 0; i < nTnodes -1; i++) {
508                 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
509                 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
510                 curr->internal[0] = next;
511         }
512         
513         curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
514         curr->internal[0] = dev->freeTnodes;
515         dev->freeTnodes = (yaffs_Tnode *)mem;
516
517 #endif
518
519
520         dev->nFreeTnodes += nTnodes;
521         dev->nTnodesCreated += nTnodes;
522
523         /* Now add this bunch of tnodes to a list for freeing up.
524          * NB If we can't add this to the management list it isn't fatal
525          * but it just means we can't free this bunch of tnodes later.
526          */
527          
528         tnl = YMALLOC(sizeof(yaffs_TnodeList));
529         if (!tnl) {
530                 T(YAFFS_TRACE_ERROR,
531                   (TSTR
532                    ("yaffs: Could not add tnodes to management list" TENDSTR)));
533
534         } else {
535                 tnl->tnodes = newTnodes;
536                 tnl->next = dev->allocatedTnodeList;
537                 dev->allocatedTnodeList = tnl;
538         }
539
540         T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
541
542         return YAFFS_OK;
543 }
544
545 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
546
547 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
548 {
549         yaffs_Tnode *tn = NULL;
550
551         /* If there are none left make more */
552         if (!dev->freeTnodes) {
553                 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
554         }
555
556         if (dev->freeTnodes) {
557                 tn = dev->freeTnodes;
558 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
559                 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
560                         /* Hoosterman, this thing looks like it isn't in the list */
561                         T(YAFFS_TRACE_ALWAYS,
562                           (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
563                 }
564 #endif
565                 dev->freeTnodes = dev->freeTnodes->internal[0];
566                 dev->nFreeTnodes--;
567         }
568
569         return tn;
570 }
571
572 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
573 {
574         yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
575         
576         if(tn)
577                 memset(tn, 0, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
578
579         return tn;      
580 }
581
582 /* FreeTnode frees up a tnode and puts it back on the free list */
583 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
584 {
585         if (tn) {
586 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
587                 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
588                         /* Hoosterman, this thing looks like it is already in the list */
589                         T(YAFFS_TRACE_ALWAYS,
590                           (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
591                 }
592                 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
593 #endif
594                 tn->internal[0] = dev->freeTnodes;
595                 dev->freeTnodes = tn;
596                 dev->nFreeTnodes++;
597         }
598 }
599
600 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
601 {
602         /* Free the list of allocated tnodes */
603         yaffs_TnodeList *tmp;
604
605         while (dev->allocatedTnodeList) {
606                 tmp = dev->allocatedTnodeList->next;
607
608                 YFREE(dev->allocatedTnodeList->tnodes);
609                 YFREE(dev->allocatedTnodeList);
610                 dev->allocatedTnodeList = tmp;
611
612         }
613
614         dev->freeTnodes = NULL;
615         dev->nFreeTnodes = 0;
616 }
617
618 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
619 {
620         dev->allocatedTnodeList = NULL;
621         dev->freeTnodes = NULL;
622         dev->nFreeTnodes = 0;
623         dev->nTnodesCreated = 0;
624
625 }
626
627
628 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
629 {
630   __u32 *map = (__u32 *)tn;
631   __u32 bitInMap;
632   __u32 bitInWord;
633   __u32 wordInMap;
634   __u32 mask;
635   
636   pos &= YAFFS_TNODES_LEVEL0_MASK;
637   val >>= dev->chunkGroupBits;
638   
639   bitInMap = pos * dev->tnodeWidth;
640   wordInMap = bitInMap /32;
641   bitInWord = bitInMap & (32 -1);
642   
643   mask = dev->tnodeMask << bitInWord;
644   
645   map[wordInMap] &= ~mask;
646   map[wordInMap] |= (mask & (val << bitInWord));
647   
648   if(dev->tnodeWidth > (32-bitInWord)) {
649     bitInWord = (32 - bitInWord);
650     wordInMap++;;
651     mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
652     map[wordInMap] &= ~mask;
653     map[wordInMap] |= (mask & (val >> bitInWord));
654   }
655 }
656
657 __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
658 {
659   __u32 *map = (__u32 *)tn;
660   __u32 bitInMap;
661   __u32 bitInWord;
662   __u32 wordInMap;
663   __u32 val;
664   
665   pos &= YAFFS_TNODES_LEVEL0_MASK;
666   
667   bitInMap = pos * dev->tnodeWidth;
668   wordInMap = bitInMap /32;
669   bitInWord = bitInMap & (32 -1);
670   
671   val = map[wordInMap] >> bitInWord;
672   
673   if(dev->tnodeWidth > (32-bitInWord)) {
674     bitInWord = (32 - bitInWord);
675     wordInMap++;;
676     val |= (map[wordInMap] << bitInWord);
677   }
678   
679   val &= dev->tnodeMask;
680   val <<= dev->chunkGroupBits;
681   
682   return val;
683 }
684
685 /* ------------------- End of individual tnode manipulation -----------------*/
686
687 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
688  * The look up tree is represented by the top tnode and the number of topLevel
689  * in the tree. 0 means only the level 0 tnode is in the tree.
690  */
691
692 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
693 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
694                                           yaffs_FileStructure * fStruct,
695                                           __u32 chunkId)
696 {
697
698         yaffs_Tnode *tn = fStruct->top;
699         __u32 i;
700         int requiredTallness;
701         int level = fStruct->topLevel;
702
703         /* Check sane level and chunk Id */
704         if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
705                 return NULL;
706         }
707
708         if (chunkId > YAFFS_MAX_CHUNK_ID) {
709                 return NULL;
710         }
711
712         /* First check we're tall enough (ie enough topLevel) */
713
714         i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
715         requiredTallness = 0;
716         while (i) {
717                 i >>= YAFFS_TNODES_INTERNAL_BITS;
718                 requiredTallness++;
719         }
720
721         if (requiredTallness > fStruct->topLevel) {
722                 /* Not tall enough, so we can't find it, return NULL. */
723                 return NULL;
724         }
725
726         /* Traverse down to level 0 */
727         while (level > 0 && tn) {
728                 tn = tn->
729                     internal[(chunkId >>
730                                ( YAFFS_TNODES_LEVEL0_BITS + 
731                                  (level - 1) *
732                                  YAFFS_TNODES_INTERNAL_BITS)
733                               ) &
734                              YAFFS_TNODES_INTERNAL_MASK];
735                 level--;
736
737         }
738
739         return tn;
740 }
741
742 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
743  * This happens in two steps:
744  *  1. If the tree isn't tall enough, then make it taller.
745  *  2. Scan down the tree towards the level 0 tnode adding tnodes if required.
746  *
747  * Used when modifying the tree.
748  *
749  *  If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
750  *  be plugged into the ttree.
751  */
752  
753 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
754                                                yaffs_FileStructure * fStruct,
755                                                __u32 chunkId,
756                                                yaffs_Tnode *passedTn)
757 {
758
759         int requiredTallness;
760         int i;
761         int l;
762         yaffs_Tnode *tn;
763
764         __u32 x;
765
766
767         /* Check sane level and page Id */
768         if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
769                 return NULL;
770         }
771
772         if (chunkId > YAFFS_MAX_CHUNK_ID) {
773                 return NULL;
774         }
775
776         /* First check we're tall enough (ie enough topLevel) */
777
778         x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
779         requiredTallness = 0;
780         while (x) {
781                 x >>= YAFFS_TNODES_INTERNAL_BITS;
782                 requiredTallness++;
783         }
784
785
786         if (requiredTallness > fStruct->topLevel) {
787                 /* Not tall enough,gotta make the tree taller */
788                 for (i = fStruct->topLevel; i < requiredTallness; i++) {
789                 
790                         tn = yaffs_GetTnode(dev);
791
792                         if (tn) {
793                                 tn->internal[0] = fStruct->top;
794                                 fStruct->top = tn;
795                         } else {
796                                 T(YAFFS_TRACE_ERROR,
797                                   (TSTR("yaffs: no more tnodes" TENDSTR)));
798                         }
799                 }
800
801                 fStruct->topLevel = requiredTallness;
802         }
803
804         /* Traverse down to level 0, adding anything we need */
805
806         l = fStruct->topLevel;
807         tn = fStruct->top;
808         
809         if(l > 0) {
810                 while (l > 0 && tn) {
811                         x = (chunkId >>
812                              ( YAFFS_TNODES_LEVEL0_BITS +
813                               (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
814                             YAFFS_TNODES_INTERNAL_MASK;
815
816
817                         if((l>1) && !tn->internal[x]){
818                                 /* Add missing non-level-zero tnode */
819                                 tn->internal[x] = yaffs_GetTnode(dev);
820
821                         } else if(l == 1) {
822                                 /* Looking from level 1 at level 0 */
823                                 if (passedTn) {
824                                         /* If we already have one, then release it.*/
825                                         if(tn->internal[x])
826                                                 yaffs_FreeTnode(dev,tn->internal[x]);
827                                         tn->internal[x] = passedTn;
828                         
829                                 } else if(!tn->internal[x]) {
830                                         /* Don't have one, none passed in */
831                                         tn->internal[x] = yaffs_GetTnode(dev);
832                                 }
833                         }
834                 
835                         tn = tn->internal[x];
836                         l--;
837                 }
838         } else {
839                 /* top is level 0 */
840                 if(passedTn) {
841                         memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
842                         yaffs_FreeTnode(dev,passedTn);
843                 }
844         }
845
846         return tn;
847 }
848
849 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
850                                   yaffs_ExtendedTags * tags, int objectId,
851                                   int chunkInInode)
852 {
853         int j;
854
855         for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
856                 if (yaffs_CheckChunkBit
857                     (dev, theChunk / dev->nChunksPerBlock,
858                      theChunk % dev->nChunksPerBlock)) {
859                         yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
860                                                         tags);
861                         if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
862                                 /* found it; */
863                                 return theChunk;
864
865                         }
866                 }
867                 theChunk++;
868         }
869         return -1;
870 }
871
872
873 /* DeleteWorker scans backwards through the tnode tree and deletes all the
874  * chunks and tnodes in the file
875  * Returns 1 if the tree was deleted. 
876  * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
877  */
878
879 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
880                               int chunkOffset, int *limit)
881 {
882         int i;
883         int chunkInInode;
884         int theChunk;
885         yaffs_ExtendedTags tags;
886         int foundChunk;
887         yaffs_Device *dev = in->myDev;
888
889         int allDone = 1;
890
891         if (tn) {
892                 if (level > 0) {
893
894                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
895                              i--) {
896                                 if (tn->internal[i]) {
897                                         if (limit && (*limit) < 0) {
898                                                 allDone = 0;
899                                         } else {
900                                                 allDone =
901                                                     yaffs_DeleteWorker(in,
902                                                                        tn->
903                                                                        internal
904                                                                        [i],
905                                                                        level -
906                                                                        1,
907                                                                        (chunkOffset
908                                                                         <<
909                                                                         YAFFS_TNODES_INTERNAL_BITS)
910                                                                        + i,
911                                                                        limit);
912                                         }
913                                         if (allDone) {
914                                                 yaffs_FreeTnode(dev,
915                                                                 tn->
916                                                                 internal[i]);
917                                                 tn->internal[i] = NULL;
918                                         }
919                                 }
920
921                         }
922                         return (allDone) ? 1 : 0;
923                 } else if (level == 0) {
924                         int hitLimit = 0;
925
926                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
927                              i--) {
928                                 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
929                                 if (theChunk) {
930
931                                         chunkInInode =
932                                             (chunkOffset <<
933                                              YAFFS_TNODES_LEVEL0_BITS) + i;
934
935                                         foundChunk =
936                                             yaffs_FindChunkInGroup(dev,
937                                                                    theChunk,
938                                                                    &tags,
939                                                                    in->objectId,
940                                                                    chunkInInode);
941
942                                         if (foundChunk > 0) {
943                                                 yaffs_DeleteChunk(dev,
944                                                                   foundChunk, 1,
945                                                                   __LINE__);
946                                                 in->nDataChunks--;
947                                                 if (limit) {
948                                                         *limit = *limit - 1;
949                                                         if (*limit <= 0) {
950                                                                 hitLimit = 1;
951                                                         }
952                                                 }
953
954                                         }
955
956                                         yaffs_PutLevel0Tnode(dev,tn,i,0);
957                                 }
958
959                         }
960                         return (i < 0) ? 1 : 0;
961
962                 }
963
964         }
965
966         return 1;
967
968 }
969
970 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
971 {
972
973         yaffs_BlockInfo *theBlock;
974
975         T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
976
977         theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
978         if (theBlock) {
979                 theBlock->softDeletions++;
980                 dev->nFreeChunks++;
981         }
982 }
983
984 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
985  * All soft deleting does is increment the block's softdelete count and pulls the chunk out
986  * of the tnode.
987  * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
988  */
989  
990 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
991                                   __u32 level, int chunkOffset)
992 {
993         int i;
994         int theChunk;
995         int allDone = 1;
996         yaffs_Device *dev = in->myDev;
997
998         if (tn) {
999                 if (level > 0) {
1000
1001                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1002                              i--) {
1003                                 if (tn->internal[i]) {
1004                                         allDone =
1005                                             yaffs_SoftDeleteWorker(in,
1006                                                                    tn->
1007                                                                    internal[i],
1008                                                                    level - 1,
1009                                                                    (chunkOffset
1010                                                                     <<
1011                                                                     YAFFS_TNODES_INTERNAL_BITS)
1012                                                                    + i);
1013                                         if (allDone) {
1014                                                 yaffs_FreeTnode(dev,
1015                                                                 tn->
1016                                                                 internal[i]);
1017                                                 tn->internal[i] = NULL;
1018                                         } else {
1019                                                 /* Hoosterman... how could this happen? */
1020                                         }
1021                                 }
1022                         }
1023                         return (allDone) ? 1 : 0;
1024                 } else if (level == 0) {
1025
1026                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1027                                 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1028                                 if (theChunk) {
1029                                         /* Note this does not find the real chunk, only the chunk group.
1030                                          * We make an assumption that a chunk group is not larger than 
1031                                          * a block.
1032                                          */
1033                                         yaffs_SoftDeleteChunk(dev, theChunk);
1034                                         yaffs_PutLevel0Tnode(dev,tn,i,0);
1035                                 }
1036
1037                         }
1038                         return 1;
1039
1040                 }
1041
1042         }
1043
1044         return 1;
1045
1046 }
1047
1048 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1049 {
1050         if (obj->deleted &&
1051             obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1052                 if (obj->nDataChunks <= 0) {
1053                         /* Empty file with no duplicate object headers, just delete it immediately */
1054                         yaffs_FreeTnode(obj->myDev,
1055                                         obj->variant.fileVariant.top);
1056                         obj->variant.fileVariant.top = NULL;
1057                         T(YAFFS_TRACE_TRACING,
1058                           (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1059                            obj->objectId));
1060                         yaffs_DoGenericObjectDeletion(obj);
1061                 } else {
1062                         yaffs_SoftDeleteWorker(obj,
1063                                                obj->variant.fileVariant.top,
1064                                                obj->variant.fileVariant.
1065                                                topLevel, 0);
1066                         obj->softDeleted = 1;
1067                 }
1068         }
1069 }
1070
1071 /* Pruning removes any part of the file structure tree that is beyond the
1072  * bounds of the file (ie that does not point to chunks).
1073  *
1074  * A file should only get pruned when its size is reduced.
1075  *
1076  * Before pruning, the chunks must be pulled from the tree and the
1077  * level 0 tnode entries must be zeroed out.
1078  * Could also use this for file deletion, but that's probably better handled
1079  * by a special case.
1080  */
1081
1082 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1083                                       __u32 level, int del0)
1084 {
1085         int i;
1086         int hasData;
1087
1088         if (tn) {
1089                 hasData = 0;
1090
1091                 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1092                         if (tn->internal[i] && level > 0) {
1093                                 tn->internal[i] =
1094                                     yaffs_PruneWorker(dev, tn->internal[i],
1095                                                       level - 1,
1096                                                       (i == 0) ? del0 : 1);
1097                         }
1098
1099                         if (tn->internal[i]) {
1100                                 hasData++;
1101                         }
1102                 }
1103
1104                 if (hasData == 0 && del0) {
1105                         /* Free and return NULL */
1106
1107                         yaffs_FreeTnode(dev, tn);
1108                         tn = NULL;
1109                 }
1110
1111         }
1112
1113         return tn;
1114
1115 }
1116
1117 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1118                                     yaffs_FileStructure * fStruct)
1119 {
1120         int i;
1121         int hasData;
1122         int done = 0;
1123         yaffs_Tnode *tn;
1124
1125         if (fStruct->topLevel > 0) {
1126                 fStruct->top =
1127                     yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1128
1129                 /* Now we have a tree with all the non-zero branches NULL but the height
1130                  * is the same as it was.
1131                  * Let's see if we can trim internal tnodes to shorten the tree.
1132                  * We can do this if only the 0th element in the tnode is in use 
1133                  * (ie all the non-zero are NULL)
1134                  */
1135
1136                 while (fStruct->topLevel && !done) {
1137                         tn = fStruct->top;
1138
1139                         hasData = 0;
1140                         for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1141                                 if (tn->internal[i]) {
1142                                         hasData++;
1143                                 }
1144                         }
1145
1146                         if (!hasData) {
1147                                 fStruct->top = tn->internal[0];
1148                                 fStruct->topLevel--;
1149                                 yaffs_FreeTnode(dev, tn);
1150                         } else {
1151                                 done = 1;
1152                         }
1153                 }
1154         }
1155
1156         return YAFFS_OK;
1157 }
1158
1159 /*-------------------- End of File Structure functions.-------------------*/
1160
1161 /* yaffs_CreateFreeObjects creates a bunch more objects and
1162  * adds them to the object free list.
1163  */
1164 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1165 {
1166         int i;
1167         yaffs_Object *newObjects;
1168         yaffs_ObjectList *list;
1169
1170         if (nObjects < 1)
1171                 return YAFFS_OK;
1172
1173         /* make these things */
1174         newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1175
1176         if (!newObjects) {
1177                 T(YAFFS_TRACE_ALLOCATE,
1178                   (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1179                 return YAFFS_FAIL;
1180         }
1181         
1182         /* Hook them into the free list */
1183         for (i = 0; i < nObjects - 1; i++) {
1184                 newObjects[i].siblings.next =
1185                     (struct list_head *)(&newObjects[i + 1]);
1186         }
1187
1188         newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1189         dev->freeObjects = newObjects;
1190         dev->nFreeObjects += nObjects;
1191         dev->nObjectsCreated += nObjects;
1192
1193         /* Now add this bunch of Objects to a list for freeing up. */
1194
1195         list = YMALLOC(sizeof(yaffs_ObjectList));
1196         if (!list) {
1197                 T(YAFFS_TRACE_ALLOCATE,
1198                   (TSTR("Could not add objects to management list" TENDSTR)));
1199         } else {
1200                 list->objects = newObjects;
1201                 list->next = dev->allocatedObjectList;
1202                 dev->allocatedObjectList = list;
1203         }
1204
1205         return YAFFS_OK;
1206 }
1207
1208
1209 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1210 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1211 {
1212         yaffs_Object *tn = NULL;
1213
1214         /* If there are none left make more */
1215         if (!dev->freeObjects) {
1216                 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1217         }
1218
1219         if (dev->freeObjects) {
1220                 tn = dev->freeObjects;
1221                 dev->freeObjects =
1222                     (yaffs_Object *) (dev->freeObjects->siblings.next);
1223                 dev->nFreeObjects--;
1224
1225                 /* Now sweeten it up... */
1226
1227                 memset(tn, 0, sizeof(yaffs_Object));
1228                 tn->myDev = dev;
1229                 tn->chunkId = -1;
1230                 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1231                 INIT_LIST_HEAD(&(tn->hardLinks));
1232                 INIT_LIST_HEAD(&(tn->hashLink));
1233                 INIT_LIST_HEAD(&tn->siblings);
1234
1235                 /* Add it to the lost and found directory.
1236                  * NB Can't put root or lostNFound in lostNFound so
1237                  * check if lostNFound exists first
1238                  */
1239                 if (dev->lostNFoundDir) {
1240                         yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1241                 }
1242         }
1243
1244         return tn;
1245 }
1246
1247 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1248                                                __u32 mode)
1249 {
1250
1251         yaffs_Object *obj =
1252             yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1253         if (obj) {
1254                 obj->fake = 1;          /* it is fake so it has no NAND presence... */
1255                 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1256                 obj->unlinkAllowed = 0; /* ... or unlink it */
1257                 obj->deleted = 0;
1258                 obj->unlinked = 0;
1259                 obj->yst_mode = mode;
1260                 obj->myDev = dev;
1261                 obj->chunkId = 0;       /* Not a valid chunk. */
1262         }
1263
1264         return obj;
1265
1266 }
1267
1268 static void yaffs_UnhashObject(yaffs_Object * tn)
1269 {
1270         int bucket;
1271         yaffs_Device *dev = tn->myDev;
1272
1273         /* If it is still linked into the bucket list, free from the list */
1274         if (!list_empty(&tn->hashLink)) {
1275                 list_del_init(&tn->hashLink);
1276                 bucket = yaffs_HashFunction(tn->objectId);
1277                 dev->objectBucket[bucket].count--;
1278         }
1279
1280 }
1281
1282 /*  FreeObject frees up a Object and puts it back on the free list */
1283 static void yaffs_FreeObject(yaffs_Object * tn)
1284 {
1285
1286         yaffs_Device *dev = tn->myDev;
1287
1288 #ifdef  __KERNEL__
1289         if (tn->myInode) {
1290                 /* We're still hooked up to a cached inode.
1291                  * Don't delete now, but mark for later deletion
1292                  */
1293                 tn->deferedFree = 1;
1294                 return;
1295         }
1296 #endif
1297
1298         yaffs_UnhashObject(tn);
1299
1300         /* Link into the free list. */
1301         tn->siblings.next = (struct list_head *)(dev->freeObjects);
1302         dev->freeObjects = tn;
1303         dev->nFreeObjects++;
1304 }
1305
1306 #ifdef __KERNEL__
1307
1308 void yaffs_HandleDeferedFree(yaffs_Object * obj)
1309 {
1310         if (obj->deferedFree) {
1311                 yaffs_FreeObject(obj);
1312         }
1313 }
1314
1315 #endif
1316
1317 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
1318 {
1319         /* Free the list of allocated Objects */
1320
1321         yaffs_ObjectList *tmp;
1322
1323         while (dev->allocatedObjectList) {
1324                 tmp = dev->allocatedObjectList->next;
1325                 YFREE(dev->allocatedObjectList->objects);
1326                 YFREE(dev->allocatedObjectList);
1327
1328                 dev->allocatedObjectList = tmp;
1329         }
1330
1331         dev->freeObjects = NULL;
1332         dev->nFreeObjects = 0;
1333 }
1334
1335 static void yaffs_InitialiseObjects(yaffs_Device * dev)
1336 {
1337         int i;
1338
1339         dev->allocatedObjectList = NULL;
1340         dev->freeObjects = NULL;
1341         dev->nFreeObjects = 0;
1342
1343         for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
1344                 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1345                 dev->objectBucket[i].count = 0;
1346         }
1347
1348 }
1349
1350 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
1351 {
1352         static int x = 0;
1353         int i;
1354         int l = 999;
1355         int lowest = 999999;
1356
1357         /* First let's see if we can find one that's empty. */
1358
1359         for (i = 0; i < 10 && lowest > 0; i++) {
1360                 x++;
1361                 x %= YAFFS_NOBJECT_BUCKETS;
1362                 if (dev->objectBucket[x].count < lowest) {
1363                         lowest = dev->objectBucket[x].count;
1364                         l = x;
1365                 }
1366
1367         }
1368
1369         /* If we didn't find an empty list, then try
1370          * looking a bit further for a short one
1371          */
1372
1373         for (i = 0; i < 10 && lowest > 3; i++) {
1374                 x++;
1375                 x %= YAFFS_NOBJECT_BUCKETS;
1376                 if (dev->objectBucket[x].count < lowest) {
1377                         lowest = dev->objectBucket[x].count;
1378                         l = x;
1379                 }
1380
1381         }
1382
1383         return l;
1384 }
1385
1386 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
1387 {
1388         int bucket = yaffs_FindNiceObjectBucket(dev);
1389
1390         /* Now find an object value that has not already been taken
1391          * by scanning the list.
1392          */
1393
1394         int found = 0;
1395         struct list_head *i;
1396
1397         __u32 n = (__u32) bucket;
1398
1399         /* yaffs_CheckObjectHashSanity();  */
1400
1401         while (!found) {
1402                 found = 1;
1403                 n += YAFFS_NOBJECT_BUCKETS;
1404                 if (1 || dev->objectBucket[bucket].count > 0) {
1405                         list_for_each(i, &dev->objectBucket[bucket].list) {
1406                                 /* If there is already one in the list */
1407                                 if (i
1408                                     && list_entry(i, yaffs_Object,
1409                                                   hashLink)->objectId == n) {
1410                                         found = 0;
1411                                 }
1412                         }
1413                 }
1414         }
1415
1416
1417         return n;
1418 }
1419
1420 static void yaffs_HashObject(yaffs_Object * in)
1421 {
1422         int bucket = yaffs_HashFunction(in->objectId);
1423         yaffs_Device *dev = in->myDev;
1424
1425         list_add(&in->hashLink, &dev->objectBucket[bucket].list);
1426         dev->objectBucket[bucket].count++;
1427
1428 }
1429
1430 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
1431 {
1432         int bucket = yaffs_HashFunction(number);
1433         struct list_head *i;
1434         yaffs_Object *in;
1435
1436         list_for_each(i, &dev->objectBucket[bucket].list) {
1437                 /* Look if it is in the list */
1438                 if (i) {
1439                         in = list_entry(i, yaffs_Object, hashLink);
1440                         if (in->objectId == number) {
1441 #ifdef __KERNEL__
1442                                 /* Don't tell the VFS about this one if it is defered free */
1443                                 if (in->deferedFree)
1444                                         return NULL;
1445 #endif
1446
1447                                 return in;
1448                         }
1449                 }
1450         }
1451
1452         return NULL;
1453 }
1454
1455 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
1456                                     yaffs_ObjectType type)
1457 {
1458
1459         yaffs_Object *theObject;
1460
1461         if (number < 0) {
1462                 number = yaffs_CreateNewObjectNumber(dev);
1463         }
1464
1465         theObject = yaffs_AllocateEmptyObject(dev);
1466
1467         if (theObject) {
1468                 theObject->fake = 0;
1469                 theObject->renameAllowed = 1;
1470                 theObject->unlinkAllowed = 1;
1471                 theObject->objectId = number;
1472                 yaffs_HashObject(theObject);
1473                 theObject->variantType = type;
1474 #ifdef CONFIG_YAFFS_WINCE
1475                 yfsd_WinFileTimeNow(theObject->win_atime);
1476                 theObject->win_ctime[0] = theObject->win_mtime[0] =
1477                     theObject->win_atime[0];
1478                 theObject->win_ctime[1] = theObject->win_mtime[1] =
1479                     theObject->win_atime[1];
1480
1481 #else
1482
1483                 theObject->yst_atime = theObject->yst_mtime =
1484                     theObject->yst_ctime = Y_CURRENT_TIME;
1485 #endif
1486                 switch (type) {
1487                 case YAFFS_OBJECT_TYPE_FILE:
1488                         theObject->variant.fileVariant.fileSize = 0;
1489                         theObject->variant.fileVariant.scannedFileSize = 0;
1490                         theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
1491                         theObject->variant.fileVariant.topLevel = 0;
1492                         theObject->variant.fileVariant.top =
1493                             yaffs_GetTnode(dev);
1494                         break;
1495                 case YAFFS_OBJECT_TYPE_DIRECTORY:
1496                         INIT_LIST_HEAD(&theObject->variant.directoryVariant.
1497                                        children);
1498                         break;
1499                 case YAFFS_OBJECT_TYPE_SYMLINK:
1500                 case YAFFS_OBJECT_TYPE_HARDLINK:
1501                 case YAFFS_OBJECT_TYPE_SPECIAL:
1502                         /* No action required */
1503                         break;
1504                 case YAFFS_OBJECT_TYPE_UNKNOWN:
1505                         /* todo this should not happen */
1506                         break;
1507                 }
1508         }
1509
1510         return theObject;
1511 }
1512
1513 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
1514                                                       int number,
1515                                                       yaffs_ObjectType type)
1516 {
1517         yaffs_Object *theObject = NULL;
1518
1519         if (number > 0) {
1520                 theObject = yaffs_FindObjectByNumber(dev, number);
1521         }
1522
1523         if (!theObject) {
1524                 theObject = yaffs_CreateNewObject(dev, number, type);
1525         }
1526
1527         return theObject;
1528
1529 }
1530                         
1531
1532 static YCHAR *yaffs_CloneString(const YCHAR * str)
1533 {
1534         YCHAR *newStr = NULL;
1535
1536         if (str && *str) {
1537                 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
1538                 yaffs_strcpy(newStr, str);
1539         }
1540
1541         return newStr;
1542
1543 }
1544
1545 /*
1546  * Mknod (create) a new object.
1547  * equivalentObject only has meaning for a hard link;
1548  * aliasString only has meaning for a sumlink.
1549  * rdev only has meaning for devices (a subset of special objects)
1550  */
1551  
1552 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
1553                                        yaffs_Object * parent,
1554                                        const YCHAR * name,
1555                                        __u32 mode,
1556                                        __u32 uid,
1557                                        __u32 gid,
1558                                        yaffs_Object * equivalentObject,
1559                                        const YCHAR * aliasString, __u32 rdev)
1560 {
1561         yaffs_Object *in;
1562
1563         yaffs_Device *dev = parent->myDev;
1564
1565         /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
1566         if (yaffs_FindObjectByName(parent, name)) {
1567                 return NULL;
1568         }
1569
1570         in = yaffs_CreateNewObject(dev, -1, type);
1571
1572         if (in) {
1573                 in->chunkId = -1;
1574                 in->valid = 1;
1575                 in->variantType = type;
1576
1577                 in->yst_mode = mode;
1578
1579 #ifdef CONFIG_YAFFS_WINCE
1580                 yfsd_WinFileTimeNow(in->win_atime);
1581                 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1582                 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
1583
1584 #else
1585                 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
1586
1587                 in->yst_rdev = rdev;
1588                 in->yst_uid = uid;
1589                 in->yst_gid = gid;
1590 #endif
1591                 in->nDataChunks = 0;
1592
1593                 yaffs_SetObjectName(in, name);
1594                 in->dirty = 1;
1595
1596                 yaffs_AddObjectToDirectory(parent, in);
1597
1598                 in->myDev = parent->myDev;
1599
1600                 switch (type) {
1601                 case YAFFS_OBJECT_TYPE_SYMLINK:
1602                         in->variant.symLinkVariant.alias =
1603                             yaffs_CloneString(aliasString);
1604                         break;
1605                 case YAFFS_OBJECT_TYPE_HARDLINK:
1606                         in->variant.hardLinkVariant.equivalentObject =
1607                             equivalentObject;
1608                         in->variant.hardLinkVariant.equivalentObjectId =
1609                             equivalentObject->objectId;
1610                         list_add(&in->hardLinks, &equivalentObject->hardLinks);
1611                         break;
1612                 case YAFFS_OBJECT_TYPE_FILE:    
1613                 case YAFFS_OBJECT_TYPE_DIRECTORY:
1614                 case YAFFS_OBJECT_TYPE_SPECIAL:
1615                 case YAFFS_OBJECT_TYPE_UNKNOWN:
1616                         /* do nothing */
1617                         break;
1618                 }
1619
1620                 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
1621                         /* Could not create the object header, fail the creation */
1622                         yaffs_DestroyObject(in);
1623                         in = NULL;
1624                 }
1625
1626         }
1627
1628         return in;
1629 }
1630
1631 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
1632                               __u32 mode, __u32 uid, __u32 gid)
1633 {
1634         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
1635                                  uid, gid, NULL, NULL, 0);
1636 }
1637
1638 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
1639                                    __u32 mode, __u32 uid, __u32 gid)
1640 {
1641         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
1642                                  mode, uid, gid, NULL, NULL, 0);
1643 }
1644
1645 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
1646                                  __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1647 {
1648         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
1649                                  uid, gid, NULL, NULL, rdev);
1650 }
1651
1652 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
1653                                  __u32 mode, __u32 uid, __u32 gid,
1654                                  const YCHAR * alias)
1655 {
1656         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
1657                                  uid, gid, NULL, alias, 0);
1658 }
1659
1660 /* yaffs_Link returns the object id of the equivalent object.*/
1661 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
1662                          yaffs_Object * equivalentObject)
1663 {
1664         /* Get the real object in case we were fed a hard link as an equivalent object */
1665         equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1666
1667         if (yaffs_MknodObject
1668             (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
1669              equivalentObject, NULL, 0)) {
1670                 return equivalentObject;
1671         } else {
1672                 return NULL;
1673         }
1674
1675 }
1676
1677 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
1678                                   const YCHAR * newName, int force, int shadows)
1679 {
1680         int unlinkOp;
1681         int deleteOp;
1682
1683         yaffs_Object *existingTarget;
1684
1685         if (newDir == NULL) {
1686                 newDir = obj->parent;   /* use the old directory */
1687         }
1688
1689         if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
1690                 T(YAFFS_TRACE_ALWAYS,
1691                   (TSTR
1692                    ("tragendy: yaffs_ChangeObjectName: newDir is not a directory"
1693                     TENDSTR)));
1694                 YBUG();
1695         }
1696         
1697         /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
1698         if (obj->myDev->isYaffs2) {
1699                 unlinkOp = (newDir == obj->myDev->unlinkedDir);
1700         } else {
1701                 unlinkOp = (newDir == obj->myDev->unlinkedDir
1702                             && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1703         }
1704
1705         deleteOp = (newDir == obj->myDev->deletedDir);
1706
1707         existingTarget = yaffs_FindObjectByName(newDir, newName);
1708
1709         /* If the object is a file going into the unlinked directory, 
1710          *   then it is OK to just stuff it in since duplicate names are allowed.
1711          *   else only proceed if the new name does not exist and if we're putting 
1712          *   it into a directory.
1713          */
1714         if ((unlinkOp ||
1715              deleteOp ||
1716              force ||
1717              (shadows > 0) ||
1718              !existingTarget) &&
1719             newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
1720                 yaffs_SetObjectName(obj, newName);
1721                 obj->dirty = 1;
1722
1723                 yaffs_AddObjectToDirectory(newDir, obj);
1724
1725                 if (unlinkOp)
1726                         obj->unlinked = 1;
1727
1728                 /* If it is a deletion then we mark it as a shrink for gc purposes. */
1729                 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
1730                         return YAFFS_OK;
1731         }
1732
1733         return YAFFS_FAIL;
1734 }
1735
1736 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
1737                        yaffs_Object * newDir, const YCHAR * newName)
1738 {
1739         yaffs_Object *obj;
1740         yaffs_Object *existingTarget;
1741         int force = 0;
1742
1743 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1744         /* Special case for case insemsitive systems (eg. WinCE).
1745          * While look-up is case insensitive, the name isn't.
1746          * Therefore we might want to change x.txt to X.txt
1747         */
1748         if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
1749                 force = 1;
1750         }
1751 #endif
1752
1753         obj = yaffs_FindObjectByName(oldDir, oldName);
1754         /* Check new name to long. */
1755         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK &&
1756             yaffs_strlen(newName) > YAFFS_MAX_ALIAS_LENGTH)
1757           /* ENAMETOOLONG */
1758           return YAFFS_FAIL;
1759         else if (obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK &&
1760                  yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
1761           /* ENAMETOOLONG */
1762           return YAFFS_FAIL;
1763
1764         if (obj && obj->renameAllowed) {
1765
1766                 /* Now do the handling for an existing target, if there is one */
1767
1768                 existingTarget = yaffs_FindObjectByName(newDir, newName);
1769                 if (existingTarget &&
1770                     existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
1771                     !list_empty(&existingTarget->variant.directoryVariant.children)) {
1772                         /* There is a target that is a non-empty directory, so we fail */
1773                         return YAFFS_FAIL;      /* EEXIST or ENOTEMPTY */
1774                 } else if (existingTarget && existingTarget != obj) {
1775                         /* Nuke the target first, using shadowing, 
1776                          * but only if it isn't the same object
1777                          */
1778                         yaffs_ChangeObjectName(obj, newDir, newName, force,
1779                                                existingTarget->objectId);
1780                         yaffs_UnlinkObject(existingTarget);
1781                 }
1782
1783                 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
1784         }
1785         return YAFFS_FAIL;
1786 }
1787
1788 /*------------------------- Block Management and Page Allocation ----------------*/
1789
1790 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
1791 {
1792         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
1793         
1794         dev->allocationBlock = -1;      /* force it to get a new one */
1795
1796         /* Todo we're assuming the malloc will pass. */
1797         dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1798         if(!dev->blockInfo){
1799                 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
1800                 dev->blockInfoAlt = 1;
1801         }
1802         else
1803                 dev->blockInfoAlt = 0;
1804         
1805         /* Set up dynamic blockinfo stuff. */
1806         dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; // round up bytes
1807         dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
1808         if(!dev->chunkBits){
1809                 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
1810                 dev->chunkBitsAlt = 1;
1811         }
1812         else
1813                 dev->chunkBitsAlt = 0;
1814         
1815         if (dev->blockInfo && dev->chunkBits) {
1816                 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
1817                 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
1818                 return YAFFS_OK;
1819         }
1820
1821         return YAFFS_FAIL;
1822
1823 }
1824
1825 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
1826 {
1827         if(dev->blockInfoAlt)
1828                 YFREE_ALT(dev->blockInfo);
1829         else
1830                 YFREE(dev->blockInfo);
1831         dev->blockInfoAlt = 0;
1832
1833         dev->blockInfo = NULL;
1834         
1835         if(dev->chunkBitsAlt)
1836                 YFREE_ALT(dev->chunkBits);
1837         else
1838                 YFREE(dev->chunkBits);
1839         dev->chunkBitsAlt = 0;
1840         dev->chunkBits = NULL;
1841 }
1842
1843 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
1844                                             yaffs_BlockInfo * bi)
1845 {
1846         int i;
1847         __u32 seq;
1848         yaffs_BlockInfo *b;
1849
1850         if (!dev->isYaffs2)
1851                 return 1;       /* disqualification only applies to yaffs2. */
1852
1853         if (!bi->hasShrinkHeader)
1854                 return 1;       /* can gc */
1855
1856         /* Find the oldest dirty sequence number if we don't know it and save it
1857          * so we don't have to keep recomputing it.
1858          */
1859         if (!dev->oldestDirtySequence) {
1860                 seq = dev->sequenceNumber;
1861
1862                 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
1863                      i++) {
1864                         b = yaffs_GetBlockInfo(dev, i);
1865                         if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
1866                             (b->pagesInUse - b->softDeletions) <
1867                             dev->nChunksPerBlock && b->sequenceNumber < seq) {
1868                                 seq = b->sequenceNumber;
1869                         }
1870                 }
1871                 dev->oldestDirtySequence = seq;
1872         }
1873
1874         /* Can't do gc of this block if there are any blocks older than this one that have
1875          * discarded pages.
1876          */
1877         return (bi->sequenceNumber <= dev->oldestDirtySequence);
1878
1879         return 1;
1880
1881 }
1882
1883 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
1884  * for garbage collection.
1885  */
1886
1887 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
1888                                                int aggressive)
1889 {
1890
1891         int b = dev->currentDirtyChecker;
1892
1893         int i;
1894         int iterations;
1895         int dirtiest = -1;
1896         int pagesInUse;
1897         yaffs_BlockInfo *bi;
1898         static int nonAggressiveSkip = 0;
1899
1900         /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
1901          * search harder.
1902          * else (we're doing a leasurely gc), then we only bother to do this if the
1903          * block has only a few pages in use.
1904          */
1905
1906         nonAggressiveSkip--;
1907
1908         if (!aggressive && (nonAggressiveSkip > 0)) {
1909                 return -1;
1910         }
1911
1912         pagesInUse =
1913             (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
1914
1915         if (aggressive) {
1916                 iterations =
1917                     dev->internalEndBlock - dev->internalStartBlock + 1;
1918         } else {
1919                 iterations =
1920                     dev->internalEndBlock - dev->internalStartBlock + 1;
1921                 iterations = iterations / 16;
1922                 if (iterations > 200) {
1923                         iterations = 200;
1924                 }
1925         }
1926
1927         for (i = 0; i <= iterations && pagesInUse > 0; i++) {
1928                 b++;
1929                 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
1930                         b = dev->internalStartBlock;
1931                 }
1932
1933                 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
1934                         T(YAFFS_TRACE_ERROR,
1935                           (TSTR("**>> Block %d is not valid" TENDSTR), b));
1936                         YBUG();
1937                 }
1938
1939                 bi = yaffs_GetBlockInfo(dev, b);
1940
1941 #if 0
1942                 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
1943                         dirtiest = b;
1944                         pagesInUse = 0;
1945                 }
1946                 else 
1947 #endif
1948
1949                 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
1950                       (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
1951                         yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
1952                         dirtiest = b;
1953                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
1954                 }
1955         }
1956
1957         dev->currentDirtyChecker = b;
1958
1959         if (dirtiest > 0) {
1960                 T(YAFFS_TRACE_GC,
1961                   (TSTR("GC Selected block %d with %d free" TENDSTR), dirtiest,
1962                    dev->nChunksPerBlock - pagesInUse));
1963         }
1964
1965         dev->oldestDirtySequence = 0;
1966
1967         if (dirtiest > 0) {
1968                 nonAggressiveSkip = 4;
1969         }
1970
1971         return dirtiest;
1972 }
1973
1974 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
1975 {
1976         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
1977
1978         int erasedOk = 0;
1979
1980         /* If the block is still healthy erase it and mark as clean.
1981          * If the block has had a data failure, then retire it.
1982          */
1983         bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
1984
1985         if (!bi->needsRetiring) {
1986                 yaffs_InvalidateCheckpoint(dev);
1987                 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
1988                 if (!erasedOk) {
1989                         dev->nErasureFailures++;
1990                         T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1991                           (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
1992                 }
1993         }
1994
1995         if (erasedOk && (yaffs_traceMask & YAFFS_TRACE_ERASE)) {
1996                 int i;
1997                 for (i = 0; i < dev->nChunksPerBlock; i++) {
1998                         if (!yaffs_CheckChunkErased
1999                             (dev, blockNo * dev->nChunksPerBlock + i)) {
2000                                 T(YAFFS_TRACE_ERROR,
2001                                   (TSTR
2002                                    (">>Block %d erasure supposedly OK, but chunk %d not erased"
2003                                     TENDSTR), blockNo, i));
2004                         }
2005                 }
2006         }
2007
2008         if (erasedOk) {
2009                 /* Clean it up... */
2010                 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2011                 dev->nErasedBlocks++;
2012                 bi->pagesInUse = 0;
2013                 bi->softDeletions = 0;
2014                 bi->hasShrinkHeader = 0;
2015                 yaffs_ClearChunkBits(dev, blockNo);
2016
2017                 T(YAFFS_TRACE_ERASE,
2018                   (TSTR("Erased block %d" TENDSTR), blockNo));
2019         } else {
2020                 dev->nFreeChunks -= dev->nChunksPerBlock;       /* We lost a block of free space */
2021
2022                 yaffs_RetireBlock(dev, blockNo);
2023                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2024                   (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2025         }
2026 }
2027
2028 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2029 {
2030         int i;
2031
2032         yaffs_BlockInfo *bi;
2033
2034         if (dev->nErasedBlocks < 1) {
2035                 /* Hoosterman we've got a problem.
2036                  * Can't get space to gc
2037                  */
2038                 T(YAFFS_TRACE_ERROR,
2039                   (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2040
2041                 return -1;
2042         }
2043         
2044         /* Find an empty block. */
2045
2046         for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2047                 dev->allocationBlockFinder++;
2048                 if (dev->allocationBlockFinder < dev->internalStartBlock
2049                     || dev->allocationBlockFinder > dev->internalEndBlock) {
2050                         dev->allocationBlockFinder = dev->internalStartBlock;
2051                 }
2052
2053                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2054
2055                 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2056                         bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2057                         dev->sequenceNumber++;
2058                         bi->sequenceNumber = dev->sequenceNumber;
2059                         dev->nErasedBlocks--;
2060                         T(YAFFS_TRACE_ALLOCATE,
2061                           (TSTR("Allocated block %d, seq  %d, %d left" TENDSTR),
2062                            dev->allocationBlockFinder, dev->sequenceNumber,
2063                            dev->nErasedBlocks));
2064                         return dev->allocationBlockFinder;
2065                 }
2066         }
2067
2068         T(YAFFS_TRACE_ALWAYS,
2069           (TSTR
2070            ("yaffs tragedy: no more eraased blocks, but there should have been %d"
2071             TENDSTR), dev->nErasedBlocks));
2072
2073         return -1;
2074 }
2075
2076
2077 // Check if there's space to allocate...
2078 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2079 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2080 {
2081         int reservedChunks;
2082         int reservedBlocks = dev->nReservedBlocks;
2083         int checkpointBlocks;
2084         
2085         checkpointBlocks =  dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
2086         if(checkpointBlocks < 0)
2087                 checkpointBlocks = 0;
2088         
2089         reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2090         
2091         return (dev->nFreeChunks > reservedChunks);
2092 }
2093
2094 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve)
2095 {
2096         int retVal;
2097         yaffs_BlockInfo *bi;
2098
2099         if (dev->allocationBlock < 0) {
2100                 /* Get next block to allocate off */
2101                 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2102                 dev->allocationPage = 0;
2103         }
2104
2105         if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2106                 /* Not enough space to allocate unless we're allowed to use the reserve. */
2107                 return -1;
2108         }
2109
2110         if (dev->nErasedBlocks < dev->nReservedBlocks
2111             && dev->allocationPage == 0) {
2112                 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2113         }
2114
2115         /* Next page please.... */
2116         if (dev->allocationBlock >= 0) {
2117                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2118
2119                 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2120                     dev->allocationPage;
2121                 bi->pagesInUse++;
2122                 yaffs_SetChunkBit(dev, dev->allocationBlock,
2123                                   dev->allocationPage);
2124
2125                 dev->allocationPage++;
2126
2127                 dev->nFreeChunks--;
2128
2129                 /* If the block is full set the state to full */
2130                 if (dev->allocationPage >= dev->nChunksPerBlock) {
2131                         bi->blockState = YAFFS_BLOCK_STATE_FULL;
2132                         dev->allocationBlock = -1;
2133                 }
2134
2135                 return retVal;
2136         }
2137         
2138         T(YAFFS_TRACE_ERROR,
2139           (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2140
2141         return -1;
2142 }
2143
2144 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2145 {
2146         int n;
2147
2148         n = dev->nErasedBlocks * dev->nChunksPerBlock;
2149
2150         if (dev->allocationBlock > 0) {
2151                 n += (dev->nChunksPerBlock - dev->allocationPage);
2152         }
2153
2154         return n;
2155
2156 }
2157
2158 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2159 {
2160         int oldChunk;
2161         int newChunk;
2162         int chunkInBlock;
2163         int markNAND;
2164         int retVal = YAFFS_OK;
2165         int cleanups = 0;
2166         int i;
2167         int isCheckpointBlock;
2168
2169         int chunksBefore = yaffs_GetErasedChunks(dev);
2170         int chunksAfter;
2171
2172         yaffs_ExtendedTags tags;
2173
2174         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2175
2176         yaffs_Object *object;
2177
2178         isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2179         
2180         bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2181
2182         T(YAFFS_TRACE_TRACING,
2183           (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2184            bi->pagesInUse, bi->hasShrinkHeader));
2185
2186         /*yaffs_VerifyFreeChunks(dev); */
2187
2188         bi->hasShrinkHeader = 0;        /* clear the flag so that the block can erase */
2189
2190         /* Take off the number of soft deleted entries because
2191          * they're going to get really deleted during GC.
2192          */
2193         dev->nFreeChunks -= bi->softDeletions;
2194
2195         dev->isDoingGC = 1;
2196
2197         if (isCheckpointBlock ||
2198             !yaffs_StillSomeChunkBits(dev, block)) {
2199                 T(YAFFS_TRACE_TRACING,
2200                   (TSTR
2201                    ("Collecting block %d that has no chunks in use" TENDSTR),
2202                    block));
2203                 yaffs_BlockBecameDirty(dev, block);
2204         } else {
2205
2206                 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2207
2208                 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
2209                      chunkInBlock < dev->nChunksPerBlock
2210                      && yaffs_StillSomeChunkBits(dev, block);
2211                      chunkInBlock++, oldChunk++) {
2212                         if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
2213
2214                                 /* This page is in use and might need to be copied off */
2215
2216                                 markNAND = 1;
2217
2218                                 yaffs_InitialiseTags(&tags);
2219
2220                                 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2221                                                                 buffer, &tags);
2222
2223                                 object =
2224                                     yaffs_FindObjectByNumber(dev,
2225                                                              tags.objectId);
2226
2227                                 T(YAFFS_TRACE_GC_DETAIL,
2228                                   (TSTR
2229                                    ("Collecting page %d, %d %d %d " TENDSTR),
2230                                    chunkInBlock, tags.objectId, tags.chunkId,
2231                                    tags.byteCount));
2232
2233                                 if (!object) {
2234                                         T(YAFFS_TRACE_ERROR,
2235                                           (TSTR
2236                                            ("page %d in gc has no object "
2237                                             TENDSTR), oldChunk));
2238                                 }
2239
2240                                 if (object && object->deleted
2241                                     && tags.chunkId != 0) {
2242                                         /* Data chunk in a deleted file, throw it away
2243                                          * It's a soft deleted data chunk,
2244                                          * No need to copy this, just forget about it and 
2245                                          * fix up the object.
2246                                          */
2247
2248                                         object->nDataChunks--;
2249
2250                                         if (object->nDataChunks <= 0) {
2251                                                 /* remeber to clean up the object */
2252                                                 dev->gcCleanupList[cleanups] =
2253                                                     tags.objectId;
2254                                                 cleanups++;
2255                                         }
2256                                         markNAND = 0;
2257                                 } else if (0
2258                                            /* Todo object && object->deleted && object->nDataChunks == 0 */
2259                                            ) {
2260                                         /* Deleted object header with no data chunks.
2261                                          * Can be discarded and the file deleted.
2262                                          */
2263                                         object->chunkId = 0;
2264                                         yaffs_FreeTnode(object->myDev,
2265                                                         object->variant.
2266                                                         fileVariant.top);
2267                                         object->variant.fileVariant.top = NULL;
2268                                         yaffs_DoGenericObjectDeletion(object);
2269
2270                                 } else if (object) {
2271                                         /* It's either a data chunk in a live file or
2272                                          * an ObjectHeader, so we're interested in it.
2273                                          * NB Need to keep the ObjectHeaders of deleted files
2274                                          * until the whole file has been deleted off
2275                                          */
2276                                         tags.serialNumber++;
2277
2278                                         dev->nGCCopies++;
2279
2280                                         if (tags.chunkId == 0) {
2281                                                 /* It is an object Id,
2282                                                  * We need to nuke the shrinkheader flags first
2283                                                  * We no longer want the shrinkHeader flag since its work is done
2284                                                  * and if it is left in place it will mess up scanning.
2285                                                  * Also, clear out any shadowing stuff
2286                                                  */
2287
2288                                                 yaffs_ObjectHeader *oh;
2289                                                 oh = (yaffs_ObjectHeader *)buffer;
2290                                                 oh->isShrink = 0;
2291                                                 oh->shadowsObject = -1;
2292                                                 tags.extraShadows = 0;
2293                                                 tags.extraIsShrinkHeader = 0;
2294                                         }
2295
2296                                         newChunk =
2297                                             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
2298
2299                                         if (newChunk < 0) {
2300                                                 retVal = YAFFS_FAIL;
2301                                         } else {
2302
2303                                                 /* Ok, now fix up the Tnodes etc. */
2304
2305                                                 if (tags.chunkId == 0) {
2306                                                         /* It's a header */
2307                                                         object->chunkId =  newChunk;
2308                                                         object->serial =   tags.serialNumber;
2309                                                 } else {
2310                                                         /* It's a data chunk */
2311                                                         yaffs_PutChunkIntoFile
2312                                                             (object,
2313                                                              tags.chunkId,
2314                                                              newChunk, 0);
2315                                                 }
2316                                         }
2317                                 }
2318
2319                                 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
2320
2321                         }
2322                 }
2323
2324                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2325
2326
2327                 /* Do any required cleanups */
2328                 for (i = 0; i < cleanups; i++) {
2329                         /* Time to delete the file too */
2330                         object =
2331                             yaffs_FindObjectByNumber(dev,
2332                                                      dev->gcCleanupList[i]);
2333                         if (object) {
2334                                 yaffs_FreeTnode(dev,
2335                                                 object->variant.fileVariant.
2336                                                 top);
2337                                 object->variant.fileVariant.top = NULL;
2338                                 T(YAFFS_TRACE_GC,
2339                                   (TSTR
2340                                    ("yaffs: About to finally delete object %d"
2341                                     TENDSTR), object->objectId));
2342                                 yaffs_DoGenericObjectDeletion(object);
2343                                 object->myDev->nDeletedFiles--;
2344                         }
2345
2346                 }
2347
2348         }
2349
2350         if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
2351                 T(YAFFS_TRACE_GC,
2352                   (TSTR
2353                    ("gc did not increase free chunks before %d after %d"
2354                     TENDSTR), chunksBefore, chunksAfter));
2355         }
2356
2357         dev->isDoingGC = 0;
2358
2359         return YAFFS_OK;
2360 }
2361
2362 /* New garbage collector
2363  * If we're very low on erased blocks then we do aggressive garbage collection
2364  * otherwise we do "leasurely" garbage collection.
2365  * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2366  * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2367  *
2368  * The idea is to help clear out space in a more spread-out manner.
2369  * Dunno if it really does anything useful.
2370  */
2371 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
2372 {
2373         int block;
2374         int aggressive;
2375         int gcOk = YAFFS_OK;
2376         int maxTries = 0;
2377         
2378         int checkpointBlockAdjust;
2379
2380         if (dev->isDoingGC) {
2381                 /* Bail out so we don't get recursive gc */
2382                 return YAFFS_OK;
2383         }
2384         
2385         /* This loop should pass the first time.
2386          * We'll only see looping here if the erase of the collected block fails.
2387          */
2388
2389         do {
2390                 maxTries++;
2391                 
2392                 checkpointBlockAdjust = (dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint);
2393                 if(checkpointBlockAdjust < 0)
2394                         checkpointBlockAdjust = 0;
2395
2396                 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust)) {
2397                         /* We need a block soon...*/
2398                         aggressive = 1;
2399                 } else {
2400                         /* We're in no hurry */
2401                         aggressive = 0;
2402                 }
2403
2404                 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
2405
2406                 if (block > 0) {
2407                         dev->garbageCollections++;
2408                         if (!aggressive) {
2409                                 dev->passiveGarbageCollections++;
2410                         }
2411
2412                         T(YAFFS_TRACE_GC,
2413                           (TSTR
2414                            ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
2415                            dev->nErasedBlocks, aggressive));
2416
2417                         gcOk = yaffs_GarbageCollectBlock(dev, block);
2418                 }
2419
2420                 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
2421                         T(YAFFS_TRACE_GC,
2422                           (TSTR
2423                            ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
2424                             TENDSTR), dev->nErasedBlocks, maxTries, block));
2425                 }
2426         } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
2427                  && (maxTries < 2));
2428
2429         return aggressive ? gcOk : YAFFS_OK;
2430 }
2431
2432 /*-------------------------  TAGS --------------------------------*/
2433
2434 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
2435                            int chunkInObject)
2436 {
2437         return (tags->chunkId == chunkInObject &&
2438                 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
2439
2440 }
2441
2442
2443 /*-------------------- Data file manipulation -----------------*/
2444
2445 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
2446                                  yaffs_ExtendedTags * tags)
2447 {
2448         /*Get the Tnode, then get the level 0 offset chunk offset */
2449         yaffs_Tnode *tn;
2450         int theChunk = -1;
2451         yaffs_ExtendedTags localTags;
2452         int retVal = -1;
2453
2454         yaffs_Device *dev = in->myDev;
2455
2456         if (!tags) {
2457                 /* Passed a NULL, so use our own tags space */
2458                 tags = &localTags;
2459         }
2460
2461         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2462
2463         if (tn) {
2464                 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2465
2466                 retVal =
2467                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2468                                            chunkInInode);
2469         }
2470         return retVal;
2471 }
2472
2473 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
2474                                           yaffs_ExtendedTags * tags)
2475 {
2476         /* Get the Tnode, then get the level 0 offset chunk offset */
2477         yaffs_Tnode *tn;
2478         int theChunk = -1;
2479         yaffs_ExtendedTags localTags;
2480
2481         yaffs_Device *dev = in->myDev;
2482         int retVal = -1;
2483
2484         if (!tags) {
2485                 /* Passed a NULL, so use our own tags space */
2486                 tags = &localTags;
2487         }
2488
2489         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2490
2491         if (tn) {
2492
2493                 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2494
2495                 retVal =
2496                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2497                                            chunkInInode);
2498
2499                 /* Delete the entry in the filestructure (if found) */
2500                 if (retVal != -1) {
2501                         yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
2502                 }
2503         } else {
2504                 /*T(("No level 0 found for %d\n", chunkInInode)); */
2505         }
2506
2507         if (retVal == -1) {
2508                 /* T(("Could not find %d to delete\n",chunkInInode)); */
2509         }
2510         return retVal;
2511 }
2512
2513 #ifdef YAFFS_PARANOID
2514
2515 static int yaffs_CheckFileSanity(yaffs_Object * in)
2516 {
2517         int chunk;
2518         int nChunks;
2519         int fSize;
2520         int failed = 0;
2521         int objId;
2522         yaffs_Tnode *tn;
2523         yaffs_Tags localTags;
2524         yaffs_Tags *tags = &localTags;
2525         int theChunk;
2526         int chunkDeleted;
2527
2528         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2529                 /* T(("Object not a file\n")); */
2530                 return YAFFS_FAIL;
2531         }
2532
2533         objId = in->objectId;
2534         fSize = in->variant.fileVariant.fileSize;
2535         nChunks =
2536             (fSize + in->myDev->nBytesPerChunk - 1) / in->myDev->nBytesPerChunk;
2537
2538         for (chunk = 1; chunk <= nChunks; chunk++) {
2539                 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
2540                                            chunk);
2541
2542                 if (tn) {
2543
2544                         theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
2545
2546                         if (yaffs_CheckChunkBits
2547                             (dev, theChunk / dev->nChunksPerBlock,
2548                              theChunk % dev->nChunksPerBlock)) {
2549
2550                                 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
2551                                                             tags,
2552                                                             &chunkDeleted);
2553                                 if (yaffs_TagsMatch
2554                                     (tags, in->objectId, chunk, chunkDeleted)) {
2555                                         /* found it; */
2556
2557                                 }
2558                         } else {
2559
2560                                 failed = 1;
2561                         }
2562
2563                 } else {
2564                         /* T(("No level 0 found for %d\n", chunk)); */
2565                 }
2566         }
2567
2568         return failed ? YAFFS_FAIL : YAFFS_OK;
2569 }
2570
2571 #endif
2572
2573 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
2574                                   int chunkInNAND, int inScan)
2575 {
2576         /* NB inScan is zero unless scanning. 
2577          * For forward scanning, inScan is > 0; 
2578          * for backward scanning inScan is < 0
2579          */
2580          
2581         yaffs_Tnode *tn;
2582         yaffs_Device *dev = in->myDev;
2583         int existingChunk;
2584         yaffs_ExtendedTags existingTags;
2585         yaffs_ExtendedTags newTags;
2586         unsigned existingSerial, newSerial;
2587
2588         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2589                 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2590                  * If it is not during Scanning then something went wrong!
2591                  */
2592                 if (!inScan) {
2593                         T(YAFFS_TRACE_ERROR,
2594                           (TSTR
2595                            ("yaffs tragedy:attempt to put data chunk into a non-file"
2596                             TENDSTR)));
2597                         YBUG();
2598                 }
2599
2600                 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
2601                 return YAFFS_OK;
2602         }
2603
2604         tn = yaffs_AddOrFindLevel0Tnode(dev, 
2605                                         &in->variant.fileVariant,
2606                                         chunkInInode,
2607                                         NULL);
2608         if (!tn) {
2609                 return YAFFS_FAIL;
2610         }
2611
2612         existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2613
2614         if (inScan != 0) {
2615                 /* If we're scanning then we need to test for duplicates
2616                  * NB This does not need to be efficient since it should only ever 
2617                  * happen when the power fails during a write, then only one
2618                  * chunk should ever be affected.
2619                  *
2620                  * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2621                  * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2622                  */
2623
2624                 if (existingChunk != 0) {
2625                         /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
2626                          *    thus we have to do a FindChunkInFile to get the real chunk id.
2627                          *
2628                          * We have a duplicate now we need to decide which one to use:
2629                          *
2630                          * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2631                          * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2632                          * YAFFS1: Get both sets of tags and compare serial numbers.
2633                          */
2634
2635                         if (inScan > 0) {
2636                                 /* Only do this for forward scanning */
2637                                 yaffs_ReadChunkWithTagsFromNAND(dev,
2638                                                                 chunkInNAND,
2639                                                                 NULL, &newTags);
2640
2641                                 /* Do a proper find */
2642                                 existingChunk =
2643                                     yaffs_FindChunkInFile(in, chunkInInode,
2644                                                           &existingTags);
2645                         }
2646
2647                         if (existingChunk <= 0) {
2648                                 /*Hoosterman - how did this happen? */
2649
2650                                 T(YAFFS_TRACE_ERROR,
2651                                   (TSTR
2652                                    ("yaffs tragedy: existing chunk < 0 in scan"
2653                                     TENDSTR)));
2654
2655                         }
2656
2657                         /* NB The deleted flags should be false, otherwise the chunks will 
2658                          * not be loaded during a scan
2659                          */
2660
2661                         newSerial = newTags.serialNumber;
2662                         existingSerial = existingTags.serialNumber;
2663
2664                         if ((inScan > 0) &&
2665                             (in->myDev->isYaffs2 ||
2666                              existingChunk <= 0 ||
2667                              ((existingSerial + 1) & 3) == newSerial)) {
2668                                 /* Forward scanning.                            
2669                                  * Use new
2670                                  * Delete the old one and drop through to update the tnode
2671                                  */
2672                                 yaffs_DeleteChunk(dev, existingChunk, 1,
2673                                                   __LINE__);
2674                         } else {
2675                                 /* Backward scanning or we want to use the existing one
2676                                  * Use existing.
2677                                  * Delete the new one and return early so that the tnode isn't changed
2678                                  */
2679                                 yaffs_DeleteChunk(dev, chunkInNAND, 1,
2680                                                   __LINE__);
2681                                 return YAFFS_OK;
2682                         }
2683                 }
2684
2685         }
2686
2687         if (existingChunk == 0) {
2688                 in->nDataChunks++;
2689         }
2690
2691         yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
2692
2693         return YAFFS_OK;
2694 }
2695
2696 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
2697                                          __u8 * buffer)
2698 {
2699         int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
2700
2701         if (chunkInNAND >= 0) {
2702                 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
2703                                                        buffer, NULL);
2704         } else {
2705                 T(YAFFS_TRACE_NANDACCESS,
2706                   (TSTR("Chunk %d not found zero instead" TENDSTR),
2707                    chunkInNAND));
2708                 /* get sane (zero) data if you read a hole */
2709                 memset(buffer, 0, in->myDev->nBytesPerChunk);   
2710                 return 0;
2711         }
2712
2713 }
2714
2715 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
2716 {
2717         int block;
2718         int page;
2719         yaffs_ExtendedTags tags;
2720         yaffs_BlockInfo *bi;
2721
2722         if (chunkId <= 0)
2723                 return;
2724
2725         dev->nDeletions++;
2726         block = chunkId / dev->nChunksPerBlock;
2727         page = chunkId % dev->nChunksPerBlock;
2728
2729         bi = yaffs_GetBlockInfo(dev, block);
2730
2731         T(YAFFS_TRACE_DELETION,
2732           (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
2733
2734         if (markNAND &&
2735             bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
2736
2737                 yaffs_InitialiseTags(&tags);
2738
2739                 tags.chunkDeleted = 1;
2740
2741                 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
2742                 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
2743         } else {
2744                 dev->nUnmarkedDeletions++;
2745         }
2746
2747         /* Pull out of the management area.
2748          * If the whole block became dirty, this will kick off an erasure.
2749          */
2750         if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2751             bi->blockState == YAFFS_BLOCK_STATE_FULL ||
2752             bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2753             bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2754                 dev->nFreeChunks++;
2755
2756                 yaffs_ClearChunkBit(dev, block, page);
2757
2758                 bi->pagesInUse--;
2759
2760                 if (bi->pagesInUse == 0 &&
2761                     !bi->hasShrinkHeader &&
2762                     bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
2763                     bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2764                         yaffs_BlockBecameDirty(dev, block);
2765                 }
2766
2767         } else {
2768                 /* T(("Bad news deleting chunk %d\n",chunkId)); */
2769         }
2770
2771 }
2772
2773 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
2774                                         const __u8 * buffer, int nBytes,
2775                                         int useReserve)
2776 {
2777         /* Find old chunk Need to do this to get serial number
2778          * Write new one and patch into tree.
2779          * Invalidate old tags.
2780          */
2781
2782         int prevChunkId;
2783         yaffs_ExtendedTags prevTags;
2784
2785         int newChunkId;
2786         yaffs_ExtendedTags newTags;
2787
2788         yaffs_Device *dev = in->myDev;
2789
2790         yaffs_CheckGarbageCollection(dev);
2791
2792         /* Get the previous chunk at this location in the file if it exists */
2793         prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
2794
2795         /* Set up new tags */
2796         yaffs_InitialiseTags(&newTags);
2797
2798         newTags.chunkId = chunkInInode;
2799         newTags.objectId = in->objectId;
2800         newTags.serialNumber =
2801             (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2802         newTags.byteCount = nBytes;
2803
2804         newChunkId =
2805             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2806                                               useReserve);
2807
2808         if (newChunkId >= 0) {
2809                 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
2810
2811                 if (prevChunkId >= 0) {
2812                         yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
2813
2814                 }
2815
2816                 yaffs_CheckFileSanity(in);
2817         }
2818         return newChunkId;
2819
2820 }
2821
2822 /* UpdateObjectHeader updates the header on NAND for an object.
2823  * If name is not NULL, then that new name is used.
2824  */
2825 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
2826                              int isShrink, int shadows)
2827 {
2828
2829         yaffs_BlockInfo *bi;
2830
2831         yaffs_Device *dev = in->myDev;
2832
2833         int prevChunkId;
2834         int retVal = 0;
2835
2836         int newChunkId;
2837         yaffs_ExtendedTags newTags;
2838
2839         __u8 *buffer = NULL;
2840         YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
2841
2842         yaffs_ObjectHeader *oh = NULL;
2843
2844         if (!in->fake || force) {
2845
2846                 yaffs_CheckGarbageCollection(dev);
2847
2848                 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
2849                 oh = (yaffs_ObjectHeader *) buffer;
2850
2851                 prevChunkId = in->chunkId;
2852
2853                 if (prevChunkId >= 0) {
2854                         yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
2855                                                         buffer, NULL);
2856                         memcpy(oldName, oh->name, sizeof(oh->name));
2857                 }
2858
2859                 memset(buffer, 0xFF, dev->nBytesPerChunk);
2860
2861                 oh->type = in->variantType;
2862                 oh->yst_mode = in->yst_mode;
2863                 oh->shadowsObject = shadows;
2864
2865 #ifdef CONFIG_YAFFS_WINCE
2866                 oh->win_atime[0] = in->win_atime[0];
2867                 oh->win_ctime[0] = in->win_ctime[0];
2868                 oh->win_mtime[0] = in->win_mtime[0];
2869                 oh->win_atime[1] = in->win_atime[1];
2870                 oh->win_ctime[1] = in->win_ctime[1];
2871                 oh->win_mtime[1] = in->win_mtime[1];
2872 #else
2873                 oh->yst_uid = in->yst_uid;
2874                 oh->yst_gid = in->yst_gid;
2875                 oh->yst_atime = in->yst_atime;
2876                 oh->yst_mtime = in->yst_mtime;
2877                 oh->yst_ctime = in->yst_ctime;
2878                 oh->yst_rdev = in->yst_rdev;
2879 #endif
2880                 if (in->parent) {
2881                         oh->parentObjectId = in->parent->objectId;
2882                 } else {
2883                         oh->parentObjectId = 0;
2884                 }
2885
2886                 if (name && *name) {
2887                         memset(oh->name, 0, sizeof(oh->name));
2888                         yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
2889                 } else if (prevChunkId) {
2890                         memcpy(oh->name, oldName, sizeof(oh->name));
2891                 } else {
2892                         memset(oh->name, 0, sizeof(oh->name));
2893                 }
2894
2895                 oh->isShrink = isShrink;
2896
2897                 switch (in->variantType) {
2898                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2899                         /* Should not happen */
2900                         break;
2901                 case YAFFS_OBJECT_TYPE_FILE:
2902                         oh->fileSize =
2903                             (oh->parentObjectId == YAFFS_OBJECTID_DELETED
2904                              || oh->parentObjectId ==
2905                              YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
2906                             fileVariant.fileSize;
2907                         break;
2908                 case YAFFS_OBJECT_TYPE_HARDLINK:
2909                         oh->equivalentObjectId =
2910                             in->variant.hardLinkVariant.equivalentObjectId;
2911                         break;
2912                 case YAFFS_OBJECT_TYPE_SPECIAL:
2913                         /* Do nothing */
2914                         break;
2915                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2916                         /* Do nothing */
2917                         break;
2918                 case YAFFS_OBJECT_TYPE_SYMLINK:
2919                         yaffs_strncpy(oh->alias,
2920                                       in->variant.symLinkVariant.alias,
2921                                       YAFFS_MAX_ALIAS_LENGTH);
2922                         oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
2923                         break;
2924                 }
2925
2926                 /* Tags */
2927                 yaffs_InitialiseTags(&newTags);
2928                 in->serial++;
2929                 newTags.chunkId = 0;
2930                 newTags.objectId = in->objectId;
2931                 newTags.serialNumber = in->serial;
2932
2933                 /* Add extra info for file header */
2934
2935                 newTags.extraHeaderInfoAvailable = 1;
2936                 newTags.extraParentObjectId = oh->parentObjectId;
2937                 newTags.extraFileLength = oh->fileSize;
2938                 newTags.extraIsShrinkHeader = oh->isShrink;
2939                 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
2940                 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
2941                 newTags.extraObjectType = in->variantType;
2942
2943                 /* Create new chunk in NAND */
2944                 newChunkId =
2945                     yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2946                                                       (prevChunkId >= 0) ? 1 : 0);
2947
2948                 if (newChunkId >= 0) {
2949
2950                         in->chunkId = newChunkId;
2951
2952                         if (prevChunkId >= 0) {
2953                                 yaffs_DeleteChunk(dev, prevChunkId, 1,
2954                                                   __LINE__);
2955                         }
2956
2957                         in->dirty = 0;
2958
2959                         /* If this was a shrink, then mark the block that the chunk lives on */
2960                         if (isShrink) {
2961                                 bi = yaffs_GetBlockInfo(in->myDev,
2962                                                         newChunkId /in->myDev-> nChunksPerBlock);
2963                                 bi->hasShrinkHeader = 1;
2964                         }
2965
2966                 }
2967
2968                 retVal = newChunkId;
2969
2970         }
2971
2972         if (buffer)
2973                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2974
2975         return retVal;
2976 }
2977
2978 /*------------------------ Short Operations Cache ----------------------------------------
2979  *   In many situations where there is no high level buffering (eg WinCE) a lot of
2980  *   reads might be short sequential reads, and a lot of writes may be short 
2981  *   sequential writes. eg. scanning/writing a jpeg file.
2982  *   In these cases, a short read/write cache can provide a huge perfomance benefit 
2983  *   with dumb-as-a-rock code.
2984  *   In Linux, the page cache provides read buffering aand the short op cache provides write 
2985  *   buffering.
2986  *
2987  *   There are a limited number (~10) of cache chunks per device so that we don't
2988  *   need a very intelligent search.
2989  */
2990
2991 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
2992 {
2993         yaffs_Device *dev = obj->myDev;
2994         int lowest = -99;       /* Stop compiler whining. */
2995         int i;
2996         yaffs_ChunkCache *cache;
2997         int chunkWritten = 0;
2998         int nCaches = obj->myDev->nShortOpCaches;
2999
3000         if (nCaches > 0) {
3001                 do {
3002                         cache = NULL;
3003
3004                         /* Find the dirty cache for this object with the lowest chunk id. */
3005                         for (i = 0; i < nCaches; i++) {
3006                                 if (dev->srCache[i].object == obj &&
3007                                     dev->srCache[i].dirty) {
3008                                         if (!cache
3009                                             || dev->srCache[i].chunkId <
3010                                             lowest) {
3011                                                 cache = &dev->srCache[i];
3012                                                 lowest = cache->chunkId;
3013                                         }
3014                                 }
3015                         }
3016
3017                         if (cache && !cache->locked) {
3018                                 /* Write it out and free it up */
3019
3020                                 chunkWritten =
3021                                     yaffs_WriteChunkDataToObject(cache->object,
3022                                                                  cache->chunkId,
3023                                                                  cache->data,
3024                                                                  cache->nBytes,
3025                                                                  1);
3026                                 cache->dirty = 0;
3027                                 cache->object = NULL;
3028                         }
3029
3030                 } while (cache && chunkWritten > 0);
3031
3032                 if (cache) {
3033                         /* Hoosterman, disk full while writing cache out. */
3034                         T(YAFFS_TRACE_ERROR,
3035                           (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3036
3037                 }
3038         }
3039
3040 }
3041
3042 /*yaffs_FlushEntireDeviceCache(dev)
3043  *
3044  *
3045  */
3046
3047 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3048 {
3049         yaffs_Object *obj;
3050         int nCaches = dev->nShortOpCaches;
3051         int i;
3052         
3053         /* Find a dirty object in the cache and flush it...
3054          * until there are no further dirty objects.
3055          */
3056         do {
3057                 obj = NULL;
3058                 for( i = 0; i < nCaches && !obj; i++) {
3059                         if (dev->srCache[i].object &&
3060                             dev->srCache[i].dirty)
3061                                 obj = dev->srCache[i].object;
3062                             
3063                 }
3064                 if(obj)
3065                         yaffs_FlushFilesChunkCache(obj);
3066                         
3067         } while(obj);
3068         
3069 }
3070
3071
3072 /* Grab us a cache chunk for use.
3073  * First look for an empty one. 
3074  * Then look for the least recently used non-dirty one.
3075  * Then look for the least recently used dirty one...., flush and look again.
3076  */
3077 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
3078 {
3079         int i;
3080         int usage;
3081         int theOne;
3082
3083         if (dev->nShortOpCaches > 0) {
3084                 for (i = 0; i < dev->nShortOpCaches; i++) {
3085                         if (!dev->srCache[i].object) 
3086                                 return &dev->srCache[i];
3087                 }
3088
3089                 return NULL;
3090
3091                 theOne = -1;
3092                 usage = 0;      /* just to stop the compiler grizzling */
3093
3094                 for (i = 0; i < dev->nShortOpCaches; i++) {
3095                         if (!dev->srCache[i].dirty &&
3096                             ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
3097                              theOne < 0)) {
3098                                 usage = dev->srCache[i].lastUse;
3099                                 theOne = i;
3100                         }
3101                 }
3102
3103
3104                 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3105         } else {
3106                 return NULL;
3107         }
3108
3109 }
3110
3111 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
3112 {
3113         yaffs_ChunkCache *cache;
3114         yaffs_Object *theObj;
3115         int usage;
3116         int i;
3117         int pushout;
3118
3119         if (dev->nShortOpCaches > 0) {
3120                 /* Try find a non-dirty one... */
3121
3122                 cache = yaffs_GrabChunkCacheWorker(dev);
3123
3124                 if (!cache) {
3125                         /* They were all dirty, find the last recently used object and flush
3126                          * its cache, then  find again.
3127                          * NB what's here is not very accurate, we actually flush the object
3128                          * the last recently used page.
3129                          */
3130
3131                         /* With locking we can't assume we can use entry zero */
3132
3133                         theObj = NULL;
3134                         usage = -1;
3135                         cache = NULL;
3136                         pushout = -1;
3137
3138                         for (i = 0; i < dev->nShortOpCaches; i++) {
3139                                 if (dev->srCache[i].object &&
3140                                     !dev->srCache[i].locked &&
3141                                     (dev->srCache[i].lastUse < usage || !cache))
3142                                 {
3143                                         usage = dev->srCache[i].lastUse;
3144                                         theObj = dev->srCache[i].object;
3145                                         cache = &dev->srCache[i];
3146                                         pushout = i;
3147                                 }
3148                         }
3149
3150                         if (!cache || cache->dirty) {
3151                                 /* Flush and try again */
3152                                 yaffs_FlushFilesChunkCache(theObj);
3153                                 cache = yaffs_GrabChunkCacheWorker(dev);
3154                         }
3155
3156                 }
3157                 return cache;
3158         } else
3159                 return NULL;
3160
3161 }
3162
3163 /* Find a cached chunk */
3164 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
3165                                               int chunkId)
3166 {
3167         yaffs_Device *dev = obj->myDev;
3168         int i;
3169         if (dev->nShortOpCaches > 0) {
3170                 for (i = 0; i < dev->nShortOpCaches; i++) {
3171                         if (dev->srCache[i].object == obj &&
3172                             dev->srCache[i].chunkId == chunkId) {
3173                                 dev->cacheHits++;
3174
3175                                 return &dev->srCache[i];
3176                         }
3177                 }
3178         }
3179         return NULL;
3180 }
3181
3182 /* Mark the chunk for the least recently used algorithym */
3183 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
3184                                 int isAWrite)
3185 {
3186
3187         if (dev->nShortOpCaches > 0) {
3188                 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
3189                         /* Reset the cache usages */
3190                         int i;
3191                         for (i = 1; i < dev->nShortOpCaches; i++) {
3192                                 dev->srCache[i].lastUse = 0;
3193                         }
3194                         dev->srLastUse = 0;
3195                 }
3196
3197                 dev->srLastUse++;
3198
3199                 cache->lastUse = dev->srLastUse;
3200
3201                 if (isAWrite) {
3202                         cache->dirty = 1;
3203                 }
3204         }
3205 }
3206
3207 /* Invalidate a single cache page.
3208  * Do this when a whole page gets written,
3209  * ie the short cache for this page is no longer valid.
3210  */
3211 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
3212 {
3213         if (object->myDev->nShortOpCaches > 0) {
3214                 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
3215
3216                 if (cache) {
3217                         cache->object = NULL;
3218                 }
3219         }
3220 }
3221
3222 /* Invalidate all the cache pages associated with this object
3223  * Do this whenever ther file is deleted or resized.
3224  */
3225 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
3226 {
3227         int i;
3228         yaffs_Device *dev = in->myDev;
3229
3230         if (dev->nShortOpCaches > 0) {
3231                 /* Invalidate it. */
3232                 for (i = 0; i < dev->nShortOpCaches; i++) {
3233                         if (dev->srCache[i].object == in) {
3234                                 dev->srCache[i].object = NULL;
3235                         }
3236                 }
3237         }
3238 }
3239
3240 /*--------------------- Checkpointing --------------------*/
3241
3242
3243 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
3244 {
3245         yaffs_CheckpointValidity cp;
3246         cp.structType = sizeof(cp);
3247         cp.magic = YAFFS_MAGIC;
3248         cp.version = 1;
3249         cp.head = (head) ? 1 : 0;
3250         
3251         return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
3252                 1 : 0;
3253 }
3254
3255 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
3256 {
3257         yaffs_CheckpointValidity cp;
3258         int ok;
3259         
3260         ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3261         
3262         if(ok)
3263                 ok = (cp.structType == sizeof(cp)) &&
3264                      (cp.magic == YAFFS_MAGIC) &&
3265                      (cp.version == 1) &&
3266                      (cp.head == ((head) ? 1 : 0));
3267         return ok ? 1 : 0;
3268 }
3269
3270 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp, 
3271                                            yaffs_Device *dev)
3272 {
3273         cp->nErasedBlocks = dev->nErasedBlocks;
3274         cp->allocationBlock = dev->allocationBlock;
3275         cp->allocationPage = dev->allocationPage;
3276         cp->nFreeChunks = dev->nFreeChunks;
3277         
3278         cp->nDeletedFiles = dev->nDeletedFiles;
3279         cp->nUnlinkedFiles = dev->nUnlinkedFiles;
3280         cp->nBackgroundDeletions = dev->nBackgroundDeletions;
3281         cp->sequenceNumber = dev->sequenceNumber;
3282         cp->oldestDirtySequence = dev->oldestDirtySequence;
3283         
3284 }
3285
3286 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
3287                                            yaffs_CheckpointDevice *cp)
3288 {
3289         dev->nErasedBlocks = cp->nErasedBlocks;
3290         dev->allocationBlock = cp->allocationBlock;
3291         dev->allocationPage = cp->allocationPage;
3292         dev->nFreeChunks = cp->nFreeChunks;
3293         
3294         dev->nDeletedFiles = cp->nDeletedFiles;
3295         dev->nUnlinkedFiles = cp->nUnlinkedFiles;
3296         dev->nBackgroundDeletions = cp->nBackgroundDeletions;
3297         dev->sequenceNumber = cp->sequenceNumber;
3298         dev->oldestDirtySequence = cp->oldestDirtySequence;
3299 }
3300
3301
3302 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
3303 {
3304         yaffs_CheckpointDevice cp;
3305         __u32 nBytes;
3306         __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
3307
3308         int ok;
3309                 
3310         /* Write device runtime values*/
3311         yaffs_DeviceToCheckpointDevice(&cp,dev);
3312         cp.structType = sizeof(cp);
3313         
3314         ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3315         
3316         /* Write block info */
3317         if(ok) {
3318                 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
3319                 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
3320         }
3321                 
3322         /* Write chunk bits */          
3323         if(ok) {
3324                 nBytes = nBlocks * dev->chunkBitmapStride;
3325                 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
3326         }
3327         return   ok ? 1 : 0;
3328
3329 }
3330
3331 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
3332 {
3333         yaffs_CheckpointDevice cp;
3334         __u32 nBytes;
3335         __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
3336
3337         int ok; 
3338         
3339     &