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