Add YYIELD to yaffs_Scan loop
[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.56 2008-05-08 23:23:26 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 = (obj->chunkId >= chunkMin && obj->chunkId <= chunkMax);
775         chunkIsLive = chunkIdOk &&
776                         yaffs_CheckChunkBit(dev,
777                                             obj->chunkId / dev->nChunksPerBlock,
778                                             obj->chunkId % 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->chunkId,
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->chunkId,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  */
880
881 yaffs_Object *yaffs_Root(yaffs_Device * dev)
882 {
883         return dev->rootDir;
884 }
885
886 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
887 {
888         return dev->lostNFoundDir;
889 }
890
891
892 /*
893  *  Erased NAND checking functions
894  */
895
896 int yaffs_CheckFF(__u8 * buffer, int nBytes)
897 {
898         /* Horrible, slow implementation */
899         while (nBytes--) {
900                 if (*buffer != 0xFF)
901                         return 0;
902                 buffer++;
903         }
904         return 1;
905 }
906
907 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
908                                   int chunkInNAND)
909 {
910
911         int retval = YAFFS_OK;
912         __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
913         yaffs_ExtendedTags tags;
914         int result;
915
916         result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
917
918         if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
919                 retval = YAFFS_FAIL;
920
921
922         if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
923                 T(YAFFS_TRACE_NANDACCESS,
924                   (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
925                 retval = YAFFS_FAIL;
926         }
927
928         yaffs_ReleaseTempBuffer(dev, data, __LINE__);
929
930         return retval;
931
932 }
933
934 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
935                                              const __u8 * data,
936                                              yaffs_ExtendedTags * tags,
937                                              int useReserve)
938 {
939         int attempts = 0;
940         int writeOk = 0;
941         int chunk;
942
943         yaffs_InvalidateCheckpoint(dev);
944
945         do {
946                 yaffs_BlockInfo *bi = 0;
947                 int erasedOk = 0;
948
949                 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
950                 if (chunk < 0) {
951                         /* no space */
952                         break;
953                 }
954
955                 /* First check this chunk is erased, if it needs
956                  * checking.  The checking policy (unless forced
957                  * always on) is as follows:
958                  *
959                  * Check the first page we try to write in a block.
960                  * If the check passes then we don't need to check any
961                  * more.        If the check fails, we check again...
962                  * If the block has been erased, we don't need to check.
963                  *
964                  * However, if the block has been prioritised for gc,
965                  * then we think there might be something odd about
966                  * this block and stop using it.
967                  *
968                  * Rationale: We should only ever see chunks that have
969                  * not been erased if there was a partially written
970                  * chunk due to power loss.  This checking policy should
971                  * catch that case with very few checks and thus save a
972                  * lot of checks that are most likely not needed.
973                  */
974                 if (bi->gcPrioritise) {
975                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
976                         /* try another chunk */
977                         continue;
978                 }
979
980                 /* let's give it a try */
981                 attempts++;
982
983 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
984                 bi->skipErasedCheck = 0;
985 #endif
986                 if (!bi->skipErasedCheck) {
987                         erasedOk = yaffs_CheckChunkErased(dev, chunk);
988                         if (erasedOk != YAFFS_OK) {
989                                 T(YAFFS_TRACE_ERROR,
990                                 (TSTR ("**>> yaffs chunk %d was not erased"
991                                 TENDSTR), chunk));
992
993                                 /* try another chunk */
994                                 continue;
995                         }
996                         bi->skipErasedCheck = 1;
997                 }
998
999                 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
1000                                 data, tags);
1001                 if (writeOk != YAFFS_OK) {
1002                         yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
1003                         /* try another chunk */
1004                         continue;
1005                 }
1006
1007                 /* Copy the data into the robustification buffer */
1008                 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1009
1010         } while (writeOk != YAFFS_OK &&
1011                 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1012
1013         if(!writeOk)
1014                 chunk = -1;
1015
1016         if (attempts > 1) {
1017                 T(YAFFS_TRACE_ERROR,
1018                         (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1019                         attempts));
1020
1021                 dev->nRetriedWrites += (attempts - 1);
1022         }
1023
1024         return chunk;
1025 }
1026
1027 /*
1028  * Block retiring for handling a broken block.
1029  */
1030
1031 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
1032 {
1033         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1034
1035         yaffs_InvalidateCheckpoint(dev);
1036
1037         yaffs_MarkBlockBad(dev, blockInNAND);
1038
1039         bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1040         bi->gcPrioritise = 0;
1041         bi->needsRetiring = 0;
1042
1043         dev->nRetiredBlocks++;
1044 }
1045
1046 /*
1047  * Functions for robustisizing TODO
1048  *
1049  */
1050
1051 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
1052                                      const __u8 * data,
1053                                      const yaffs_ExtendedTags * tags)
1054 {
1055 }
1056
1057 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
1058                                     const yaffs_ExtendedTags * tags)
1059 {
1060 }
1061
1062 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1063 {
1064         if(!bi->gcPrioritise){
1065                 bi->gcPrioritise = 1;
1066                 dev->hasPendingPrioritisedGCs = 1;
1067                 bi->chunkErrorStrikes ++;
1068
1069                 if(bi->chunkErrorStrikes > 3){
1070                         bi->needsRetiring = 1; /* Too many stikes, so retire this */
1071                         T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1072
1073                 }
1074
1075         }
1076 }
1077
1078 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
1079 {
1080
1081         int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1082         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1083
1084         yaffs_HandleChunkError(dev,bi);
1085
1086
1087         if(erasedOk ) {
1088                 /* Was an actual write failure, so mark the block for retirement  */
1089                 bi->needsRetiring = 1;
1090                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1091                   (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1092
1093
1094         }
1095
1096         /* Delete the chunk */
1097         yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1098 }
1099
1100
1101 /*---------------- Name handling functions ------------*/
1102
1103 static __u16 yaffs_CalcNameSum(const YCHAR * name)
1104 {
1105         __u16 sum = 0;
1106         __u16 i = 1;
1107
1108         YUCHAR *bname = (YUCHAR *) name;
1109         if (bname) {
1110                 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1111
1112 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1113                         sum += yaffs_toupper(*bname) * i;
1114 #else
1115                         sum += (*bname) * i;
1116 #endif
1117                         i++;
1118                         bname++;
1119                 }
1120         }
1121         return sum;
1122 }
1123
1124 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
1125 {
1126 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1127         if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
1128                 yaffs_strcpy(obj->shortName, name);
1129         } else {
1130                 obj->shortName[0] = _Y('\0');
1131         }
1132 #endif
1133         obj->sum = yaffs_CalcNameSum(name);
1134 }
1135
1136 /*-------------------- TNODES -------------------
1137
1138  * List of spare tnodes
1139  * The list is hooked together using the first pointer
1140  * in the tnode.
1141  */
1142
1143 /* yaffs_CreateTnodes creates a bunch more tnodes and
1144  * adds them to the tnode free list.
1145  * Don't use this function directly
1146  */
1147
1148 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
1149 {
1150         int i;
1151         int tnodeSize;
1152         yaffs_Tnode *newTnodes;
1153         __u8 *mem;
1154         yaffs_Tnode *curr;
1155         yaffs_Tnode *next;
1156         yaffs_TnodeList *tnl;
1157
1158         if (nTnodes < 1)
1159                 return YAFFS_OK;
1160
1161         /* Calculate the tnode size in bytes for variable width tnode support.
1162          * Must be a multiple of 32-bits  */
1163         tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1164
1165         if(tnodeSize < sizeof(yaffs_Tnode))
1166                 tnodeSize = sizeof(yaffs_Tnode);
1167
1168
1169         /* make these things */
1170
1171         newTnodes = YMALLOC(nTnodes * tnodeSize);
1172         mem = (__u8 *)newTnodes;
1173
1174         if (!newTnodes) {
1175                 T(YAFFS_TRACE_ERROR,
1176                   (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1177                 return YAFFS_FAIL;
1178         }
1179
1180         /* Hook them into the free list */
1181 #if 0
1182         for (i = 0; i < nTnodes - 1; i++) {
1183                 newTnodes[i].internal[0] = &newTnodes[i + 1];
1184 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1185                 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1186 #endif
1187         }
1188
1189         newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1190 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1191         newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1192 #endif
1193         dev->freeTnodes = newTnodes;
1194 #else
1195         /* New hookup for wide tnodes */
1196         for(i = 0; i < nTnodes -1; i++) {
1197                 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1198                 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1199                 curr->internal[0] = next;
1200         }
1201
1202         curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1203         curr->internal[0] = dev->freeTnodes;
1204         dev->freeTnodes = (yaffs_Tnode *)mem;
1205
1206 #endif
1207
1208
1209         dev->nFreeTnodes += nTnodes;
1210         dev->nTnodesCreated += nTnodes;
1211
1212         /* Now add this bunch of tnodes to a list for freeing up.
1213          * NB If we can't add this to the management list it isn't fatal
1214          * but it just means we can't free this bunch of tnodes later.
1215          */
1216
1217         tnl = YMALLOC(sizeof(yaffs_TnodeList));
1218         if (!tnl) {
1219                 T(YAFFS_TRACE_ERROR,
1220                   (TSTR
1221                    ("yaffs: Could not add tnodes to management list" TENDSTR)));
1222                    return YAFFS_FAIL;
1223
1224         } else {
1225                 tnl->tnodes = newTnodes;
1226                 tnl->next = dev->allocatedTnodeList;
1227                 dev->allocatedTnodeList = tnl;
1228         }
1229
1230         T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1231
1232         return YAFFS_OK;
1233 }
1234
1235 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1236
1237 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
1238 {
1239         yaffs_Tnode *tn = NULL;
1240
1241         /* If there are none left make more */
1242         if (!dev->freeTnodes) {
1243                 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1244         }
1245
1246         if (dev->freeTnodes) {
1247                 tn = dev->freeTnodes;
1248 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1249                 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1250                         /* Hoosterman, this thing looks like it isn't in the list */
1251                         T(YAFFS_TRACE_ALWAYS,
1252                           (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1253                 }
1254 #endif
1255                 dev->freeTnodes = dev->freeTnodes->internal[0];
1256                 dev->nFreeTnodes--;
1257         }
1258
1259         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1260
1261         return tn;
1262 }
1263
1264 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
1265 {
1266         yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1267         int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1268
1269         if(tnodeSize < sizeof(yaffs_Tnode))
1270                 tnodeSize = sizeof(yaffs_Tnode);
1271
1272         if(tn)
1273                 memset(tn, 0, tnodeSize);
1274
1275         return tn;
1276 }
1277
1278 /* FreeTnode frees up a tnode and puts it back on the free list */
1279 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
1280 {
1281         if (tn) {
1282 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1283                 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1284                         /* Hoosterman, this thing looks like it is already in the list */
1285                         T(YAFFS_TRACE_ALWAYS,
1286                           (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1287                 }
1288                 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1289 #endif
1290                 tn->internal[0] = dev->freeTnodes;
1291                 dev->freeTnodes = tn;
1292                 dev->nFreeTnodes++;
1293         }
1294         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1295
1296 }
1297
1298 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
1299 {
1300         /* Free the list of allocated tnodes */
1301         yaffs_TnodeList *tmp;
1302
1303         while (dev->allocatedTnodeList) {
1304                 tmp = dev->allocatedTnodeList->next;
1305
1306                 YFREE(dev->allocatedTnodeList->tnodes);
1307                 YFREE(dev->allocatedTnodeList);
1308                 dev->allocatedTnodeList = tmp;
1309
1310         }
1311
1312         dev->freeTnodes = NULL;
1313         dev->nFreeTnodes = 0;
1314 }
1315
1316 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
1317 {
1318         dev->allocatedTnodeList = NULL;
1319         dev->freeTnodes = NULL;
1320         dev->nFreeTnodes = 0;
1321         dev->nTnodesCreated = 0;
1322
1323 }
1324
1325
1326 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
1327 {
1328   __u32 *map = (__u32 *)tn;
1329   __u32 bitInMap;
1330   __u32 bitInWord;
1331   __u32 wordInMap;
1332   __u32 mask;
1333
1334   pos &= YAFFS_TNODES_LEVEL0_MASK;
1335   val >>= dev->chunkGroupBits;
1336
1337   bitInMap = pos * dev->tnodeWidth;
1338   wordInMap = bitInMap /32;
1339   bitInWord = bitInMap & (32 -1);
1340
1341   mask = dev->tnodeMask << bitInWord;
1342
1343   map[wordInMap] &= ~mask;
1344   map[wordInMap] |= (mask & (val << bitInWord));
1345
1346   if(dev->tnodeWidth > (32-bitInWord)) {
1347     bitInWord = (32 - bitInWord);
1348     wordInMap++;;
1349     mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1350     map[wordInMap] &= ~mask;
1351     map[wordInMap] |= (mask & (val >> bitInWord));
1352   }
1353 }
1354
1355 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
1356 {
1357   __u32 *map = (__u32 *)tn;
1358   __u32 bitInMap;
1359   __u32 bitInWord;
1360   __u32 wordInMap;
1361   __u32 val;
1362
1363   pos &= YAFFS_TNODES_LEVEL0_MASK;
1364
1365   bitInMap = pos * dev->tnodeWidth;
1366   wordInMap = bitInMap /32;
1367   bitInWord = bitInMap & (32 -1);
1368
1369   val = map[wordInMap] >> bitInWord;
1370
1371   if(dev->tnodeWidth > (32-bitInWord)) {
1372     bitInWord = (32 - bitInWord);
1373     wordInMap++;;
1374     val |= (map[wordInMap] << bitInWord);
1375   }
1376
1377   val &= dev->tnodeMask;
1378   val <<= dev->chunkGroupBits;
1379
1380   return val;
1381 }
1382
1383 /* ------------------- End of individual tnode manipulation -----------------*/
1384
1385 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1386  * The look up tree is represented by the top tnode and the number of topLevel
1387  * in the tree. 0 means only the level 0 tnode is in the tree.
1388  */
1389
1390 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1391 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
1392                                           yaffs_FileStructure * fStruct,
1393                                           __u32 chunkId)
1394 {
1395
1396         yaffs_Tnode *tn = fStruct->top;
1397         __u32 i;
1398         int requiredTallness;
1399         int level = fStruct->topLevel;
1400
1401         /* Check sane level and chunk Id */
1402         if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
1403                 return NULL;
1404         }
1405
1406         if (chunkId > YAFFS_MAX_CHUNK_ID) {
1407                 return NULL;
1408         }
1409
1410         /* First check we're tall enough (ie enough topLevel) */
1411
1412         i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1413         requiredTallness = 0;
1414         while (i) {
1415                 i >>= YAFFS_TNODES_INTERNAL_BITS;
1416                 requiredTallness++;
1417         }
1418
1419         if (requiredTallness > fStruct->topLevel) {
1420                 /* Not tall enough, so we can't find it, return NULL. */
1421                 return NULL;
1422         }
1423
1424         /* Traverse down to level 0 */
1425         while (level > 0 && tn) {
1426                 tn = tn->
1427                     internal[(chunkId >>
1428                                ( YAFFS_TNODES_LEVEL0_BITS +
1429                                  (level - 1) *
1430                                  YAFFS_TNODES_INTERNAL_BITS)
1431                               ) &
1432                              YAFFS_TNODES_INTERNAL_MASK];
1433                 level--;
1434
1435         }
1436
1437         return tn;
1438 }
1439
1440 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1441  * This happens in two steps:
1442  *  1. If the tree isn't tall enough, then make it taller.
1443  *  2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1444  *
1445  * Used when modifying the tree.
1446  *
1447  *  If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1448  *  be plugged into the ttree.
1449  */
1450
1451 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
1452                                                yaffs_FileStructure * fStruct,
1453                                                __u32 chunkId,
1454                                                yaffs_Tnode *passedTn)
1455 {
1456
1457         int requiredTallness;
1458         int i;
1459         int l;
1460         yaffs_Tnode *tn;
1461
1462         __u32 x;
1463
1464
1465         /* Check sane level and page Id */
1466         if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
1467                 return NULL;
1468         }
1469
1470         if (chunkId > YAFFS_MAX_CHUNK_ID) {
1471                 return NULL;
1472         }
1473
1474         /* First check we're tall enough (ie enough topLevel) */
1475
1476         x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1477         requiredTallness = 0;
1478         while (x) {
1479                 x >>= YAFFS_TNODES_INTERNAL_BITS;
1480                 requiredTallness++;
1481         }
1482
1483
1484         if (requiredTallness > fStruct->topLevel) {
1485                 /* Not tall enough,gotta make the tree taller */
1486                 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1487
1488                         tn = yaffs_GetTnode(dev);
1489
1490                         if (tn) {
1491                                 tn->internal[0] = fStruct->top;
1492                                 fStruct->top = tn;
1493                         } else {
1494                                 T(YAFFS_TRACE_ERROR,
1495                                   (TSTR("yaffs: no more tnodes" TENDSTR)));
1496                         }
1497                 }
1498
1499                 fStruct->topLevel = requiredTallness;
1500         }
1501
1502         /* Traverse down to level 0, adding anything we need */
1503
1504         l = fStruct->topLevel;
1505         tn = fStruct->top;
1506
1507         if(l > 0) {
1508                 while (l > 0 && tn) {
1509                         x = (chunkId >>
1510                              ( YAFFS_TNODES_LEVEL0_BITS +
1511                               (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1512                             YAFFS_TNODES_INTERNAL_MASK;
1513
1514
1515                         if((l>1) && !tn->internal[x]){
1516                                 /* Add missing non-level-zero tnode */
1517                                 tn->internal[x] = yaffs_GetTnode(dev);
1518
1519                         } else if(l == 1) {
1520                                 /* Looking from level 1 at level 0 */
1521                                 if (passedTn) {
1522                                         /* If we already have one, then release it.*/
1523                                         if(tn->internal[x])
1524                                                 yaffs_FreeTnode(dev,tn->internal[x]);
1525                                         tn->internal[x] = passedTn;
1526
1527                                 } else if(!tn->internal[x]) {
1528                                         /* Don't have one, none passed in */
1529                                         tn->internal[x] = yaffs_GetTnode(dev);
1530                                 }
1531                         }
1532
1533                         tn = tn->internal[x];
1534                         l--;
1535                 }
1536         } else {
1537                 /* top is level 0 */
1538                 if(passedTn) {
1539                         memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1540                         yaffs_FreeTnode(dev,passedTn);
1541                 }
1542         }
1543
1544         return tn;
1545 }
1546
1547 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1548                                   yaffs_ExtendedTags * tags, int objectId,
1549                                   int chunkInInode)
1550 {
1551         int j;
1552
1553         for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1554                 if (yaffs_CheckChunkBit
1555                     (dev, theChunk / dev->nChunksPerBlock,
1556                      theChunk % dev->nChunksPerBlock)) {
1557                         yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1558                                                         tags);
1559                         if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1560                                 /* found it; */
1561                                 return theChunk;
1562
1563                         }
1564                 }
1565                 theChunk++;
1566         }
1567         return -1;
1568 }
1569
1570
1571 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1572  * chunks and tnodes in the file
1573  * Returns 1 if the tree was deleted.
1574  * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1575  */
1576
1577 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1578                               int chunkOffset, int *limit)
1579 {
1580         int i;
1581         int chunkInInode;
1582         int theChunk;
1583         yaffs_ExtendedTags tags;
1584         int foundChunk;
1585         yaffs_Device *dev = in->myDev;
1586
1587         int allDone = 1;
1588
1589         if (tn) {
1590                 if (level > 0) {
1591
1592                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1593                              i--) {
1594                                 if (tn->internal[i]) {
1595                                         if (limit && (*limit) < 0) {
1596                                                 allDone = 0;
1597                                         } else {
1598                                                 allDone =
1599                                                     yaffs_DeleteWorker(in,
1600                                                                        tn->
1601                                                                        internal
1602                                                                        [i],
1603                                                                        level -
1604                                                                        1,
1605                                                                        (chunkOffset
1606                                                                         <<
1607                                                                         YAFFS_TNODES_INTERNAL_BITS)
1608                                                                        + i,
1609                                                                        limit);
1610                                         }
1611                                         if (allDone) {
1612                                                 yaffs_FreeTnode(dev,
1613                                                                 tn->
1614                                                                 internal[i]);
1615                                                 tn->internal[i] = NULL;
1616                                         }
1617                                 }
1618
1619                         }
1620                         return (allDone) ? 1 : 0;
1621                 } else if (level == 0) {
1622                         int hitLimit = 0;
1623
1624                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1625                              i--) {
1626                                 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1627                                 if (theChunk) {
1628
1629                                         chunkInInode =
1630                                             (chunkOffset <<
1631                                              YAFFS_TNODES_LEVEL0_BITS) + i;
1632
1633                                         foundChunk =
1634                                             yaffs_FindChunkInGroup(dev,
1635                                                                    theChunk,
1636                                                                    &tags,
1637                                                                    in->objectId,
1638                                                                    chunkInInode);
1639
1640                                         if (foundChunk > 0) {
1641                                                 yaffs_DeleteChunk(dev,
1642                                                                   foundChunk, 1,
1643                                                                   __LINE__);
1644                                                 in->nDataChunks--;
1645                                                 if (limit) {
1646                                                         *limit = *limit - 1;
1647                                                         if (*limit <= 0) {
1648                                                                 hitLimit = 1;
1649                                                         }
1650                                                 }
1651
1652                                         }
1653
1654                                         yaffs_PutLevel0Tnode(dev,tn,i,0);
1655                                 }
1656
1657                         }
1658                         return (i < 0) ? 1 : 0;
1659
1660                 }
1661
1662         }
1663
1664         return 1;
1665
1666 }
1667
1668 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1669 {
1670
1671         yaffs_BlockInfo *theBlock;
1672
1673         T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1674
1675         theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1676         if (theBlock) {
1677                 theBlock->softDeletions++;
1678                 dev->nFreeChunks++;
1679         }
1680 }
1681
1682 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1683  * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1684  * of the tnode.
1685  * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1686  */
1687
1688 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1689                                   __u32 level, int chunkOffset)
1690 {
1691         int i;
1692         int theChunk;
1693         int allDone = 1;
1694         yaffs_Device *dev = in->myDev;
1695
1696         if (tn) {
1697                 if (level > 0) {
1698
1699                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1700                              i--) {
1701                                 if (tn->internal[i]) {
1702                                         allDone =
1703                                             yaffs_SoftDeleteWorker(in,
1704                                                                    tn->
1705                                                                    internal[i],
1706                                                                    level - 1,
1707                                                                    (chunkOffset
1708                                                                     <<
1709                                                                     YAFFS_TNODES_INTERNAL_BITS)
1710                                                                    + i);
1711                                         if (allDone) {
1712                                                 yaffs_FreeTnode(dev,
1713                                                                 tn->
1714                                                                 internal[i]);
1715                                                 tn->internal[i] = NULL;
1716                                         } else {
1717                                                 /* Hoosterman... how could this happen? */
1718                                         }
1719                                 }
1720                         }
1721                         return (allDone) ? 1 : 0;
1722                 } else if (level == 0) {
1723
1724                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1725                                 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1726                                 if (theChunk) {
1727                                         /* Note this does not find the real chunk, only the chunk group.
1728                                          * We make an assumption that a chunk group is not larger than
1729                                          * a block.
1730                                          */
1731                                         yaffs_SoftDeleteChunk(dev, theChunk);
1732                                         yaffs_PutLevel0Tnode(dev,tn,i,0);
1733                                 }
1734
1735                         }
1736                         return 1;
1737
1738                 }
1739
1740         }
1741
1742         return 1;
1743
1744 }
1745
1746 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1747 {
1748         if (obj->deleted &&
1749             obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1750                 if (obj->nDataChunks <= 0) {
1751                         /* Empty file with no duplicate object headers, just delete it immediately */
1752                         yaffs_FreeTnode(obj->myDev,
1753                                         obj->variant.fileVariant.top);
1754                         obj->variant.fileVariant.top = NULL;
1755                         T(YAFFS_TRACE_TRACING,
1756                           (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1757                            obj->objectId));
1758                         yaffs_DoGenericObjectDeletion(obj);
1759                 } else {
1760                         yaffs_SoftDeleteWorker(obj,
1761                                                obj->variant.fileVariant.top,
1762                                                obj->variant.fileVariant.
1763                                                topLevel, 0);
1764                         obj->softDeleted = 1;
1765                 }
1766         }
1767 }
1768
1769 /* Pruning removes any part of the file structure tree that is beyond the
1770  * bounds of the file (ie that does not point to chunks).
1771  *
1772  * A file should only get pruned when its size is reduced.
1773  *
1774  * Before pruning, the chunks must be pulled from the tree and the
1775  * level 0 tnode entries must be zeroed out.
1776  * Could also use this for file deletion, but that's probably better handled
1777  * by a special case.
1778  */
1779
1780 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1781                                       __u32 level, int del0)
1782 {
1783         int i;
1784         int hasData;
1785
1786         if (tn) {
1787                 hasData = 0;
1788
1789                 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1790                         if (tn->internal[i] && level > 0) {
1791                                 tn->internal[i] =
1792                                     yaffs_PruneWorker(dev, tn->internal[i],
1793                                                       level - 1,
1794                                                       (i == 0) ? del0 : 1);
1795                         }
1796
1797                         if (tn->internal[i]) {
1798                                 hasData++;
1799                         }
1800                 }
1801
1802                 if (hasData == 0 && del0) {
1803                         /* Free and return NULL */
1804
1805                         yaffs_FreeTnode(dev, tn);
1806                         tn = NULL;
1807                 }
1808
1809         }
1810
1811         return tn;
1812
1813 }
1814
1815 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1816                                     yaffs_FileStructure * fStruct)
1817 {
1818         int i;
1819         int hasData;
1820         int done = 0;
1821         yaffs_Tnode *tn;
1822
1823         if (fStruct->topLevel > 0) {
1824                 fStruct->top =
1825                     yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1826
1827                 /* Now we have a tree with all the non-zero branches NULL but the height
1828                  * is the same as it was.
1829                  * Let's see if we can trim internal tnodes to shorten the tree.
1830                  * We can do this if only the 0th element in the tnode is in use
1831                  * (ie all the non-zero are NULL)
1832                  */
1833
1834                 while (fStruct->topLevel && !done) {
1835                         tn = fStruct->top;
1836
1837                         hasData = 0;
1838                         for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1839                                 if (tn->internal[i]) {
1840                                         hasData++;
1841                                 }
1842                         }
1843
1844                         if (!hasData) {
1845                                 fStruct->top = tn->internal[0];
1846                                 fStruct->topLevel--;
1847                                 yaffs_FreeTnode(dev, tn);
1848                         } else {
1849                                 done = 1;
1850                         }
1851                 }
1852         }
1853
1854         return YAFFS_OK;
1855 }
1856
1857 /*-------------------- End of File Structure functions.-------------------*/
1858
1859 /* yaffs_CreateFreeObjects creates a bunch more objects and
1860  * adds them to the object free list.
1861  */
1862 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1863 {
1864         int i;
1865         yaffs_Object *newObjects;
1866         yaffs_ObjectList *list;
1867
1868         if (nObjects < 1)
1869                 return YAFFS_OK;
1870
1871         /* make these things */
1872         newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1873         list = YMALLOC(sizeof(yaffs_ObjectList));
1874
1875         if (!newObjects || !list) {
1876                 if(newObjects)
1877                         YFREE(newObjects);
1878                 if(list)
1879                         YFREE(list);
1880                 T(YAFFS_TRACE_ALLOCATE,
1881                   (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1882                 return YAFFS_FAIL;
1883         }
1884
1885         /* Hook them into the free list */
1886         for (i = 0; i < nObjects - 1; i++) {
1887                 newObjects[i].siblings.next =
1888                     (struct ylist_head *)(&newObjects[i + 1]);
1889         }
1890
1891         newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1892         dev->freeObjects = newObjects;
1893         dev->nFreeObjects += nObjects;
1894         dev->nObjectsCreated += nObjects;
1895
1896         /* Now add this bunch of Objects to a list for freeing up. */
1897
1898         list->objects = newObjects;
1899         list->next = dev->allocatedObjectList;
1900         dev->allocatedObjectList = list;
1901
1902         return YAFFS_OK;
1903 }
1904
1905
1906 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1907 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1908 {
1909         yaffs_Object *tn = NULL;
1910
1911         /* If there are none left make more */
1912         if (!dev->freeObjects) {
1913                 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1914         }
1915
1916         if (dev->freeObjects) {
1917                 tn = dev->freeObjects;
1918                 dev->freeObjects =
1919                     (yaffs_Object *) (dev->freeObjects->siblings.next);
1920                 dev->nFreeObjects--;
1921
1922                 /* Now sweeten it up... */
1923
1924                 memset(tn, 0, sizeof(yaffs_Object));
1925                 tn->myDev = dev;
1926                 tn->chunkId = -1;
1927                 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1928                 YINIT_LIST_HEAD(&(tn->hardLinks));
1929                 YINIT_LIST_HEAD(&(tn->hashLink));
1930                 YINIT_LIST_HEAD(&tn->siblings);
1931
1932                 /* Add it to the lost and found directory.
1933                  * NB Can't put root or lostNFound in lostNFound so
1934                  * check if lostNFound exists first
1935                  */
1936                 if (dev->lostNFoundDir) {
1937                         yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1938                 }
1939         }
1940
1941         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1942
1943         return tn;
1944 }
1945
1946 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1947                                                __u32 mode)
1948 {
1949
1950         yaffs_Object *obj =
1951             yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1952         if (obj) {
1953                 obj->fake = 1;          /* it is fake so it has no NAND presence... */
1954                 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1955                 obj->unlinkAllowed = 0; /* ... or unlink it */
1956                 obj->deleted = 0;
1957                 obj->unlinked = 0;
1958                 obj->yst_mode = mode;
1959                 obj->myDev = dev;
1960                 obj->chunkId = 0;       /* Not a valid chunk. */
1961         }
1962
1963         return obj;
1964
1965 }
1966
1967 static void yaffs_UnhashObject(yaffs_Object * tn)
1968 {
1969         int bucket;
1970         yaffs_Device *dev = tn->myDev;
1971
1972         /* If it is still linked into the bucket list, free from the list */
1973         if (!ylist_empty(&tn->hashLink)) {
1974                 ylist_del_init(&tn->hashLink);
1975                 bucket = yaffs_HashFunction(tn->objectId);
1976                 dev->objectBucket[bucket].count--;
1977         }
1978
1979 }
1980
1981 /*  FreeObject frees up a Object and puts it back on the free list */
1982 static void yaffs_FreeObject(yaffs_Object * tn)
1983 {
1984
1985         yaffs_Device *dev = tn->myDev;
1986
1987 #ifdef  __KERNEL__
1988         if (tn->myInode) {
1989                 /* We're still hooked up to a cached inode.
1990                  * Don't delete now, but mark for later deletion
1991                  */
1992                 tn->deferedFree = 1;
1993                 return;
1994         }
1995 #endif
1996
1997         yaffs_UnhashObject(tn);
1998
1999         /* Link into the free list. */
2000         tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2001         dev->freeObjects = tn;
2002         dev->nFreeObjects++;
2003
2004         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2005
2006 }
2007
2008 #ifdef __KERNEL__
2009
2010 void yaffs_HandleDeferedFree(yaffs_Object * obj)
2011 {
2012         if (obj->deferedFree) {
2013                 yaffs_FreeObject(obj);
2014         }
2015 }
2016
2017 #endif
2018
2019 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
2020 {
2021         /* Free the list of allocated Objects */
2022
2023         yaffs_ObjectList *tmp;
2024
2025         while (dev->allocatedObjectList) {
2026                 tmp = dev->allocatedObjectList->next;
2027                 YFREE(dev->allocatedObjectList->objects);
2028                 YFREE(dev->allocatedObjectList);
2029
2030                 dev->allocatedObjectList = tmp;
2031         }
2032
2033         dev->freeObjects = NULL;
2034         dev->nFreeObjects = 0;
2035 }
2036
2037 static void yaffs_InitialiseObjects(yaffs_Device * dev)
2038 {
2039         int i;
2040
2041         dev->allocatedObjectList = NULL;
2042         dev->freeObjects = NULL;
2043         dev->nFreeObjects = 0;
2044
2045         for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2046                 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2047                 dev->objectBucket[i].count = 0;
2048         }
2049
2050 }
2051
2052 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
2053 {
2054         static int x = 0;
2055         int i;
2056         int l = 999;
2057         int lowest = 999999;
2058
2059         /* First let's see if we can find one that's empty. */
2060
2061         for (i = 0; i < 10 && lowest > 0; i++) {
2062                 x++;
2063                 x %= YAFFS_NOBJECT_BUCKETS;
2064                 if (dev->objectBucket[x].count < lowest) {
2065                         lowest = dev->objectBucket[x].count;
2066                         l = x;
2067                 }
2068
2069         }
2070
2071         /* If we didn't find an empty list, then try
2072          * looking a bit further for a short one
2073          */
2074
2075         for (i = 0; i < 10 && lowest > 3; i++) {
2076                 x++;
2077                 x %= YAFFS_NOBJECT_BUCKETS;
2078                 if (dev->objectBucket[x].count < lowest) {
2079                         lowest = dev->objectBucket[x].count;
2080                         l = x;
2081                 }
2082
2083         }
2084
2085         return l;
2086 }
2087
2088 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
2089 {
2090         int bucket = yaffs_FindNiceObjectBucket(dev);
2091
2092         /* Now find an object value that has not already been taken
2093          * by scanning the list.
2094          */
2095
2096         int found = 0;
2097         struct ylist_head *i;
2098
2099         __u32 n = (__u32) bucket;
2100
2101         /* yaffs_CheckObjectHashSanity();  */
2102
2103         while (!found) {
2104                 found = 1;
2105                 n += YAFFS_NOBJECT_BUCKETS;
2106                 if (1 || dev->objectBucket[bucket].count > 0) {
2107                         ylist_for_each(i, &dev->objectBucket[bucket].list) {
2108                                 /* If there is already one in the list */
2109                                 if (i
2110                                     && ylist_entry(i, yaffs_Object,
2111                                                   hashLink)->objectId == n) {
2112                                         found = 0;
2113                                 }
2114                         }
2115                 }
2116         }
2117
2118
2119         return n;
2120 }
2121
2122 static void yaffs_HashObject(yaffs_Object * in)
2123 {
2124         int bucket = yaffs_HashFunction(in->objectId);
2125         yaffs_Device *dev = in->myDev;
2126
2127         ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2128         dev->objectBucket[bucket].count++;
2129
2130 }
2131
2132 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
2133 {
2134         int bucket = yaffs_HashFunction(number);
2135         struct ylist_head *i;
2136         yaffs_Object *in;
2137
2138         ylist_for_each(i, &dev->objectBucket[bucket].list) {
2139                 /* Look if it is in the list */
2140                 if (i) {
2141                         in = ylist_entry(i, yaffs_Object, hashLink);
2142                         if (in->objectId == number) {
2143 #ifdef __KERNEL__
2144                                 /* Don't tell the VFS about this one if it is defered free */
2145                                 if (in->deferedFree)
2146                                         return NULL;
2147 #endif
2148
2149                                 return in;
2150                         }
2151                 }
2152         }
2153
2154         return NULL;
2155 }
2156
2157 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
2158                                     yaffs_ObjectType type)
2159 {
2160
2161         yaffs_Object *theObject;
2162         yaffs_Tnode *tn = NULL;
2163
2164         if (number < 0) {
2165                 number = yaffs_CreateNewObjectNumber(dev);
2166         }
2167
2168         theObject = yaffs_AllocateEmptyObject(dev);
2169         if(!theObject)
2170                 return NULL;
2171
2172         if(type == YAFFS_OBJECT_TYPE_FILE){
2173                 tn = yaffs_GetTnode(dev);
2174                 if(!tn){
2175                         yaffs_FreeObject(theObject);
2176                         return NULL;
2177                 }
2178         }
2179
2180
2181
2182         if (theObject) {
2183                 theObject->fake = 0;
2184                 theObject->renameAllowed = 1;
2185                 theObject->unlinkAllowed = 1;
2186                 theObject->objectId = number;
2187                 yaffs_HashObject(theObject);
2188                 theObject->variantType = type;
2189 #ifdef CONFIG_YAFFS_WINCE
2190                 yfsd_WinFileTimeNow(theObject->win_atime);
2191                 theObject->win_ctime[0] = theObject->win_mtime[0] =
2192                     theObject->win_atime[0];
2193                 theObject->win_ctime[1] = theObject->win_mtime[1] =
2194                     theObject->win_atime[1];
2195
2196 #else
2197
2198                 theObject->yst_atime = theObject->yst_mtime =
2199                     theObject->yst_ctime = Y_CURRENT_TIME;
2200 #endif
2201                 switch (type) {
2202                 case YAFFS_OBJECT_TYPE_FILE:
2203                         theObject->variant.fileVariant.fileSize = 0;
2204                         theObject->variant.fileVariant.scannedFileSize = 0;
2205                         theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2206                         theObject->variant.fileVariant.topLevel = 0;
2207                         theObject->variant.fileVariant.top = tn;
2208                         break;
2209                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2210                         YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2211                                        children);
2212                         break;
2213                 case YAFFS_OBJECT_TYPE_SYMLINK:
2214                 case YAFFS_OBJECT_TYPE_HARDLINK:
2215                 case YAFFS_OBJECT_TYPE_SPECIAL:
2216                         /* No action required */
2217                         break;
2218                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2219                         /* todo this should not happen */
2220                         break;
2221                 }
2222         }
2223
2224         return theObject;
2225 }
2226
2227 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
2228                                                       int number,
2229                                                       yaffs_ObjectType type)
2230 {
2231         yaffs_Object *theObject = NULL;
2232
2233         if (number > 0) {
2234                 theObject = yaffs_FindObjectByNumber(dev, number);
2235         }
2236
2237         if (!theObject) {
2238                 theObject = yaffs_CreateNewObject(dev, number, type);
2239         }
2240
2241         return theObject;
2242
2243 }
2244
2245
2246 static YCHAR *yaffs_CloneString(const YCHAR * str)
2247 {
2248         YCHAR *newStr = NULL;
2249
2250         if (str && *str) {
2251                 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2252                 if(newStr)
2253                         yaffs_strcpy(newStr, str);
2254         }
2255
2256         return newStr;
2257
2258 }
2259
2260 /*
2261  * Mknod (create) a new object.
2262  * equivalentObject only has meaning for a hard link;
2263  * aliasString only has meaning for a sumlink.
2264  * rdev only has meaning for devices (a subset of special objects)
2265  */
2266
2267 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2268                                        yaffs_Object * parent,
2269                                        const YCHAR * name,
2270                                        __u32 mode,
2271                                        __u32 uid,
2272                                        __u32 gid,
2273                                        yaffs_Object * equivalentObject,
2274                                        const YCHAR * aliasString, __u32 rdev)
2275 {
2276         yaffs_Object *in;
2277         YCHAR *str = NULL;
2278
2279         yaffs_Device *dev = parent->myDev;
2280
2281         /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2282         if (yaffs_FindObjectByName(parent, name)) {
2283                 return NULL;
2284         }
2285
2286         in = yaffs_CreateNewObject(dev, -1, type);
2287
2288         if(type == YAFFS_OBJECT_TYPE_SYMLINK){
2289                 str = yaffs_CloneString(aliasString);
2290                 if(!str){
2291                         yaffs_FreeObject(in);
2292                         return NULL;
2293                 }
2294         }
2295
2296
2297
2298         if (in) {
2299                 in->chunkId = -1;
2300                 in->valid = 1;
2301                 in->variantType = type;
2302
2303                 in->yst_mode = mode;
2304
2305 #ifdef CONFIG_YAFFS_WINCE
2306                 yfsd_WinFileTimeNow(in->win_atime);
2307                 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2308                 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2309
2310 #else
2311                 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2312
2313                 in->yst_rdev = rdev;
2314                 in->yst_uid = uid;
2315                 in->yst_gid = gid;
2316 #endif
2317                 in->nDataChunks = 0;
2318
2319                 yaffs_SetObjectName(in, name);
2320                 in->dirty = 1;
2321
2322                 yaffs_AddObjectToDirectory(parent, in);
2323
2324                 in->myDev = parent->myDev;
2325
2326                 switch (type) {
2327                 case YAFFS_OBJECT_TYPE_SYMLINK:
2328                         in->variant.symLinkVariant.alias = str;
2329                         break;
2330                 case YAFFS_OBJECT_TYPE_HARDLINK:
2331                         in->variant.hardLinkVariant.equivalentObject =
2332                             equivalentObject;
2333                         in->variant.hardLinkVariant.equivalentObjectId =
2334                             equivalentObject->objectId;
2335                         ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2336                         break;
2337                 case YAFFS_OBJECT_TYPE_FILE:
2338                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2339                 case YAFFS_OBJECT_TYPE_SPECIAL:
2340                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2341                         /* do nothing */
2342                         break;
2343                 }
2344
2345                 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2346                         /* Could not create the object header, fail the creation */
2347                         yaffs_DestroyObject(in);
2348                         in = NULL;
2349                 }
2350
2351         }
2352
2353         return in;
2354 }
2355
2356 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
2357                               __u32 mode, __u32 uid, __u32 gid)
2358 {
2359         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2360                                  uid, gid, NULL, NULL, 0);
2361 }
2362
2363 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
2364                                    __u32 mode, __u32 uid, __u32 gid)
2365 {
2366         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2367                                  mode, uid, gid, NULL, NULL, 0);
2368 }
2369
2370 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
2371                                  __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2372 {
2373         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2374                                  uid, gid, NULL, NULL, rdev);
2375 }
2376
2377 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
2378                                  __u32 mode, __u32 uid, __u32 gid,
2379                                  const YCHAR * alias)
2380 {
2381         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2382                                  uid, gid, NULL, alias, 0);
2383 }
2384
2385 /* yaffs_Link returns the object id of the equivalent object.*/
2386 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
2387                          yaffs_Object * equivalentObject)
2388 {
2389         /* Get the real object in case we were fed a hard link as an equivalent object */
2390         equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2391
2392         if (yaffs_MknodObject
2393             (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2394              equivalentObject, NULL, 0)) {
2395                 return equivalentObject;
2396         } else {
2397                 return NULL;
2398         }
2399
2400 }
2401
2402 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
2403                                   const YCHAR * newName, int force, int shadows)
2404 {
2405         int unlinkOp;
2406         int deleteOp;
2407
2408         yaffs_Object *existingTarget;
2409
2410         if (newDir == NULL) {
2411                 newDir = obj->parent;   /* use the old directory */
2412         }
2413
2414         if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2415                 T(YAFFS_TRACE_ALWAYS,
2416                   (TSTR
2417                    ("tragendy: yaffs_ChangeObjectName: newDir is not a directory"
2418                     TENDSTR)));
2419                 YBUG();
2420         }
2421
2422         /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2423         if (obj->myDev->isYaffs2) {
2424                 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2425         } else {
2426                 unlinkOp = (newDir == obj->myDev->unlinkedDir
2427                             && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2428         }
2429
2430         deleteOp = (newDir == obj->myDev->deletedDir);
2431
2432         existingTarget = yaffs_FindObjectByName(newDir, newName);
2433
2434         /* If the object is a file going into the unlinked directory,
2435          *   then it is OK to just stuff it in since duplicate names are allowed.
2436          *   else only proceed if the new name does not exist and if we're putting
2437          *   it into a directory.
2438          */
2439         if ((unlinkOp ||
2440              deleteOp ||
2441              force ||
2442              (shadows > 0) ||
2443              !existingTarget) &&
2444             newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2445                 yaffs_SetObjectName(obj, newName);
2446                 obj->dirty = 1;
2447
2448                 yaffs_AddObjectToDirectory(newDir, obj);
2449
2450                 if (unlinkOp)
2451                         obj->unlinked = 1;
2452
2453                 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2454                 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
2455                         return YAFFS_OK;
2456         }
2457
2458         return YAFFS_FAIL;
2459 }
2460
2461 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
2462                        yaffs_Object * newDir, const YCHAR * newName)
2463 {
2464         yaffs_Object *obj;
2465         yaffs_Object *existingTarget;
2466         int force = 0;
2467
2468 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2469         /* Special case for case insemsitive systems (eg. WinCE).
2470          * While look-up is case insensitive, the name isn't.
2471          * Therefore we might want to change x.txt to X.txt
2472         */
2473         if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
2474                 force = 1;
2475         }
2476 #endif
2477
2478         obj = yaffs_FindObjectByName(oldDir, oldName);
2479         /* Check new name to long. */
2480         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK &&
2481             yaffs_strlen(newName) > YAFFS_MAX_ALIAS_LENGTH)
2482           /* ENAMETOOLONG */
2483           return YAFFS_FAIL;
2484         else if (obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK &&
2485                  yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2486           /* ENAMETOOLONG */
2487           return YAFFS_FAIL;
2488
2489         if (obj && obj->renameAllowed) {
2490
2491                 /* Now do the handling for an existing target, if there is one */
2492
2493                 existingTarget = yaffs_FindObjectByName(newDir, newName);
2494                 if (existingTarget &&
2495                     existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2496                     !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2497                         /* There is a target that is a non-empty directory, so we fail */
2498                         return YAFFS_FAIL;      /* EEXIST or ENOTEMPTY */
2499                 } else if (existingTarget && existingTarget != obj) {
2500                         /* Nuke the target first, using shadowing,
2501                          * but only if it isn't the same object
2502                          */
2503                         yaffs_ChangeObjectName(obj, newDir, newName, force,
2504                                                existingTarget->objectId);
2505                         yaffs_UnlinkObject(existingTarget);
2506                 }
2507
2508                 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2509         }
2510         return YAFFS_FAIL;
2511 }
2512
2513 /*------------------------- Block Management and Page Allocation ----------------*/
2514
2515 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
2516 {
2517         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2518
2519         dev->blockInfo = NULL;
2520         dev->chunkBits = NULL;
2521
2522         dev->allocationBlock = -1;      /* force it to get a new one */
2523
2524         /* If the first allocation strategy fails, thry the alternate one */
2525         dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2526         if(!dev->blockInfo){
2527                 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2528                 dev->blockInfoAlt = 1;
2529         }
2530         else
2531                 dev->blockInfoAlt = 0;
2532
2533         if(dev->blockInfo){
2534
2535                 /* Set up dynamic blockinfo stuff. */
2536                 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2537                 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2538                 if(!dev->chunkBits){
2539                         dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2540                         dev->chunkBitsAlt = 1;
2541                 }
2542                 else
2543                         dev->chunkBitsAlt = 0;
2544         }
2545
2546         if (dev->blockInfo && dev->chunkBits) {
2547                 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2548                 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2549                 return YAFFS_OK;
2550         }
2551
2552         return YAFFS_FAIL;
2553
2554 }
2555
2556 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
2557 {
2558         if(dev->blockInfoAlt && dev->blockInfo)
2559                 YFREE_ALT(dev->blockInfo);
2560         else if(dev->blockInfo)
2561                 YFREE(dev->blockInfo);
2562
2563         dev->blockInfoAlt = 0;
2564
2565         dev->blockInfo = NULL;
2566
2567         if(dev->chunkBitsAlt && dev->chunkBits)
2568                 YFREE_ALT(dev->chunkBits);
2569         else if(dev->chunkBits)
2570                 YFREE(dev->chunkBits);
2571         dev->chunkBitsAlt = 0;
2572         dev->chunkBits = NULL;
2573 }
2574
2575 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
2576                                             yaffs_BlockInfo * bi)
2577 {
2578         int i;
2579         __u32 seq;
2580         yaffs_BlockInfo *b;
2581
2582         if (!dev->isYaffs2)
2583                 return 1;       /* disqualification only applies to yaffs2. */
2584
2585         if (!bi->hasShrinkHeader)
2586                 return 1;       /* can gc */
2587
2588         /* Find the oldest dirty sequence number if we don't know it and save it
2589          * so we don't have to keep recomputing it.
2590          */
2591         if (!dev->oldestDirtySequence) {
2592                 seq = dev->sequenceNumber;
2593
2594                 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2595                      i++) {
2596                         b = yaffs_GetBlockInfo(dev, i);
2597                         if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2598                             (b->pagesInUse - b->softDeletions) <
2599                             dev->nChunksPerBlock && b->sequenceNumber < seq) {
2600                                 seq = b->sequenceNumber;
2601                         }
2602                 }
2603                 dev->oldestDirtySequence = seq;
2604         }
2605
2606         /* Can't do gc of this block if there are any blocks older than this one that have
2607          * discarded pages.
2608          */
2609         return (bi->sequenceNumber <= dev->oldestDirtySequence);
2610
2611 }
2612
2613 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2614  * for garbage collection.
2615  */
2616
2617 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2618                                                int aggressive)
2619 {
2620
2621         int b = dev->currentDirtyChecker;
2622
2623         int i;
2624         int iterations;
2625         int dirtiest = -1;
2626         int pagesInUse = 0;
2627         int prioritised=0;
2628         yaffs_BlockInfo *bi;
2629         int pendingPrioritisedExist = 0;
2630
2631         /* First let's see if we need to grab a prioritised block */
2632         if(dev->hasPendingPrioritisedGCs){
2633                 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2634
2635                         bi = yaffs_GetBlockInfo(dev, i);
2636                         //yaffs_VerifyBlock(dev,bi,i);
2637
2638                         if(bi->gcPrioritise) {
2639                                 pendingPrioritisedExist = 1;
2640                                 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2641                                    yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2642                                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
2643                                         dirtiest = i;
2644                                         prioritised = 1;
2645                                         aggressive = 1; /* Fool the non-aggressive skip logiv below */
2646                                 }
2647                         }
2648                 }
2649
2650                 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2651                         dev->hasPendingPrioritisedGCs = 0;
2652         }
2653
2654         /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2655          * search harder.
2656          * else (we're doing a leasurely gc), then we only bother to do this if the
2657          * block has only a few pages in use.
2658          */
2659
2660         dev->nonAggressiveSkip--;
2661
2662         if (!aggressive && (dev->nonAggressiveSkip > 0)) {
2663                 return -1;
2664         }
2665
2666         if(!prioritised)
2667                 pagesInUse =
2668                         (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2669
2670         if (aggressive) {
2671                 iterations =
2672                     dev->internalEndBlock - dev->internalStartBlock + 1;
2673         } else {
2674                 iterations =
2675                     dev->internalEndBlock - dev->internalStartBlock + 1;
2676                 iterations = iterations / 16;
2677                 if (iterations > 200) {
2678                         iterations = 200;
2679                 }
2680         }
2681
2682         for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2683                 b++;
2684                 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2685                         b = dev->internalStartBlock;
2686                 }
2687
2688                 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2689                         T(YAFFS_TRACE_ERROR,
2690                           (TSTR("**>> Block %d is not valid" TENDSTR), b));
2691                         YBUG();
2692                 }
2693
2694                 bi = yaffs_GetBlockInfo(dev, b);
2695
2696 #if 0
2697                 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2698                         dirtiest = b;
2699                         pagesInUse = 0;
2700                 }
2701                 else
2702 #endif
2703
2704                 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2705                        (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2706                         yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2707                         dirtiest = b;
2708                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
2709                 }
2710         }
2711
2712         dev->currentDirtyChecker = b;
2713
2714         if (dirtiest > 0) {
2715                 T(YAFFS_TRACE_GC,
2716                   (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2717                    dev->nChunksPerBlock - pagesInUse,prioritised));
2718         }
2719
2720         dev->oldestDirtySequence = 0;
2721
2722         if (dirtiest > 0) {
2723                 dev->nonAggressiveSkip = 4;
2724         }
2725
2726         return dirtiest;
2727 }
2728
2729 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2730 {
2731         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2732
2733         int erasedOk = 0;
2734
2735         /* If the block is still healthy erase it and mark as clean.
2736          * If the block has had a data failure, then retire it.
2737          */
2738
2739         T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2740                 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2741                 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2742
2743         bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2744
2745         if (!bi->needsRetiring) {
2746                 yaffs_InvalidateCheckpoint(dev);
2747                 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2748                 if (!erasedOk) {
2749                         dev->nErasureFailures++;
2750                         T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2751                           (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2752                 }
2753         }
2754
2755         if (erasedOk &&
2756             ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2757                 int i;
2758                 for (i = 0; i < dev->nChunksPerBlock; i++) {
2759                         if (!yaffs_CheckChunkErased
2760                             (dev, blockNo * dev->nChunksPerBlock + i)) {
2761                                 T(YAFFS_TRACE_ERROR,
2762                                   (TSTR
2763                                    (">>Block %d erasure supposedly OK, but chunk %d not erased"
2764                                     TENDSTR), blockNo, i));
2765                         }
2766                 }
2767         }
2768
2769         if (erasedOk) {
2770                 /* Clean it up... */
2771                 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2772                 dev->nErasedBlocks++;
2773                 bi->pagesInUse = 0;
2774                 bi->softDeletions = 0;
2775                 bi->hasShrinkHeader = 0;
2776                 bi->skipErasedCheck = 1;  /* This is clean, so no need to check */
2777                 bi->gcPrioritise = 0;
2778                 yaffs_ClearChunkBits(dev, blockNo);
2779
2780                 T(YAFFS_TRACE_ERASE,
2781                   (TSTR("Erased block %d" TENDSTR), blockNo));
2782         } else {
2783                 dev->nFreeChunks -= dev->nChunksPerBlock;       /* We lost a block of free space */
2784
2785                 yaffs_RetireBlock(dev, blockNo);
2786                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2787                   (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2788         }
2789 }
2790
2791 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2792 {
2793         int i;
2794
2795         yaffs_BlockInfo *bi;
2796
2797         if (dev->nErasedBlocks < 1) {
2798                 /* Hoosterman we've got a problem.
2799                  * Can't get space to gc
2800                  */
2801                 T(YAFFS_TRACE_ERROR,
2802                   (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2803
2804                 return -1;
2805         }
2806
2807         /* Find an empty block. */
2808
2809         for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2810                 dev->allocationBlockFinder++;
2811                 if (dev->allocationBlockFinder < dev->internalStartBlock
2812                     || dev->allocationBlockFinder > dev->internalEndBlock) {
2813                         dev->allocationBlockFinder = dev->internalStartBlock;
2814                 }
2815
2816                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2817
2818                 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2819                         bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2820                         dev->sequenceNumber++;
2821                         bi->sequenceNumber = dev->sequenceNumber;
2822                         dev->nErasedBlocks--;
2823                         T(YAFFS_TRACE_ALLOCATE,
2824                           (TSTR("Allocated block %d, seq  %d, %d left" TENDSTR),
2825                            dev->allocationBlockFinder, dev->sequenceNumber,
2826                            dev->nErasedBlocks));
2827                         return dev->allocationBlockFinder;
2828                 }
2829         }
2830
2831         T(YAFFS_TRACE_ALWAYS,
2832           (TSTR
2833            ("yaffs tragedy: no more eraased blocks, but there should have been %d"
2834             TENDSTR), dev->nErasedBlocks));
2835
2836         return -1;
2837 }
2838
2839
2840
2841 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2842 {
2843         if(!dev->nCheckpointBlocksRequired){
2844                 /* Not a valid value so recalculate */
2845                 int nBytes = 0;
2846                 int nBlocks;
2847                 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2848                 int tnodeSize;
2849
2850                 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2851
2852                 if(tnodeSize < sizeof(yaffs_Tnode))
2853                         tnodeSize = sizeof(yaffs_Tnode);
2854
2855                 nBytes += sizeof(yaffs_CheckpointValidity);
2856                 nBytes += sizeof(yaffs_CheckpointDevice);
2857                 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2858                 nBytes += devBlocks * dev->chunkBitmapStride;
2859                 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2860                 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2861                 nBytes += sizeof(yaffs_CheckpointValidity);
2862                 nBytes += sizeof(__u32); /* checksum*/
2863
2864                 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2865
2866                 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2867
2868                 dev->nCheckpointBlocksRequired = nBlocks;
2869         }
2870
2871         return dev->nCheckpointBlocksRequired;
2872 }
2873
2874 // Check if there's space to allocate...
2875 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2876 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2877 {
2878         int reservedChunks;
2879         int reservedBlocks = dev->nReservedBlocks;
2880         int checkpointBlocks;
2881
2882         checkpointBlocks =  yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
2883         if(checkpointBlocks < 0)
2884                 checkpointBlocks = 0;
2885
2886         reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2887
2888         return (dev->nFreeChunks > reservedChunks);
2889 }
2890
2891 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2892 {
2893         int retVal;
2894         yaffs_BlockInfo *bi;
2895
2896         if (dev->allocationBlock < 0) {
2897                 /* Get next block to allocate off */
2898                 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2899                 dev->allocationPage = 0;
2900         }
2901
2902         if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2903                 /* Not enough space to allocate unless we're allowed to use the reserve. */
2904                 return -1;
2905         }
2906
2907         if (dev->nErasedBlocks < dev->nReservedBlocks
2908             && dev->allocationPage == 0) {
2909                 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2910         }
2911
2912         /* Next page please.... */
2913         if (dev->allocationBlock >= 0) {
2914                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2915
2916                 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2917                     dev->allocationPage;
2918                 bi->pagesInUse++;
2919                 yaffs_SetChunkBit(dev, dev->allocationBlock,
2920                                   dev->allocationPage);
2921
2922                 dev->allocationPage++;
2923
2924                 dev->nFreeChunks--;
2925
2926                 /* If the block is full set the state to full */
2927                 if (dev->allocationPage >= dev->nChunksPerBlock) {
2928                         bi->blockState = YAFFS_BLOCK_STATE_FULL;
2929                         dev->allocationBlock = -1;
2930                 }
2931
2932                 if(blockUsedPtr)
2933                         *blockUsedPtr = bi;
2934
2935                 return retVal;
2936         }
2937
2938         T(YAFFS_TRACE_ERROR,
2939           (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2940
2941         return -1;
2942 }
2943
2944 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2945 {
2946         int n;
2947
2948         n = dev->nErasedBlocks * dev->nChunksPerBlock;
2949
2950         if (dev->allocationBlock > 0) {
2951                 n += (dev->nChunksPerBlock - dev->allocationPage);
2952         }
2953
2954         return n;
2955
2956 }
2957
2958 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2959 {
2960         int oldChunk;
2961         int newChunk;
2962         int chunkInBlock;
2963         int markNAND;
2964         int retVal = YAFFS_OK;
2965         int cleanups = 0;
2966         int i;
2967         int isCheckpointBlock;
2968         int matchingChunk;
2969
2970         int chunksBefore = yaffs_GetErasedChunks(dev);
2971         int chunksAfter;
2972
2973         yaffs_ExtendedTags tags;
2974
2975         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2976
2977         yaffs_Object *object;
2978
2979         isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2980
2981         bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2982
2983         T(YAFFS_TRACE_TRACING,
2984           (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2985            bi->pagesInUse, bi->hasShrinkHeader));
2986
2987         /*yaffs_VerifyFreeChunks(dev); */
2988
2989         bi->hasShrinkHeader = 0;        /* clear the flag so that the block can erase */
2990
2991         /* Take off the number of soft deleted entries because
2992          * they're going to get really deleted during GC.
2993          */
2994         dev->nFreeChunks -= bi->softDeletions;
2995
2996         dev->isDoingGC = 1;
2997
2998         if (isCheckpointBlock ||
2999             !yaffs_StillSomeChunkBits(dev, block)) {
3000                 T(YAFFS_TRACE_TRACING,
3001                   (TSTR
3002                    ("Collecting block %d that has no chunks in use" TENDSTR),
3003                    block));
3004                 yaffs_BlockBecameDirty(dev, block);
3005         } else {
3006
3007                 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3008
3009                 yaffs_VerifyBlock(dev,bi,block);
3010
3011                 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
3012                      chunkInBlock < dev->nChunksPerBlock
3013                      && yaffs_StillSomeChunkBits(dev, block);
3014                      chunkInBlock++, oldChunk++) {
3015                         if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
3016
3017                                 /* This page is in use and might need to be copied off */
3018
3019                                 markNAND = 1;
3020
3021                                 yaffs_InitialiseTags(&tags);
3022
3023                                 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3024                                                                 buffer, &tags);
3025
3026                                 object =
3027                                     yaffs_FindObjectByNumber(dev,
3028                                                              tags.objectId);
3029
3030                                 T(YAFFS_TRACE_GC_DETAIL,
3031                                   (TSTR
3032                                    ("Collecting page %d, %d %d %d " TENDSTR),
3033                                    chunkInBlock, tags.objectId, tags.chunkId,
3034                                    tags.byteCount));
3035
3036                                 if(object && !yaffs_SkipVerification(dev)){
3037                                         if(tags.chunkId == 0)
3038                                                 matchingChunk = object->chunkId;
3039                                         else if(object->softDeleted)
3040                                                 matchingChunk = oldChunk; /* Defeat the test */
3041                                         else
3042                                                 matchingChunk = yaffs_FindChunkInFile(object,tags.chunkId,NULL);
3043
3044                                         if(oldChunk != matchingChunk)
3045                                                 T(YAFFS_TRACE_ERROR,
3046                                                   (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3047                                                   oldChunk,matchingChunk,tags.objectId, tags.chunkId));
3048
3049                                 }
3050
3051                                 if (!object) {
3052                                         T(YAFFS_TRACE_ERROR,
3053                                           (TSTR
3054                                            ("page %d in gc has no object: %d %d %d "
3055                                             TENDSTR), oldChunk,
3056                                             tags.objectId, tags.chunkId, tags.byteCount));
3057                                 }
3058
3059                                 if (object && object->deleted
3060                                     && tags.chunkId != 0) {
3061                                         /* Data chunk in a deleted file, throw it away
3062                                          * It's a soft deleted data chunk,
3063                                          * No need to copy this, just forget about it and
3064                                          * fix up the object.
3065                                          */
3066
3067                                         object->nDataChunks--;
3068
3069                                         if (object->nDataChunks <= 0) {
3070                                                 /* remeber to clean up the object */
3071                                                 dev->gcCleanupList[cleanups] =
3072                                                     tags.objectId;
3073                                                 cleanups++;
3074                                         }
3075                                         markNAND = 0;
3076                                 } else if (0
3077                                            /* Todo object && object->deleted && object->nDataChunks == 0 */
3078                                            ) {
3079                                         /* Deleted object header with no data chunks.
3080                                          * Can be discarded and the file deleted.
3081                                          */
3082                                         object->chunkId = 0;
3083                                         yaffs_FreeTnode(object->myDev,
3084                                                         object->variant.
3085                                                         fileVariant.top);
3086                                         object->variant.fileVariant.top = NULL;
3087                                         yaffs_DoGenericObjectDeletion(object);
3088
3089                                 } else if (object) {
3090                                         /* It's either a data chunk in a live file or
3091                                          * an ObjectHeader, so we're interested in it.
3092                                          * NB Need to keep the ObjectHeaders of deleted files
3093                                          * until the whole file has been deleted off
3094                                          */
3095                                         tags.serialNumber++;
3096
3097                                         dev->nGCCopies++;
3098
3099                                         if (tags.chunkId == 0) {
3100                                                 /* It is an object Id,
3101                                                  * We need to nuke the shrinkheader flags first
3102                                                  * We no longer want the shrinkHeader flag since its work is done
3103                                                  * and if it is left in place it will mess up scanning.
3104                                                  * Also, clear out any shadowing stuff
3105                                                  */
3106
3107                                                 yaffs_ObjectHeader *oh;
3108                                                 oh = (yaffs_ObjectHeader *)buffer;
3109                                                 oh->isShrink = 0;
3110                                                 oh->shadowsObject = oh->inbandShadowsObject = -1;
3111                                                 tags.extraShadows = 0;
3112                                                 tags.extraIsShrinkHeader = 0;
3113
3114                                                 yaffs_VerifyObjectHeader(object,oh,&tags,1);
3115                                         }
3116
3117                                         newChunk =
3118                                             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3119
3120                                         if (newChunk < 0) {
3121                                                 retVal = YAFFS_FAIL;
3122                                         } else {
3123
3124                                                 /* Ok, now fix up the Tnodes etc. */
3125
3126                                                 if (tags.chunkId == 0) {
3127                                                         /* It's a header */
3128                                                         object->chunkId =  newChunk;
3129                                                         object->serial =   tags.serialNumber;
3130                                                 } else {
3131                                                         /* It's a data chunk */
3132                                                         yaffs_PutChunkIntoFile
3133                                                             (object,
3134                                                              tags.chunkId,
3135                                                              newChunk, 0);
3136                                                 }
3137                                         }
3138                                 }
3139
3140                                 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3141
3142                         }
3143                 }
3144
3145                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3146
3147
3148                 /* Do any required cleanups */
3149                 for (i = 0; i < cleanups; i++) {
3150                         /* Time to delete the file too */
3151                         object =
3152                             yaffs_FindObjectByNumber(dev,
3153                                                      dev->gcCleanupList[i]);
3154                         if (object) {
3155                                 yaffs_FreeTnode(dev,
3156                                                 object->variant.fileVariant.
3157                                                 top);
3158                                 object->variant.fileVariant.top = NULL;
3159                                 T(YAFFS_TRACE_GC,
3160                                   (TSTR
3161                                    ("yaffs: About to finally delete object %d"
3162                                     TENDSTR), object->objectId));
3163                                 yaffs_DoGenericObjectDeletion(object);
3164                                 object->myDev->nDeletedFiles--;
3165                         }
3166
3167                 }
3168
3169         }
3170
3171         yaffs_VerifyCollectedBlock(dev,bi,block);
3172
3173         if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
3174                 T(YAFFS_TRACE_GC,
3175                   (TSTR
3176                    ("gc did not increase free chunks before %d after %d"
3177                     TENDSTR), chunksBefore, chunksAfter));
3178         }
3179
3180         dev->isDoingGC = 0;
3181
3182         return YAFFS_OK;
3183 }
3184
3185 /* New garbage collector
3186  * If we're very low on erased blocks then we do aggressive garbage collection
3187  * otherwise we do "leasurely" garbage collection.
3188  * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3189  * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3190  *
3191  * The idea is to help clear out space in a more spread-out manner.
3192  * Dunno if it really does anything useful.
3193  */
3194 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
3195 {
3196         int block;
3197         int aggressive;
3198         int gcOk = YAFFS_OK;
3199         int maxTries = 0;
3200
3201         int checkpointBlockAdjust;
3202
3203         if (dev->isDoingGC) {
3204                 /* Bail out so we don't get recursive gc */
3205                 return YAFFS_OK;
3206         }
3207
3208         /* This loop should pass the first time.
3209          * We'll only see looping here if the erase of the collected block fails.
3210          */
3211
3212         do {
3213                 maxTries++;
3214
3215                 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3216                 if(checkpointBlockAdjust < 0)
3217                         checkpointBlockAdjust = 0;
3218
3219                 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3220                         /* We need a block soon...*/
3221                         aggressive = 1;
3222                 } else {
3223                         /* We're in no hurry */
3224                         aggressive = 0;
3225                 }
3226
3227                 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3228
3229                 if (block > 0) {
3230                         dev->garbageCollections++;
3231                         if (!aggressive) {
3232                                 dev->passiveGarbageCollections++;
3233                         }
3234
3235                         T(YAFFS_TRACE_GC,
3236                           (TSTR
3237                            ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3238                            dev->nErasedBlocks, aggressive));
3239
3240                         gcOk = yaffs_GarbageCollectBlock(dev, block);
3241                 }
3242
3243                 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3244                         T(YAFFS_TRACE_GC,
3245                           (TSTR
3246                            ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3247                             TENDSTR), dev->nErasedBlocks, maxTries, block));
3248                 }
3249         } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
3250                  && (maxTries < 2));
3251
3252         return aggressive ? gcOk : YAFFS_OK;
3253 }
3254
3255 /*-------------------------  TAGS --------------------------------*/
3256
3257 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
3258                            int chunkInObject)
3259 {
3260         return (tags->chunkId == chunkInObject &&
3261                 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3262
3263 }
3264
3265
3266 /*-------------------- Data file manipulation -----------------*/
3267
3268 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
3269                                  yaffs_ExtendedTags * tags)
3270 {
3271         /*Get the Tnode, then get the level 0 offset chunk offset */
3272         yaffs_Tnode *tn;
3273         int theChunk = -1;
3274         yaffs_ExtendedTags localTags;
3275         int retVal = -1;
3276
3277         yaffs_Device *dev = in->myDev;
3278
3279         if (!tags) {
3280                 /* Passed a NULL, so use our own tags space */
3281                 tags = &localTags;
3282         }
3283
3284         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3285
3286         if (tn) {
3287                 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3288
3289                 retVal =
3290                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3291                                            chunkInInode);
3292         }
3293         return retVal;
3294 }
3295
3296 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
3297                                           yaffs_ExtendedTags * tags)
3298 {
3299         /* Get the Tnode, then get the level 0 offset chunk offset */
3300         yaffs_Tnode *tn;
3301         int theChunk = -1;
3302         yaffs_ExtendedTags localTags;
3303
3304         yaffs_Device *dev = in->myDev;
3305         int retVal = -1;
3306
3307         if (!tags) {
3308                 /* Passed a NULL, so use our own tags space */
3309                 tags = &localTags;
3310         }
3311
3312         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3313
3314         if (tn) {
3315
3316                 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3317
3318                 retVal =
3319                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3320                                            chunkInInode);
3321
3322                 /* Delete the entry in the filestructure (if found) */
3323                 if (retVal != -1) {
3324                         yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
3325                 }
3326         } else {
3327                 /*T(("No level 0 found for %d\n", chunkInInode)); */
3328         }
3329
3330         if (retVal == -1) {
3331                 /* T(("Could not find %d to delete\n",chunkInInode)); */
3332         }
3333         return retVal;
3334 }
3335
3336 #ifdef YAFFS_PARANOID
3337
3338 static int yaffs_CheckFileSanity(yaffs_Object * in)
3339 {
3340         int chunk;
3341         int nChunks;
3342         int fSize;
3343         int failed = 0;
3344         int objId;
3345         yaffs_Tnode *tn;
3346         yaffs_Tags localTags;
3347         yaffs_Tags *tags = &localTags;
3348         int theChunk;
3349         int chunkDeleted;
3350
3351         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3352                 /* T(("Object not a file\n")); */
3353                 return YAFFS_FAIL;
3354         }
3355
3356         objId = in->objectId;
3357         fSize = in->variant.fileVariant.fileSize;
3358         nChunks =
3359             (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3360
3361         for (chunk = 1; chunk <= nChunks; chunk++) {
3362                 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3363                                            chunk);
3364
3365                 if (tn) {
3366
3367                         theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
3368
3369                         if (yaffs_CheckChunkBits
3370                             (dev, theChunk / dev->nChunksPerBlock,
3371                              theChunk % dev->nChunksPerBlock)) {
3372
3373                                 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3374                                                             tags,
3375                                                             &chunkDeleted);
3376                                 if (yaffs_TagsMatch
3377                                     (tags, in->objectId, chunk, chunkDeleted)) {
3378                                         /* found it; */
3379
3380                                 }
3381                         } else {
3382
3383                                 failed = 1;
3384                         }
3385
3386                 } else {
3387                         /* T(("No level 0 found for %d\n", chunk)); */
3388                 }
3389         }
3390
3391         return failed ? YAFFS_FAIL : YAFFS_OK;
3392 }
3393
3394 #endif
3395
3396 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
3397            &nb