ab22c85e54979803998fb711854a274bfef5c3af
[yaffs2.git] / yaffs_guts.c
1 /*
2  * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
3  *
4  * Copyright (C) 2002-2007 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.46 2007-02-12 16:55:26 wookey 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         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
488
489         yaffs_InvalidateCheckpoint(dev);
490         
491         yaffs_MarkBlockBad(dev, blockInNAND);
492
493         bi->blockState = YAFFS_BLOCK_STATE_DEAD;
494         bi->gcPrioritise = 0;
495         bi->needsRetiring = 0;
496
497         dev->nRetiredBlocks++;
498 }
499
500 /*
501  * Functions for robustisizing TODO
502  *
503  */
504  
505 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
506                                      const __u8 * data,
507                                      const yaffs_ExtendedTags * tags)
508 {
509 }
510
511 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
512                                     const yaffs_ExtendedTags * tags)
513 {
514 }
515
516 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
517 {
518         if(!bi->gcPrioritise){
519                 bi->gcPrioritise = 1;
520                 dev->hasPendingPrioritisedGCs = 1;
521                 bi->chunkErrorStrikes ++;
522                 
523                 if(bi->chunkErrorStrikes > 3){
524                         bi->needsRetiring = 1; /* Too many stikes, so retire this */
525                         T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
526
527                 }
528                 
529         }
530 }
531
532 static void yaffs_ReportOddballBlocks(yaffs_Device *dev)
533 {
534         int i;
535                 
536         for(i = dev->internalStartBlock; i <= dev->internalEndBlock && (yaffs_traceMask & YAFFS_TRACE_BAD_BLOCKS); i++){
537                 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
538                 if(bi->needsRetiring || bi->gcPrioritise)
539                         T(YAFFS_TRACE_BAD_BLOCKS,(TSTR("yaffs block %d%s%s" TENDSTR),
540                                 i,
541                                 bi->needsRetiring ? " needs retiring" : "",
542                                 bi->gcPrioritise ?  " gc prioritised" : ""));
543                 
544         }
545 }
546
547 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
548 {
549
550         int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
551         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
552
553         yaffs_HandleChunkError(dev,bi);
554                 
555         
556         if(erasedOk ) {
557                 /* Was an actual write failure, so mark the block for retirement  */
558                 bi->needsRetiring = 1;
559                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
560                   (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
561
562                 
563         }
564         
565         /* Delete the chunk */
566         yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
567 }
568
569
570 /*---------------- Name handling functions ------------*/ 
571
572 static __u16 yaffs_CalcNameSum(const YCHAR * name)
573 {
574         __u16 sum = 0;
575         __u16 i = 1;
576
577         YUCHAR *bname = (YUCHAR *) name;
578         if (bname) {
579                 while ((*bname) && (i <= YAFFS_MAX_NAME_LENGTH)) {
580
581 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
582                         sum += yaffs_toupper(*bname) * i;
583 #else
584                         sum += (*bname) * i;
585 #endif
586                         i++;
587                         bname++;
588                 }
589         }
590         return sum;
591 }
592
593 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
594 {
595 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
596         if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
597                 yaffs_strcpy(obj->shortName, name);
598         } else {
599                 obj->shortName[0] = _Y('\0');
600         }
601 #endif
602         obj->sum = yaffs_CalcNameSum(name);
603 }
604
605 /*-------------------- TNODES -------------------
606
607  * List of spare tnodes
608  * The list is hooked together using the first pointer
609  * in the tnode.
610  */
611  
612 /* yaffs_CreateTnodes creates a bunch more tnodes and
613  * adds them to the tnode free list.
614  * Don't use this function directly
615  */
616
617 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
618 {
619         int i;
620         int tnodeSize;
621         yaffs_Tnode *newTnodes;
622         __u8 *mem;
623         yaffs_Tnode *curr;
624         yaffs_Tnode *next;
625         yaffs_TnodeList *tnl;
626
627         if (nTnodes < 1)
628                 return YAFFS_OK;
629                 
630         /* Calculate the tnode size in bytes for variable width tnode support.
631          * Must be a multiple of 32-bits  */
632         tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
633
634         /* make these things */
635
636         newTnodes = YMALLOC(nTnodes * tnodeSize);
637         mem = (__u8 *)newTnodes;
638
639         if (!newTnodes) {
640                 T(YAFFS_TRACE_ERROR,
641                   (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
642                 return YAFFS_FAIL;
643         }
644
645         /* Hook them into the free list */
646 #if 0
647         for (i = 0; i < nTnodes - 1; i++) {
648                 newTnodes[i].internal[0] = &newTnodes[i + 1];
649 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
650                 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
651 #endif
652         }
653
654         newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
655 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
656         newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
657 #endif
658         dev->freeTnodes = newTnodes;
659 #else
660         /* New hookup for wide tnodes */
661         for(i = 0; i < nTnodes -1; i++) {
662                 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
663                 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
664                 curr->internal[0] = next;
665         }
666         
667         curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
668         curr->internal[0] = dev->freeTnodes;
669         dev->freeTnodes = (yaffs_Tnode *)mem;
670
671 #endif
672
673
674         dev->nFreeTnodes += nTnodes;
675         dev->nTnodesCreated += nTnodes;
676
677         /* Now add this bunch of tnodes to a list for freeing up.
678          * NB If we can't add this to the management list it isn't fatal
679          * but it just means we can't free this bunch of tnodes later.
680          */
681          
682         tnl = YMALLOC(sizeof(yaffs_TnodeList));
683         if (!tnl) {
684                 T(YAFFS_TRACE_ERROR,
685                   (TSTR
686                    ("yaffs: Could not add tnodes to management list" TENDSTR)));
687
688         } else {
689                 tnl->tnodes = newTnodes;
690                 tnl->next = dev->allocatedTnodeList;
691                 dev->allocatedTnodeList = tnl;
692         }
693
694         T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
695
696         return YAFFS_OK;
697 }
698
699 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
700
701 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
702 {
703         yaffs_Tnode *tn = NULL;
704
705         /* If there are none left make more */
706         if (!dev->freeTnodes) {
707                 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
708         }
709
710         if (dev->freeTnodes) {
711                 tn = dev->freeTnodes;
712 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
713                 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
714                         /* Hoosterman, this thing looks like it isn't in the list */
715                         T(YAFFS_TRACE_ALWAYS,
716                           (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
717                 }
718 #endif
719                 dev->freeTnodes = dev->freeTnodes->internal[0];
720                 dev->nFreeTnodes--;
721         }
722
723         return tn;
724 }
725
726 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
727 {
728         yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
729         
730         if(tn)
731                 memset(tn, 0, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
732
733         return tn;      
734 }
735
736 /* FreeTnode frees up a tnode and puts it back on the free list */
737 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
738 {
739         if (tn) {
740 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
741                 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
742                         /* Hoosterman, this thing looks like it is already in the list */
743                         T(YAFFS_TRACE_ALWAYS,
744                           (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
745                 }
746                 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
747 #endif
748                 tn->internal[0] = dev->freeTnodes;
749                 dev->freeTnodes = tn;
750                 dev->nFreeTnodes++;
751         }
752 }
753
754 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
755 {
756         /* Free the list of allocated tnodes */
757         yaffs_TnodeList *tmp;
758
759         while (dev->allocatedTnodeList) {
760                 tmp = dev->allocatedTnodeList->next;
761
762                 YFREE(dev->allocatedTnodeList->tnodes);
763                 YFREE(dev->allocatedTnodeList);
764                 dev->allocatedTnodeList = tmp;
765
766         }
767
768         dev->freeTnodes = NULL;
769         dev->nFreeTnodes = 0;
770 }
771
772 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
773 {
774         dev->allocatedTnodeList = NULL;
775         dev->freeTnodes = NULL;
776         dev->nFreeTnodes = 0;
777         dev->nTnodesCreated = 0;
778
779 }
780
781
782 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
783 {
784   __u32 *map = (__u32 *)tn;
785   __u32 bitInMap;
786   __u32 bitInWord;
787   __u32 wordInMap;
788   __u32 mask;
789   
790   pos &= YAFFS_TNODES_LEVEL0_MASK;
791   val >>= dev->chunkGroupBits;
792   
793   bitInMap = pos * dev->tnodeWidth;
794   wordInMap = bitInMap /32;
795   bitInWord = bitInMap & (32 -1);
796   
797   mask = dev->tnodeMask << bitInWord;
798   
799   map[wordInMap] &= ~mask;
800   map[wordInMap] |= (mask & (val << bitInWord));
801   
802   if(dev->tnodeWidth > (32-bitInWord)) {
803     bitInWord = (32 - bitInWord);
804     wordInMap++;;
805     mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
806     map[wordInMap] &= ~mask;
807     map[wordInMap] |= (mask & (val >> bitInWord));
808   }
809 }
810
811 __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
812 {
813   __u32 *map = (__u32 *)tn;
814   __u32 bitInMap;
815   __u32 bitInWord;
816   __u32 wordInMap;
817   __u32 val;
818   
819   pos &= YAFFS_TNODES_LEVEL0_MASK;
820   
821   bitInMap = pos * dev->tnodeWidth;
822   wordInMap = bitInMap /32;
823   bitInWord = bitInMap & (32 -1);
824   
825   val = map[wordInMap] >> bitInWord;
826   
827   if(dev->tnodeWidth > (32-bitInWord)) {
828     bitInWord = (32 - bitInWord);
829     wordInMap++;;
830     val |= (map[wordInMap] << bitInWord);
831   }
832   
833   val &= dev->tnodeMask;
834   val <<= dev->chunkGroupBits;
835   
836   return val;
837 }
838
839 /* ------------------- End of individual tnode manipulation -----------------*/
840
841 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
842  * The look up tree is represented by the top tnode and the number of topLevel
843  * in the tree. 0 means only the level 0 tnode is in the tree.
844  */
845
846 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
847 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
848                                           yaffs_FileStructure * fStruct,
849                                           __u32 chunkId)
850 {
851
852         yaffs_Tnode *tn = fStruct->top;
853         __u32 i;
854         int requiredTallness;
855         int level = fStruct->topLevel;
856
857         /* Check sane level and chunk Id */
858         if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
859                 return NULL;
860         }
861
862         if (chunkId > YAFFS_MAX_CHUNK_ID) {
863                 return NULL;
864         }
865
866         /* First check we're tall enough (ie enough topLevel) */
867
868         i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
869         requiredTallness = 0;
870         while (i) {
871                 i >>= YAFFS_TNODES_INTERNAL_BITS;
872                 requiredTallness++;
873         }
874
875         if (requiredTallness > fStruct->topLevel) {
876                 /* Not tall enough, so we can't find it, return NULL. */
877                 return NULL;
878         }
879
880         /* Traverse down to level 0 */
881         while (level > 0 && tn) {
882                 tn = tn->
883                     internal[(chunkId >>
884                                ( YAFFS_TNODES_LEVEL0_BITS + 
885                                  (level - 1) *
886                                  YAFFS_TNODES_INTERNAL_BITS)
887                               ) &
888                              YAFFS_TNODES_INTERNAL_MASK];
889                 level--;
890
891         }
892
893         return tn;
894 }
895
896 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
897  * This happens in two steps:
898  *  1. If the tree isn't tall enough, then make it taller.
899  *  2. Scan down the tree towards the level 0 tnode adding tnodes if required.
900  *
901  * Used when modifying the tree.
902  *
903  *  If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
904  *  be plugged into the ttree.
905  */
906  
907 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
908                                                yaffs_FileStructure * fStruct,
909                                                __u32 chunkId,
910                                                yaffs_Tnode *passedTn)
911 {
912
913         int requiredTallness;
914         int i;
915         int l;
916         yaffs_Tnode *tn;
917
918         __u32 x;
919
920
921         /* Check sane level and page Id */
922         if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
923                 return NULL;
924         }
925
926         if (chunkId > YAFFS_MAX_CHUNK_ID) {
927                 return NULL;
928         }
929
930         /* First check we're tall enough (ie enough topLevel) */
931
932         x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
933         requiredTallness = 0;
934         while (x) {
935                 x >>= YAFFS_TNODES_INTERNAL_BITS;
936                 requiredTallness++;
937         }
938
939
940         if (requiredTallness > fStruct->topLevel) {
941                 /* Not tall enough,gotta make the tree taller */
942                 for (i = fStruct->topLevel; i < requiredTallness; i++) {
943                 
944                         tn = yaffs_GetTnode(dev);
945
946                         if (tn) {
947                                 tn->internal[0] = fStruct->top;
948                                 fStruct->top = tn;
949                         } else {
950                                 T(YAFFS_TRACE_ERROR,
951                                   (TSTR("yaffs: no more tnodes" TENDSTR)));
952                         }
953                 }
954
955                 fStruct->topLevel = requiredTallness;
956         }
957
958         /* Traverse down to level 0, adding anything we need */
959
960         l = fStruct->topLevel;
961         tn = fStruct->top;
962         
963         if(l > 0) {
964                 while (l > 0 && tn) {
965                         x = (chunkId >>
966                              ( YAFFS_TNODES_LEVEL0_BITS +
967                               (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
968                             YAFFS_TNODES_INTERNAL_MASK;
969
970
971                         if((l>1) && !tn->internal[x]){
972                                 /* Add missing non-level-zero tnode */
973                                 tn->internal[x] = yaffs_GetTnode(dev);
974
975                         } else if(l == 1) {
976                                 /* Looking from level 1 at level 0 */
977                                 if (passedTn) {
978                                         /* If we already have one, then release it.*/
979                                         if(tn->internal[x])
980                                                 yaffs_FreeTnode(dev,tn->internal[x]);
981                                         tn->internal[x] = passedTn;
982                         
983                                 } else if(!tn->internal[x]) {
984                                         /* Don't have one, none passed in */
985                                         tn->internal[x] = yaffs_GetTnode(dev);
986                                 }
987                         }
988                 
989                         tn = tn->internal[x];
990                         l--;
991                 }
992         } else {
993                 /* top is level 0 */
994                 if(passedTn) {
995                         memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
996                         yaffs_FreeTnode(dev,passedTn);
997                 }
998         }
999
1000         return tn;
1001 }
1002
1003 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1004                                   yaffs_ExtendedTags * tags, int objectId,
1005                                   int chunkInInode)
1006 {
1007         int j;
1008
1009         for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1010                 if (yaffs_CheckChunkBit
1011                     (dev, theChunk / dev->nChunksPerBlock,
1012                      theChunk % dev->nChunksPerBlock)) {
1013                         yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1014                                                         tags);
1015                         if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1016                                 /* found it; */
1017                                 return theChunk;
1018
1019                         }
1020                 }
1021                 theChunk++;
1022         }
1023         return -1;
1024 }
1025
1026
1027 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1028  * chunks and tnodes in the file
1029  * Returns 1 if the tree was deleted. 
1030  * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1031  */
1032
1033 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1034                               int chunkOffset, int *limit)
1035 {
1036         int i;
1037         int chunkInInode;
1038         int theChunk;
1039         yaffs_ExtendedTags tags;
1040         int foundChunk;
1041         yaffs_Device *dev = in->myDev;
1042
1043         int allDone = 1;
1044
1045         if (tn) {
1046                 if (level > 0) {
1047
1048                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1049                              i--) {
1050                                 if (tn->internal[i]) {
1051                                         if (limit && (*limit) < 0) {
1052                                                 allDone = 0;
1053                                         } else {
1054                                                 allDone =
1055                                                     yaffs_DeleteWorker(in,
1056                                                                        tn->
1057                                                                        internal
1058                                                                        [i],
1059                                                                        level -
1060                                                                        1,
1061                                                                        (chunkOffset
1062                                                                         <<
1063                                                                         YAFFS_TNODES_INTERNAL_BITS)
1064                                                                        + i,
1065                                                                        limit);
1066                                         }
1067                                         if (allDone) {
1068                                                 yaffs_FreeTnode(dev,
1069                                                                 tn->
1070                                                                 internal[i]);
1071                                                 tn->internal[i] = NULL;
1072                                         }
1073                                 }
1074
1075                         }
1076                         return (allDone) ? 1 : 0;
1077                 } else if (level == 0) {
1078                         int hitLimit = 0;
1079
1080                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1081                              i--) {
1082                                 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1083                                 if (theChunk) {
1084
1085                                         chunkInInode =
1086                                             (chunkOffset <<
1087                                              YAFFS_TNODES_LEVEL0_BITS) + i;
1088
1089                                         foundChunk =
1090                                             yaffs_FindChunkInGroup(dev,
1091                                                                    theChunk,
1092                                                                    &tags,
1093                                                                    in->objectId,
1094                                                                    chunkInInode);
1095
1096                                         if (foundChunk > 0) {
1097                                                 yaffs_DeleteChunk(dev,
1098                                                                   foundChunk, 1,
1099                                                                   __LINE__);
1100                                                 in->nDataChunks--;
1101                                                 if (limit) {
1102                                                         *limit = *limit - 1;
1103                                                         if (*limit <= 0) {
1104                                                                 hitLimit = 1;
1105                                                         }
1106                                                 }
1107
1108                                         }
1109
1110                                         yaffs_PutLevel0Tnode(dev,tn,i,0);
1111                                 }
1112
1113                         }
1114                         return (i < 0) ? 1 : 0;
1115
1116                 }
1117
1118         }
1119
1120         return 1;
1121
1122 }
1123
1124 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1125 {
1126
1127         yaffs_BlockInfo *theBlock;
1128
1129         T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1130
1131         theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1132         if (theBlock) {
1133                 theBlock->softDeletions++;
1134                 dev->nFreeChunks++;
1135         }
1136 }
1137
1138 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1139  * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1140  * of the tnode.
1141  * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1142  */
1143  
1144 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1145                                   __u32 level, int chunkOffset)
1146 {
1147         int i;
1148         int theChunk;
1149         int allDone = 1;
1150         yaffs_Device *dev = in->myDev;
1151
1152         if (tn) {
1153                 if (level > 0) {
1154
1155                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1156                              i--) {
1157                                 if (tn->internal[i]) {
1158                                         allDone =
1159                                             yaffs_SoftDeleteWorker(in,
1160                                                                    tn->
1161                                                                    internal[i],
1162                                                                    level - 1,
1163                                                                    (chunkOffset
1164                                                                     <<
1165                                                                     YAFFS_TNODES_INTERNAL_BITS)
1166                                                                    + i);
1167                                         if (allDone) {
1168                                                 yaffs_FreeTnode(dev,
1169                                                                 tn->
1170                                                                 internal[i]);
1171                                                 tn->internal[i] = NULL;
1172                                         } else {
1173                                                 /* Hoosterman... how could this happen? */
1174                                         }
1175                                 }
1176                         }
1177                         return (allDone) ? 1 : 0;
1178                 } else if (level == 0) {
1179
1180                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1181                                 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1182                                 if (theChunk) {
1183                                         /* Note this does not find the real chunk, only the chunk group.
1184                                          * We make an assumption that a chunk group is not larger than 
1185                                          * a block.
1186                                          */
1187                                         yaffs_SoftDeleteChunk(dev, theChunk);
1188                                         yaffs_PutLevel0Tnode(dev,tn,i,0);
1189                                 }
1190
1191                         }
1192                         return 1;
1193
1194                 }
1195
1196         }
1197
1198         return 1;
1199
1200 }
1201
1202 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1203 {
1204         if (obj->deleted &&
1205             obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1206                 if (obj->nDataChunks <= 0) {
1207                         /* Empty file with no duplicate object headers, just delete it immediately */
1208                         yaffs_FreeTnode(obj->myDev,
1209                                         obj->variant.fileVariant.top);
1210                         obj->variant.fileVariant.top = NULL;
1211                         T(YAFFS_TRACE_TRACING,
1212                           (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1213                            obj->objectId));
1214                         yaffs_DoGenericObjectDeletion(obj);
1215                 } else {
1216                         yaffs_SoftDeleteWorker(obj,
1217                                                obj->variant.fileVariant.top,
1218                                                obj->variant.fileVariant.
1219                                                topLevel, 0);
1220                         obj->softDeleted = 1;
1221                 }
1222         }
1223 }
1224
1225 /* Pruning removes any part of the file structure tree that is beyond the
1226  * bounds of the file (ie that does not point to chunks).
1227  *
1228  * A file should only get pruned when its size is reduced.
1229  *
1230  * Before pruning, the chunks must be pulled from the tree and the
1231  * level 0 tnode entries must be zeroed out.
1232  * Could also use this for file deletion, but that's probably better handled
1233  * by a special case.
1234  */
1235
1236 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1237                                       __u32 level, int del0)
1238 {
1239         int i;
1240         int hasData;
1241
1242         if (tn) {
1243                 hasData = 0;
1244
1245                 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1246                         if (tn->internal[i] && level > 0) {
1247                                 tn->internal[i] =
1248                                     yaffs_PruneWorker(dev, tn->internal[i],
1249                                                       level - 1,
1250                                                       (i == 0) ? del0 : 1);
1251                         }
1252
1253                         if (tn->internal[i]) {
1254                                 hasData++;
1255                         }
1256                 }
1257
1258                 if (hasData == 0 && del0) {
1259                         /* Free and return NULL */
1260
1261                         yaffs_FreeTnode(dev, tn);
1262                         tn = NULL;
1263                 }
1264
1265         }
1266
1267         return tn;
1268
1269 }
1270
1271 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1272                                     yaffs_FileStructure * fStruct)
1273 {
1274         int i;
1275         int hasData;
1276         int done = 0;
1277         yaffs_Tnode *tn;
1278
1279         if (fStruct->topLevel > 0) {
1280                 fStruct->top =
1281                     yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1282
1283                 /* Now we have a tree with all the non-zero branches NULL but the height
1284                  * is the same as it was.
1285                  * Let's see if we can trim internal tnodes to shorten the tree.
1286                  * We can do this if only the 0th element in the tnode is in use 
1287                  * (ie all the non-zero are NULL)
1288                  */
1289
1290                 while (fStruct->topLevel && !done) {
1291                         tn = fStruct->top;
1292
1293                         hasData = 0;
1294                         for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1295                                 if (tn->internal[i]) {
1296                                         hasData++;
1297                                 }
1298                         }
1299
1300                         if (!hasData) {
1301                                 fStruct->top = tn->internal[0];
1302                                 fStruct->topLevel--;
1303                                 yaffs_FreeTnode(dev, tn);
1304                         } else {
1305                                 done = 1;
1306                         }
1307                 }
1308         }
1309
1310         return YAFFS_OK;
1311 }
1312
1313 /*-------------------- End of File Structure functions.-------------------*/
1314
1315 /* yaffs_CreateFreeObjects creates a bunch more objects and
1316  * adds them to the object free list.
1317  */
1318 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1319 {
1320         int i;
1321         yaffs_Object *newObjects;
1322         yaffs_ObjectList *list;
1323
1324         if (nObjects < 1)
1325                 return YAFFS_OK;
1326
1327         /* make these things */
1328         newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1329
1330         if (!newObjects) {
1331                 T(YAFFS_TRACE_ALLOCATE,
1332                   (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1333                 return YAFFS_FAIL;
1334         }
1335         
1336         /* Hook them into the free list */
1337         for (i = 0; i < nObjects - 1; i++) {
1338                 newObjects[i].siblings.next =
1339                     (struct list_head *)(&newObjects[i + 1]);
1340         }
1341
1342         newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1343         dev->freeObjects = newObjects;
1344         dev->nFreeObjects += nObjects;
1345         dev->nObjectsCreated += nObjects;
1346
1347         /* Now add this bunch of Objects to a list for freeing up. */
1348
1349         list = YMALLOC(sizeof(yaffs_ObjectList));
1350         if (!list) {
1351                 T(YAFFS_TRACE_ALLOCATE,
1352                   (TSTR("Could not add objects to management list" TENDSTR)));
1353         } else {
1354                 list->objects = newObjects;
1355                 list->next = dev->allocatedObjectList;
1356                 dev->allocatedObjectList = list;
1357         }
1358
1359         return YAFFS_OK;
1360 }
1361
1362
1363 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1364 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1365 {
1366         yaffs_Object *tn = NULL;
1367
1368         /* If there are none left make more */
1369         if (!dev->freeObjects) {
1370                 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1371         }
1372
1373         if (dev->freeObjects) {
1374                 tn = dev->freeObjects;
1375                 dev->freeObjects =
1376                     (yaffs_Object *) (dev->freeObjects->siblings.next);
1377                 dev->nFreeObjects--;
1378
1379                 /* Now sweeten it up... */
1380
1381                 memset(tn, 0, sizeof(yaffs_Object));
1382                 tn->myDev = dev;
1383                 tn->chunkId = -1;
1384                 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1385                 INIT_LIST_HEAD(&(tn->hardLinks));
1386                 INIT_LIST_HEAD(&(tn->hashLink));
1387                 INIT_LIST_HEAD(&tn->siblings);
1388
1389                 /* Add it to the lost and found directory.
1390                  * NB Can't put root or lostNFound in lostNFound so
1391                  * check if lostNFound exists first
1392                  */
1393                 if (dev->lostNFoundDir) {
1394                         yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1395                 }
1396         }
1397
1398         return tn;
1399 }
1400
1401 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1402                                                __u32 mode)
1403 {
1404
1405         yaffs_Object *obj =
1406             yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1407         if (obj) {
1408                 obj->fake = 1;          /* it is fake so it has no NAND presence... */
1409                 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1410                 obj->unlinkAllowed = 0; /* ... or unlink it */
1411                 obj->deleted = 0;
1412                 obj->unlinked = 0;
1413                 obj->yst_mode = mode;
1414                 obj->myDev = dev;
1415                 obj->chunkId = 0;       /* Not a valid chunk. */
1416         }
1417
1418         return obj;
1419
1420 }
1421
1422 static void yaffs_UnhashObject(yaffs_Object * tn)
1423 {
1424         int bucket;
1425         yaffs_Device *dev = tn->myDev;
1426
1427         /* If it is still linked into the bucket list, free from the list */
1428         if (!list_empty(&tn->hashLink)) {
1429                 list_del_init(&tn->hashLink);
1430                 bucket = yaffs_HashFunction(tn->objectId);
1431                 dev->objectBucket[bucket].count--;
1432         }
1433
1434 }
1435
1436 /*  FreeObject frees up a Object and puts it back on the free list */
1437 static void yaffs_FreeObject(yaffs_Object * tn)
1438 {
1439
1440         yaffs_Device *dev = tn->myDev;
1441
1442 #ifdef  __KERNEL__
1443         if (tn->myInode) {
1444                 /* We're still hooked up to a cached inode.
1445                  * Don't delete now, but mark for later deletion
1446                  */
1447                 tn->deferedFree = 1;
1448                 return;
1449         }
1450 #endif
1451
1452         yaffs_UnhashObject(tn);
1453
1454         /* Link into the free list. */
1455         tn->siblings.next = (struct list_head *)(dev->freeObjects);
1456         dev->freeObjects = tn;
1457         dev->nFreeObjects++;
1458 }
1459
1460 #ifdef __KERNEL__
1461
1462 void yaffs_HandleDeferedFree(yaffs_Object * obj)
1463 {
1464         if (obj->deferedFree) {
1465                 yaffs_FreeObject(obj);
1466         }
1467 }
1468
1469 #endif
1470
1471 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
1472 {
1473         /* Free the list of allocated Objects */
1474
1475         yaffs_ObjectList *tmp;
1476
1477         while (dev->allocatedObjectList) {
1478                 tmp = dev->allocatedObjectList->next;
1479                 YFREE(dev->allocatedObjectList->objects);
1480                 YFREE(dev->allocatedObjectList);
1481
1482                 dev->allocatedObjectList = tmp;
1483         }
1484
1485         dev->freeObjects = NULL;
1486         dev->nFreeObjects = 0;
1487 }
1488
1489 static void yaffs_InitialiseObjects(yaffs_Device * dev)
1490 {
1491         int i;
1492
1493         dev->allocatedObjectList = NULL;
1494         dev->freeObjects = NULL;
1495         dev->nFreeObjects = 0;
1496
1497         for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
1498                 INIT_LIST_HEAD(&dev->objectBucket[i].list);
1499                 dev->objectBucket[i].count = 0;
1500         }
1501
1502 }
1503
1504 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
1505 {
1506         static int x = 0;
1507         int i;
1508         int l = 999;
1509         int lowest = 999999;
1510
1511         /* First let's see if we can find one that's empty. */
1512
1513         for (i = 0; i < 10 && lowest > 0; i++) {
1514                 x++;
1515                 x %= YAFFS_NOBJECT_BUCKETS;
1516                 if (dev->objectBucket[x].count < lowest) {
1517                         lowest = dev->objectBucket[x].count;
1518                         l = x;
1519                 }
1520
1521         }
1522
1523         /* If we didn't find an empty list, then try
1524          * looking a bit further for a short one
1525          */
1526
1527         for (i = 0; i < 10 && lowest > 3; i++) {
1528                 x++;
1529                 x %= YAFFS_NOBJECT_BUCKETS;
1530                 if (dev->objectBucket[x].count < lowest) {
1531                         lowest = dev->objectBucket[x].count;
1532                         l = x;
1533                 }
1534
1535         }
1536
1537         return l;
1538 }
1539
1540 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
1541 {
1542         int bucket = yaffs_FindNiceObjectBucket(dev);
1543
1544         /* Now find an object value that has not already been taken
1545          * by scanning the list.
1546          */
1547
1548         int found = 0;
1549         struct list_head *i;
1550
1551         __u32 n = (__u32) bucket;
1552
1553         /* yaffs_CheckObjectHashSanity();  */
1554
1555         while (!found) {
1556                 found = 1;
1557                 n += YAFFS_NOBJECT_BUCKETS;
1558                 if (1 || dev->objectBucket[bucket].count > 0) {
1559                         list_for_each(i, &dev->objectBucket[bucket].list) {
1560                                 /* If there is already one in the list */
1561                                 if (i
1562                                     && list_entry(i, yaffs_Object,
1563                                                   hashLink)->objectId == n) {
1564                                         found = 0;
1565                                 }
1566                         }
1567                 }
1568         }
1569
1570
1571         return n;
1572 }
1573
1574 static void yaffs_HashObject(yaffs_Object * in)
1575 {
1576         int bucket = yaffs_HashFunction(in->objectId);
1577         yaffs_Device *dev = in->myDev;
1578
1579         list_add(&in->hashLink, &dev->objectBucket[bucket].list);
1580         dev->objectBucket[bucket].count++;
1581
1582 }
1583
1584 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
1585 {
1586         int bucket = yaffs_HashFunction(number);
1587         struct list_head *i;
1588         yaffs_Object *in;
1589
1590         list_for_each(i, &dev->objectBucket[bucket].list) {
1591                 /* Look if it is in the list */
1592                 if (i) {
1593                         in = list_entry(i, yaffs_Object, hashLink);
1594                         if (in->objectId == number) {
1595 #ifdef __KERNEL__
1596                                 /* Don't tell the VFS about this one if it is defered free */
1597                                 if (in->deferedFree)
1598                                         return NULL;
1599 #endif
1600
1601                                 return in;
1602                         }
1603                 }
1604         }
1605
1606         return NULL;
1607 }
1608
1609 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
1610                                     yaffs_ObjectType type)
1611 {
1612
1613         yaffs_Object *theObject;
1614
1615         if (number < 0) {
1616                 number = yaffs_CreateNewObjectNumber(dev);
1617         }
1618
1619         theObject = yaffs_AllocateEmptyObject(dev);
1620
1621         if (theObject) {
1622                 theObject->fake = 0;
1623                 theObject->renameAllowed = 1;
1624                 theObject->unlinkAllowed = 1;
1625                 theObject->objectId = number;
1626                 yaffs_HashObject(theObject);
1627                 theObject->variantType = type;
1628 #ifdef CONFIG_YAFFS_WINCE
1629                 yfsd_WinFileTimeNow(theObject->win_atime);
1630                 theObject->win_ctime[0] = theObject->win_mtime[0] =
1631                     theObject->win_atime[0];
1632                 theObject->win_ctime[1] = theObject->win_mtime[1] =
1633                     theObject->win_atime[1];
1634
1635 #else
1636
1637                 theObject->yst_atime = theObject->yst_mtime =
1638                     theObject->yst_ctime = Y_CURRENT_TIME;
1639 #endif
1640                 switch (type) {
1641                 case YAFFS_OBJECT_TYPE_FILE:
1642                         theObject->variant.fileVariant.fileSize = 0;
1643                         theObject->variant.fileVariant.scannedFileSize = 0;
1644                         theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
1645                         theObject->variant.fileVariant.topLevel = 0;
1646                         theObject->variant.fileVariant.top =
1647                             yaffs_GetTnode(dev);
1648                         break;
1649                 case YAFFS_OBJECT_TYPE_DIRECTORY:
1650                         INIT_LIST_HEAD(&theObject->variant.directoryVariant.
1651                                        children);
1652                         break;
1653                 case YAFFS_OBJECT_TYPE_SYMLINK:
1654                 case YAFFS_OBJECT_TYPE_HARDLINK:
1655                 case YAFFS_OBJECT_TYPE_SPECIAL:
1656                         /* No action required */
1657                         break;
1658                 case YAFFS_OBJECT_TYPE_UNKNOWN:
1659                         /* todo this should not happen */
1660                         break;
1661                 }
1662         }
1663
1664         return theObject;
1665 }
1666
1667 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
1668                                                       int number,
1669                                                       yaffs_ObjectType type)
1670 {
1671         yaffs_Object *theObject = NULL;
1672
1673         if (number > 0) {
1674                 theObject = yaffs_FindObjectByNumber(dev, number);
1675         }
1676
1677         if (!theObject) {
1678                 theObject = yaffs_CreateNewObject(dev, number, type);
1679         }
1680
1681         return theObject;
1682
1683 }
1684                         
1685
1686 static YCHAR *yaffs_CloneString(const YCHAR * str)
1687 {
1688         YCHAR *newStr = NULL;
1689
1690         if (str && *str) {
1691                 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
1692                 yaffs_strcpy(newStr, str);
1693         }
1694
1695         return newStr;
1696
1697 }
1698
1699 /*
1700  * Mknod (create) a new object.
1701  * equivalentObject only has meaning for a hard link;
1702  * aliasString only has meaning for a sumlink.
1703  * rdev only has meaning for devices (a subset of special objects)
1704  */
1705  
1706 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
1707                                        yaffs_Object * parent,
1708                                        const YCHAR * name,
1709                                        __u32 mode,
1710                                        __u32 uid,
1711                                        __u32 gid,
1712                                        yaffs_Object * equivalentObject,
1713                                        const YCHAR * aliasString, __u32 rdev)
1714 {
1715         yaffs_Object *in;
1716
1717         yaffs_Device *dev = parent->myDev;
1718
1719         /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
1720         if (yaffs_FindObjectByName(parent, name)) {
1721                 return NULL;
1722         }
1723
1724         in = yaffs_CreateNewObject(dev, -1, type);
1725
1726         if (in) {
1727                 in->chunkId = -1;
1728                 in->valid = 1;
1729                 in->variantType = type;
1730
1731                 in->yst_mode = mode;
1732
1733 #ifdef CONFIG_YAFFS_WINCE
1734                 yfsd_WinFileTimeNow(in->win_atime);
1735                 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1736                 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
1737
1738 #else
1739                 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
1740
1741                 in->yst_rdev = rdev;
1742                 in->yst_uid = uid;
1743                 in->yst_gid = gid;
1744 #endif
1745                 in->nDataChunks = 0;
1746
1747                 yaffs_SetObjectName(in, name);
1748                 in->dirty = 1;
1749
1750                 yaffs_AddObjectToDirectory(parent, in);
1751
1752                 in->myDev = parent->myDev;
1753
1754                 switch (type) {
1755                 case YAFFS_OBJECT_TYPE_SYMLINK:
1756                         in->variant.symLinkVariant.alias =
1757                             yaffs_CloneString(aliasString);
1758                         break;
1759                 case YAFFS_OBJECT_TYPE_HARDLINK:
1760                         in->variant.hardLinkVariant.equivalentObject =
1761                             equivalentObject;
1762                         in->variant.hardLinkVariant.equivalentObjectId =
1763                             equivalentObject->objectId;
1764                         list_add(&in->hardLinks, &equivalentObject->hardLinks);
1765                         break;
1766                 case YAFFS_OBJECT_TYPE_FILE:    
1767                 case YAFFS_OBJECT_TYPE_DIRECTORY:
1768                 case YAFFS_OBJECT_TYPE_SPECIAL:
1769                 case YAFFS_OBJECT_TYPE_UNKNOWN:
1770                         /* do nothing */
1771                         break;
1772                 }
1773
1774                 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
1775                         /* Could not create the object header, fail the creation */
1776                         yaffs_DestroyObject(in);
1777                         in = NULL;
1778                 }
1779
1780         }
1781
1782         return in;
1783 }
1784
1785 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
1786                               __u32 mode, __u32 uid, __u32 gid)
1787 {
1788         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
1789                                  uid, gid, NULL, NULL, 0);
1790 }
1791
1792 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
1793                                    __u32 mode, __u32 uid, __u32 gid)
1794 {
1795         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
1796                                  mode, uid, gid, NULL, NULL, 0);
1797 }
1798
1799 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
1800                                  __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1801 {
1802         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
1803                                  uid, gid, NULL, NULL, rdev);
1804 }
1805
1806 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
1807                                  __u32 mode, __u32 uid, __u32 gid,
1808                                  const YCHAR * alias)
1809 {
1810         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
1811                                  uid, gid, NULL, alias, 0);
1812 }
1813
1814 /* yaffs_Link returns the object id of the equivalent object.*/
1815 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
1816                          yaffs_Object * equivalentObject)
1817 {
1818         /* Get the real object in case we were fed a hard link as an equivalent object */
1819         equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1820
1821         if (yaffs_MknodObject
1822             (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
1823              equivalentObject, NULL, 0)) {
1824                 return equivalentObject;
1825         } else {
1826                 return NULL;
1827         }
1828
1829 }
1830
1831 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
1832                                   const YCHAR * newName, int force, int shadows)
1833 {
1834         int unlinkOp;
1835         int deleteOp;
1836
1837         yaffs_Object *existingTarget;
1838
1839         if (newDir == NULL) {
1840                 newDir = obj->parent;   /* use the old directory */
1841         }
1842
1843         if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
1844                 T(YAFFS_TRACE_ALWAYS,
1845                   (TSTR
1846                    ("tragendy: yaffs_ChangeObjectName: newDir is not a directory"
1847                     TENDSTR)));
1848                 YBUG();
1849         }
1850         
1851         /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
1852         if (obj->myDev->isYaffs2) {
1853                 unlinkOp = (newDir == obj->myDev->unlinkedDir);
1854         } else {
1855                 unlinkOp = (newDir == obj->myDev->unlinkedDir
1856                             && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1857         }
1858
1859         deleteOp = (newDir == obj->myDev->deletedDir);
1860
1861         existingTarget = yaffs_FindObjectByName(newDir, newName);
1862
1863         /* If the object is a file going into the unlinked directory, 
1864          *   then it is OK to just stuff it in since duplicate names are allowed.
1865          *   else only proceed if the new name does not exist and if we're putting 
1866          *   it into a directory.
1867          */
1868         if ((unlinkOp ||
1869              deleteOp ||
1870              force ||
1871              (shadows > 0) ||
1872              !existingTarget) &&
1873             newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
1874                 yaffs_SetObjectName(obj, newName);
1875                 obj->dirty = 1;
1876
1877                 yaffs_AddObjectToDirectory(newDir, obj);
1878
1879                 if (unlinkOp)
1880                         obj->unlinked = 1;
1881
1882                 /* If it is a deletion then we mark it as a shrink for gc purposes. */
1883                 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
1884                         return YAFFS_OK;
1885         }
1886
1887         return YAFFS_FAIL;
1888 }
1889
1890 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
1891                        yaffs_Object * newDir, const YCHAR * newName)
1892 {
1893         yaffs_Object *obj;
1894         yaffs_Object *existingTarget;
1895         int force = 0;
1896
1897 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1898         /* Special case for case insemsitive systems (eg. WinCE).
1899          * While look-up is case insensitive, the name isn't.
1900          * Therefore we might want to change x.txt to X.txt
1901         */
1902         if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
1903                 force = 1;
1904         }
1905 #endif
1906
1907         obj = yaffs_FindObjectByName(oldDir, oldName);
1908         /* Check new name to long. */
1909         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK &&
1910             yaffs_strlen(newName) > YAFFS_MAX_ALIAS_LENGTH)
1911           /* ENAMETOOLONG */
1912           return YAFFS_FAIL;
1913         else if (obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK &&
1914                  yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
1915           /* ENAMETOOLONG */
1916           return YAFFS_FAIL;
1917
1918         if (obj && obj->renameAllowed) {
1919
1920                 /* Now do the handling for an existing target, if there is one */
1921
1922                 existingTarget = yaffs_FindObjectByName(newDir, newName);
1923                 if (existingTarget &&
1924                     existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
1925                     !list_empty(&existingTarget->variant.directoryVariant.children)) {
1926                         /* There is a target that is a non-empty directory, so we fail */
1927                         return YAFFS_FAIL;      /* EEXIST or ENOTEMPTY */
1928                 } else if (existingTarget && existingTarget != obj) {
1929                         /* Nuke the target first, using shadowing, 
1930                          * but only if it isn't the same object
1931                          */
1932                         yaffs_ChangeObjectName(obj, newDir, newName, force,
1933                                                existingTarget->objectId);
1934                         yaffs_UnlinkObject(existingTarget);
1935                 }
1936
1937                 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
1938         }
1939         return YAFFS_FAIL;
1940 }
1941
1942 /*------------------------- Block Management and Page Allocation ----------------*/
1943
1944 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
1945 {
1946         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
1947         
1948         dev->allocationBlock = -1;      /* force it to get a new one */
1949
1950         /* Todo we're assuming the malloc will pass. */
1951         dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1952         if(!dev->blockInfo){
1953                 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
1954                 dev->blockInfoAlt = 1;
1955         }
1956         else
1957                 dev->blockInfoAlt = 0;
1958         
1959         /* Set up dynamic blockinfo stuff. */
1960         dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
1961         dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
1962         if(!dev->chunkBits){
1963                 dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
1964                 dev->chunkBitsAlt = 1;
1965         }
1966         else
1967                 dev->chunkBitsAlt = 0;
1968         
1969         if (dev->blockInfo && dev->chunkBits) {
1970                 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
1971                 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
1972                 return YAFFS_OK;
1973         }
1974
1975         return YAFFS_FAIL;
1976
1977 }
1978
1979 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
1980 {
1981         if(dev->blockInfoAlt)
1982                 YFREE_ALT(dev->blockInfo);
1983         else
1984                 YFREE(dev->blockInfo);
1985         dev->blockInfoAlt = 0;
1986
1987         dev->blockInfo = NULL;
1988         
1989         if(dev->chunkBitsAlt)
1990                 YFREE_ALT(dev->chunkBits);
1991         else
1992                 YFREE(dev->chunkBits);
1993         dev->chunkBitsAlt = 0;
1994         dev->chunkBits = NULL;
1995 }
1996
1997 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
1998                                             yaffs_BlockInfo * bi)
1999 {
2000         int i;
2001         __u32 seq;
2002         yaffs_BlockInfo *b;
2003
2004         if (!dev->isYaffs2)
2005                 return 1;       /* disqualification only applies to yaffs2. */
2006
2007         if (!bi->hasShrinkHeader)
2008                 return 1;       /* can gc */
2009
2010         /* Find the oldest dirty sequence number if we don't know it and save it
2011          * so we don't have to keep recomputing it.
2012          */
2013         if (!dev->oldestDirtySequence) {
2014                 seq = dev->sequenceNumber;
2015
2016                 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2017                      i++) {
2018                         b = yaffs_GetBlockInfo(dev, i);
2019                         if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2020                             (b->pagesInUse - b->softDeletions) <
2021                             dev->nChunksPerBlock && b->sequenceNumber < seq) {
2022                                 seq = b->sequenceNumber;
2023                         }
2024                 }
2025                 dev->oldestDirtySequence = seq;
2026         }
2027
2028         /* Can't do gc of this block if there are any blocks older than this one that have
2029          * discarded pages.
2030          */
2031         return (bi->sequenceNumber <= dev->oldestDirtySequence);
2032
2033 }
2034
2035 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2036  * for garbage collection.
2037  */
2038
2039 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2040                                                int aggressive)
2041 {
2042
2043         int b = dev->currentDirtyChecker;
2044
2045         int i;
2046         int iterations;
2047         int dirtiest = -1;
2048         int pagesInUse;
2049         int prioritised=0;
2050         yaffs_BlockInfo *bi;
2051         static int nonAggressiveSkip = 0;
2052         int pendingPrioritisedExist = 0;
2053         
2054         /* First let's see if we need to grab a prioritised block */
2055         if(dev->hasPendingPrioritisedGCs){
2056                 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2057
2058                         bi = yaffs_GetBlockInfo(dev, i);
2059                         if(bi->gcPrioritise) {
2060                                 pendingPrioritisedExist = 1;
2061                                 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2062                                    yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2063                                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
2064                                         dirtiest = i;
2065                                         prioritised = 1;
2066                                         aggressive = 1; /* Fool the non-aggressive skip logiv below */
2067                                 }
2068                         }
2069                 }
2070                 
2071                 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2072                         dev->hasPendingPrioritisedGCs = 0;
2073         }
2074
2075         /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2076          * search harder.
2077          * else (we're doing a leasurely gc), then we only bother to do this if the
2078          * block has only a few pages in use.
2079          */
2080
2081         nonAggressiveSkip--;
2082
2083         if (!aggressive && (nonAggressiveSkip > 0)) {
2084                 return -1;
2085         }
2086
2087         if(!prioritised)
2088                 pagesInUse =
2089                         (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2090
2091         if (aggressive) {
2092                 iterations =
2093                     dev->internalEndBlock - dev->internalStartBlock + 1;
2094         } else {
2095                 iterations =
2096                     dev->internalEndBlock - dev->internalStartBlock + 1;
2097                 iterations = iterations / 16;
2098                 if (iterations > 200) {
2099                         iterations = 200;
2100                 }
2101         }
2102
2103         for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2104                 b++;
2105                 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2106                         b = dev->internalStartBlock;
2107                 }
2108
2109                 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2110                         T(YAFFS_TRACE_ERROR,
2111                           (TSTR("**>> Block %d is not valid" TENDSTR), b));
2112                         YBUG();
2113                 }
2114
2115                 bi = yaffs_GetBlockInfo(dev, b);
2116
2117 #if 0
2118                 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2119                         dirtiest = b;
2120                         pagesInUse = 0;
2121                 }
2122                 else 
2123 #endif
2124
2125                 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2126                        (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2127                         yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2128                         dirtiest = b;
2129                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
2130                 }
2131         }
2132
2133         dev->currentDirtyChecker = b;
2134
2135         if (dirtiest > 0) {
2136                 T(YAFFS_TRACE_GC,
2137                   (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2138                    dev->nChunksPerBlock - pagesInUse,prioritised));
2139         }
2140
2141         dev->oldestDirtySequence = 0;
2142
2143         if (dirtiest > 0) {
2144                 nonAggressiveSkip = 4;
2145         }
2146
2147         return dirtiest;
2148 }
2149
2150 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2151 {
2152         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2153
2154         int erasedOk = 0;
2155
2156         /* If the block is still healthy erase it and mark as clean.
2157          * If the block has had a data failure, then retire it.
2158          */
2159          
2160         T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2161                 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2162                 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2163                 
2164         bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2165
2166         if (!bi->needsRetiring) {
2167                 yaffs_InvalidateCheckpoint(dev);
2168                 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2169                 if (!erasedOk) {
2170                         dev->nErasureFailures++;
2171                         T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2172                           (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2173                 }
2174         }
2175
2176         if (erasedOk && (yaffs_traceMask & YAFFS_TRACE_ERASE)) {
2177                 int i;
2178                 for (i = 0; i < dev->nChunksPerBlock; i++) {
2179                         if (!yaffs_CheckChunkErased
2180                             (dev, blockNo * dev->nChunksPerBlock + i)) {
2181                                 T(YAFFS_TRACE_ERROR,
2182                                   (TSTR
2183                                    (">>Block %d erasure supposedly OK, but chunk %d not erased"
2184                                     TENDSTR), blockNo, i));
2185                         }
2186                 }
2187         }
2188
2189         if (erasedOk) {
2190                 /* Clean it up... */
2191                 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2192                 dev->nErasedBlocks++;
2193                 bi->pagesInUse = 0;
2194                 bi->softDeletions = 0;
2195                 bi->hasShrinkHeader = 0;
2196                 bi->skipErasedCheck = 1;  /* This is clean, so no need to check */
2197                 bi->gcPrioritise = 0;
2198                 yaffs_ClearChunkBits(dev, blockNo);
2199
2200                 T(YAFFS_TRACE_ERASE,
2201                   (TSTR("Erased block %d" TENDSTR), blockNo));
2202         } else {
2203                 dev->nFreeChunks -= dev->nChunksPerBlock;       /* We lost a block of free space */
2204
2205                 yaffs_RetireBlock(dev, blockNo);
2206                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2207                   (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2208         }
2209 }
2210
2211 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2212 {
2213         int i;
2214
2215         yaffs_BlockInfo *bi;
2216
2217         if (dev->nErasedBlocks < 1) {
2218                 /* Hoosterman we've got a problem.
2219                  * Can't get space to gc
2220                  */
2221                 T(YAFFS_TRACE_ERROR,
2222                   (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2223
2224                 return -1;
2225         }
2226         
2227         /* Find an empty block. */
2228
2229         for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2230                 dev->allocationBlockFinder++;
2231                 if (dev->allocationBlockFinder < dev->internalStartBlock
2232                     || dev->allocationBlockFinder > dev->internalEndBlock) {
2233                         dev->allocationBlockFinder = dev->internalStartBlock;
2234                 }
2235
2236                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2237
2238                 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2239                         bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2240                         dev->sequenceNumber++;
2241                         bi->sequenceNumber = dev->sequenceNumber;
2242                         dev->nErasedBlocks--;
2243                         T(YAFFS_TRACE_ALLOCATE,
2244                           (TSTR("Allocated block %d, seq  %d, %d left" TENDSTR),
2245                            dev->allocationBlockFinder, dev->sequenceNumber,
2246                            dev->nErasedBlocks));
2247                         return dev->allocationBlockFinder;
2248                 }
2249         }
2250
2251         T(YAFFS_TRACE_ALWAYS,
2252           (TSTR
2253            ("yaffs tragedy: no more eraased blocks, but there should have been %d"
2254             TENDSTR), dev->nErasedBlocks));
2255
2256         return -1;
2257 }
2258
2259
2260 // Check if there's space to allocate...
2261 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2262 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2263 {
2264         int reservedChunks;
2265         int reservedBlocks = dev->nReservedBlocks;
2266         int checkpointBlocks;
2267         
2268         checkpointBlocks =  dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
2269         if(checkpointBlocks < 0)
2270                 checkpointBlocks = 0;
2271         
2272         reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2273         
2274         return (dev->nFreeChunks > reservedChunks);
2275 }
2276
2277 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2278 {
2279         int retVal;
2280         yaffs_BlockInfo *bi;
2281
2282         if (dev->allocationBlock < 0) {
2283                 /* Get next block to allocate off */
2284                 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2285                 dev->allocationPage = 0;
2286         }
2287
2288         if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2289                 /* Not enough space to allocate unless we're allowed to use the reserve. */
2290                 return -1;
2291         }
2292
2293         if (dev->nErasedBlocks < dev->nReservedBlocks
2294             && dev->allocationPage == 0) {
2295                 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2296         }
2297
2298         /* Next page please.... */
2299         if (dev->allocationBlock >= 0) {
2300                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2301
2302                 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2303                     dev->allocationPage;
2304                 bi->pagesInUse++;
2305                 yaffs_SetChunkBit(dev, dev->allocationBlock,
2306                                   dev->allocationPage);
2307
2308                 dev->allocationPage++;
2309
2310                 dev->nFreeChunks--;
2311
2312                 /* If the block is full set the state to full */
2313                 if (dev->allocationPage >= dev->nChunksPerBlock) {
2314                         bi->blockState = YAFFS_BLOCK_STATE_FULL;
2315                         dev->allocationBlock = -1;
2316                 }
2317
2318                 if(blockUsedPtr)
2319                         *blockUsedPtr = bi;
2320                         
2321                 return retVal;
2322         }
2323         
2324         T(YAFFS_TRACE_ERROR,
2325           (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2326
2327         return -1;
2328 }
2329
2330 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2331 {
2332         int n;
2333
2334         n = dev->nErasedBlocks * dev->nChunksPerBlock;
2335
2336         if (dev->allocationBlock > 0) {
2337                 n += (dev->nChunksPerBlock - dev->allocationPage);
2338         }
2339
2340         return n;
2341
2342 }
2343
2344 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2345 {
2346         int oldChunk;
2347         int newChunk;
2348         int chunkInBlock;
2349         int markNAND;
2350         int retVal = YAFFS_OK;
2351         int cleanups = 0;
2352         int i;
2353         int isCheckpointBlock;
2354
2355         int chunksBefore = yaffs_GetErasedChunks(dev);
2356         int chunksAfter;
2357
2358         yaffs_ExtendedTags tags;
2359
2360         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2361
2362         yaffs_Object *object;
2363
2364         isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2365         
2366         bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2367
2368         T(YAFFS_TRACE_TRACING,
2369           (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2370            bi->pagesInUse, bi->hasShrinkHeader));
2371
2372         /*yaffs_VerifyFreeChunks(dev); */
2373
2374         bi->hasShrinkHeader = 0;        /* clear the flag so that the block can erase */
2375
2376         /* Take off the number of soft deleted entries because
2377          * they're going to get really deleted during GC.
2378          */
2379         dev->nFreeChunks -= bi->softDeletions;
2380
2381         dev->isDoingGC = 1;
2382
2383         if (isCheckpointBlock ||
2384             !yaffs_StillSomeChunkBits(dev, block)) {
2385                 T(YAFFS_TRACE_TRACING,
2386                   (TSTR
2387                    ("Collecting block %d that has no chunks in use" TENDSTR),
2388                    block));
2389                 yaffs_BlockBecameDirty(dev, block);
2390         } else {
2391
2392                 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2393
2394                 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
2395                      chunkInBlock < dev->nChunksPerBlock
2396                      && yaffs_StillSomeChunkBits(dev, block);
2397                      chunkInBlock++, oldChunk++) {
2398                         if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
2399
2400                                 /* This page is in use and might need to be copied off */
2401
2402                                 markNAND = 1;
2403
2404                                 yaffs_InitialiseTags(&tags);
2405
2406                                 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2407                                                                 buffer, &tags);
2408
2409                                 object =
2410                                     yaffs_FindObjectByNumber(dev,
2411                                                              tags.objectId);
2412
2413                                 T(YAFFS_TRACE_GC_DETAIL,
2414                                   (TSTR
2415                                    ("Collecting page %d, %d %d %d " TENDSTR),
2416                                    chunkInBlock, tags.objectId, tags.chunkId,
2417                                    tags.byteCount));
2418
2419                                 if (!object) {
2420                                         T(YAFFS_TRACE_ERROR,
2421                                           (TSTR
2422                                            ("page %d in gc has no object "
2423                                             TENDSTR), oldChunk));
2424                                 }
2425
2426                                 if (object && object->deleted
2427                                     && tags.chunkId != 0) {
2428                                         /* Data chunk in a deleted file, throw it away
2429                                          * It's a soft deleted data chunk,
2430                                          * No need to copy this, just forget about it and 
2431                                          * fix up the object.
2432                                          */
2433
2434                                         object->nDataChunks--;
2435
2436                                         if (object->nDataChunks <= 0) {
2437                                                 /* remeber to clean up the object */
2438                                                 dev->gcCleanupList[cleanups] =
2439                                                     tags.objectId;
2440                                                 cleanups++;
2441                                         }
2442                                         markNAND = 0;
2443                                 } else if (0
2444                                            /* Todo object && object->deleted && object->nDataChunks == 0 */
2445                                            ) {
2446                                         /* Deleted object header with no data chunks.
2447                                          * Can be discarded and the file deleted.
2448                                          */
2449                                         object->chunkId = 0;
2450                                         yaffs_FreeTnode(object->myDev,
2451                                                         object->variant.
2452                                                         fileVariant.top);
2453                                         object->variant.fileVariant.top = NULL;
2454                                         yaffs_DoGenericObjectDeletion(object);
2455
2456                                 } else if (object) {
2457                                         /* It's either a data chunk in a live file or
2458                                          * an ObjectHeader, so we're interested in it.
2459                                          * NB Need to keep the ObjectHeaders of deleted files
2460                                          * until the whole file has been deleted off
2461                                          */
2462                                         tags.serialNumber++;
2463
2464                                         dev->nGCCopies++;
2465
2466                                         if (tags.chunkId == 0) {
2467                                                 /* It is an object Id,
2468                                                  * We need to nuke the shrinkheader flags first
2469                                                  * We no longer want the shrinkHeader flag since its work is done
2470                                                  * and if it is left in place it will mess up scanning.
2471                                                  * Also, clear out any shadowing stuff
2472                                                  */
2473
2474                                                 yaffs_ObjectHeader *oh;
2475                                                 oh = (yaffs_ObjectHeader *)buffer;
2476                                                 oh->isShrink = 0;
2477                                                 oh->shadowsObject = -1;
2478                                                 tags.extraShadows = 0;
2479                                                 tags.extraIsShrinkHeader = 0;
2480                                         }
2481
2482                                         newChunk =
2483                                             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
2484
2485                                         if (newChunk < 0) {
2486                                                 retVal = YAFFS_FAIL;
2487                                         } else {
2488
2489                                                 /* Ok, now fix up the Tnodes etc. */
2490
2491                                                 if (tags.chunkId == 0) {
2492                                                         /* It's a header */
2493                                                         object->chunkId =  newChunk;
2494                                                         object->serial =   tags.serialNumber;
2495                                                 } else {
2496                                                         /* It's a data chunk */
2497                                                         yaffs_PutChunkIntoFile
2498                                                             (object,
2499                                                              tags.chunkId,
2500                                                              newChunk, 0);
2501                                                 }
2502                                         }
2503                                 }
2504
2505                                 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
2506
2507                         }
2508                 }
2509
2510                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2511
2512
2513                 /* Do any required cleanups */
2514                 for (i = 0; i < cleanups; i++) {
2515                         /* Time to delete the file too */
2516                         object =
2517                             yaffs_FindObjectByNumber(dev,
2518                                                      dev->gcCleanupList[i]);
2519                         if (object) {
2520                                 yaffs_FreeTnode(dev,
2521                                                 object->variant.fileVariant.
2522                                                 top);
2523                                 object->variant.fileVariant.top = NULL;
2524                                 T(YAFFS_TRACE_GC,
2525                                   (TSTR
2526                                    ("yaffs: About to finally delete object %d"
2527                                     TENDSTR), object->objectId));
2528                                 yaffs_DoGenericObjectDeletion(object);
2529                                 object->myDev->nDeletedFiles--;
2530                         }
2531
2532                 }
2533
2534         }
2535
2536         if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
2537                 T(YAFFS_TRACE_GC,
2538                   (TSTR
2539                    ("gc did not increase free chunks before %d after %d"
2540                     TENDSTR), chunksBefore, chunksAfter));
2541         }
2542
2543         dev->isDoingGC = 0;
2544
2545         return YAFFS_OK;
2546 }
2547
2548 /* New garbage collector
2549  * If we're very low on erased blocks then we do aggressive garbage collection
2550  * otherwise we do "leasurely" garbage collection.
2551  * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2552  * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2553  *
2554  * The idea is to help clear out space in a more spread-out manner.
2555  * Dunno if it really does anything useful.
2556  */
2557 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
2558 {
2559         int block;
2560         int aggressive;
2561         int gcOk = YAFFS_OK;
2562         int maxTries = 0;
2563         
2564         int checkpointBlockAdjust;
2565
2566         if (dev->isDoingGC) {
2567                 /* Bail out so we don't get recursive gc */
2568                 return YAFFS_OK;
2569         }
2570         
2571         /* This loop should pass the first time.
2572          * We'll only see looping here if the erase of the collected block fails.
2573          */
2574
2575         do {
2576                 maxTries++;
2577                 
2578                 checkpointBlockAdjust = (dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint);
2579                 if(checkpointBlockAdjust < 0)
2580                         checkpointBlockAdjust = 0;
2581
2582                 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust)) {
2583                         /* We need a block soon...*/
2584                         aggressive = 1;
2585                 } else {
2586                         /* We're in no hurry */
2587                         aggressive = 0;
2588                 }
2589
2590                 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
2591
2592                 if (block > 0) {
2593                         dev->garbageCollections++;
2594                         if (!aggressive) {
2595                                 dev->passiveGarbageCollections++;
2596                         }
2597
2598                         T(YAFFS_TRACE_GC,
2599                           (TSTR
2600                            ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
2601                            dev->nErasedBlocks, aggressive));
2602
2603                         gcOk = yaffs_GarbageCollectBlock(dev, block);
2604                 }
2605
2606                 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
2607                         T(YAFFS_TRACE_GC,
2608                           (TSTR
2609                            ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
2610                             TENDSTR), dev->nErasedBlocks, maxTries, block));
2611                 }
2612         } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
2613                  && (maxTries < 2));
2614
2615         return aggressive ? gcOk : YAFFS_OK;
2616 }
2617
2618 /*-------------------------  TAGS --------------------------------*/
2619
2620 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
2621                            int chunkInObject)
2622 {
2623         return (tags->chunkId == chunkInObject &&
2624                 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
2625
2626 }
2627
2628
2629 /*-------------------- Data file manipulation -----------------*/
2630
2631 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
2632                                  yaffs_ExtendedTags * tags)
2633 {
2634         /*Get the Tnode, then get the level 0 offset chunk offset */
2635         yaffs_Tnode *tn;
2636         int theChunk = -1;
2637         yaffs_ExtendedTags localTags;
2638         int retVal = -1;
2639
2640         yaffs_Device *dev = in->myDev;
2641
2642         if (!tags) {
2643                 /* Passed a NULL, so use our own tags space */
2644                 tags = &localTags;
2645         }
2646
2647         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2648
2649         if (tn) {
2650                 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2651
2652                 retVal =
2653                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2654                                            chunkInInode);
2655         }
2656         return retVal;
2657 }
2658
2659 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
2660                                           yaffs_ExtendedTags * tags)
2661 {
2662         /* Get the Tnode, then get the level 0 offset chunk offset */
2663         yaffs_Tnode *tn;
2664         int theChunk = -1;
2665         yaffs_ExtendedTags localTags;
2666
2667         yaffs_Device *dev = in->myDev;
2668         int retVal = -1;
2669
2670         if (!tags) {
2671                 /* Passed a NULL, so use our own tags space */
2672                 tags = &localTags;
2673         }
2674
2675         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2676
2677         if (tn) {
2678
2679                 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2680
2681                 retVal =
2682                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2683                                            chunkInInode);
2684
2685                 /* Delete the entry in the filestructure (if found) */
2686                 if (retVal != -1) {
2687                         yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
2688                 }
2689         } else {
2690                 /*T(("No level 0 found for %d\n", chunkInInode)); */
2691         }
2692
2693         if (retVal == -1) {
2694                 /* T(("Could not find %d to delete\n",chunkInInode)); */
2695         }
2696         return retVal;
2697 }
2698
2699 #ifdef YAFFS_PARANOID
2700
2701 static int yaffs_CheckFileSanity(yaffs_Object * in)
2702 {
2703         int chunk;
2704         int nChunks;
2705         int fSize;
2706         int failed = 0;
2707         int objId;
2708         yaffs_Tnode *tn;
2709         yaffs_Tags localTags;
2710         yaffs_Tags *tags = &localTags;
2711         int theChunk;
2712         int chunkDeleted;
2713
2714         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2715                 /* T(("Object not a file\n")); */
2716                 return YAFFS_FAIL;
2717         }
2718
2719         objId = in->objectId;
2720         fSize = in->variant.fileVariant.fileSize;
2721         nChunks =
2722             (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
2723
2724         for (chunk = 1; chunk <= nChunks; chunk++) {
2725                 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
2726                                            chunk);
2727
2728                 if (tn) {
2729
2730                         theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
2731
2732                         if (yaffs_CheckChunkBits
2733                             (dev, theChunk / dev->nChunksPerBlock,
2734                              theChunk % dev->nChunksPerBlock)) {
2735
2736                                 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
2737                                                             tags,
2738                                                             &chunkDeleted);
2739                                 if (yaffs_TagsMatch
2740                                     (tags, in->objectId, chunk, chunkDeleted)) {
2741                                         /* found it; */
2742
2743                                 }
2744                         } else {
2745
2746                                 failed = 1;
2747                         }
2748
2749                 } else {
2750                         /* T(("No level 0 found for %d\n", chunk)); */
2751                 }
2752         }
2753
2754         return failed ? YAFFS_FAIL : YAFFS_OK;
2755 }
2756
2757 #endif
2758
2759 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
2760                                   int chunkInNAND, int inScan)
2761 {
2762         /* NB inScan is zero unless scanning. 
2763          * For forward scanning, inScan is > 0; 
2764          * for backward scanning inScan is < 0
2765          */
2766          
2767         yaffs_Tnode *tn;
2768         yaffs_Device *dev = in->myDev;
2769         int existingChunk;
2770         yaffs_ExtendedTags existingTags;
2771         yaffs_ExtendedTags newTags;
2772         unsigned existingSerial, newSerial;
2773
2774         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2775                 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2776                  * If it is not during Scanning then something went wrong!
2777                  */
2778                 if (!inScan) {
2779                         T(YAFFS_TRACE_ERROR,
2780                           (TSTR
2781                            ("yaffs tragedy:attempt to put data chunk into a non-file"
2782                             TENDSTR)));
2783                         YBUG();
2784                 }
2785
2786                 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
2787                 return YAFFS_OK;
2788         }
2789
2790         tn = yaffs_AddOrFindLevel0Tnode(dev, 
2791                                         &in->variant.fileVariant,
2792                                         chunkInInode,
2793                                         NULL);
2794         if (!tn) {
2795                 return YAFFS_FAIL;
2796         }
2797
2798         existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
2799
2800         if (inScan != 0) {
2801                 /* If we're scanning then we need to test for duplicates
2802                  * NB This does not need to be efficient since it should only ever 
2803                  * happen when the power fails during a write, then only one
2804                  * chunk should ever be affected.
2805                  *
2806                  * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2807                  * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2808                  */
2809
2810                 if (existingChunk != 0) {
2811                         /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
2812                          *    thus we have to do a FindChunkInFile to get the real chunk id.
2813                          *
2814                          * We have a duplicate now we need to decide which one to use:
2815                          *
2816                          * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2817                          * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2818                          * YAFFS1: Get both sets of tags and compare serial numbers.
2819                          */
2820
2821                         if (inScan > 0) {
2822                                 /* Only do this for forward scanning */
2823                                 yaffs_ReadChunkWithTagsFromNAND(dev,
2824                                                                 chunkInNAND,
2825                                                                 NULL, &newTags);
2826
2827                                 /* Do a proper find */
2828                                 existingChunk =
2829                                     yaffs_FindChunkInFile(in, chunkInInode,
2830                                                           &existingTags);
2831                         }
2832
2833                         if (existingChunk <= 0) {
2834                                 /*Hoosterman - how did this happen? */
2835
2836                                 T(YAFFS_TRACE_ERROR,
2837                                   (TSTR
2838                                    ("yaffs tragedy: existing chunk < 0 in scan"
2839                                     TENDSTR)));
2840
2841                         }
2842
2843                         /* NB The deleted flags should be false, otherwise the chunks will 
2844                          * not be loaded during a scan
2845                          */
2846
2847                         newSerial = newTags.serialNumber;
2848                         existingSerial = existingTags.serialNumber;
2849
2850                         if ((inScan > 0) &&
2851                             (in->myDev->isYaffs2 ||
2852                              existingChunk <= 0 ||
2853                              ((existingSerial + 1) & 3) == newSerial)) {
2854                                 /* Forward scanning.                            
2855                                  * Use new
2856                                  * Delete the old one and drop through to update the tnode
2857                                  */
2858                                 yaffs_DeleteChunk(dev, existingChunk, 1,
2859                                                   __LINE__);
2860                         } else {
2861                                 /* Backward scanning or we want to use the existing one
2862                                  * Use existing.
2863                                  * Delete the new one and return early so that the tnode isn't changed
2864                                  */
2865                                 yaffs_DeleteChunk(dev, chunkInNAND, 1,
2866                                                   __LINE__);
2867                                 return YAFFS_OK;
2868                         }
2869                 }
2870
2871         }
2872
2873         if (existingChunk == 0) {
2874                 in->nDataChunks++;
2875         }
2876
2877         yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
2878
2879         return YAFFS_OK;
2880 }
2881
2882 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
2883                                          __u8 * buffer)
2884 {
2885         int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
2886
2887         if (chunkInNAND >= 0) {
2888                 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
2889                                                        buffer,NULL);
2890         } else {
2891                 T(YAFFS_TRACE_NANDACCESS,
2892                   (TSTR("Chunk %d not found zero instead" TENDSTR),
2893                    chunkInNAND));
2894                 /* get sane (zero) data if you read a hole */
2895                 memset(buffer, 0, in->myDev->nDataBytesPerChunk);       
2896                 return 0;
2897         }
2898
2899 }
2900
2901 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
2902 {
2903         int block;
2904         int page;
2905         yaffs_ExtendedTags tags;
2906         yaffs_BlockInfo *bi;
2907
2908         if (chunkId <= 0)
2909                 return;
2910
2911         dev->nDeletions++;
2912         block = chunkId / dev->nChunksPerBlock;
2913         page = chunkId % dev->nChunksPerBlock;
2914
2915         bi = yaffs_GetBlockInfo(dev, block);
2916
2917         T(YAFFS_TRACE_DELETION,
2918           (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
2919
2920         if (markNAND &&
2921             bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
2922
2923                 yaffs_InitialiseTags(&tags);
2924
2925                 tags.chunkDeleted = 1;
2926
2927                 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
2928                 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
2929         } else {
2930                 dev->nUnmarkedDeletions++;
2931         }
2932
2933         /* Pull out of the management area.
2934          * If the whole block became dirty, this will kick off an erasure.
2935          */
2936         if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2937             bi->blockState == YAFFS_BLOCK_STATE_FULL ||
2938             bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2939             bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2940                 dev->nFreeChunks++;
2941
2942                 yaffs_ClearChunkBit(dev, block, page);
2943
2944                 bi->pagesInUse--;
2945
2946                 if (bi->pagesInUse == 0 &&
2947                     !bi->hasShrinkHeader &&
2948                     bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
2949                     bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2950                         yaffs_BlockBecameDirty(dev, block);
2951                 }
2952
2953         } else {
2954                 /* T(("Bad news deleting chunk %d\n",chunkId)); */
2955         }
2956
2957 }
2958
2959 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
2960                                         const __u8 * buffer, int nBytes,
2961                                         int useReserve)
2962 {
2963         /* Find old chunk Need to do this to get serial number
2964          * Write new one and patch into tree.
2965          * Invalidate old tags.
2966          */
2967
2968         int prevChunkId;
2969         yaffs_ExtendedTags prevTags;
2970
2971         int newChunkId;
2972         yaffs_ExtendedTags newTags;
2973
2974         yaffs_Device *dev = in->myDev;
2975
2976         yaffs_CheckGarbageCollection(dev);
2977
2978         /* Get the previous chunk at this location in the file if it exists */
2979         prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
2980
2981         /* Set up new tags */
2982         yaffs_InitialiseTags(&newTags);
2983
2984         newTags.chunkId = chunkInInode;
2985         newTags.objectId = in->objectId;
2986         newTags.serialNumber =
2987             (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
2988         newTags.byteCount = nBytes;
2989
2990         newChunkId =
2991             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2992                                               useReserve);
2993
2994         if (newChunkId >= 0) {
2995                 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
2996
2997                 if (prevChunkId >= 0) {
2998                         yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
2999
3000                 }
3001
3002                 yaffs_CheckFileSanity(in);
3003         }
3004         return newChunkId;
3005
3006 }
3007
3008 /* UpdateObjectHeader updates the header on NAND for an object.
3009  * If name is not NULL, then that new name is used.
3010  */
3011 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
3012                              int isShrink, int shadows)
3013 {
3014
3015         yaffs_BlockInfo *bi;
3016
3017         yaffs_Device *dev = in->myDev;
3018
3019         int prevChunkId;
3020         int retVal = 0;
3021         int result = 0;
3022
3023         int newChunkId;
3024         yaffs_ExtendedTags newTags;
3025
3026         __u8 *buffer = NULL;
3027         YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3028
3029         yaffs_ObjectHeader *oh = NULL;
3030
3031         if (!in->fake || force) {
3032
3033                 yaffs_CheckGarbageCollection(dev);
3034
3035                 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3036                 oh = (yaffs_ObjectHeader *) buffer;
3037
3038                 prevChunkId = in->chunkId;
3039
3040                 if (prevChunkId >= 0) {
3041                         result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3042                                                         buffer, NULL);
3043                         memcpy(oldName, oh->name, sizeof(oh->name));
3044                 }
3045
3046                 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3047
3048                 oh->type = in->variantType;
3049                 oh->yst_mode = in->yst_mode;
3050                 oh->shadowsObject = shadows;
3051
3052 #ifdef CONFIG_YAFFS_WINCE
3053                 oh->win_atime[0] = in->win_atime[0];
3054                 oh->win_ctime[0] = in->win_ctime[0];
3055                 oh->win_mtime[0] = in->win_mtime[0];
3056                 oh->win_atime[1] = in->win_atime[1];
3057                 oh->win_ctime[1] = in->win_ctime[1];
3058                 oh->win_mtime[1] = in->win_mtime[1];
3059 #else
3060                 oh->yst_uid = in->yst_uid;
3061                 oh->yst_gid = in->yst_gid;
3062                 oh->yst_atime = in->yst_atime;
3063                 oh->yst_mtime = in->yst_mtime;
3064                 oh->yst_ctime = in->yst_ctime;
3065                 oh->yst_rdev = in->yst_rdev;
3066 #endif
3067                 if (in->parent) {
3068                         oh->parentObjectId = in->parent->objectId;
3069                 } else {
3070                         oh->parentObjectId = 0;
3071                 }
3072
3073                 if (name && *name) {
3074                         memset(oh->name, 0, sizeof(oh->name));
3075                         yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3076                 } else if (prevChunkId) {
3077                         memcpy(oh->name, oldName, sizeof(oh->name));
3078                 } else {
3079                         memset(oh->name, 0, sizeof(oh->name));
3080                 }
3081
3082                 oh->isShrink = isShrink;
3083
3084                 switch (in->variantType) {
3085                 case YAFFS_OBJECT_TYPE_UNKNOWN:
3086                         /* Should not happen */
3087                         break;
3088                 case YAFFS_OBJECT_TYPE_FILE:
3089                         oh->fileSize =
3090                             (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3091                              || oh->parentObjectId ==
3092                              YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3093                             fileVariant.fileSize;
3094                         break;
3095                 case YAFFS_OBJECT_TYPE_HARDLINK:
3096                         oh->equivalentObjectId =
3097                             in->variant.hardLinkVariant.equivalentObjectId;
3098                         break;
3099                 case YAFFS_OBJECT_TYPE_SPECIAL:
3100                         /* Do nothing */
3101                         break;
3102                 case YAFFS_OBJECT_TYPE_DIRECTORY:
3103                         /* Do nothing */
3104                         break;
3105                 case YAFFS_OBJECT_TYPE_SYMLINK:
3106                         yaffs_strncpy(oh->alias,
3107                                       in->variant.symLinkVariant.alias,
3108                                       YAFFS_MAX_ALIAS_LENGTH);
3109                         oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3110                         break;
3111                 }
3112
3113                 /* Tags */
3114                 yaffs_InitialiseTags(&newTags);
3115                 in->serial++;
3116                 newTags.chunkId = 0;
3117                 newTags.objectId = in->objectId;
3118                 newTags.serialNumber = in->serial;
3119
3120                 /* Add extra info for file header */
3121
3122                 newTags.extraHeaderInfoAvailable = 1;
3123                 newTags.extraParentObjectId = oh->parentObjectId;
3124                 newTags.extraFileLength = oh->fileSize;
3125                 newTags.extraIsShrinkHeader = oh->isShrink;
3126                 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3127                 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3128                 newTags.extraObjectType = in->variantType;
3129
3130                 /* Create new chunk in NAND */
3131                 newChunkId =
3132                     yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3133                                                       (prevChunkId >= 0) ? 1 : 0);
3134
3135                 if (newChunkId >= 0) {
3136
3137                         in->chunkId = newChunkId;
3138
3139                         if (prevChunkId >= 0) {
3140                                 yaffs_DeleteChunk(dev, prevChunkId, 1,
3141                                                   __LINE__);
3142                         }
3143
3144                         if(!yaffs_ObjectHasCachedWriteData(in))
3145                                 in->dirty = 0;
3146
3147                         /* If this was a shrink, then mark the block that the chunk lives on */
3148                         if (isShrink) {
3149                                 bi = yaffs_GetBlockInfo(in->myDev,
3150                                                         newChunkId /in->myDev-> nChunksPerBlock);
3151                                 bi->hasShrinkHeader = 1;
3152                         }
3153
3154                 }
3155
3156                 retVal = newChunkId;
3157
3158         }
3159
3160         if (buffer)
3161                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3162
3163         return retVal;
3164 }
3165
3166 /*------------------------ Short Operations Cache ----------------------------------------
3167  *   In many situations where there is no high level buffering (eg WinCE) a lot of
3168  *   reads might be short sequential reads, and a lot of writes may be short 
3169  *   sequential writes. eg. scanning/writing a jpeg file.
3170  *   In these cases, a short read/write cache can provide a huge perfomance benefit 
3171  *   with dumb-as-a-rock code.
3172  *   In Linux, the page cache provides read buffering aand the short op cache provides write 
3173  *   buffering.
3174  *
3175  *   There are a limited number (~10) of cache chunks per device so that we don't
3176  *   need a very intelligent search.
3177  */
3178
3179 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3180 {
3181         yaffs_Device *dev = obj->myDev;
3182         int i;
3183         yaffs_ChunkCache *cache;
3184         int nCaches = obj->myDev->nShortOpCaches;
3185         
3186         for(i = 0; i < nCaches; i++){
3187                 cache = &dev->srCache[i];
3188                 if (cache->object == obj &&
3189                     cache->dirty)
3190                         return 1;
3191         }
3192         
3193         return 0;
3194 }
3195
3196
3197 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3198 {
3199         yaffs_Device *dev = obj->myDev;
3200         int lowest = -99;       /* Stop compiler whining. */
3201         int i;
3202         yaffs_ChunkCache *cache;
3203         int chunkWritten = 0;
3204         int nCaches = obj->myDev->nShortOpCaches;
3205
3206         if (nCaches > 0) {
3207                 do {
3208                         cache = NULL;
3209
3210                         /* Find the dirty cache for this object with the lowest chunk id. */
3211                         for (i = 0; i < nCaches; i++) {
3212                                 if (dev->srCache[i].object == obj &&
3213                                     dev->srCache[i].dirty) {
3214                                         if (!cache
3215                                             || dev->srCache[i].chunkId <
3216                                             lowest) {
3217                                                 cache = &dev->srCache[i];
3218                                                 lowest = cache->chunkId;
3219                                         }
3220                                 }
3221                         }
3222
3223                         if (cache && !cache->locked) {
3224                                 /* Write it out and free it up */
3225
3226                                 chunkWritten =
3227                                     yaffs_WriteChunkDataToObject(cache->object,
3228                                                                  cache->chunkId,
3229                                                                  cache->data,
3230                                                                  cache->nBytes,
3231                                                                  1);
3232                                 cache->dirty = 0;
3233                                 cache->object = NULL;
3234                         }
3235
3236                 } while (cache && chunkWritten > 0);
3237
3238                 if (cache) {
3239                         /* Hoosterman, disk full while writing cache out. */
3240                         T(YAFFS_TRACE_ERROR,
3241                           (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3242
3243                 }
3244         }
3245
3246 }
3247
3248 /*yaffs_FlushEntireDeviceCache(dev)
3249  *
3250  *
3251  */
3252
3253 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3254 {
3255         yaffs_Object *obj;
3256         int nCaches = dev->nShortOpCaches;
3257         int i;
3258         
3259         /* Find a dirty object in the cache and flush it...
3260          * until there are no further dirty objects.
3261          */
3262         do {
3263                 obj = NULL;
3264                 for( i = 0; i < nCaches && !obj; i++) {
3265                         if (dev->srCache[i].object &&
3266                             dev->srCache[i].dirty)
3267                                 obj = dev->srCache[i].object;
3268                             
3269                 }
3270                 if(obj)
3271                         yaffs_FlushFilesChunkCache(obj);
3272                         
3273         } while(obj);
3274         
3275 }
3276
3277
3278 /* Grab us a cache chunk for use.
3279  * First look for an empty one. 
3280  * Then look for the least recently used non-dirty one.
3281  * Then look for the least recently used dirty one...., flush and look again.
3282  */
3283 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
3284 {
3285         int i;
3286         int usage;
3287         int theOne;
3288
3289         if (dev->nShortOpCaches > 0) {
3290                 for (i = 0; i < dev->nShortOpCaches; i++) {
3291                         if (!dev->srCache[i].object) 
3292                                 return &dev->srCache[i];
3293                 }
3294
3295                 return NULL;
3296
3297                 theOne = -1;
3298                 usage = 0;      /* just to stop the compiler grizzling */
3299
3300                 for (i = 0; i < dev->nShortOpCaches; i++) {
3301                         if (!dev->srCache[i].dirty &&
3302                             ((dev->srCache[i].lastUse < usage && theOne >= 0) ||
3303                              theOne < 0)) {
3304                                 usage = dev->srCache[i].lastUse;
3305                                 theOne = i;
3306                         }
3307                 }
3308
3309
3310                 return theOne >= 0 ? &dev->srCache[theOne] : NULL;
3311         } else {
3312                 return NULL;
3313         }
3314
3315 }
3316
3317 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
3318 {
3319         yaffs_ChunkCache *cache;
3320         yaffs_Object *theObj;
3321         int usage;
3322         int i;
3323         int pushout;
3324
3325         if (dev->nShortOpCaches > 0) {
3326                 /* Try find a non-dirty one... */
3327
3328                 cache = yaffs_GrabChunkCacheWorker(dev);
3329
3330                 if (!cache) {
3331                         /* They were all dirty, find the last recently used object and flush
3332                          * its cache, then  find again.
3333                          * NB what's here is not very accurate, we actually flush the object
3334                          * the last recently used page.
3335                          */
3336
3337                         /* With locking we can't assume we can use entry zero */
3338
3339                         theObj = NULL;
3340                         usage = -1;
3341                         cache = NULL;
3342                         pushout = -1;
3343
3344                         for (i = 0; i < dev->nShortOpCaches; i++) {
3345                                 if (dev->srCache[i].object &&
3346                                     !dev->srCache[i].locked &&
3347                                     (dev->srCache[i].lastUse < usage || !cache))
3348                                 {
3349                                         usage = dev->srCache[i].lastUse;
3350                                         theObj = dev->srCache[i].object;
3351                                         cache = &dev->srCache[i];
3352                                         pushout = i;
3353                                 }
3354                         }
3355
3356                         if (!cache || cache->dirty) {
3357                                 /* Flush and try again */
3358                                 yaffs_FlushFilesChunkCache(theObj);
3359                                 cache = yaffs_GrabChunkCacheWorker(dev);
3360                         }
3361
3362                 }
3363                 return cache;
3364         } else
3365                 return NULL;
3366
3367 }
3368
3369 /* Find a cached chunk */
3370 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
3371                                               int chunkId)
3372 {
3373         yaffs_Device *dev = obj->myDev;
3374         int i;
3375         if (dev->nShortOpCaches > 0) {
3376                 for (i = 0; i < dev->nShortOpCaches; i++) {
3377                         if (dev->srCache[i].object == obj &&
3378                             dev->srCache[i].chunkId == chunkId) {
3379                                 dev->cacheHits++;
3380
3381                                 return &dev->srCache[i];
3382                         }
3383                 }
3384         }
3385         return NULL;
3386 }
3387
3388 /* Mark the chunk for the least recently used algorithym */
3389 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
3390                                 int isAWrite)
3391 {
3392
3393         if (dev->nShortOpCaches > 0) {
3394                 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
3395                         /* Reset the cache usages */
3396                         int i;
3397                         for (i = 1; i < dev->nShortOpCaches; i++) {
3398                                 dev->srCache[i].lastUse = 0;
3399                         }
3400                         dev->srLastUse = 0;
3401                 }
3402
3403                 dev->srLastUse++;
3404
3405                 cache->lastUse = dev->srLastUse;
3406
3407                 if (isAWrite) {
3408                         cache->dirty = 1;
3409                 }
3410         }
3411 }
3412
3413 /* Invalidate a single cache page.
3414  * Do this when a whole page gets written,
3415  * ie the short cache for this page is no longer valid.
3416  */
3417 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
3418 {
3419         if (object->myDev->nShortOpCaches > 0) {
3420                 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
3421
3422                 if (cache) {
3423                         cache->object = NULL;
3424                 }
3425         }
3426 }
3427
3428 /* Invalidate all the cache pages associated with this object
3429  * Do this whenever ther file is deleted or resized.
3430  */
3431 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
3432 {
3433         int i;
3434         yaffs_Device *dev = in->myDev;
3435
3436         if (dev->nShortOpCaches > 0) {
3437                 /* Invalidate it. */
3438                 for (i = 0; i < dev->nShortOpCaches; i++) {
3439                         if (dev->srCache[i].object == in) {
3440                                 dev->srCache[i].object = NULL;
3441                         }
3442                 }
3443         }
3444 }
3445
3446 /*--------------------- Checkpointing --------------------*/
3447
3448
3449 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
3450 {
3451         yaffs_CheckpointValidity cp;
3452         cp.structType = sizeof(cp);
3453         cp.magic = YAFFS_MAGIC;
3454         cp.version = YAFFS_CHECKPOINT_VERSION;
3455         cp.head = (head) ? 1 : 0;
3456         
3457         return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
3458                 1 : 0;
3459 }
3460
3461 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
3462 {
3463         yaffs_CheckpointValidity cp;
3464         int ok;
3465         
3466         ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3467         
3468         if(ok)
3469                 ok = (cp.structType == sizeof(cp)) &&
3470                      (cp.magic == YAFFS_MAGIC) &&
3471                      (cp.version == YAFFS_CHECKPOINT_VERSION) &&
3472                      (cp.head == ((head) ? 1 : 0));
3473         return ok ? 1 : 0;
3474 }
3475
3476 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp, 
3477                                            yaffs_Device *dev)
3478 {
3479         cp->nErasedBlocks = dev->nErasedBlocks;
3480         cp->allocationBlock = dev->allocationBlock;
3481         cp->allocationPage = dev->allocationPage;
3482         cp->nFreeChunks = dev->nFreeChunks;
3483         
3484         cp->nDeletedFiles = dev->nDeletedFiles;
3485         cp->nUnlinkedFiles = dev->nUnlinkedFiles;
3486         cp->nBackgroundDeletions = dev->nBackgroundDeletions;
3487         cp->sequenceNumber = dev->sequenceNumber;
3488         cp->oldestDirtySequence = dev->oldestDirtySequence;
3489         
3490 }
3491
3492 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
3493                                            yaffs_CheckpointDevice *cp)
3494 {
3495         dev->nErasedBlocks = cp->nErasedBlocks;
3496         dev->allocationBlock = cp->allocationBlock;
3497         dev->allocationPage = cp->allocationPage;
3498         dev->nFreeChunks = cp->nFreeChunks;
3499         
3500         dev->nDeletedFiles = cp->nDeletedFiles;
3501         dev->nUnlinkedFiles = cp->nUnlinkedFiles;
3502         dev->nBackgroundDeletions = cp->nBackgroundDeletions;
3503         dev->sequenceNumber = cp->sequenceNumber;
3504         dev->oldestDirtySequence = cp->oldestDirtySequence;
3505 }
3506
3507
3508 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
3509 {
3510         yaffs_CheckpointDevice cp;
3511         __u32 nBytes;
3512         __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
3513
3514         int ok;
3515                 
3516         /* Write device runtime values*/
3517         yaffs_DeviceToCheckpointDevice(&cp,dev);
3518         cp.structType = sizeof(cp);
3519         
3520         ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3521         
3522         /* Write block info */
3523         if(ok) {
3524                 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
3525                 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
3526         }
3527                 
3528         /* Write chunk bits */          
3529         if(ok) {
3530                 nBytes = nBlocks * dev->chunkBitmapStride;
3531                 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
3532         }
3533         return   ok ? 1 : 0;
3534
3535 }
3536
3537 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
3538 {
3539         yaffs_CheckpointDevice cp;
3540         __u32 nBytes;
3541         __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
3542
3543         int ok; 
3544         
3545         ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3546         if(!ok)
3547                 return 0;
3548                 
3549         if(cp.structType != sizeof(cp))
3550                 return 0;
3551                 
3552         
3553         yaffs_CheckpointDeviceToDevice(dev,&cp);
3554         
3555         nBytes = nBlocks * sizeof(yaffs_BlockInfo);
3556         
3557         ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
3558         
3559         if(!ok)
3560                 return 0;
3561         nBytes = nBlocks * dev->chunkBitmapStride;
3562         
3563         ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
3564         
3565         return ok ? 1 : 0;
3566 }
3567
3568 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
3569                                            yaffs_Object *obj)
3570 {
3571
3572         cp->objectId = obj->objectId;
3573         cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
3574         cp->chunkId = obj->chunkId;
3575         cp->variantType = obj->variantType;                     
3576         cp->deleted = obj->deleted;
3577         cp->softDeleted = obj->softDeleted;
3578         cp->unlinked = obj->unlinked;
3579         cp->fake = obj->fake;
3580         cp->renameAllowed = obj->renameAllowed;
3581         cp->unlinkAllowed = obj->unlinkAllowed;
3582         cp->serial = obj->serial;
3583         cp->nDataChunks = obj->nDataChunks;
3584         
3585         if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
3586                 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
3587         else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3588                 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
3589 }
3590
3591 static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
3592 {
3593
3594         yaffs_Object *parent;
3595         
3596         obj->objectId = cp->objectId;
3597         
3598         if(cp->parentId)
3599                 parent = yaffs_FindOrCreateObjectByNumber(
3600                                         obj->myDev,
3601                                         cp->parentId,
3602                                         YAFFS_OBJECT_TYPE_DIRECTORY);
3603         else
3604                 parent = NULL;
3605                 
3606         if(parent)
3607                 yaffs_AddObjectToDirectory(parent, obj);
3608                 
3609         obj->chunkId = cp->chunkId;
3610         obj->variantType = cp->variantType;                     
3611         obj->deleted = cp->deleted;
3612         obj->softDeleted = cp->softDeleted;
3613         obj->unlinked = cp->unlinked;
3614         obj->fake = cp->fake;
3615         obj->renameAllowed = cp->renameAllowed;
3616         obj->unlinkAllowed = cp->unlinkAllowed;
3617         obj->serial = cp->serial;
3618         obj->nDataChunks = cp->nDataChunks;
3619         
3620         if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
3621                 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
3622         else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
3623                 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
3624                 
3625         if(obj->objectId >= YAFFS_NOBJECT_BUCKETS)
3626                 obj->lazyLoaded = 1;
3627 }
3628
3629
3630
3631 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
3632                                         __u32 level, int chunkOffset)
3633 {
3634         int i;
3635         yaffs_Device *dev = in->myDev;
3636         int ok = 1;
3637         int nTnodeBytes = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
3638
3639         if (tn) {
3640                 if (level > 0) {
3641
3642                         for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
3643                                 if (tn->internal[i]) {
3644                                         ok = yaffs_CheckpointTnodeWorker(in,
3645                                                         tn->internal[i],
3646                                                         level - 1,
3647                                                         (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
3648                                 }
3649                         }
3650                 } else if (level == 0) {
3651                         __u32 baseOffset = chunkOffset <<  YAFFS_TNODES_LEVEL0_BITS;
3652                         /* printf("write tnode at %d\n",baseOffset); */
3653                         ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
3654                         if(ok)
3655                                 ok = (yaffs_CheckpointWrite(dev,tn,nTnodeBytes) == nTnodeBytes);
3656                 }
3657         }
3658
3659         return ok;
3660
3661 }
3662
3663 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
3664 {
3665         __u32 endMarker = ~0;
3666         int ok = 1;
3667         
3668         if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
3669                 ok = yaffs_CheckpointTnodeWorker(obj,
3670                                             obj->variant.fileVariant.top,
3671                                             obj->variant.fileVariant.topLevel,
3672                                             0);
3673                 if(ok)
3674                         ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) == 
3675                                 sizeof(endMarker));
3676         }
3677         
3678         return ok ? 1 : 0;
3679 }
3680
3681 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
3682 {
3683         __u32 baseChunk;
3684         int ok = 1;
3685         yaffs_Device *dev = obj->myDev;
3686         yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
3687         yaffs_Tnode *tn;
3688         
3689         ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
3690         
3691         while(ok && (~baseChunk)){
3692                 /* Read level 0 tnode */
3693                 
3694                 /* printf("read  tnode at %d\n",baseChunk); */
3695                 tn = yaffs_GetTnodeRaw(dev);
3696                 if(tn)
3697                         ok = (yaffs_CheckpointRead(dev,tn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8) ==
3698                               (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
3699                 else
3700                         ok = 0;
3701                         
3702                 if(tn && ok){
3703                         ok = yaffs_AddOrFindLevel0Tnode(dev,
3704                                                         fileStructPtr,
3705                                                         baseChunk,
3706                                                         tn) ? 1 : 0;
3707                 }
3708                         
3709                 if(ok)
3710                         ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
3711                 
3712         }
3713
3714         return ok ? 1 : 0;      
3715 }
3716  
3717
3718 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
3719 {
3720         yaffs_Object *obj;
3721         yaffs_CheckpointObject cp;
3722         int i;
3723         int ok = 1;
3724         struct list_head *lh;
3725
3726         
3727         /* Iterate through the objects in each hash entry,
3728          * dumping them to the checkpointing stream.
3729          */
3730          
3731          for(i = 0; ok &&  i <  YAFFS_NOBJECT_BUCKETS; i++){
3732                 list_for_each(lh, &dev->objectBucket[i].list) {
3733                         if (lh) {
3734                                 obj = list_entry(lh, yaffs_Object, hashLink);
3735                                 if (!obj->deferedFree) {
3736                                         yaffs_ObjectToCheckpointObject(&cp,obj);
3737                                         cp.structType = sizeof(cp);
3738
3739                                         T(YAFFS_TRACE_CHECKPOINT,(
3740                                                 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
3741                                                 cp.objectId,cp.parentId,cp.variantType,cp.chunkId,(unsigned) obj));
3742                                                 
3743                                         ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3744                                         
3745                                         if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
3746                                                 ok = yaffs_WriteCheckpointTnodes(obj);
3747                                         }
3748                                 }
3749                         }
3750                 }
3751          }
3752          
3753          /* Dump end of list */
3754         memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
3755         cp.structType = sizeof(cp);
3756         
3757         if(ok)
3758                 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
3759                 
3760         return ok ? 1 : 0;
3761 }
3762
3763 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
3764 {
3765         yaffs_Object *obj;
3766         yaffs_CheckpointObject cp;
3767         int ok = 1;
3768         int done = 0;
3769         yaffs_Object *hardList = NULL;
3770         
3771         while(ok && !done) {
3772                 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
3773                 if(cp.structType != sizeof(cp)) {
3774                         /* printf("structure parsing failed\n"); */
3775                         ok = 0;
3776                 }
3777                         
3778                 if(ok && cp.objectId == ~0)
3779                         done = 1;
3780                 else if(ok){
3781                         obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
3782                         T(YAFFS_TRACE_CHECKPOINT,(TSTR("Checkpoint read object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
3783                                 cp.objectId,cp.parentId,cp.variantType,cp.chunkId,(unsigned) obj));
3784                         if(obj) {
3785                                 yaffs_CheckpointObjectToObject(obj,&cp);
3786                                 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
3787                                         ok = yaffs_ReadCheckpointTnodes(obj);
3788                                 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
3789                                         obj->hardLinks.next =
3790                                                     (struct list_head *)
3791                                                     hardList;
3792                                         hardList = obj;
3793                                 }
3794                            
3795                         }
3796                 }
3797         }
3798         
3799         if(ok)
3800                 yaffs_HardlinkFixup(dev,hardList);
3801         
3802         return ok ? 1 : 0;
3803 }
3804
3805 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
3806 {
3807
3808         int ok;
3809         
3810         ok = yaffs_CheckpointOpen(dev,1);
3811         
3812         if(ok)
3813                 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
3814         if(ok)
3815                 ok = yaffs_WriteCheckpointDevice(dev);
3816         if(ok)
3817                 ok = yaffs_WriteCheckpointObjects(dev);
3818         if(ok)
3819                 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
3820                 
3821         if(!yaffs_CheckpointClose(dev))
3822                  ok = 0;
3823                  
3824         if(ok)
3825                 dev->isCheckpointed = 1;
3826          else 
3827                 dev->isCheckpointed = 0;
3828
3829         return dev->isCheckpointed;
3830 }
3831
3832 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
3833 {
3834         int ok;
3835         
3836         ok = yaffs_CheckpointOpen(dev,0); /* open for read */
3837         
3838         if(ok)
3839                 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
3840         if(ok)
3841                 ok = yaffs_ReadCheckpointDevice(dev);
3842         if(ok)
3843                 ok = yaffs_ReadCheckpointObjects(dev);
3844         if(ok)
3845                 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
3846                 
3847
3848
3849         if(!yaffs_CheckpointClose(dev))
3850                 ok = 0;
3851
3852         if(ok)
3853                 dev->isCheckpointed = 1;
3854          else 
3855                 dev->isCheckpointed = 0;
3856
3857         return ok ? 1 : 0;
3858
3859 }
3860
3861 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
3862 {
3863         if(dev->isCheckpointed || 
3864            dev->blocksInCheckpoint > 0){
3865                 dev->isCheckpointed = 0;
3866                 yaffs_CheckpointInvalidateStream(dev);
3867                 if(dev->superBlock && dev->markSuperBlockDirty)
3868