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