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