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