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