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