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