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