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