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