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