cad48e69c5295409442d5b2f9869f59a18f7bc32
[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.53 2007-12-03 03:21:48 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         if(tnodeSize < sizeof(yaffs_Tnode))
1150                 tnodeSize = sizeof(yaffs_Tnode);
1151                 
1152
1153         /* make these things */
1154
1155         newTnodes = YMALLOC(nTnodes * tnodeSize);
1156         mem = (__u8 *)newTnodes;
1157
1158         if (!newTnodes) {
1159                 T(YAFFS_TRACE_ERROR,
1160                   (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1161                 return YAFFS_FAIL;
1162         }
1163
1164         /* Hook them into the free list */
1165 #if 0
1166         for (i = 0; i < nTnodes - 1; i++) {
1167                 newTnodes[i].internal[0] = &newTnodes[i + 1];
1168 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1169                 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1170 #endif
1171         }
1172
1173         newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1174 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1175         newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1176 #endif
1177         dev->freeTnodes = newTnodes;
1178 #else
1179         /* New hookup for wide tnodes */
1180         for(i = 0; i < nTnodes -1; i++) {
1181                 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1182                 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1183                 curr->internal[0] = next;
1184         }
1185         
1186         curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1187         curr->internal[0] = dev->freeTnodes;
1188         dev->freeTnodes = (yaffs_Tnode *)mem;
1189
1190 #endif
1191
1192
1193         dev->nFreeTnodes += nTnodes;
1194         dev->nTnodesCreated += nTnodes;
1195
1196         /* Now add this bunch of tnodes to a list for freeing up.
1197          * NB If we can't add this to the management list it isn't fatal
1198          * but it just means we can't free this bunch of tnodes later.
1199          */
1200          
1201         tnl = YMALLOC(sizeof(yaffs_TnodeList));
1202         if (!tnl) {
1203                 T(YAFFS_TRACE_ERROR,
1204                   (TSTR
1205                    ("yaffs: Could not add tnodes to management list" TENDSTR)));
1206                    return YAFFS_FAIL;
1207
1208         } else {
1209                 tnl->tnodes = newTnodes;
1210                 tnl->next = dev->allocatedTnodeList;
1211                 dev->allocatedTnodeList = tnl;
1212         }
1213
1214         T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1215
1216         return YAFFS_OK;
1217 }
1218
1219 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1220
1221 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
1222 {
1223         yaffs_Tnode *tn = NULL;
1224
1225         /* If there are none left make more */
1226         if (!dev->freeTnodes) {
1227                 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1228         }
1229
1230         if (dev->freeTnodes) {
1231                 tn = dev->freeTnodes;
1232 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1233                 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1234                         /* Hoosterman, this thing looks like it isn't in the list */
1235                         T(YAFFS_TRACE_ALWAYS,
1236                           (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1237                 }
1238 #endif
1239                 dev->freeTnodes = dev->freeTnodes->internal[0];
1240                 dev->nFreeTnodes--;
1241         }
1242
1243         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1244
1245         return tn;
1246 }
1247
1248 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
1249 {
1250         yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1251         int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1252
1253         if(tnodeSize < sizeof(yaffs_Tnode))
1254                 tnodeSize = sizeof(yaffs_Tnode);
1255         
1256         if(tn)
1257                 memset(tn, 0, tnodeSize);
1258
1259         return tn;      
1260 }
1261
1262 /* FreeTnode frees up a tnode and puts it back on the free list */
1263 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
1264 {
1265         if (tn) {
1266 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1267                 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1268                         /* Hoosterman, this thing looks like it is already in the list */
1269                         T(YAFFS_TRACE_ALWAYS,
1270                           (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1271                 }
1272                 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1273 #endif
1274                 tn->internal[0] = dev->freeTnodes;
1275                 dev->freeTnodes = tn;
1276                 dev->nFreeTnodes++;
1277         }
1278         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1279         
1280 }
1281
1282 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
1283 {
1284         /* Free the list of allocated tnodes */
1285         yaffs_TnodeList *tmp;
1286
1287         while (dev->allocatedTnodeList) {
1288                 tmp = dev->allocatedTnodeList->next;
1289
1290                 YFREE(dev->allocatedTnodeList->tnodes);
1291                 YFREE(dev->allocatedTnodeList);
1292                 dev->allocatedTnodeList = tmp;
1293
1294         }
1295
1296         dev->freeTnodes = NULL;
1297         dev->nFreeTnodes = 0;
1298 }
1299
1300 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
1301 {
1302         dev->allocatedTnodeList = NULL;
1303         dev->freeTnodes = NULL;
1304         dev->nFreeTnodes = 0;
1305         dev->nTnodesCreated = 0;
1306
1307 }
1308
1309
1310 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
1311 {
1312   __u32 *map = (__u32 *)tn;
1313   __u32 bitInMap;
1314   __u32 bitInWord;
1315   __u32 wordInMap;
1316   __u32 mask;
1317   
1318   pos &= YAFFS_TNODES_LEVEL0_MASK;
1319   val >>= dev->chunkGroupBits;
1320   
1321   bitInMap = pos * dev->tnodeWidth;
1322   wordInMap = bitInMap /32;
1323   bitInWord = bitInMap & (32 -1);
1324   
1325   mask = dev->tnodeMask << bitInWord;
1326   
1327   map[wordInMap] &= ~mask;
1328   map[wordInMap] |= (mask & (val << bitInWord));
1329   
1330   if(dev->tnodeWidth > (32-bitInWord)) {
1331     bitInWord = (32 - bitInWord);
1332     wordInMap++;;
1333     mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1334     map[wordInMap] &= ~mask;
1335     map[wordInMap] |= (mask & (val >> bitInWord));
1336   }
1337 }
1338
1339 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
1340 {
1341   __u32 *map = (__u32 *)tn;
1342   __u32 bitInMap;
1343   __u32 bitInWord;
1344   __u32 wordInMap;
1345   __u32 val;
1346   
1347   pos &= YAFFS_TNODES_LEVEL0_MASK;
1348   
1349   bitInMap = pos * dev->tnodeWidth;
1350   wordInMap = bitInMap /32;
1351   bitInWord = bitInMap & (32 -1);
1352   
1353   val = map[wordInMap] >> bitInWord;
1354   
1355   if(dev->tnodeWidth > (32-bitInWord)) {
1356     bitInWord = (32 - bitInWord);
1357     wordInMap++;;
1358     val |= (map[wordInMap] << bitInWord);
1359   }
1360   
1361   val &= dev->tnodeMask;
1362   val <<= dev->chunkGroupBits;
1363   
1364   return val;
1365 }
1366
1367 /* ------------------- End of individual tnode manipulation -----------------*/
1368
1369 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1370  * The look up tree is represented by the top tnode and the number of topLevel
1371  * in the tree. 0 means only the level 0 tnode is in the tree.
1372  */
1373
1374 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1375 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
1376                                           yaffs_FileStructure * fStruct,
1377                                           __u32 chunkId)
1378 {
1379
1380         yaffs_Tnode *tn = fStruct->top;
1381         __u32 i;
1382         int requiredTallness;
1383         int level = fStruct->topLevel;
1384
1385         /* Check sane level and chunk Id */
1386         if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
1387                 return NULL;
1388         }
1389
1390         if (chunkId > YAFFS_MAX_CHUNK_ID) {
1391                 return NULL;
1392         }
1393
1394         /* First check we're tall enough (ie enough topLevel) */
1395
1396         i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1397         requiredTallness = 0;
1398         while (i) {
1399                 i >>= YAFFS_TNODES_INTERNAL_BITS;
1400                 requiredTallness++;
1401         }
1402
1403         if (requiredTallness > fStruct->topLevel) {
1404                 /* Not tall enough, so we can't find it, return NULL. */
1405                 return NULL;
1406         }
1407
1408         /* Traverse down to level 0 */
1409         while (level > 0 && tn) {
1410                 tn = tn->
1411                     internal[(chunkId >>
1412                                ( YAFFS_TNODES_LEVEL0_BITS + 
1413                                  (level - 1) *
1414                                  YAFFS_TNODES_INTERNAL_BITS)
1415                               ) &
1416                              YAFFS_TNODES_INTERNAL_MASK];
1417                 level--;
1418
1419         }
1420
1421         return tn;
1422 }
1423
1424 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1425  * This happens in two steps:
1426  *  1. If the tree isn't tall enough, then make it taller.
1427  *  2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1428  *
1429  * Used when modifying the tree.
1430  *
1431  *  If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1432  *  be plugged into the ttree.
1433  */
1434  
1435 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
1436                                                yaffs_FileStructure * fStruct,
1437                                                __u32 chunkId,
1438                                                yaffs_Tnode *passedTn)
1439 {
1440
1441         int requiredTallness;
1442         int i;
1443         int l;
1444         yaffs_Tnode *tn;
1445
1446         __u32 x;
1447
1448
1449         /* Check sane level and page Id */
1450         if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
1451                 return NULL;
1452         }
1453
1454         if (chunkId > YAFFS_MAX_CHUNK_ID) {
1455                 return NULL;
1456         }
1457
1458         /* First check we're tall enough (ie enough topLevel) */
1459
1460         x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1461         requiredTallness = 0;
1462         while (x) {
1463                 x >>= YAFFS_TNODES_INTERNAL_BITS;
1464                 requiredTallness++;
1465         }
1466
1467
1468         if (requiredTallness > fStruct->topLevel) {
1469                 /* Not tall enough,gotta make the tree taller */
1470                 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1471                 
1472                         tn = yaffs_GetTnode(dev);
1473
1474                         if (tn) {
1475                                 tn->internal[0] = fStruct->top;
1476                                 fStruct->top = tn;
1477                         } else {
1478                                 T(YAFFS_TRACE_ERROR,
1479                                   (TSTR("yaffs: no more tnodes" TENDSTR)));
1480                         }
1481                 }
1482
1483                 fStruct->topLevel = requiredTallness;
1484         }
1485
1486         /* Traverse down to level 0, adding anything we need */
1487
1488         l = fStruct->topLevel;
1489         tn = fStruct->top;
1490         
1491         if(l > 0) {
1492                 while (l > 0 && tn) {
1493                         x = (chunkId >>
1494                              ( YAFFS_TNODES_LEVEL0_BITS +
1495                               (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1496                             YAFFS_TNODES_INTERNAL_MASK;
1497
1498
1499                         if((l>1) && !tn->internal[x]){
1500                                 /* Add missing non-level-zero tnode */
1501                                 tn->internal[x] = yaffs_GetTnode(dev);
1502
1503                         } else if(l == 1) {
1504                                 /* Looking from level 1 at level 0 */
1505                                 if (passedTn) {
1506                                         /* If we already have one, then release it.*/
1507                                         if(tn->internal[x])
1508                                                 yaffs_FreeTnode(dev,tn->internal[x]);
1509                                         tn->internal[x] = passedTn;
1510                         
1511                                 } else if(!tn->internal[x]) {
1512                                         /* Don't have one, none passed in */
1513                                         tn->internal[x] = yaffs_GetTnode(dev);
1514                                 }
1515                         }
1516                 
1517                         tn = tn->internal[x];
1518                         l--;
1519                 }
1520         } else {
1521                 /* top is level 0 */
1522                 if(passedTn) {
1523                         memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1524                         yaffs_FreeTnode(dev,passedTn);
1525                 }
1526         }
1527
1528         return tn;
1529 }
1530
1531 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1532                                   yaffs_ExtendedTags * tags, int objectId,
1533                                   int chunkInInode)
1534 {
1535         int j;
1536
1537         for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1538                 if (yaffs_CheckChunkBit
1539                     (dev, theChunk / dev->nChunksPerBlock,
1540                      theChunk % dev->nChunksPerBlock)) {
1541                         yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1542                                                         tags);
1543                         if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1544                                 /* found it; */
1545                                 return theChunk;
1546
1547                         }
1548                 }
1549                 theChunk++;
1550         }
1551         return -1;
1552 }
1553
1554
1555 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1556  * chunks and tnodes in the file
1557  * Returns 1 if the tree was deleted. 
1558  * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1559  */
1560
1561 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1562                               int chunkOffset, int *limit)
1563 {
1564         int i;
1565         int chunkInInode;
1566         int theChunk;
1567         yaffs_ExtendedTags tags;
1568         int foundChunk;
1569         yaffs_Device *dev = in->myDev;
1570
1571         int allDone = 1;
1572
1573         if (tn) {
1574                 if (level > 0) {
1575
1576                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1577                              i--) {
1578                                 if (tn->internal[i]) {
1579                                         if (limit && (*limit) < 0) {
1580                                                 allDone = 0;
1581                                         } else {
1582                                                 allDone =
1583                                                     yaffs_DeleteWorker(in,
1584                                                                        tn->
1585                                                                        internal
1586                                                                        [i],
1587                                                                        level -
1588                                                                        1,
1589                                                                        (chunkOffset
1590                                                                         <<
1591                                                                         YAFFS_TNODES_INTERNAL_BITS)
1592                                                                        + i,
1593                                                                        limit);
1594                                         }
1595                                         if (allDone) {
1596                                                 yaffs_FreeTnode(dev,
1597                                                                 tn->
1598                                                                 internal[i]);
1599                                                 tn->internal[i] = NULL;
1600                                         }
1601                                 }
1602
1603                         }
1604                         return (allDone) ? 1 : 0;
1605                 } else if (level == 0) {
1606                         int hitLimit = 0;
1607
1608                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1609                              i--) {
1610                                 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1611                                 if (theChunk) {
1612
1613                                         chunkInInode =
1614                                             (chunkOffset <<
1615                                              YAFFS_TNODES_LEVEL0_BITS) + i;
1616
1617                                         foundChunk =
1618                                             yaffs_FindChunkInGroup(dev,
1619                                                                    theChunk,
1620                                                                    &tags,
1621                                                                    in->objectId,
1622                                                                    chunkInInode);
1623
1624                                         if (foundChunk > 0) {
1625                                                 yaffs_DeleteChunk(dev,
1626                                                                   foundChunk, 1,
1627                                                                   __LINE__);
1628                                                 in->nDataChunks--;
1629                                                 if (limit) {
1630                                                         *limit = *limit - 1;
1631                                                         if (*limit <= 0) {
1632                                                                 hitLimit = 1;
1633                                                         }
1634                                                 }
1635
1636                                         }
1637
1638                                         yaffs_PutLevel0Tnode(dev,tn,i,0);
1639                                 }
1640
1641                         }
1642                         return (i < 0) ? 1 : 0;
1643
1644                 }
1645
1646         }
1647
1648         return 1;
1649
1650 }
1651
1652 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1653 {
1654
1655         yaffs_BlockInfo *theBlock;
1656
1657         T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1658
1659         theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1660         if (theBlock) {
1661                 theBlock->softDeletions++;
1662                 dev->nFreeChunks++;
1663         }
1664 }
1665
1666 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1667  * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1668  * of the tnode.
1669  * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1670  */
1671  
1672 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1673                                   __u32 level, int chunkOffset)
1674 {
1675         int i;
1676         int theChunk;
1677         int allDone = 1;
1678         yaffs_Device *dev = in->myDev;
1679
1680         if (tn) {
1681                 if (level > 0) {
1682
1683                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1684                              i--) {
1685                                 if (tn->internal[i]) {
1686                                         allDone =
1687                                             yaffs_SoftDeleteWorker(in,
1688                                                                    tn->
1689                                                                    internal[i],
1690                                                                    level - 1,
1691                                                                    (chunkOffset
1692                                                                     <<
1693                                                                     YAFFS_TNODES_INTERNAL_BITS)
1694                                                                    + i);
1695                                         if (allDone) {
1696                                                 yaffs_FreeTnode(dev,
1697                                                                 tn->
1698                                                                 internal[i]);
1699                                                 tn->internal[i] = NULL;
1700                                         } else {
1701                                                 /* Hoosterman... how could this happen? */
1702                                         }
1703                                 }
1704                         }
1705                         return (allDone) ? 1 : 0;
1706                 } else if (level == 0) {
1707
1708                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1709                                 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1710                                 if (theChunk) {
1711                                         /* Note this does not find the real chunk, only the chunk group.
1712                                          * We make an assumption that a chunk group is not larger than 
1713                                          * a block.
1714                                          */
1715                                         yaffs_SoftDeleteChunk(dev, theChunk);
1716                                         yaffs_PutLevel0Tnode(dev,tn,i,0);
1717                                 }
1718
1719                         }
1720                         return 1;
1721
1722                 }
1723
1724         }
1725
1726         return 1;
1727
1728 }
1729
1730 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1731 {
1732         if (obj->deleted &&
1733             obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1734                 if (obj->nDataChunks <= 0) {
1735                         /* Empty file with no duplicate object headers, just delete it immediately */
1736                         yaffs_FreeTnode(obj->myDev,
1737                                         obj->variant.fileVariant.top);
1738                         obj->variant.fileVariant.top = NULL;
1739                         T(YAFFS_TRACE_TRACING,
1740                           (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1741                            obj->objectId));
1742                         yaffs_DoGenericObjectDeletion(obj);
1743                 } else {
1744                         yaffs_SoftDeleteWorker(obj,
1745                                                obj->variant.fileVariant.top,
1746                                                obj->variant.fileVariant.
1747                                                topLevel, 0);
1748                         obj->softDeleted = 1;
1749                 }
1750         }
1751 }
1752
1753 /* Pruning removes any part of the file structure tree that is beyond the
1754  * bounds of the file (ie that does not point to chunks).
1755  *
1756  * A file should only get pruned when its size is reduced.
1757  *
1758  * Before pruning, the chunks must be pulled from the tree and the
1759  * level 0 tnode entries must be zeroed out.
1760  * Could also use this for file deletion, but that's probably better handled
1761  * by a special case.
1762  */
1763
1764 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1765                                       __u32 level, int del0)
1766 {
1767         int i;
1768         int hasData;
1769
1770         if (tn) {
1771                 hasData = 0;
1772
1773                 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1774                         if (tn->internal[i] && level > 0) {
1775                                 tn->internal[i] =
1776                                     yaffs_PruneWorker(dev, tn->internal[i],
1777                                                       level - 1,
1778                                                       (i == 0) ? del0 : 1);
1779                         }
1780
1781                         if (tn->internal[i]) {
1782                                 hasData++;
1783                         }
1784                 }
1785
1786                 if (hasData == 0 && del0) {
1787                         /* Free and return NULL */
1788
1789                         yaffs_FreeTnode(dev, tn);
1790                         tn = NULL;
1791                 }
1792
1793         }
1794
1795         return tn;
1796
1797 }
1798
1799 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1800                                     yaffs_FileStructure * fStruct)
1801 {
1802         int i;
1803         int hasData;
1804         int done = 0;
1805         yaffs_Tnode *tn;
1806
1807         if (fStruct->topLevel > 0) {
1808                 fStruct->top =
1809                     yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1810
1811                 /* Now we have a tree with all the non-zero branches NULL but the height
1812                  * is the same as it was.
1813                  * Let's see if we can trim internal tnodes to shorten the tree.
1814                  * We can do this if only the 0th element in the tnode is in use 
1815                  * (ie all the non-zero are NULL)
1816                  */
1817
1818                 while (fStruct->topLevel && !done) {
1819                         tn = fStruct->top;
1820
1821                         hasData = 0;
1822                         for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1823                                 if (tn->internal[i]) {
1824                                         hasData++;
1825                                 }
1826                         }
1827
1828                         if (!hasData) {
1829                                 fStruct->top = tn->internal[0];
1830                                 fStruct->topLevel--;
1831                                 yaffs_FreeTnode(dev, tn);
1832                         } else {
1833                                 done = 1;
1834                         }
1835                 }
1836         }
1837
1838         return YAFFS_OK;
1839 }
1840
1841 /*-------------------- End of File Structure functions.-------------------*/
1842
1843 /* yaffs_CreateFreeObjects creates a bunch more objects and
1844  * adds them to the object free list.
1845  */
1846 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1847 {
1848         int i;
1849         yaffs_Object *newObjects;
1850         yaffs_ObjectList *list;
1851
1852         if (nObjects < 1)
1853                 return YAFFS_OK;
1854
1855         /* make these things */
1856         newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1857         list = YMALLOC(sizeof(yaffs_ObjectList));
1858
1859         if (!newObjects || !list) {
1860                 if(newObjects)
1861                         YFREE(newObjects);
1862                 if(list)
1863                         YFREE(list);
1864                 T(YAFFS_TRACE_ALLOCATE,
1865                   (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1866                 return YAFFS_FAIL;
1867         }
1868         
1869         /* Hook them into the free list */
1870         for (i = 0; i < nObjects - 1; i++) {
1871                 newObjects[i].siblings.next =
1872                     (struct list_head *)(&newObjects[i + 1]);
1873         }
1874
1875         newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1876         dev->freeObjects = newObjects;
1877         dev->nFreeObjects += nObjects;
1878         dev->nObjectsCreated += nObjects;
1879
1880         /* Now add this bunch of Objects to a list for freeing up. */
1881
1882         list->objects = newObjects;
1883         list->next = dev->allocatedObjectList;
1884         dev->allocatedObjectList = list;
1885
1886         return YAFFS_OK;
1887 }
1888
1889
1890 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1891 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1892 {
1893         yaffs_Object *tn = NULL;
1894
1895         /* If there are none left make more */
1896         if (!dev->freeObjects) {
1897                 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1898         }
1899
1900         if (dev->freeObjects) {
1901                 tn = dev->freeObjects;
1902                 dev->freeObjects =
1903                     (yaffs_Object *) (dev->freeObjects->siblings.next);
1904                 dev->nFreeObjects--;
1905
1906                 /* Now sweeten it up... */
1907
1908                 memset(tn, 0, sizeof(yaffs_Object));
1909                 tn->myDev = dev;
1910                 tn->chunkId = -1;
1911                 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1912                 INIT_LIST_HEAD(&(tn->hardLinks));
1913                 INIT_LIST_HEAD(&(tn->hashLink));
1914                 INIT_LIST_HEAD(&tn->siblings);
1915
1916                 /* Add it to the lost and found directory.
1917                  * NB Can't put root or lostNFound in lostNFound so
1918                  * check if lostNFound exists first
1919                  */
1920                 if (dev->lostNFoundDir) {
1921                         yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1922                 }
1923         }
1924         
1925         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1926
1927         return tn;
1928 }
1929
1930 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1931                                                __u32 mode)
1932 {
1933
1934         yaffs_Object *obj =
1935             yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1936         if (obj) {
1937                 obj->fake = 1;          /* it is fake so it has no NAND presence... */
1938                 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1939                 obj->unlinkAllowed = 0; /* ... or unlink it */
1940                 obj->deleted = 0;
1941                 obj->unlinked = 0;
1942                 obj->yst_mode = mode;
1943                 obj->myDev = dev;
1944                 obj->chunkId = 0;       /* Not a valid chunk. */
1945         }
1946
1947         return obj;
1948
1949 }
1950
1951 static void yaffs_UnhashObject(yaffs_Object * tn)
1952 {
1953         int bucket;
1954         yaffs_Device *dev = tn->myDev;
1955
1956         /* If it is still linked into the bucket list, free from the list */
1957         if (!list_empty(&tn->hashLink)) {
1958                 list_del_init(&tn->hashLink);
1959                 bucket = yaffs_HashFunction(tn->objectId);
1960                 dev->objectBucket[bucket].count--;
1961         }
1962
1963 }
1964
1965 /*  FreeObject frees up a Object and puts it back on the free list */
1966 static void yaffs_FreeObject(yaffs_Object * tn)
1967 {
1968
1969         yaffs_Device *dev = tn->myDev;
1970
1971 #ifdef  __KERNEL__
1972         if (tn->myInode) {
1973                 /* We're still hooked up to a cached inode.
1974                  * Don't delete now, but mark for later deletion
1975                  */
1976                 tn->deferedFree = 1;
1977                 return;
1978         }
1979 #endif
1980
1981         yaffs_UnhashObject(tn);
1982
1983         /* Link into the free list. */
1984         tn->siblings.next = (struct list_head *)(dev->freeObjects);
1985         dev->freeObjects = tn;
1986         dev->nFreeObjects++;
1987
1988         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1989
1990 }
1991
1992 #ifdef __KERNEL__
1993
1994 void yaffs_HandleDeferedFree(yaffs_Object * obj)
1995 {
1996         if (obj->deferedFree) {
1997                 yaffs_FreeObject(obj);
1998         }
1999 }
2000
2001 #endif
2002
2003 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
2004 {
2005         /* Free the list of allocated Objects */
2006
2007         yaffs_ObjectList *tmp;
2008
2009         while (dev->allocatedObjectList) {
2010                 tmp = dev->allocatedObjectList->next;
2011                 YFREE(dev->allocatedObjectList->objects);
2012                 YFREE(dev->allocatedObjectList);
2013
2014                 dev->allocatedObjectList = tmp;
2015         }
2016
2017         dev->freeObjects = NULL;
2018         dev->nFreeObjects = 0;
2019 }
2020
2021 static void yaffs_InitialiseObjects(yaffs_Device * dev)
2022 {
2023         int i;
2024
2025         dev->allocatedObjectList = NULL;
2026         dev->freeObjects = NULL;
2027         dev->nFreeObjects = 0;
2028
2029         for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2030                 INIT_LIST_HEAD(&dev->objectBucket[i].list);
2031                 dev->objectBucket[i].count = 0;
2032         }
2033
2034 }
2035
2036 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
2037 {
2038         static int x = 0;
2039         int i;
2040         int l = 999;
2041         int lowest = 999999;
2042
2043         /* First let's see if we can find one that's empty. */
2044
2045         for (i = 0; i < 10 && lowest > 0; i++) {
2046                 x++;
2047                 x %= YAFFS_NOBJECT_BUCKETS;
2048                 if (dev->objectBucket[x].count < lowest) {
2049                         lowest = dev->objectBucket[x].count;
2050                         l = x;
2051                 }
2052
2053         }
2054
2055         /* If we didn't find an empty list, then try
2056          * looking a bit further for a short one
2057          */
2058
2059         for (i = 0; i < 10 && lowest > 3; i++) {
2060                 x++;
2061                 x %= YAFFS_NOBJECT_BUCKETS;
2062                 if (dev->objectBucket[x].count < lowest) {
2063                         lowest = dev->objectBucket[x].count;
2064                         l = x;
2065                 }
2066
2067         }
2068
2069         return l;
2070 }
2071
2072 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
2073 {
2074         int bucket = yaffs_FindNiceObjectBucket(dev);
2075
2076         /* Now find an object value that has not already been taken
2077          * by scanning the list.
2078          */
2079
2080         int found = 0;
2081         struct list_head *i;
2082
2083         __u32 n = (__u32) bucket;
2084
2085         /* yaffs_CheckObjectHashSanity();  */
2086
2087         while (!found) {
2088                 found = 1;
2089                 n += YAFFS_NOBJECT_BUCKETS;
2090                 if (1 || dev->objectBucket[bucket].count > 0) {
2091                         list_for_each(i, &dev->objectBucket[bucket].list) {
2092                                 /* If there is already one in the list */
2093                                 if (i
2094                                     && list_entry(i, yaffs_Object,
2095                                                   hashLink)->objectId == n) {
2096                                         found = 0;
2097                                 }
2098                         }
2099                 }
2100         }
2101
2102
2103         return n;
2104 }
2105
2106 static void yaffs_HashObject(yaffs_Object * in)
2107 {
2108         int bucket = yaffs_HashFunction(in->objectId);
2109         yaffs_Device *dev = in->myDev;
2110
2111         list_add(&in->hashLink, &dev->objectBucket[bucket].list);
2112         dev->objectBucket[bucket].count++;
2113
2114 }
2115
2116 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
2117 {
2118         int bucket = yaffs_HashFunction(number);
2119         struct list_head *i;
2120         yaffs_Object *in;
2121
2122         list_for_each(i, &dev->objectBucket[bucket].list) {
2123                 /* Look if it is in the list */
2124                 if (i) {
2125                         in = list_entry(i, yaffs_Object, hashLink);
2126                         if (in->objectId == number) {
2127 #ifdef __KERNEL__
2128                                 /* Don't tell the VFS about this one if it is defered free */
2129                                 if (in->deferedFree)
2130                                         return NULL;
2131 #endif
2132
2133                                 return in;
2134                         }
2135                 }
2136         }
2137
2138         return NULL;
2139 }
2140
2141 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
2142                                     yaffs_ObjectType type)
2143 {
2144
2145         yaffs_Object *theObject;
2146         yaffs_Tnode *tn;
2147
2148         if (number < 0) {
2149                 number = yaffs_CreateNewObjectNumber(dev);
2150         }
2151
2152         theObject = yaffs_AllocateEmptyObject(dev);
2153         if(!theObject)
2154                 return NULL;
2155                 
2156         if(type == YAFFS_OBJECT_TYPE_FILE){
2157                 tn = yaffs_GetTnode(dev);
2158                 if(!tn){
2159                         yaffs_FreeObject(theObject);
2160                         return NULL;
2161                 }
2162         }
2163                 
2164         
2165
2166         if (theObject) {
2167                 theObject->fake = 0;
2168                 theObject->renameAllowed = 1;
2169                 theObject->unlinkAllowed = 1;
2170                 theObject->objectId = number;
2171                 yaffs_HashObject(theObject);
2172                 theObject->variantType = type;
2173 #ifdef CONFIG_YAFFS_WINCE
2174                 yfsd_WinFileTimeNow(theObject->win_atime);
2175                 theObject->win_ctime[0] = theObject->win_mtime[0] =
2176                     theObject->win_atime[0];
2177                 theObject->win_ctime[1] = theObject->win_mtime[1] =
2178                     theObject->win_atime[1];
2179
2180 #else
2181
2182                 theObject->yst_atime = theObject->yst_mtime =
2183                     theObject->yst_ctime = Y_CURRENT_TIME;
2184 #endif
2185                 switch (type) {
2186                 case YAFFS_OBJECT_TYPE_FILE:
2187                         theObject->variant.fileVariant.fileSize = 0;
2188                         theObject->variant.fileVariant.scannedFileSize = 0;
2189                         theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2190                         theObject->variant.fileVariant.topLevel = 0;
2191                         theObject->variant.fileVariant.top = tn;
2192                         break;
2193                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2194                         INIT_LIST_HEAD(&theObject->variant.directoryVariant.
2195                                        children);
2196                         break;
2197                 case YAFFS_OBJECT_TYPE_SYMLINK:
2198                 case YAFFS_OBJECT_TYPE_HARDLINK:
2199                 case YAFFS_OBJECT_TYPE_SPECIAL:
2200                         /* No action required */
2201                         break;
2202                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2203                         /* todo this should not happen */
2204                         break;
2205                 }
2206         }
2207
2208         return theObject;
2209 }
2210
2211 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
2212                                                       int number,
2213                                                       yaffs_ObjectType type)
2214 {
2215         yaffs_Object *theObject = NULL;
2216
2217         if (number > 0) {
2218                 theObject = yaffs_FindObjectByNumber(dev, number);
2219         }
2220
2221         if (!theObject) {
2222                 theObject = yaffs_CreateNewObject(dev, number, type);
2223         }
2224
2225         return theObject;
2226
2227 }
2228                         
2229
2230 static YCHAR *yaffs_CloneString(const YCHAR * str)
2231 {
2232         YCHAR *newStr = NULL;
2233
2234         if (str && *str) {
2235                 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2236                 if(newStr)
2237                         yaffs_strcpy(newStr, str);
2238         }
2239
2240         return newStr;
2241
2242 }
2243
2244 /*
2245  * Mknod (create) a new object.
2246  * equivalentObject only has meaning for a hard link;
2247  * aliasString only has meaning for a sumlink.
2248  * rdev only has meaning for devices (a subset of special objects)
2249  */
2250  
2251 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2252                                        yaffs_Object * parent,
2253                                        const YCHAR * name,
2254                                        __u32 mode,
2255                                        __u32 uid,
2256                                        __u32 gid,
2257                                        yaffs_Object * equivalentObject,
2258                                        const YCHAR * aliasString, __u32 rdev)
2259 {
2260         yaffs_Object *in;
2261         YCHAR *str;
2262
2263         yaffs_Device *dev = parent->myDev;
2264
2265         /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2266         if (yaffs_FindObjectByName(parent, name)) {
2267                 return NULL;
2268         }
2269
2270         in = yaffs_CreateNewObject(dev, -1, type);
2271         
2272         if(type == YAFFS_OBJECT_TYPE_SYMLINK){
2273                 str = yaffs_CloneString(aliasString);
2274                 if(!str){
2275                         yaffs_FreeObject(in);
2276                         return NULL;
2277                 }
2278         }
2279         
2280         
2281
2282         if (in) {
2283                 in->chunkId = -1;
2284                 in->valid = 1;
2285                 in->variantType = type;
2286
2287                 in->yst_mode = mode;
2288
2289 #ifdef CONFIG_YAFFS_WINCE
2290                 yfsd_WinFileTimeNow(in->win_atime);
2291                 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2292                 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2293
2294 #else
2295                 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2296
2297                 in->yst_rdev = rdev;
2298                 in->yst_uid = uid;
2299                 in->yst_gid = gid;
2300 #endif
2301                 in->nDataChunks = 0;
2302
2303                 yaffs_SetObjectName(in, name);
2304                 in->dirty = 1;
2305
2306                 yaffs_AddObjectToDirectory(parent, in);
2307
2308                 in->myDev = parent->myDev;
2309
2310                 switch (type) {
2311                 case YAFFS_OBJECT_TYPE_SYMLINK:
2312                         in->variant.symLinkVariant.alias = str;
2313                         break;
2314                 case YAFFS_OBJECT_TYPE_HARDLINK:
2315                         in->variant.hardLinkVariant.equivalentObject =
2316                             equivalentObject;
2317                         in->variant.hardLinkVariant.equivalentObjectId =
2318                             equivalentObject->objectId;
2319                         list_add(&in->hardLinks, &equivalentObject->hardLinks);
2320                         break;
2321                 case YAFFS_OBJECT_TYPE_FILE:    
2322                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2323                 case YAFFS_OBJECT_TYPE_SPECIAL:
2324                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2325                         /* do nothing */
2326                         break;
2327                 }
2328
2329                 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2330                         /* Could not create the object header, fail the creation */
2331                         yaffs_DestroyObject(in);
2332                         in = NULL;
2333                 }
2334
2335         }
2336
2337         return in;
2338 }
2339
2340 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
2341                               __u32 mode, __u32 uid, __u32 gid)
2342 {
2343         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2344                                  uid, gid, NULL, NULL, 0);
2345 }
2346
2347 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
2348                                    __u32 mode, __u32 uid, __u32 gid)
2349 {
2350         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2351                                  mode, uid, gid, NULL, NULL, 0);
2352 }
2353
2354 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
2355                                  __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2356 {
2357         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2358                                  uid, gid, NULL, NULL, rdev);
2359 }
2360
2361 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
2362                                  __u32 mode, __u32 uid, __u32 gid,
2363                                  const YCHAR * alias)
2364 {
2365         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2366                                  uid, gid, NULL, alias, 0);
2367 }
2368
2369 /* yaffs_Link returns the object id of the equivalent object.*/
2370 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
2371                          yaffs_Object * equivalentObject)
2372 {
2373         /* Get the real object in case we were fed a hard link as an equivalent object */
2374         equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2375
2376         if (yaffs_MknodObject
2377             (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2378              equivalentObject, NULL, 0)) {
2379                 return equivalentObject;
2380         } else {
2381                 return NULL;
2382         }
2383
2384 }
2385
2386 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
2387                                   const YCHAR * newName, int force, int shadows)
2388 {
2389         int unlinkOp;
2390         int deleteOp;
2391
2392         yaffs_Object *existingTarget;
2393
2394         if (newDir == NULL) {
2395                 newDir = obj->parent;   /* use the old directory */
2396         }
2397
2398         if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2399                 T(YAFFS_TRACE_ALWAYS,
2400                   (TSTR
2401                    ("tragendy: yaffs_ChangeObjectName: newDir is not a directory"
2402                     TENDSTR)));
2403                 YBUG();
2404         }
2405         
2406         /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2407         if (obj->myDev->isYaffs2) {
2408                 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2409         } else {
2410                 unlinkOp = (newDir == obj->myDev->unlinkedDir
2411                             && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2412         }
2413
2414         deleteOp = (newDir == obj->myDev->deletedDir);
2415
2416         existingTarget = yaffs_FindObjectByName(newDir, newName);
2417
2418         /* If the object is a file going into the unlinked directory, 
2419          *   then it is OK to just stuff it in since duplicate names are allowed.
2420          *   else only proceed if the new name does not exist and if we're putting 
2421          *   it into a directory.
2422          */
2423         if ((unlinkOp ||
2424              deleteOp ||
2425              force ||
2426              (shadows > 0) ||
2427              !existingTarget) &&
2428             newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2429                 yaffs_SetObjectName(obj, newName);
2430                 obj->dirty = 1;
2431
2432                 yaffs_AddObjectToDirectory(newDir, obj);
2433
2434                 if (unlinkOp)
2435                         obj->unlinked = 1;
2436
2437                 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2438                 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
2439                         return YAFFS_OK;
2440         }
2441
2442         return YAFFS_FAIL;
2443 }
2444
2445 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
2446                        yaffs_Object * newDir, const YCHAR * newName)
2447 {
2448         yaffs_Object *obj;
2449         yaffs_Object *existingTarget;
2450         int force = 0;
2451
2452 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2453         /* Special case for case insemsitive systems (eg. WinCE).
2454          * While look-up is case insensitive, the name isn't.
2455          * Therefore we might want to change x.txt to X.txt
2456         */
2457         if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
2458                 force = 1;
2459         }
2460 #endif
2461
2462         obj = yaffs_FindObjectByName(oldDir, oldName);
2463         /* Check new name to long. */
2464         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK &&
2465             yaffs_strlen(newName) > YAFFS_MAX_ALIAS_LENGTH)
2466           /* ENAMETOOLONG */
2467           return YAFFS_FAIL;
2468         else if (obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK &&
2469                  yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2470           /* ENAMETOOLONG */
2471           return YAFFS_FAIL;
2472
2473         if (obj && obj->renameAllowed) {
2474
2475                 /* Now do the handling for an existing target, if there is one */
2476
2477                 existingTarget = yaffs_FindObjectByName(newDir, newName);
2478                 if (existingTarget &&
2479                     existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2480                     !list_empty(&existingTarget->variant.directoryVariant.children)) {
2481                         /* There is a target that is a non-empty directory, so we fail */
2482                         return YAFFS_FAIL;      /* EEXIST or ENOTEMPTY */
2483                 } else if (existingTarget && existingTarget != obj) {
2484                         /* Nuke the target first, using shadowing, 
2485                          * but only if it isn't the same object
2486                          */
2487                         yaffs_ChangeObjectName(obj, newDir, newName, force,
2488                                                existingTarget->objectId);
2489                         yaffs_UnlinkObject(existingTarget);
2490                 }
2491
2492                 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2493         }
2494         return YAFFS_FAIL;
2495 }
2496
2497 /*------------------------- Block Management and Page Allocation ----------------*/
2498
2499 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
2500 {
2501         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2502         
2503         dev->blockInfo = NULL;
2504         dev->chunkBits = NULL;
2505         
2506         dev->allocationBlock = -1;      /* force it to get a new one */
2507
2508         /* If the first allocation strategy fails, thry the alternate one */
2509         dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2510         if(!dev->blockInfo){
2511                 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2512                 dev->blockInfoAlt = 1;
2513         }
2514         else
2515                 dev->blockInfoAlt = 0;
2516                 
2517         if(dev->blockInfo){
2518         
2519                 /* Set up dynamic blockinfo stuff. */
2520                 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2521                 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2522                 if(!dev->chunkBits){
2523                         dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2524                         dev->chunkBitsAlt = 1;
2525                 }
2526                 else
2527                         dev->chunkBitsAlt = 0;
2528         }
2529         
2530         if (dev->blockInfo && dev->chunkBits) {
2531                 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2532                 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2533                 return YAFFS_OK;
2534         }
2535
2536         return YAFFS_FAIL;
2537
2538 }
2539
2540 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
2541 {
2542         if(dev->blockInfoAlt && dev->blockInfo)
2543                 YFREE_ALT(dev->blockInfo);
2544         else if(dev->blockInfo)
2545                 YFREE(dev->blockInfo);
2546
2547         dev->blockInfoAlt = 0;
2548
2549         dev->blockInfo = NULL;
2550         
2551         if(dev->chunkBitsAlt && dev->chunkBits)
2552                 YFREE_ALT(dev->chunkBits);
2553         else if(dev->chunkBits)
2554                 YFREE(dev->chunkBits);
2555         dev->chunkBitsAlt = 0;
2556         dev->chunkBits = NULL;
2557 }
2558
2559 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
2560                                             yaffs_BlockInfo * bi)
2561 {
2562         int i;
2563         __u32 seq;
2564         yaffs_BlockInfo *b;
2565
2566         if (!dev->isYaffs2)
2567                 return 1;       /* disqualification only applies to yaffs2. */
2568
2569         if (!bi->hasShrinkHeader)
2570                 return 1;       /* can gc */
2571
2572         /* Find the oldest dirty sequence number if we don't know it and save it
2573          * so we don't have to keep recomputing it.
2574          */
2575         if (!dev->oldestDirtySequence) {
2576                 seq = dev->sequenceNumber;
2577
2578                 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2579                      i++) {
2580                         b = yaffs_GetBlockInfo(dev, i);
2581                         if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2582                             (b->pagesInUse - b->softDeletions) <
2583                             dev->nChunksPerBlock && b->sequenceNumber < seq) {
2584                                 seq = b->sequenceNumber;
2585                         }
2586                 }
2587                 dev->oldestDirtySequence = seq;
2588         }
2589
2590         /* Can't do gc of this block if there are any blocks older than this one that have
2591          * discarded pages.
2592          */
2593         return (bi->sequenceNumber <= dev->oldestDirtySequence);
2594
2595 }
2596
2597 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2598  * for garbage collection.
2599  */
2600
2601 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2602                                                int aggressive)
2603 {
2604
2605         int b = dev->currentDirtyChecker;
2606
2607         int i;
2608         int iterations;
2609         int dirtiest = -1;
2610         int pagesInUse = 0;
2611         int prioritised=0;
2612         yaffs_BlockInfo *bi;
2613         int pendingPrioritisedExist = 0;
2614         
2615         /* First let's see if we need to grab a prioritised block */
2616         if(dev->hasPendingPrioritisedGCs){
2617                 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2618
2619                         bi = yaffs_GetBlockInfo(dev, i);
2620                         //yaffs_VerifyBlock(dev,bi,i);
2621                         
2622                         if(bi->gcPrioritise) {
2623                                 pendingPrioritisedExist = 1;
2624                                 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2625                                    yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2626                                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
2627                                         dirtiest = i;
2628                                         prioritised = 1;
2629                                         aggressive = 1; /* Fool the non-aggressive skip logiv below */
2630                                 }
2631                         }
2632                 }
2633                 
2634                 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2635                         dev->hasPendingPrioritisedGCs = 0;
2636         }
2637
2638         /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2639          * search harder.
2640          * else (we're doing a leasurely gc), then we only bother to do this if the
2641          * block has only a few pages in use.
2642          */
2643
2644         dev->nonAggressiveSkip--;
2645
2646         if (!aggressive && (dev->nonAggressiveSkip > 0)) {
2647                 return -1;
2648         }
2649
2650         if(!prioritised)
2651                 pagesInUse =
2652                         (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2653
2654         if (aggressive) {
2655                 iterations =
2656                     dev->internalEndBlock - dev->internalStartBlock + 1;
2657         } else {
2658                 iterations =
2659                     dev->internalEndBlock - dev->internalStartBlock + 1;
2660                 iterations = iterations / 16;
2661                 if (iterations > 200) {
2662                         iterations = 200;
2663                 }
2664         }
2665
2666         for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2667                 b++;
2668                 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2669                         b = dev->internalStartBlock;
2670                 }
2671
2672                 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2673                         T(YAFFS_TRACE_ERROR,
2674                           (TSTR("**>> Block %d is not valid" TENDSTR), b));
2675                         YBUG();
2676                 }
2677
2678                 bi = yaffs_GetBlockInfo(dev, b);
2679
2680 #if 0
2681                 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2682                         dirtiest = b;
2683                         pagesInUse = 0;
2684                 }
2685                 else 
2686 #endif
2687
2688                 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2689                        (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2690                         yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2691                         dirtiest = b;
2692                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
2693                 }
2694         }
2695
2696         dev->currentDirtyChecker = b;
2697
2698         if (dirtiest > 0) {
2699                 T(YAFFS_TRACE_GC,
2700                   (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2701                    dev->nChunksPerBlock - pagesInUse,prioritised));
2702         }
2703
2704         dev->oldestDirtySequence = 0;
2705
2706         if (dirtiest > 0) {
2707                 dev->nonAggressiveSkip = 4;
2708         }
2709
2710         return dirtiest;
2711 }
2712
2713 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2714 {
2715         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2716
2717         int erasedOk = 0;
2718
2719         /* If the block is still healthy erase it and mark as clean.
2720          * If the block has had a data failure, then retire it.
2721          */
2722          
2723         T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2724                 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2725                 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2726                 
2727         bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2728
2729         if (!bi->needsRetiring) {
2730                 yaffs_InvalidateCheckpoint(dev);
2731                 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2732                 if (!erasedOk) {
2733                         dev->nErasureFailures++;
2734                         T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2735                           (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2736                 }
2737         }
2738
2739         if (erasedOk && 
2740             ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2741                 int i;
2742                 for (i = 0; i < dev->nChunksPerBlock; i++) {
2743                         if (!yaffs_CheckChunkErased
2744                             (dev, blockNo * dev->nChunksPerBlock + i)) {
2745                                 T(YAFFS_TRACE_ERROR,
2746                                   (TSTR
2747                                    (">>Block %d erasure supposedly OK, but chunk %d not erased"
2748                                     TENDSTR), blockNo, i));
2749                         }
2750                 }
2751         }
2752
2753         if (erasedOk) {
2754                 /* Clean it up... */
2755                 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2756                 dev->nErasedBlocks++;
2757                 bi->pagesInUse = 0;
2758                 bi->softDeletions = 0;
2759                 bi->hasShrinkHeader = 0;
2760                 bi->skipErasedCheck = 1;  /* This is clean, so no need to check */
2761                 bi->gcPrioritise = 0;
2762                 yaffs_ClearChunkBits(dev, blockNo);
2763
2764                 T(YAFFS_TRACE_ERASE,
2765                   (TSTR("Erased block %d" TENDSTR), blockNo));
2766         } else {
2767                 dev->nFreeChunks -= dev->nChunksPerBlock;       /* We lost a block of free space */
2768
2769                 yaffs_RetireBlock(dev, blockNo);
2770                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2771                   (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2772         }
2773 }
2774
2775 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2776 {
2777         int i;
2778
2779         yaffs_BlockInfo *bi;
2780
2781         if (dev->nErasedBlocks < 1) {
2782                 /* Hoosterman we've got a problem.
2783                  * Can't get space to gc
2784                  */
2785                 T(YAFFS_TRACE_ERROR,
2786                   (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2787
2788                 return -1;
2789         }
2790         
2791         /* Find an empty block. */
2792
2793         for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2794                 dev->allocationBlockFinder++;
2795                 if (dev->allocationBlockFinder < dev->internalStartBlock
2796                     || dev->allocationBlockFinder > dev->internalEndBlock) {
2797                         dev->allocationBlockFinder = dev->internalStartBlock;
2798                 }
2799
2800                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2801
2802                 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2803                         bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2804                         dev->sequenceNumber++;
2805                         bi->sequenceNumber = dev->sequenceNumber;
2806                         dev->nErasedBlocks--;
2807                         T(YAFFS_TRACE_ALLOCATE,
2808                           (TSTR("Allocated block %d, seq  %d, %d left" TENDSTR),
2809                            dev->allocationBlockFinder, dev->sequenceNumber,
2810                            dev->nErasedBlocks));
2811                         return dev->allocationBlockFinder;
2812                 }
2813         }
2814
2815         T(YAFFS_TRACE_ALWAYS,
2816           (TSTR
2817            ("yaffs tragedy: no more eraased blocks, but there should have been %d"
2818             TENDSTR), dev->nErasedBlocks));
2819
2820         return -1;
2821 }
2822
2823
2824
2825 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2826 {
2827         if(!dev->nCheckpointBlocksRequired){
2828                 /* Not a valid value so recalculate */
2829                 int nBytes = 0;
2830                 int nBlocks;
2831                 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2832                 int tnodeSize;
2833
2834                 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2835
2836                 if(tnodeSize < sizeof(yaffs_Tnode))
2837                         tnodeSize = sizeof(yaffs_Tnode);
2838                 
2839                 nBytes += sizeof(yaffs_CheckpointValidity);
2840                 nBytes += sizeof(yaffs_CheckpointDevice);
2841                 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2842                 nBytes += devBlocks * dev->chunkBitmapStride;
2843                 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2844                 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2845                 nBytes += sizeof(yaffs_CheckpointValidity);
2846                 nBytes += sizeof(__u32); /* checksum*/
2847         
2848                 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2849         
2850                 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2851         
2852                 dev->nCheckpointBlocksRequired = nBlocks;
2853         }
2854
2855         return dev->nCheckpointBlocksRequired;
2856 }
2857
2858 // Check if there's space to allocate...
2859 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2860 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2861 {
2862         int reservedChunks;
2863         int reservedBlocks = dev->nReservedBlocks;
2864         int checkpointBlocks;
2865         
2866         checkpointBlocks =  yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
2867         if(checkpointBlocks < 0)
2868                 checkpointBlocks = 0;
2869         
2870         reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2871         
2872         return (dev->nFreeChunks > reservedChunks);
2873 }
2874
2875 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2876 {
2877         int retVal;
2878         yaffs_BlockInfo *bi;
2879
2880         if (dev->allocationBlock < 0) {
2881                 /* Get next block to allocate off */
2882                 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2883                 dev->allocationPage = 0;
2884         }
2885
2886         if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2887                 /* Not enough space to allocate unless we're allowed to use the reserve. */
2888                 return -1;
2889         }
2890
2891         if (dev->nErasedBlocks < dev->nReservedBlocks
2892             && dev->allocationPage == 0) {
2893                 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2894         }
2895
2896         /* Next page please.... */
2897         if (dev->allocationBlock >= 0) {
2898                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2899
2900                 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2901                     dev->allocationPage;
2902                 bi->pagesInUse++;
2903                 yaffs_SetChunkBit(dev, dev->allocationBlock,
2904                                   dev->allocationPage);
2905
2906                 dev->allocationPage++;
2907
2908                 dev->nFreeChunks--;
2909
2910                 /* If the block is full set the state to full */
2911                 if (dev->allocationPage >= dev->nChunksPerBlock) {
2912                         bi->blockState = YAFFS_BLOCK_STATE_FULL;
2913                         dev->allocationBlock = -1;
2914                 }
2915
2916                 if(blockUsedPtr)
2917                         *blockUsedPtr = bi;
2918                         
2919                 return retVal;
2920         }
2921         
2922         T(YAFFS_TRACE_ERROR,
2923           (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2924
2925         return -1;
2926 }
2927
2928 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2929 {
2930         int n;
2931
2932         n = dev->nErasedBlocks * dev->nChunksPerBlock;
2933
2934         if (dev->allocationBlock > 0) {
2935                 n += (dev->nChunksPerBlock - dev->allocationPage);
2936         }
2937
2938         return n;
2939
2940 }
2941
2942 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2943 {
2944         int oldChunk;
2945         int newChunk;
2946         int chunkInBlock;
2947         int markNAND;
2948         int retVal = YAFFS_OK;
2949         int cleanups = 0;
2950         int i;
2951         int isCheckpointBlock;
2952         int matchingChunk;
2953
2954         int chunksBefore = yaffs_GetErasedChunks(dev);
2955         int chunksAfter;
2956
2957         yaffs_ExtendedTags tags;
2958
2959         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2960
2961         yaffs_Object *object;
2962
2963         isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2964         
2965         bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2966
2967         T(YAFFS_TRACE_TRACING,
2968           (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2969            bi->pagesInUse, bi->hasShrinkHeader));
2970
2971         /*yaffs_VerifyFreeChunks(dev); */
2972
2973         bi->hasShrinkHeader = 0;        /* clear the flag so that the block can erase */
2974
2975         /* Take off the number of soft deleted entries because
2976          * they're going to get really deleted during GC.
2977          */
2978         dev->nFreeChunks -= bi->softDeletions;
2979
2980         dev->isDoingGC = 1;
2981
2982         if (isCheckpointBlock ||
2983             !yaffs_StillSomeChunkBits(dev, block)) {
2984                 T(YAFFS_TRACE_TRACING,
2985                   (TSTR
2986                    ("Collecting block %d that has no chunks in use" TENDSTR),
2987                    block));
2988                 yaffs_BlockBecameDirty(dev, block);
2989         } else {
2990
2991                 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2992                 
2993                 yaffs_VerifyBlock(dev,bi,block);
2994
2995                 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
2996                      chunkInBlock < dev->nChunksPerBlock
2997                      && yaffs_StillSomeChunkBits(dev, block);
2998                      chunkInBlock++, oldChunk++) {
2999                         if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
3000
3001                                 /* This page is in use and might need to be copied off */
3002
3003                                 markNAND = 1;
3004
3005                                 yaffs_InitialiseTags(&tags);
3006
3007                                 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3008                                                                 buffer, &tags);
3009
3010                                 object =
3011                                     yaffs_FindObjectByNumber(dev,
3012                                                              tags.objectId);
3013
3014                                 T(YAFFS_TRACE_GC_DETAIL,
3015                                   (TSTR
3016                                    ("Collecting page %d, %d %d %d " TENDSTR),
3017                                    chunkInBlock, tags.objectId, tags.chunkId,
3018                                    tags.byteCount));
3019                                    
3020                                 if(object && !yaffs_SkipVerification(dev)){
3021                                         if(tags.chunkId == 0)
3022                                                 matchingChunk = object->chunkId;
3023                                         else if(object->softDeleted)
3024                                                 matchingChunk = oldChunk; /* Defeat the test */
3025                                         else
3026                                                 matchingChunk = yaffs_FindChunkInFile(object,tags.chunkId,NULL);
3027                                         
3028                                         if(oldChunk != matchingChunk)
3029                                                 T(YAFFS_TRACE_ERROR,
3030                                                   (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3031                                                   oldChunk,matchingChunk,tags.objectId, tags.chunkId));
3032                                                 
3033                                 }
3034
3035                                 if (!object) {
3036                                         T(YAFFS_TRACE_ERROR,
3037                                           (TSTR
3038                                            ("page %d in gc has no object: %d %d %d "
3039                                             TENDSTR), oldChunk,
3040                                             tags.objectId, tags.chunkId, tags.byteCount));
3041                                 }
3042
3043                                 if (object && object->deleted
3044                                     && tags.chunkId != 0) {
3045                                         /* Data chunk in a deleted file, throw it away
3046                                          * It's a soft deleted data chunk,
3047                                          * No need to copy this, just forget about it and 
3048                                          * fix up the object.
3049                                          */
3050
3051                                         object->nDataChunks--;
3052
3053                                         if (object->nDataChunks <= 0) {
3054                                                 /* remeber to clean up the object */
3055                                                 dev->gcCleanupList[cleanups] =
3056                                                     tags.objectId;
3057                                                 cleanups++;
3058                                         }
3059                                         markNAND = 0;
3060                                 } else if (0
3061                                            /* Todo object && object->deleted && object->nDataChunks == 0 */
3062                                            ) {
3063                                         /* Deleted object header with no data chunks.
3064                                          * Can be discarded and the file deleted.
3065                                          */
3066                                         object->chunkId = 0;
3067                                         yaffs_FreeTnode(object->myDev,
3068                                                         object->variant.
3069                                                         fileVariant.top);
3070                                         object->variant.fileVariant.top = NULL;
3071                                         yaffs_DoGenericObjectDeletion(object);
3072
3073                                 } else if (object) {
3074                                         /* It's either a data chunk in a live file or
3075                                          * an ObjectHeader, so we're interested in it.
3076                                          * NB Need to keep the ObjectHeaders of deleted files
3077                                          * until the whole file has been deleted off
3078                                          */
3079                                         tags.serialNumber++;
3080
3081                                         dev->nGCCopies++;
3082
3083                                         if (tags.chunkId == 0) {
3084                                                 /* It is an object Id,
3085                                                  * We need to nuke the shrinkheader flags first
3086                                                  * We no longer want the shrinkHeader flag since its work is done
3087                                                  * and if it is left in place it will mess up scanning.
3088                                                  * Also, clear out any shadowing stuff
3089                                                  */
3090
3091                                                 yaffs_ObjectHeader *oh;
3092                                                 oh = (yaffs_ObjectHeader *)buffer;
3093                                                 oh->isShrink = 0;
3094                                                 oh->shadowsObject = -1;
3095                                                 tags.extraShadows = 0;
3096                                                 tags.extraIsShrinkHeader = 0;
3097                                                 
3098                                                 yaffs_VerifyObjectHeader(object,oh,&tags,1);
3099                                         }
3100
3101                                         newChunk =
3102                                             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3103
3104                                         if (newChunk < 0) {
3105                                                 retVal = YAFFS_FAIL;
3106                                         } else {
3107
3108                                                 /* Ok, now fix up the Tnodes etc. */
3109
3110                                                 if (tags.chunkId == 0) {
3111                                                         /* It's a header */
3112                                                         object->chunkId =  newChunk;
3113                                                         object->serial =   tags.serialNumber;
3114                                                 } else {
3115                                                         /* It's a data chunk */
3116                                                         yaffs_PutChunkIntoFile
3117                                                             (object,
3118                                                              tags.chunkId,
3119                                                              newChunk, 0);
3120                                                 }
3121                                         }
3122                                 }
3123
3124                                 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3125
3126                         }
3127                 }
3128
3129                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3130
3131
3132                 /* Do any required cleanups */
3133                 for (i = 0; i < cleanups; i++) {
3134                         /* Time to delete the file too */
3135                         object =
3136                             yaffs_FindObjectByNumber(dev,
3137                                                      dev->gcCleanupList[i]);
3138                         if (object) {
3139                                 yaffs_FreeTnode(dev,
3140                                                 object->variant.fileVariant.
3141                                                 top);
3142                                 object->variant.fileVariant.top = NULL;
3143                                 T(YAFFS_TRACE_GC,
3144                                   (TSTR
3145                                    ("yaffs: About to finally delete object %d"
3146                                     TENDSTR), object->objectId));
3147                                 yaffs_DoGenericObjectDeletion(object);
3148                                 object->myDev->nDeletedFiles--;
3149                         }
3150
3151                 }
3152
3153         }
3154
3155         yaffs_VerifyCollectedBlock(dev,bi,block);
3156           
3157         if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
3158                 T(YAFFS_TRACE_GC,
3159                   (TSTR
3160                    ("gc did not increase free chunks before %d after %d"
3161                     TENDSTR), chunksBefore, chunksAfter));
3162         }
3163
3164         dev->isDoingGC = 0;
3165
3166         return YAFFS_OK;
3167 }
3168
3169 /* New garbage collector
3170  * If we're very low on erased blocks then we do aggressive garbage collection
3171  * otherwise we do "leasurely" garbage collection.
3172  * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3173  * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3174  *
3175  * The idea is to help clear out space in a more spread-out manner.
3176  * Dunno if it really does anything useful.
3177  */
3178 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
3179 {
3180         int block;
3181         int aggressive;
3182         int gcOk = YAFFS_OK;
3183         int maxTries = 0;
3184         
3185         int checkpointBlockAdjust;
3186
3187         if (dev->isDoingGC) {
3188                 /* Bail out so we don't get recursive gc */
3189                 return YAFFS_OK;
3190         }
3191         
3192         /* This loop should pass the first time.
3193          * We'll only see looping here if the erase of the collected block fails.
3194          */
3195
3196         do {
3197                 maxTries++;
3198                 
3199                 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3200                 if(checkpointBlockAdjust < 0)
3201                         checkpointBlockAdjust = 0;
3202
3203                 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3204                         /* We need a block soon...*/
3205                         aggressive = 1;
3206                 } else {
3207                         /* We're in no hurry */
3208                         aggressive = 0;
3209                 }
3210
3211                 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3212
3213                 if (block > 0) {
3214                         dev->garbageCollections++;
3215                         if (!aggressive) {
3216                                 dev->passiveGarbageCollections++;
3217                         }
3218
3219                         T(YAFFS_TRACE_GC,
3220                           (TSTR
3221                            ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3222                            dev->nErasedBlocks, aggressive));
3223
3224                         gcOk = yaffs_GarbageCollectBlock(dev, block);
3225                 }
3226
3227                 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3228                         T(YAFFS_TRACE_GC,
3229                           (TSTR
3230                            ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3231                             TENDSTR), dev->nErasedBlocks, maxTries, block));
3232                 }
3233         } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
3234                  && (maxTries < 2));
3235
3236         return aggressive ? gcOk : YAFFS_OK;
3237 }
3238
3239 /*-------------------------  TAGS --------------------------------*/
3240
3241 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
3242                            int chunkInObject)
3243 {
3244         return (tags->chunkId == chunkInObject &&
3245                 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3246
3247 }
3248
3249
3250 /*-------------------- Data file manipulation -----------------*/
3251
3252 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
3253                                  yaffs_ExtendedTags * tags)
3254 {
3255         /*Get the Tnode, then get the level 0 offset chunk offset */
3256         yaffs_Tnode *tn;
3257         int theChunk = -1;
3258         yaffs_ExtendedTags localTags;
3259         int retVal = -1;
3260
3261         yaffs_Device *dev = in->myDev;
3262
3263         if (!tags) {
3264                 /* Passed a NULL, so use our own tags space */
3265                 tags = &localTags;
3266         }
3267
3268         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3269
3270         if (tn) {
3271                 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3272
3273                 retVal =
3274                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3275                                            chunkInInode);
3276         }
3277         return retVal;
3278 }
3279
3280 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
3281                                           yaffs_ExtendedTags * tags)
3282 {
3283         /* Get the Tnode, then get the level 0 offset chunk offset */
3284         yaffs_Tnode *tn;
3285         int theChunk = -1;
3286         yaffs_ExtendedTags localTags;
3287
3288         yaffs_Device *dev = in->myDev;
3289         int retVal = -1;
3290
3291         if (!tags) {
3292                 /* Passed a NULL, so use our own tags space */
3293                 tags = &localTags;
3294         }
3295
3296         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3297
3298         if (tn) {
3299
3300                 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3301
3302                 retVal =
3303                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3304                                            chunkInInode);
3305
3306                 /* Delete the entry in the filestructure (if found) */
3307                 if (retVal != -1) {
3308                         yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
3309                 }
3310         } else {
3311                 /*T(("No level 0 found for %d\n", chunkInInode)); */
3312         }
3313
3314         if (retVal == -1) {
3315                 /* T(("Could not find %d to delete\n",chunkInInode)); */
3316         }
3317         return retVal;
3318 }
3319
3320 #ifdef YAFFS_PARANOID
3321
3322 static int yaffs_CheckFileSanity(yaffs_Object * in)
3323 {
3324         int chunk;
3325         int nChunks;
3326         int fSize;
3327         int failed = 0;
3328         int objId;
3329         yaffs_Tnode *tn;
3330         yaffs_Tags localTags;
3331         yaffs_Tags *tags = &localTags;
3332         int theChunk;
3333         int chunkDeleted;
3334
3335         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3336                 /* T(("Object not a file\n")); */
3337                 return YAFFS_FAIL;
3338         }
3339
3340         objId = in->objectId;
3341         fSize = in->variant.fileVariant.fileSize;
3342         nChunks =
3343             (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3344
3345         for (chunk = 1; chunk <= nChunks; chunk++) {
3346                 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3347                                            chunk);
3348
3349                 if (tn) {
3350
3351                         theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
3352
3353                         if (yaffs_CheckChunkBits
3354                             (dev, theChunk / dev->nChunksPerBlock,
3355                              theChunk % dev->nChunksPerBlock)) {
3356
3357                                 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3358                                                             tags,
3359                                                             &chunkDeleted);
3360                                 if (yaffs_TagsMatch
3361                                     (tags, in->objectId, chunk, chunkDeleted)) {
3362                                         /* found it; */
3363
3364                                 }
3365                         } else {
3366
3367                                 failed = 1;
3368                         }
3369
3370                 } else {
3371                         /* T(("No level 0 found for %d\n", chunk)); */
3372                 }
3373         }
3374
3375         return failed ? YAFFS_FAIL : YAFFS_OK;
3376 }
3377
3378 #endif
3379
3380 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
3381                                   int chunkInNAND, int inScan)
3382 {
3383         /* NB inScan is zero unless scanning. 
3384          * For forward scanning, inScan is > 0; 
3385          * for backward scanning inScan is < 0
3386          */
3387          
3388         yaffs_Tnode *tn;
3389         yaffs_Device *dev = in->myDev;
3390         int existingChunk;
3391         yaffs_ExtendedTags existingTags;
3392         yaffs_ExtendedTags newTags;
3393         unsigned existingSerial, newSerial;
3394
3395         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3396                 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3397                  * If it is not during Scanning then something went wrong!
3398                  */
3399                 if (!inScan) {
3400                         T(YAFFS_TRACE_ERROR,
3401                           (TSTR
3402                            ("yaffs tragedy:attempt to put data chunk into a non-file"
3403                             TENDSTR)));
3404                         YBUG();
3405                 }
3406
3407                 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3408                 return YAFFS_OK;
3409         }
3410
3411         tn = yaffs_AddOrFindLevel0Tnode(dev, 
3412                                         &in->variant.fileVariant,
3413                                         chunkInInode,
3414                                         NULL);
3415         if (!tn) {
3416                 return YAFFS_FAIL;
3417         }
3418
3419         existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3420
3421         if (inScan != 0) {
3422                 /* If we're scanning then we need to test for duplicates
3423                  * NB This does not need to be efficient since it should only ever 
3424                  * happen when the power fails during a write, then only one
3425                  * chunk should ever be affected.
3426                  *
3427                  * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3428                  * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3429                  */
3430
3431                 if (existingChunk != 0) {
3432                         /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3433                          *    thus we have to do a FindChunkInFile to get the real chunk id.
3434                          *
3435                          * We have a duplicate now we need to decide which one to use:
3436                          *
3437                          * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3438                          * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3439                          * YAFFS1: Get both sets of tags and compare serial numbers.
3440                          */
3441
3442                         if (inScan > 0) {
3443                                 /* Only do this for forward scanning */
3444                                 yaffs_ReadChunkWithTagsFromNAND(dev,
3445                                                                 chunkInNAND,
3446                                                                 NULL, &newTags);
3447
3448                                 /* Do a proper find */
3449                                 existingChunk =
3450                                     yaffs_FindChunkInFile(in, chunkInInode,
3451                                                           &existingTags);
3452                         }
3453
3454                         if (existingChunk <= 0) {
3455                                 /*Hoosterman - how did this happen? */
3456
3457                                 T(YAFFS_TRACE_ERROR,
3458                                   (TSTR
3459                                    ("yaffs tragedy: existing chunk < 0 in scan"
3460                                     TENDSTR)));
3461
3462                         }
3463
3464                         /* NB The deleted flags should be false, otherwise the chunks will 
3465                          * not be loaded during a scan
3466                          */
3467
3468                         newSerial = newTags.serialNumber;
3469                         existingSerial = existingTags.serialNumber;
3470
3471                         if ((inScan > 0) &&
3472                             (in->myDev->isYaffs2 ||
3473                              existingChunk <= 0 ||
3474                              ((existingSerial + 1) & 3) == newSerial)) {
3475                                 /* Forward scanning.                            
3476                                  * Use new
3477                                  * Delete the old one and drop through to update the tnode
3478                                  */
3479                                 yaffs_DeleteChunk(dev, existingChunk, 1,
3480                                                   __LINE__);
3481                         } else {
3482                                 /* Backward scanning or we want to use the existing one
3483                                  * Use existing.
3484                                  * Delete the new one and return early so that the tnode isn't changed
3485                                  */
3486                                 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3487                                                   __LINE__);
3488                                 return YAFFS_OK;
3489                         }
3490                 }
3491
3492         }
3493
3494         if (existingChunk == 0) {
3495                 in->nDataChunks++;
3496         }
3497
3498         yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
3499
3500         return YAFFS_OK;
3501 }
3502
3503 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
3504                                          __u8 * buffer)
3505 {
3506         int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3507
3508         if (chunkInNAND >= 0) {
3509                 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3510                                                        buffer,NULL);
3511         } else {
3512                 T(YAFFS_TRACE_NANDACCESS,
3513                   (TSTR("Chunk %d not found zero instead" TENDSTR),
3514                    chunkInNAND));
3515                 /* get sane (zero) data if you read a hole */
3516                 memset(buffer, 0, in->myDev->nDataBytesPerChunk);       
3517                 return 0;
3518         }
3519
3520 }
3521
3522 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
3523 {
3524         int block;
3525         int page;
3526         yaffs_ExtendedTags tags;
3527         yaffs_BlockInfo *bi;
3528
3529         if (chunkId <= 0)
3530                 return;
3531                 
3532
3533         dev->nDeletions++;
3534         block = chunkId / dev->nChunksPerBlock;
3535         page = chunkId % dev->nChunksPerBlock;
3536
3537
3538         if(!yaffs_CheckChunkBit(dev,block,page))
3539                 T(YAFFS_TRACE_VERIFY,
3540                         (TSTR("Deleting invalid chunk %d"TENDSTR),
3541                          chunkId));
3542
3543         bi = yaffs_GetBlockInfo(dev, block);
3544
3545         T(YAFFS_TRACE_DELETION,
3546           (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3547
3548         if (markNAND &&
3549             bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3550
3551                 yaffs_InitialiseTags(&tags);
3552
3553                 tags.chunkDeleted = 1;
3554
3555                 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3556                 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3557         } else {
3558                 dev->nUnmarkedDeletions++;
3559         }
3560
3561         /* Pull out of the management area.
3562          * If the whole block became dirty, this will kick off an erasure.
3563          */
3564         if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3565             bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3566             bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3567             bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3568                 dev->nFreeChunks++;
3569
3570                 yaffs_ClearChunkBit(dev, block, page);
3571
3572                 bi->pagesInUse--;
3573
3574                 if (bi->pagesInUse == 0 &&
3575                     !bi->hasShrinkHeader &&
3576                     bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3577                     bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3578                         yaffs_BlockBecameDirty(dev, block);
3579                 }
3580
3581         } else {
3582                 /* T(("Bad news deleting chunk %d\n",chunkId)); */
3583         }
3584
3585 }
3586
3587 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
3588                                         const __u8 * buffer, int nBytes,
3589                                         int useReserve)
3590 {
3591         /* Find old chunk Need to do this to get serial number
3592          * Write new one and patch into tree.
3593          * Invalidate old tags.
3594          */
3595
3596         int prevChunkId;
3597         yaffs_ExtendedTags prevTags;
3598
3599         int newChunkId;
3600         yaffs_ExtendedTags newTags;
3601
3602         yaffs_Device *dev = in->myDev;
3603
3604         yaffs_CheckGarbageCollection(dev);
3605
3606         /* Get the previous chunk at this location in the file if it exists */
3607         prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3608
3609         /* Set up new tags */
3610         yaffs_InitialiseTags(&newTags);
3611
3612         newTags.chunkId = chunkInInode;
3613         newTags.objectId = in->objectId;
3614         newTags.serialNumber =
3615             (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
3616         newTags.byteCount = nBytes;
3617
3618         newChunkId =
3619             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3620                                               useReserve);
3621
3622         if (newChunkId >= 0) {
3623                 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3624
3625                 if (prevChunkId >= 0) {
3626                         yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3627
3628                 }
3629
3630                 yaffs_CheckFileSanity(in);
3631         }
3632         return newChunkId;
3633
3634 }
3635
3636 /* UpdateObjectHeader updates the header on NAND for an object.
3637  * If name is not NULL, then that new name is used.
3638  */
3639 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
3640                              int isShrink, int shadows)
3641 {
3642
3643         yaffs_BlockInfo *bi;
3644
3645         yaffs_Device *dev = in->myDev;
3646
3647         int prevChunkId;
3648         int retVal = 0;
3649         int result = 0;
3650
3651         int newChunkId;
3652         yaffs_ExtendedTags newTags;
3653         yaffs_ExtendedTags oldTags;
3654
3655         __u8 *buffer = NULL;
3656         YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3657
3658         yaffs_ObjectHeader *oh = NULL;
3659         
3660         yaffs_strcpy(oldName,"silly old name");
3661
3662         if (!in->fake || force) {
3663
3664                 yaffs_CheckGarbageCollection(dev);
3665                 yaffs_CheckObjectDetailsLoaded(in);
3666
3667                 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3668                 oh = (yaffs_ObjectHeader *) buffer;
3669
3670                 prevChunkId = in->chunkId;
3671
3672                 if (prevChunkId >= 0) {
3673                         result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3674                                                         buffer, &oldTags);
3675                         
3676                         yaffs_VerifyObjectHeader(in,oh,&oldTags,0);
3677                                                                                 
3678                         memcpy(oldName, oh->name, sizeof(oh->name));
3679                 }
3680
3681                 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3682
3683                 oh->type = in->variantType;
3684                 oh->yst_mode = in->yst_mode;
3685                 oh->shadowsObject = shadows;
3686
3687 #ifdef CONFIG_YAFFS_WINCE
3688                 oh->win_atime[0] = in->win_atime[0];
3689                 oh->win_ctime[0] = in->win_ctime[0];
3690                 oh->win_mtime[0] = in->win_mtime[0];
3691                 oh->win_atime[1] = in->win_atime[1];
3692                 oh->win_ctime[1] = in->win_ctime[1];
3693                 oh->win_mtime[1] = in->win_mtime[1];
3694 #else
3695                 oh->yst_uid = in->yst_uid;
3696                 oh->yst_gid = in->yst_gid;
3697                 oh->yst_atime = in->yst_atime;
3698                 oh->yst_mtime = in->yst_mtime;
3699                 oh->yst_ctime = in->yst_ctime;
3700                 oh->yst_rdev = in->yst_rdev;
3701 #endif
3702                 if (in->parent) {
3703                         oh->parentObjectId = in->parent->objectId;
3704                 } else {
3705                         oh->parentObjectId = 0;
3706                 }
3707
3708                 if (name && *name) {
3709                         memset(oh->name, 0, sizeof(oh->name));
3710                         yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3711                 } else if (prevChunkId>=0) {
3712                         memcpy(oh->name, oldName, sizeof(oh->name));
3713                 } else {
3714                         memset(oh->name, 0, sizeof(oh->name));
3715                 }
3716
3717                 oh->isShrink = isShrink;
3718
3719                 switch (in->variantType) {
3720                 case YAFFS_OBJECT_TYPE_UNKNOWN:
3721                         /* Should not happen */
3722                         break;
3723                 case YAFFS_OBJECT_TYPE_FILE:
3724                         oh->fileSize =
3725                             (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3726                              || oh->parentObjectId ==
3727                              YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3728                             fileVariant.fileSize;
3729                         break;
3730                 case YAFFS_OBJECT_TYPE_HARDLINK:
3731                         oh->equivalentObjectId =
3732                             in->variant.hardLinkVariant.equivalentObjectId;
3733                         break;
3734                 case YAFFS_OBJECT_TYPE_SPECIAL:
3735                         /* Do nothing */
3736                         break;
3737                 case YAFFS_OBJECT_TYPE_DIRECTORY:
3738                         /* Do nothing */
3739                         break;
3740                 case YAFFS_OBJECT_TYPE_SYMLINK:
3741                         yaffs_strncpy(oh->alias,
3742                                       in->variant.symLinkVariant.alias,
3743                                       YAFFS_MAX_ALIAS_LENGTH);
3744                         oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3745                         break;
3746                 }
3747
3748                 /* Tags */
3749                 yaffs_InitialiseTags(&newTags);
3750                 in->serial++;
3751                 newTags.chunkId = 0;
3752                 newTags.objectId = in->objectId;
3753                 newTags.serialNumber = in->serial;
3754
3755                 /* Add extra info for file header */
3756
3757                 newTags.extraHeaderInfoAvailable = 1;
3758                 newTags.extraParentObjectId = oh->parentObjectId;
3759                 newTags.extraFileLength = oh->fileSize;
3760                 newTags.extraIsShrinkHeader = oh->isShrink;
3761                 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3762                 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3763                 newTags.extraObjectType = in->variantType;
3764
3765                 yaffs_VerifyObjectHeader(in,oh,&newTags,1);
3766
3767                 /* Create new chunk in NAND */
3768                 newChunkId =
3769                     yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3770                                                       (prevChunkId >= 0) ? 1 : 0);
3771
3772                 if (newChunkId >= 0) {
3773
3774                         in->chunkId = newChunkId;
3775
3776                         if (prevChunkId >= 0) {
3777                                 yaffs_DeleteChunk(dev, prevChunkId, 1,
3778                                                   __LINE__);
3779                         }
3780
3781                         if(!yaffs_ObjectHasCachedWriteData(in))
3782                                 in->dirty = 0;
3783
3784                         /* If this was a shrink, then mark the block that the chunk lives on */
3785                         if (isShrink) {
3786                                 bi = yaffs_GetBlockInfo(in->myDev,
3787                                                         newChunkId /in->myDev-> nChunksPerBlock);
3788                                 bi->hasShrinkHeader = 1;
3789                         }
3790
3791                 }
3792
3793                 retVal = newChunkId;
3794
3795         }
3796
3797         if (buffer)
3798                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3799
3800         return retVal;
3801 }
3802
3803 /*------------------------ Short Operations Cache ----------------------------------------
3804  *   In many situations where there is no high level buffering (eg WinCE) a lot of
3805  *   reads might be short sequential reads, and a lot of writes may be short 
3806  *   sequential writes. eg. scanning/writing a jpeg file.
3807  *   In these cases, a short read/write cache can provide a huge perfomance benefit 
3808  *   with dumb-as-a-rock code.
3809  *   In Linux, the page cache provides read buffering aand the short op cache provides write 
3810  *   buffering.
3811  *
3812  *   There are a limited number (~10) of cache chunks per device so that we don't
3813  *   need a very intelligent search.
3814  */
3815
3816 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3817 {
3818         yaffs_Device *dev = obj->myDev;
3819         int i;
3820         yaffs_ChunkCache *cache;
3821         int nCaches = obj->myDev->nShortOpCaches;
3822         
3823         for(i = 0; i < nCaches; i++){
3824                 cache = &dev->srCache[i];
3825                 if (cache->object == obj &&
3826                     cache->dirty)
3827                         return 1;
3828         }
3829         
3830         return 0;
3831 }
3832
3833
3834 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3835 {
3836         yaffs_Device *dev = obj->myDev;
3837         int lowest = -99;       /* Stop compiler whining. */
3838         int i;
3839         yaffs_ChunkCache *cache;
3840         int chunkWritten = 0;
3841         int nCaches = obj->myDev->nShortOpCaches;
3842
3843         if (nCaches > 0) {
3844                 do {
3845                         cache = NULL;
3846
3847                         /* Find the dirty cache for this object with the lowest chunk id. */
3848                         for (i = 0; i < nCaches; i++) {
3849                                 if (dev->srCache[i].object == obj &&
3850                                     dev->srCache[i].dirty) {
3851                                         if (!cache
3852                                             || dev->srCache[i].chunkId <
3853                                             lowest) {
3854                                                 cache = &dev->srCache[i];
3855                                                 lowest = cache->chunkId;
3856                                         }
3857                                 }
3858                         }
3859
3860                         if (cache && !cache->locked) {
3861                                 /* Write it out and free it up */
3862
3863                                 chunkWritten =
3864                                     yaffs_WriteChunkDataToObject(cache->object,
3865                                                                  cache->chunkId,
3866                                                                  cache->data,
3867                                                                  cache->nBytes,
3868                                                                  1);
3869                                 cache->dirty = 0;
3870                                 cache->object = NULL;
3871                         }
3872
3873                 } while (cache && chunkWritten > 0);
3874
3875                 if (cache) {
3876                         /* Hoosterman, disk full while writing cache out. */
3877                         T(YAFFS_TRACE_ERROR,
3878                           (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3879
3880      &n