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