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