72532c2b6a9627f1231c7bfc33f0423c8f3453e3
[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.68 2008-11-27 20:32:52 charles Exp $";
16
17 #include "yportenv.h"
18
19 #include "yaffsinterface.h"
20 #include "yaffs_guts.h"
21 #include "yaffs_tagsvalidity.h"
22 #include "yaffs_getblockinfo.h"
23
24 #include "yaffs_tagscompat.h"
25 #ifndef  CONFIG_YAFFS_USE_OWN_SORT
26 #include "yaffs_qsort.h"
27 #endif
28 #include "yaffs_nand.h"
29
30 #include "yaffs_checkptrw.h"
31
32 #include "yaffs_nand.h"
33 #include "yaffs_packedtags2.h"
34
35
36 #ifdef CONFIG_YAFFS_WINCE
37 void yfsd_LockYAFFS(BOOL fsLockOnly);
38 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
39 #endif
40
41 #define YAFFS_PASSIVE_GC_CHUNKS 2
42
43 #include "yaffs_ecc.h"
44
45
46 /* Robustification (if it ever comes about...) */
47 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
48 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk);
49 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
50                                      const __u8 * data,
51                                      const yaffs_ExtendedTags * tags);
52 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
53                                     const yaffs_ExtendedTags * tags);
54
55 /* Other local prototypes */
56 static int yaffs_UnlinkObject( yaffs_Object *obj);
57 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
58
59 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
60
61 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
62                                              const __u8 * buffer,
63                                              yaffs_ExtendedTags * tags,
64                                              int useReserve);
65 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
66                                   int chunkInNAND, int inScan);
67
68 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
69                                            yaffs_ObjectType type);
70 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
71                                        yaffs_Object * obj);
72 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
73                                     int force, int isShrink, int shadows);
74 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
75 static int yaffs_CheckStructures(void);
76 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
77                               int chunkOffset, int *limit);
78 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
79
80 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
81
82
83 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
84                                   int chunkInNAND);
85
86 static int yaffs_UnlinkWorker(yaffs_Object * obj);
87 static void yaffs_DestroyObject(yaffs_Object * obj);
88
89 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
90                            int chunkInObject);
91
92 loff_t yaffs_GetFileSize(yaffs_Object * obj);
93
94 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr);
95
96 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
97
98 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
99
100 static void yaffs_VerifyDirectory(yaffs_Object *directory);
101 #ifdef YAFFS_PARANOID
102 static int yaffs_CheckFileSanity(yaffs_Object * in);
103 #else
104 #define yaffs_CheckFileSanity(in)
105 #endif
106
107 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
108 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
109
110 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
111
112 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
113                                  yaffs_ExtendedTags * tags);
114
115 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos);
116 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
117                                           yaffs_FileStructure * fStruct,
118                                           __u32 chunkId);
119
120
121 /* Function to calculate chunk and offset */
122
123 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut, __u32 *offsetOut)
124 {
125         int chunk;
126         __u32 offset;
127         
128         chunk  = (__u32)(addr >> dev->chunkShift);
129                 
130         if(dev->chunkDiv == 1)
131         {
132                 /* easy power of 2 case */
133                 offset = (__u32)(addr & dev->chunkMask);
134         }
135         else
136         {
137                 /* Non power-of-2 case */
138                 
139                 loff_t chunkBase;
140                 
141                 chunk /= dev->chunkDiv;
142                 
143                 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
144                 offset = (__u32)(addr - chunkBase);
145         }
146
147         *chunkOut = chunk;
148         *offsetOut = offset;
149 }
150
151 /* Function to return the number of shifts for a power of 2 greater than or equal 
152  * to the given number
153  * Note we don't try to cater for all possible numbers and this does not have to
154  * be hellishly efficient.
155  */
156  
157 static __u32 ShiftsGE(__u32 x)
158 {
159         int extraBits;
160         int nShifts;
161         
162         nShifts = extraBits = 0;
163         
164         while(x>1){
165                 if(x & 1) extraBits++;
166                 x>>=1;
167                 nShifts++;
168         }
169
170         if(extraBits) 
171                 nShifts++;
172                 
173         return nShifts;
174 }
175
176 /* Function to return the number of shifts to get a 1 in bit 0
177  */
178  
179 static __u32 Shifts(__u32 x)
180 {
181         int nShifts;
182         
183         nShifts =  0;
184         
185         if(!x) return 0;
186         
187         while( !(x&1)){
188                 x>>=1;
189                 nShifts++;
190         }
191                 
192         return nShifts;
193 }
194
195
196
197 /* 
198  * Temporary buffer manipulations.
199  */
200
201 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)       
202 {
203         int i;
204         __u8 *buf = (__u8 *)1;
205                 
206         memset(dev->tempBuffer,0,sizeof(dev->tempBuffer));
207                 
208         for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
209                 dev->tempBuffer[i].line = 0;    /* not in use */
210                 dev->tempBuffer[i].buffer = buf =
211                     YMALLOC_DMA(dev->totalBytesPerChunk);
212         }
213                 
214         return buf ? YAFFS_OK : YAFFS_FAIL;
215         
216 }
217
218 __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
219 {
220         int i, j;
221
222         dev->tempInUse++;
223         if(dev->tempInUse > dev->maxTemp)
224                 dev->maxTemp = dev->tempInUse;
225
226         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
227                 if (dev->tempBuffer[i].line == 0) {
228                         dev->tempBuffer[i].line = lineNo;
229                         if ((i + 1) > dev->maxTemp) {
230                                 dev->maxTemp = i + 1;
231                                 for (j = 0; j <= i; j++)
232                                         dev->tempBuffer[j].maxLine =
233                                             dev->tempBuffer[j].line;
234                         }
235
236                         return dev->tempBuffer[i].buffer;
237                 }
238         }
239
240         T(YAFFS_TRACE_BUFFERS,
241           (TSTR("Out of temp buffers at line %d, other held by lines:"),
242            lineNo));
243         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
244                 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
245         }
246         T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
247
248         /*
249          * If we got here then we have to allocate an unmanaged one
250          * This is not good.
251          */
252
253         dev->unmanagedTempAllocations++;
254         return YMALLOC(dev->nDataBytesPerChunk);
255
256 }
257
258 void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
259                                     int lineNo)
260 {
261         int i;
262         
263         dev->tempInUse--;
264         
265         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
266                 if (dev->tempBuffer[i].buffer == buffer) {
267                         dev->tempBuffer[i].line = 0;
268                         return;
269                 }
270         }
271
272         if (buffer) {
273                 /* assume it is an unmanaged one. */
274                 T(YAFFS_TRACE_BUFFERS,
275                   (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
276                    lineNo));
277                 YFREE(buffer);
278                 dev->unmanagedTempDeallocations++;
279         }
280
281 }
282
283 /*
284  * Determine if we have a managed buffer.
285  */
286 int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
287 {
288         int i;
289         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
290                 if (dev->tempBuffer[i].buffer == buffer)
291                         return 1;
292
293         }
294
295     for (i = 0; i < dev->nShortOpCaches; i++) {
296         if( dev->srCache[i].data == buffer )
297             return 1;
298
299     }
300
301     if (buffer == dev->checkpointBuffer)
302       return 1;
303
304     T(YAFFS_TRACE_ALWAYS,
305           (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
306     return 0;
307 }
308
309
310
311 /*
312  * Chunk bitmap manipulations
313  */
314
315 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
316 {
317         if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
318                 T(YAFFS_TRACE_ERROR,
319                   (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
320                    blk));
321                 YBUG();
322         }
323         return dev->chunkBits +
324             (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
325 }
326
327 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
328 {
329         if(blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
330            chunk < 0 || chunk >= dev->nChunksPerBlock) {
331            T(YAFFS_TRACE_ERROR,
332             (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),blk,chunk));
333             YBUG();
334         }
335 }
336
337 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
338 {
339         __u8 *blkBits = yaffs_BlockBits(dev, blk);
340
341         memset(blkBits, 0, dev->chunkBitmapStride);
342 }
343
344 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
345 {
346         __u8 *blkBits = yaffs_BlockBits(dev, blk);
347
348         yaffs_VerifyChunkBitId(dev,blk,chunk);
349
350         blkBits[chunk / 8] &= ~(1 << (chunk & 7));
351 }
352
353 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
354 {
355         __u8 *blkBits = yaffs_BlockBits(dev, blk);
356         
357         yaffs_VerifyChunkBitId(dev,blk,chunk);
358
359         blkBits[chunk / 8] |= (1 << (chunk & 7));
360 }
361
362 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
363 {
364         __u8 *blkBits = yaffs_BlockBits(dev, blk);
365         yaffs_VerifyChunkBitId(dev,blk,chunk);
366
367         return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
368 }
369
370 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
371 {
372         __u8 *blkBits = yaffs_BlockBits(dev, blk);
373         int i;
374         for (i = 0; i < dev->chunkBitmapStride; i++) {
375                 if (*blkBits)
376                         return 1;
377                 blkBits++;
378         }
379         return 0;
380 }
381
382 static int yaffs_CountChunkBits(yaffs_Device * dev, int blk)
383 {
384         __u8 *blkBits = yaffs_BlockBits(dev, blk);
385         int i;
386         int n = 0;
387         for (i = 0; i < dev->chunkBitmapStride; i++) {
388                 __u8 x = *blkBits;
389                 while(x){
390                         if(x & 1)
391                                 n++;
392                         x >>=1;
393                 }
394                         
395                 blkBits++;
396         }
397         return n;
398 }
399
400 /* 
401  * Verification code
402  */
403  
404 static int yaffs_SkipVerification(yaffs_Device *dev)
405 {
406         return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
407 }
408
409 static int yaffs_SkipFullVerification(yaffs_Device *dev)
410 {
411         return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
412 }
413
414 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
415 {
416         return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
417 }
418
419 static const char * blockStateName[] = {
420 "Unknown",
421 "Needs scanning",
422 "Scanning",
423 "Empty",
424 "Allocating",
425 "Full",
426 "Dirty",
427 "Checkpoint",
428 "Collecting",
429 "Dead"
430 };
431
432 static void yaffs_VerifyBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
433 {
434         int actuallyUsed;
435         int inUse;
436         
437         if(yaffs_SkipVerification(dev))
438                 return;
439                 
440         /* Report illegal runtime states */
441         if(bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
442                 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has undefined state %d"TENDSTR),n,bi->blockState));
443                 
444         switch(bi->blockState){
445          case YAFFS_BLOCK_STATE_UNKNOWN:
446          case YAFFS_BLOCK_STATE_SCANNING:
447          case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
448                 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has bad run-state %s"TENDSTR),
449                 n,blockStateName[bi->blockState]));
450         }
451         
452         /* Check pages in use and soft deletions are legal */
453         
454         actuallyUsed = bi->pagesInUse - bi->softDeletions;
455         
456         if(bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
457            bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
458            actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock)
459                 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
460                 n,bi->pagesInUse,bi->softDeletions));
461         
462                 
463         /* Check chunk bitmap legal */
464         inUse = yaffs_CountChunkBits(dev,n);
465         if(inUse != bi->pagesInUse)
466                 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
467                         n,bi->pagesInUse,inUse));
468         
469         /* Check that the sequence number is valid.
470          * Ten million is legal, but is very unlikely 
471          */
472         if(dev->isYaffs2 && 
473            (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
474            (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000 ))
475                 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has suspect sequence number of %d"TENDSTR),
476                 n,bi->sequenceNumber));
477                 
478 }
479
480 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
481 {
482         yaffs_VerifyBlock(dev,bi,n);
483         
484         /* After collection the block should be in the erased state */
485         /* TODO: This will need to change if we do partial gc */
486         
487         if(bi->blockState != YAFFS_BLOCK_STATE_EMPTY){
488                 T(YAFFS_TRACE_ERROR,(TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
489                         n,bi->blockState));
490         }
491 }
492
493 static void yaffs_VerifyBlocks(yaffs_Device *dev)
494 {
495         int i;
496         int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
497         int nIllegalBlockStates = 0;
498         
499
500         if(yaffs_SkipVerification(dev))
501                 return;
502
503         memset(nBlocksPerState,0,sizeof(nBlocksPerState));
504
505                 
506         for(i = dev->internalStartBlock; i <= dev->internalEndBlock; i++){
507                 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
508                 yaffs_VerifyBlock(dev,bi,i);
509
510                 if(bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
511                         nBlocksPerState[bi->blockState]++;
512                 else
513                         nIllegalBlockStates++;
514                                         
515         }
516         
517         T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
518         T(YAFFS_TRACE_VERIFY,(TSTR("Block summary"TENDSTR)));
519         
520         T(YAFFS_TRACE_VERIFY,(TSTR("%d blocks have illegal states"TENDSTR),nIllegalBlockStates));
521         if(nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
522                 T(YAFFS_TRACE_VERIFY,(TSTR("Too many allocating blocks"TENDSTR)));
523
524         for(i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
525                 T(YAFFS_TRACE_VERIFY,
526                   (TSTR("%s %d blocks"TENDSTR),
527                   blockStateName[i],nBlocksPerState[i]));
528         
529         if(dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
530                 T(YAFFS_TRACE_VERIFY,
531                  (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
532                  dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
533                  
534         if(dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
535                 T(YAFFS_TRACE_VERIFY,
536                  (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
537                  dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
538                  
539         if(nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
540                 T(YAFFS_TRACE_VERIFY,
541                  (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
542                  nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
543
544         T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
545
546 }
547
548 /*
549  * Verify the object header. oh must be valid, but obj and tags may be NULL in which
550  * case those tests will not be performed.
551  */
552 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
553 {
554         if(obj && yaffs_SkipVerification(obj->myDev))
555                 return;
556                 
557         if(!(tags && obj && oh)){
558                 T(YAFFS_TRACE_VERIFY,
559                                 (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR),
560                                 (__u32)tags,(__u32)obj,(__u32)oh));
561                 return;
562         }
563         
564         if(oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
565            oh->type > YAFFS_OBJECT_TYPE_MAX)
566                 T(YAFFS_TRACE_VERIFY,
567                  (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
568                  tags->objectId, oh->type));
569
570         if(tags->objectId != obj->objectId)
571                 T(YAFFS_TRACE_VERIFY,
572                  (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
573                  tags->objectId, obj->objectId));
574
575
576         /*
577          * Check that the object's parent ids match if parentCheck requested.
578          * 
579          * Tests do not apply to the root object.
580          */
581         
582         if(parentCheck && tags->objectId > 1 && !obj->parent)
583                 T(YAFFS_TRACE_VERIFY,
584                  (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
585                  tags->objectId, oh->parentObjectId));
586                 
587         
588         if(parentCheck && obj->parent &&
589            oh->parentObjectId != obj->parent->objectId && 
590            (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
591             obj->parent->objectId != YAFFS_OBJECTID_DELETED))
592                 T(YAFFS_TRACE_VERIFY,
593                  (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
594                  tags->objectId, oh->parentObjectId, obj->parent->objectId));
595                 
596         
597         if(tags->objectId > 1 && oh->name[0] == 0) /* Null name */
598                 T(YAFFS_TRACE_VERIFY,
599                 (TSTR("Obj %d header name is NULL"TENDSTR),
600                  obj->objectId));
601
602         if(tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
603                 T(YAFFS_TRACE_VERIFY,
604                 (TSTR("Obj %d header name is 0xFF"TENDSTR),
605                  obj->objectId));
606 }
607
608
609
610 static int yaffs_VerifyTnodeWorker(yaffs_Object * obj, yaffs_Tnode * tn,
611                                         __u32 level, int chunkOffset)
612 {
613         int i;
614         yaffs_Device *dev = obj->myDev;
615         int ok = 1;
616
617         if (tn) {
618                 if (level > 0) {
619
620                         for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
621                                 if (tn->internal[i]) {
622                                         ok = yaffs_VerifyTnodeWorker(obj,
623                                                         tn->internal[i],
624                                                         level - 1,
625                                                         (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
626                                 }
627                         }
628                 } else if (level == 0) {
629                         yaffs_ExtendedTags tags;
630                         __u32 objectId = obj->objectId;
631                         
632                         chunkOffset <<=  YAFFS_TNODES_LEVEL0_BITS;
633                         
634                         for(i = 0; i < YAFFS_NTNODES_LEVEL0; i++){
635                                 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
636                                 
637                                 if(theChunk > 0){
638                                         /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
639                                         yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
640                                         if(tags.objectId != objectId || tags.chunkId != chunkOffset){
641                                                 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
642                                                         objectId, chunkOffset, theChunk,
643                                                         tags.objectId, tags.chunkId));
644                                         }
645                                 }
646                                 chunkOffset++;
647                         }
648                 }
649         }
650
651         return ok;
652
653 }
654
655
656 static void yaffs_VerifyFile(yaffs_Object *obj)
657 {
658         int requiredTallness;
659         int actualTallness;
660         __u32 lastChunk;
661         __u32 x;
662         __u32 i;
663         yaffs_Device *dev;
664         yaffs_ExtendedTags tags;
665         yaffs_Tnode *tn;
666         __u32 objectId;
667         
668         if(!obj)
669                 return;
670
671         if(yaffs_SkipVerification(obj->myDev))
672                 return;
673         
674         dev = obj->myDev;
675         objectId = obj->objectId;
676         
677         /* Check file size is consistent with tnode depth */
678         lastChunk =  obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
679         x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
680         requiredTallness = 0;
681         while (x> 0) {
682                 x >>= YAFFS_TNODES_INTERNAL_BITS;
683                 requiredTallness++;
684         }
685         
686         actualTallness = obj->variant.fileVariant.topLevel;
687         
688         if(requiredTallness > actualTallness )
689                 T(YAFFS_TRACE_VERIFY,
690                 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
691                  obj->objectId,actualTallness, requiredTallness));
692         
693         
694         /* Check that the chunks in the tnode tree are all correct. 
695          * We do this by scanning through the tnode tree and
696          * checking the tags for every chunk match.
697          */
698
699         if(yaffs_SkipNANDVerification(dev))
700                 return;
701                 
702         for(i = 1; i <= lastChunk; i++){
703                 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant,i);
704
705                 if (tn) {
706                         __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
707                         if(theChunk > 0){
708                                 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
709                                 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
710                                 if(tags.objectId != objectId || tags.chunkId != i){
711                                         T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
712                                                 objectId, i, theChunk,
713                                                 tags.objectId, tags.chunkId));
714                                 }
715                         }
716                 }
717
718         }
719
720 }
721
722
723 static void yaffs_VerifyHardLink(yaffs_Object *obj)
724 {
725         if(obj && yaffs_SkipVerification(obj->myDev))
726                 return;
727                 
728         /* Verify sane equivalent object */
729 }
730
731 static void yaffs_VerifySymlink(yaffs_Object *obj)
732 {
733         if(obj && yaffs_SkipVerification(obj->myDev))
734                 return;
735                 
736         /* Verify symlink string */
737 }
738
739 static void yaffs_VerifySpecial(yaffs_Object *obj)
740 {
741         if(obj && yaffs_SkipVerification(obj->myDev))
742                 return;
743 }
744
745 static void yaffs_VerifyObject(yaffs_Object *obj)
746 {
747         yaffs_Device *dev;
748         
749         __u32 chunkMin;
750         __u32 chunkMax;
751         
752         __u32 chunkIdOk;
753         __u32 chunkIsLive;
754         
755         if(!obj)
756                 return;
757         
758         dev = obj->myDev;
759         
760         if(yaffs_SkipVerification(dev))
761                 return;
762                 
763         /* Check sane object header chunk */
764
765         chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
766         chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
767
768         chunkIdOk = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
769         chunkIsLive = chunkIdOk &&
770                         yaffs_CheckChunkBit(dev,
771                                             obj->hdrChunk / dev->nChunksPerBlock,
772                                             obj->hdrChunk % dev->nChunksPerBlock);
773         if(!obj->fake &&
774             (!chunkIdOk || !chunkIsLive)) {
775            T(YAFFS_TRACE_VERIFY,
776            (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
777            obj->objectId,obj->hdrChunk,
778            chunkIdOk ? "" : ",out of range",
779            chunkIsLive || !chunkIdOk ? "" : ",marked as deleted"));
780         }
781         
782         if(chunkIdOk && chunkIsLive &&!yaffs_SkipNANDVerification(dev)) {
783                 yaffs_ExtendedTags tags;
784                 yaffs_ObjectHeader *oh;
785                 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
786                 
787                 oh = (yaffs_ObjectHeader *)buffer;
788
789                 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk,buffer, &tags);
790
791                 yaffs_VerifyObjectHeader(obj,oh,&tags,1);
792                 
793                 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
794         }
795         
796         /* Verify it has a parent */
797         if(obj && !obj->fake &&
798            (!obj->parent || obj->parent->myDev != dev)){
799            T(YAFFS_TRACE_VERIFY,
800            (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
801            obj->objectId,obj->parent));    
802         }
803         
804         /* Verify parent is a directory */
805         if(obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
806            T(YAFFS_TRACE_VERIFY,
807            (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
808            obj->objectId,obj->parent->variantType));       
809         }
810         
811         switch(obj->variantType){
812         case YAFFS_OBJECT_TYPE_FILE:
813                 yaffs_VerifyFile(obj);
814                 break;
815         case YAFFS_OBJECT_TYPE_SYMLINK:
816                 yaffs_VerifySymlink(obj);
817                 break;
818         case YAFFS_OBJECT_TYPE_DIRECTORY:
819                 yaffs_VerifyDirectory(obj);
820                 break;
821         case YAFFS_OBJECT_TYPE_HARDLINK:
822                 yaffs_VerifyHardLink(obj);
823                 break;
824         case YAFFS_OBJECT_TYPE_SPECIAL:
825                 yaffs_VerifySpecial(obj);
826                 break;
827         case YAFFS_OBJECT_TYPE_UNKNOWN:
828         default:
829                 T(YAFFS_TRACE_VERIFY,
830                 (TSTR("Obj %d has illegaltype %d"TENDSTR),
831                 obj->objectId,obj->variantType));          
832                 break;
833         }
834         
835         
836 }
837
838 static void yaffs_VerifyObjects(yaffs_Device *dev)
839 {
840         yaffs_Object *obj;
841         int i;
842         struct ylist_head *lh;
843
844         if(yaffs_SkipVerification(dev))
845                 return;
846         
847         /* Iterate through the objects in each hash entry */
848          
849          for(i = 0; i <  YAFFS_NOBJECT_BUCKETS; i++){
850                 ylist_for_each(lh, &dev->objectBucket[i].list) {
851                         if (lh) {
852                                 obj = ylist_entry(lh, yaffs_Object, hashLink);
853                                 yaffs_VerifyObject(obj);
854                         }
855                 }
856          }
857
858 }
859
860
861 /*
862  *  Simple hash function. Needs to have a reasonable spread
863  */
864  
865 static Y_INLINE int yaffs_HashFunction(int n)
866 {
867         n = abs(n);
868         return (n % YAFFS_NOBJECT_BUCKETS);
869 }
870
871 /*
872  * Access functions to useful fake objects.
873  * Note that root might have a presence in NAND if permissions are set.
874  */
875  
876 yaffs_Object *yaffs_Root(yaffs_Device * dev)
877 {
878         return dev->rootDir;
879 }
880
881 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
882 {
883         return dev->lostNFoundDir;
884 }
885
886
887 /*
888  *  Erased NAND checking functions
889  */
890  
891 int yaffs_CheckFF(__u8 * buffer, int nBytes)
892 {
893         /* Horrible, slow implementation */
894         while (nBytes--) {
895                 if (*buffer != 0xFF)
896                         return 0;
897                 buffer++;
898         }
899         return 1;
900 }
901
902 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
903                                   int chunkInNAND)
904 {
905
906         int retval = YAFFS_OK;
907         __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
908         yaffs_ExtendedTags tags;
909         int result;
910
911         result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
912         
913         if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
914                 retval = YAFFS_FAIL;
915                 
916
917         if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
918                 T(YAFFS_TRACE_NANDACCESS,
919                   (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
920                 retval = YAFFS_FAIL;
921         }
922
923         yaffs_ReleaseTempBuffer(dev, data, __LINE__);
924
925         return retval;
926
927 }
928
929 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
930                                              const __u8 * data,
931                                              yaffs_ExtendedTags * tags,
932                                              int useReserve)
933 {
934         int attempts = 0;
935         int writeOk = 0;
936         int chunk;
937
938         yaffs_InvalidateCheckpoint(dev);
939
940         do {
941                 yaffs_BlockInfo *bi = 0;
942                 int erasedOk = 0;
943
944                 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
945                 if (chunk < 0) {
946                         /* no space */
947                         break;
948                 }
949
950                 /* First check this chunk is erased, if it needs
951                  * checking.  The checking policy (unless forced
952                  * always on) is as follows:
953                  *
954                  * Check the first page we try to write in a block.
955                  * If the check passes then we don't need to check any
956                  * more.        If the check fails, we check again...
957                  * If the block has been erased, we don't need to check.
958                  *
959                  * However, if the block has been prioritised for gc,
960                  * then we think there might be something odd about
961                  * this block and stop using it.
962                  *
963                  * Rationale: We should only ever see chunks that have
964                  * not been erased if there was a partially written
965                  * chunk due to power loss.  This checking policy should
966                  * catch that case with very few checks and thus save a
967                  * lot of checks that are most likely not needed.
968                  */
969                 if (bi->gcPrioritise) {
970                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
971                         /* try another chunk */
972                         continue;
973                 }
974
975                 /* let's give it a try */
976                 attempts++;
977
978 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
979                 bi->skipErasedCheck = 0;
980 #endif
981                 if (!bi->skipErasedCheck) {
982                         erasedOk = yaffs_CheckChunkErased(dev, chunk);
983                         if (erasedOk != YAFFS_OK) {
984                                 T(YAFFS_TRACE_ERROR,
985                                 (TSTR ("**>> yaffs chunk %d was not erased"
986                                 TENDSTR), chunk));
987
988                                 /* try another chunk */
989                                 continue;
990                         }
991                         bi->skipErasedCheck = 1;
992                 }
993
994                 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
995                                 data, tags);
996                 if (writeOk != YAFFS_OK) {
997                         yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
998                         /* try another chunk */
999                         continue;
1000                 }
1001
1002                 /* Copy the data into the robustification buffer */
1003                 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1004
1005         } while (writeOk != YAFFS_OK && 
1006                 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1007         
1008         if(!writeOk)
1009                 chunk = -1;
1010
1011         if (attempts > 1) {
1012                 T(YAFFS_TRACE_ERROR,
1013                         (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1014                         attempts));
1015
1016                 dev->nRetriedWrites += (attempts - 1);
1017         }
1018
1019         return chunk;
1020 }
1021
1022 /*
1023  * Block retiring for handling a broken block.
1024  */
1025  
1026 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
1027 {
1028         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1029
1030         yaffs_InvalidateCheckpoint(dev);
1031         
1032         yaffs_MarkBlockBad(dev, blockInNAND);
1033
1034         bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1035         bi->gcPrioritise = 0;
1036         bi->needsRetiring = 0;
1037
1038         dev->nRetiredBlocks++;
1039 }
1040
1041 /*
1042  * Functions for robustisizing TODO
1043  *
1044  */
1045  
1046 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
1047                                      const __u8 * data,
1048                                      const yaffs_ExtendedTags * tags)
1049 {
1050 }
1051
1052 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
1053                                     const yaffs_ExtendedTags * tags)
1054 {
1055 }
1056
1057 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1058 {
1059         if(!bi->gcPrioritise){
1060                 bi->gcPrioritise = 1;
1061                 dev->hasPendingPrioritisedGCs = 1;
1062                 bi->chunkErrorStrikes ++;
1063                 
1064                 if(bi->chunkErrorStrikes > 3){
1065                         bi->needsRetiring = 1; /* Too many stikes, so retire this */
1066                         T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1067
1068                 }
1069                 
1070         }
1071 }
1072
1073 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
1074 {
1075
1076         int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1077         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1078
1079         yaffs_HandleChunkError(dev,bi);
1080                 
1081         
1082         if(erasedOk ) {
1083                 /* Was an actual write failure, so mark the block for retirement  */
1084                 bi->needsRetiring = 1;
1085                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1086                   (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1087
1088                 
1089         }
1090         
1091         /* Delete the chunk */
1092         yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1093 }
1094
1095
1096 /*---------------- Name handling functions ------------*/ 
1097
1098 static __u16 yaffs_CalcNameSum(const YCHAR * name)
1099 {
1100         __u16 sum = 0;
1101         __u16 i = 1;
1102
1103         const YUCHAR *bname = (const YUCHAR *) name;
1104         if (bname) {
1105                 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1106
1107 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1108                         sum += yaffs_toupper(*bname) * i;
1109 #else
1110                         sum += (*bname) * i;
1111 #endif
1112                         i++;
1113                         bname++;
1114                 }
1115         }
1116         
1117         return sum;
1118 }
1119
1120 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
1121 {
1122 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1123         memset(obj->shortName,0,sizeof (YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1)); 
1124         if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
1125                 yaffs_strcpy(obj->shortName, name);
1126         } else {
1127                 obj->shortName[0] = _Y('\0');
1128         }
1129 #endif
1130         obj->sum = yaffs_CalcNameSum(name);
1131 }
1132
1133 /*-------------------- TNODES -------------------
1134
1135  * List of spare tnodes
1136  * The list is hooked together using the first pointer
1137  * in the tnode.
1138  */
1139  
1140 /* yaffs_CreateTnodes creates a bunch more tnodes and
1141  * adds them to the tnode free list.
1142  * Don't use this function directly
1143  */
1144
1145 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
1146 {
1147         int i;
1148         int tnodeSize;
1149         yaffs_Tnode *newTnodes;
1150         __u8 *mem;
1151         yaffs_Tnode *curr;
1152         yaffs_Tnode *next;
1153         yaffs_TnodeList *tnl;
1154
1155         if (nTnodes < 1)
1156                 return YAFFS_OK;
1157                 
1158         /* Calculate the tnode size in bytes for variable width tnode support.
1159          * Must be a multiple of 32-bits  */
1160         tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1161
1162         if(tnodeSize < sizeof(yaffs_Tnode))
1163                 tnodeSize = sizeof(yaffs_Tnode);
1164                 
1165
1166         /* make these things */
1167
1168         newTnodes = YMALLOC(nTnodes * tnodeSize);
1169         mem = (__u8 *)newTnodes;
1170
1171         if (!newTnodes) {
1172                 T(YAFFS_TRACE_ERROR,
1173                   (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1174                 return YAFFS_FAIL;
1175         }
1176
1177         /* Hook them into the free list */
1178 #if 0
1179         for (i = 0; i < nTnodes - 1; i++) {
1180                 newTnodes[i].internal[0] = &newTnodes[i + 1];
1181 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1182                 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1183 #endif
1184         }
1185
1186         newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1187 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1188         newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1189 #endif
1190         dev->freeTnodes = newTnodes;
1191 #else
1192         /* New hookup for wide tnodes */
1193         for(i = 0; i < nTnodes -1; i++) {
1194                 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1195                 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1196                 curr->internal[0] = next;
1197         }
1198         
1199         curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1200         curr->internal[0] = dev->freeTnodes;
1201         dev->freeTnodes = (yaffs_Tnode *)mem;
1202
1203 #endif
1204
1205
1206         dev->nFreeTnodes += nTnodes;
1207         dev->nTnodesCreated += nTnodes;
1208
1209         /* Now add this bunch of tnodes to a list for freeing up.
1210          * NB If we can't add this to the management list it isn't fatal
1211          * but it just means we can't free this bunch of tnodes later.
1212          */
1213          
1214         tnl = YMALLOC(sizeof(yaffs_TnodeList));
1215         if (!tnl) {
1216                 T(YAFFS_TRACE_ERROR,
1217                   (TSTR
1218                    ("yaffs: Could not add tnodes to management list" TENDSTR)));
1219                    return YAFFS_FAIL;
1220
1221         } else {
1222                 tnl->tnodes = newTnodes;
1223                 tnl->next = dev->allocatedTnodeList;
1224                 dev->allocatedTnodeList = tnl;
1225         }
1226
1227         T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1228
1229         return YAFFS_OK;
1230 }
1231
1232 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1233
1234 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
1235 {
1236         yaffs_Tnode *tn = NULL;
1237
1238         /* If there are none left make more */
1239         if (!dev->freeTnodes) {
1240                 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1241         }
1242
1243         if (dev->freeTnodes) {
1244                 tn = dev->freeTnodes;
1245 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1246                 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1247                         /* Hoosterman, this thing looks like it isn't in the list */
1248                         T(YAFFS_TRACE_ALWAYS,
1249                           (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1250                 }
1251 #endif
1252                 dev->freeTnodes = dev->freeTnodes->internal[0];
1253                 dev->nFreeTnodes--;
1254         }
1255
1256         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1257
1258         return tn;
1259 }
1260
1261 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
1262 {
1263         yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1264         int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1265
1266         if(tnodeSize < sizeof(yaffs_Tnode))
1267                 tnodeSize = sizeof(yaffs_Tnode);
1268         
1269         if(tn)
1270                 memset(tn, 0, tnodeSize);
1271
1272         return tn;      
1273 }
1274
1275 /* FreeTnode frees up a tnode and puts it back on the free list */
1276 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
1277 {
1278         if (tn) {
1279 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1280                 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1281                         /* Hoosterman, this thing looks like it is already in the list */
1282                         T(YAFFS_TRACE_ALWAYS,
1283                           (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1284                 }
1285                 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1286 #endif
1287                 tn->internal[0] = dev->freeTnodes;
1288                 dev->freeTnodes = tn;
1289                 dev->nFreeTnodes++;
1290         }
1291         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1292         
1293 }
1294
1295 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
1296 {
1297         /* Free the list of allocated tnodes */
1298         yaffs_TnodeList *tmp;
1299
1300         while (dev->allocatedTnodeList) {
1301                 tmp = dev->allocatedTnodeList->next;
1302
1303                 YFREE(dev->allocatedTnodeList->tnodes);
1304                 YFREE(dev->allocatedTnodeList);
1305                 dev->allocatedTnodeList = tmp;
1306
1307         }
1308
1309         dev->freeTnodes = NULL;
1310         dev->nFreeTnodes = 0;
1311 }
1312
1313 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
1314 {
1315         dev->allocatedTnodeList = NULL;
1316         dev->freeTnodes = NULL;
1317         dev->nFreeTnodes = 0;
1318         dev->nTnodesCreated = 0;
1319
1320 }
1321
1322
1323 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
1324 {
1325   __u32 *map = (__u32 *)tn;
1326   __u32 bitInMap;
1327   __u32 bitInWord;
1328   __u32 wordInMap;
1329   __u32 mask;
1330   
1331   pos &= YAFFS_TNODES_LEVEL0_MASK;
1332   val >>= dev->chunkGroupBits;
1333   
1334   bitInMap = pos * dev->tnodeWidth;
1335   wordInMap = bitInMap /32;
1336   bitInWord = bitInMap & (32 -1);
1337   
1338   mask = dev->tnodeMask << bitInWord;
1339   
1340   map[wordInMap] &= ~mask;
1341   map[wordInMap] |= (mask & (val << bitInWord));
1342   
1343   if(dev->tnodeWidth > (32-bitInWord)) {
1344     bitInWord = (32 - bitInWord);
1345     wordInMap++;;
1346     mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1347     map[wordInMap] &= ~mask;
1348     map[wordInMap] |= (mask & (val >> bitInWord));
1349   }
1350 }
1351
1352 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
1353 {
1354   __u32 *map = (__u32 *)tn;
1355   __u32 bitInMap;
1356   __u32 bitInWord;
1357   __u32 wordInMap;
1358   __u32 val;
1359   
1360   pos &= YAFFS_TNODES_LEVEL0_MASK;
1361   
1362   bitInMap = pos * dev->tnodeWidth;
1363   wordInMap = bitInMap /32;
1364   bitInWord = bitInMap & (32 -1);
1365   
1366   val = map[wordInMap] >> bitInWord;
1367   
1368   if(dev->tnodeWidth > (32-bitInWord)) {
1369     bitInWord = (32 - bitInWord);
1370     wordInMap++;;
1371     val |= (map[wordInMap] << bitInWord);
1372   }
1373   
1374   val &= dev->tnodeMask;
1375   val <<= dev->chunkGroupBits;
1376   
1377   return val;
1378 }
1379
1380 /* ------------------- End of individual tnode manipulation -----------------*/
1381
1382 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1383  * The look up tree is represented by the top tnode and the number of topLevel
1384  * in the tree. 0 means only the level 0 tnode is in the tree.
1385  */
1386
1387 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1388 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
1389                                           yaffs_FileStructure * fStruct,
1390                                           __u32 chunkId)
1391 {
1392
1393         yaffs_Tnode *tn = fStruct->top;
1394         __u32 i;
1395         int requiredTallness;
1396         int level = fStruct->topLevel;
1397
1398         /* Check sane level and chunk Id */
1399         if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
1400                 return NULL;
1401         }
1402
1403         if (chunkId > YAFFS_MAX_CHUNK_ID) {
1404                 return NULL;
1405         }
1406
1407         /* First check we're tall enough (ie enough topLevel) */
1408
1409         i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1410         requiredTallness = 0;
1411         while (i) {
1412                 i >>= YAFFS_TNODES_INTERNAL_BITS;
1413                 requiredTallness++;
1414         }
1415
1416         if (requiredTallness > fStruct->topLevel) {
1417                 /* Not tall enough, so we can't find it, return NULL. */
1418                 return NULL;
1419         }
1420
1421         /* Traverse down to level 0 */
1422         while (level > 0 && tn) {
1423                 tn = tn->
1424                     internal[(chunkId >>
1425                                ( YAFFS_TNODES_LEVEL0_BITS + 
1426                                  (level - 1) *
1427                                  YAFFS_TNODES_INTERNAL_BITS)
1428                               ) &
1429                              YAFFS_TNODES_INTERNAL_MASK];
1430                 level--;
1431
1432         }
1433
1434         return tn;
1435 }
1436
1437 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1438  * This happens in two steps:
1439  *  1. If the tree isn't tall enough, then make it taller.
1440  *  2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1441  *
1442  * Used when modifying the tree.
1443  *
1444  *  If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1445  *  be plugged into the ttree.
1446  */
1447  
1448 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
1449                                                yaffs_FileStructure * fStruct,
1450                                                __u32 chunkId,
1451                                                yaffs_Tnode *passedTn)
1452 {
1453
1454         int requiredTallness;
1455         int i;
1456         int l;
1457         yaffs_Tnode *tn;
1458
1459         __u32 x;
1460
1461
1462         /* Check sane level and page Id */
1463         if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
1464                 return NULL;
1465         }
1466
1467         if (chunkId > YAFFS_MAX_CHUNK_ID) {
1468                 return NULL;
1469         }
1470
1471         /* First check we're tall enough (ie enough topLevel) */
1472
1473         x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1474         requiredTallness = 0;
1475         while (x) {
1476                 x >>= YAFFS_TNODES_INTERNAL_BITS;
1477                 requiredTallness++;
1478         }
1479
1480
1481         if (requiredTallness > fStruct->topLevel) {
1482                 /* Not tall enough,gotta make the tree taller */
1483                 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1484                 
1485                         tn = yaffs_GetTnode(dev);
1486
1487                         if (tn) {
1488                                 tn->internal[0] = fStruct->top;
1489                                 fStruct->top = tn;
1490                         } else {
1491                                 T(YAFFS_TRACE_ERROR,
1492                                   (TSTR("yaffs: no more tnodes" TENDSTR)));
1493                         }
1494                 }
1495
1496                 fStruct->topLevel = requiredTallness;
1497         }
1498
1499         /* Traverse down to level 0, adding anything we need */
1500
1501         l = fStruct->topLevel;
1502         tn = fStruct->top;
1503         
1504         if(l > 0) {
1505                 while (l > 0 && tn) {
1506                         x = (chunkId >>
1507                              ( YAFFS_TNODES_LEVEL0_BITS +
1508                               (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1509                             YAFFS_TNODES_INTERNAL_MASK;
1510
1511
1512                         if((l>1) && !tn->internal[x]){
1513                                 /* Add missing non-level-zero tnode */
1514                                 tn->internal[x] = yaffs_GetTnode(dev);
1515
1516                         } else if(l == 1) {
1517                                 /* Looking from level 1 at level 0 */
1518                                 if (passedTn) {
1519                                         /* If we already have one, then release it.*/
1520                                         if(tn->internal[x])
1521                                                 yaffs_FreeTnode(dev,tn->internal[x]);
1522                                         tn->internal[x] = passedTn;
1523                         
1524                                 } else if(!tn->internal[x]) {
1525                                         /* Don't have one, none passed in */
1526                                         tn->internal[x] = yaffs_GetTnode(dev);
1527                                 }
1528                         }
1529                 
1530                         tn = tn->internal[x];
1531                         l--;
1532                 }
1533         } else {
1534                 /* top is level 0 */
1535                 if(passedTn) {
1536                         memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1537                         yaffs_FreeTnode(dev,passedTn);
1538                 }
1539         }
1540
1541         return tn;
1542 }
1543
1544 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1545                                   yaffs_ExtendedTags * tags, int objectId,
1546                                   int chunkInInode)
1547 {
1548         int j;
1549
1550         for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1551                 if (yaffs_CheckChunkBit
1552                     (dev, theChunk / dev->nChunksPerBlock,
1553                      theChunk % dev->nChunksPerBlock)) {
1554                         yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1555                                                         tags);
1556                         if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1557                                 /* found it; */
1558                                 return theChunk;
1559
1560                         }
1561                 }
1562                 theChunk++;
1563         }
1564         return -1;
1565 }
1566
1567
1568 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1569  * chunks and tnodes in the file
1570  * Returns 1 if the tree was deleted. 
1571  * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1572  */
1573
1574 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1575                               int chunkOffset, int *limit)
1576 {
1577         int i;
1578         int chunkInInode;
1579         int theChunk;
1580         yaffs_ExtendedTags tags;
1581         int foundChunk;
1582         yaffs_Device *dev = in->myDev;
1583
1584         int allDone = 1;
1585
1586         if (tn) {
1587                 if (level > 0) {
1588
1589                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1590                              i--) {
1591                                 if (tn->internal[i]) {
1592                                         if (limit && (*limit) < 0) {
1593                                                 allDone = 0;
1594                                         } else {
1595                                                 allDone =
1596                                                     yaffs_DeleteWorker(in,
1597                                                                        tn->
1598                                                                        internal
1599                                                                        [i],
1600                                                                        level -
1601                                                                        1,
1602                                                                        (chunkOffset
1603                                                                         <<
1604                                                                         YAFFS_TNODES_INTERNAL_BITS)
1605                                                                        + i,
1606                                                                        limit);
1607                                         }
1608                                         if (allDone) {
1609                                                 yaffs_FreeTnode(dev,
1610                                                                 tn->
1611                                                                 internal[i]);
1612                                                 tn->internal[i] = NULL;
1613                                         }
1614                                 }
1615
1616                         }
1617                         return (allDone) ? 1 : 0;
1618                 } else if (level == 0) {
1619                         int hitLimit = 0;
1620
1621                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1622                              i--) {
1623                                 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1624                                 if (theChunk) {
1625
1626                                         chunkInInode =
1627                                             (chunkOffset <<
1628                                              YAFFS_TNODES_LEVEL0_BITS) + i;
1629
1630                                         foundChunk =
1631                                             yaffs_FindChunkInGroup(dev,
1632                                                                    theChunk,
1633                                                                    &tags,
1634                                                                    in->objectId,
1635                                                                    chunkInInode);
1636
1637                                         if (foundChunk > 0) {
1638                                                 yaffs_DeleteChunk(dev,
1639                                                                   foundChunk, 1,
1640                                                                   __LINE__);
1641                                                 in->nDataChunks--;
1642                                                 if (limit) {
1643                                                         *limit = *limit - 1;
1644                                                         if (*limit <= 0) {
1645                                                                 hitLimit = 1;
1646                                                         }
1647                                                 }
1648
1649                                         }
1650
1651                                         yaffs_PutLevel0Tnode(dev,tn,i,0);
1652                                 }
1653
1654                         }
1655                         return (i < 0) ? 1 : 0;
1656
1657                 }
1658
1659         }
1660
1661         return 1;
1662
1663 }
1664
1665 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1666 {
1667
1668         yaffs_BlockInfo *theBlock;
1669
1670         T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1671
1672         theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1673         if (theBlock) {
1674                 theBlock->softDeletions++;
1675                 dev->nFreeChunks++;
1676         }
1677 }
1678
1679 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1680  * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1681  * of the tnode.
1682  * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1683  */
1684  
1685 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1686                                   __u32 level, int chunkOffset)
1687 {
1688         int i;
1689         int theChunk;
1690         int allDone = 1;
1691         yaffs_Device *dev = in->myDev;
1692
1693         if (tn) {
1694                 if (level > 0) {
1695
1696                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1697                              i--) {
1698                                 if (tn->internal[i]) {
1699                                         allDone =
1700                                             yaffs_SoftDeleteWorker(in,
1701                                                                    tn->
1702                                                                    internal[i],
1703                                                                    level - 1,
1704                                                                    (chunkOffset
1705                                                                     <<
1706                                                                     YAFFS_TNODES_INTERNAL_BITS)
1707                                                                    + i);
1708                                         if (allDone) {
1709                                                 yaffs_FreeTnode(dev,
1710                                                                 tn->
1711                                                                 internal[i]);
1712                                                 tn->internal[i] = NULL;
1713                                         } else {
1714                                                 /* Hoosterman... how could this happen? */
1715                                         }
1716                                 }
1717                         }
1718                         return (allDone) ? 1 : 0;
1719                 } else if (level == 0) {
1720
1721                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1722                                 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1723                                 if (theChunk) {
1724                                         /* Note this does not find the real chunk, only the chunk group.
1725                                          * We make an assumption that a chunk group is not larger than 
1726                                          * a block.
1727                                          */
1728                                         yaffs_SoftDeleteChunk(dev, theChunk);
1729                                         yaffs_PutLevel0Tnode(dev,tn,i,0);
1730                                 }
1731
1732                         }
1733                         return 1;
1734
1735                 }
1736
1737         }
1738
1739         return 1;
1740
1741 }
1742
1743 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1744 {
1745         if (obj->deleted &&
1746             obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1747                 if (obj->nDataChunks <= 0) {
1748                         /* Empty file with no duplicate object headers, just delete it immediately */
1749                         yaffs_FreeTnode(obj->myDev,
1750                                         obj->variant.fileVariant.top);
1751                         obj->variant.fileVariant.top = NULL;
1752                         T(YAFFS_TRACE_TRACING,
1753                           (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1754                            obj->objectId));
1755                         yaffs_DoGenericObjectDeletion(obj);
1756                 } else {
1757                         yaffs_SoftDeleteWorker(obj,
1758                                                obj->variant.fileVariant.top,
1759                                                obj->variant.fileVariant.
1760                                                topLevel, 0);
1761                         obj->softDeleted = 1;
1762                 }
1763         }
1764 }
1765
1766 /* Pruning removes any part of the file structure tree that is beyond the
1767  * bounds of the file (ie that does not point to chunks).
1768  *
1769  * A file should only get pruned when its size is reduced.
1770  *
1771  * Before pruning, the chunks must be pulled from the tree and the
1772  * level 0 tnode entries must be zeroed out.
1773  * Could also use this for file deletion, but that's probably better handled
1774  * by a special case.
1775  */
1776
1777 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1778                                       __u32 level, int del0)
1779 {
1780         int i;
1781         int hasData;
1782
1783         if (tn) {
1784                 hasData = 0;
1785
1786                 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1787                         if (tn->internal[i] && level > 0) {
1788                                 tn->internal[i] =
1789                                     yaffs_PruneWorker(dev, tn->internal[i],
1790                                                       level - 1,
1791                                                       (i == 0) ? del0 : 1);
1792                         }
1793
1794                         if (tn->internal[i]) {
1795                                 hasData++;
1796                         }
1797                 }
1798
1799                 if (hasData == 0 && del0) {
1800                         /* Free and return NULL */
1801
1802                         yaffs_FreeTnode(dev, tn);
1803                         tn = NULL;
1804                 }
1805
1806         }
1807
1808         return tn;
1809
1810 }
1811
1812 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1813                                     yaffs_FileStructure * fStruct)
1814 {
1815         int i;
1816         int hasData;
1817         int done = 0;
1818         yaffs_Tnode *tn;
1819
1820         if (fStruct->topLevel > 0) {
1821                 fStruct->top =
1822                     yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1823
1824                 /* Now we have a tree with all the non-zero branches NULL but the height
1825                  * is the same as it was.
1826                  * Let's see if we can trim internal tnodes to shorten the tree.
1827                  * We can do this if only the 0th element in the tnode is in use 
1828                  * (ie all the non-zero are NULL)
1829                  */
1830
1831                 while (fStruct->topLevel && !done) {
1832                         tn = fStruct->top;
1833
1834                         hasData = 0;
1835                         for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1836                                 if (tn->internal[i]) {
1837                                         hasData++;
1838                                 }
1839                         }
1840
1841                         if (!hasData) {
1842                                 fStruct->top = tn->internal[0];
1843                                 fStruct->topLevel--;
1844                                 yaffs_FreeTnode(dev, tn);
1845                         } else {
1846                                 done = 1;
1847                         }
1848                 }
1849         }
1850
1851         return YAFFS_OK;
1852 }
1853
1854 /*-------------------- End of File Structure functions.-------------------*/
1855
1856 /* yaffs_CreateFreeObjects creates a bunch more objects and
1857  * adds them to the object free list.
1858  */
1859 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1860 {
1861         int i;
1862         yaffs_Object *newObjects;
1863         yaffs_ObjectList *list;
1864
1865         if (nObjects < 1)
1866                 return YAFFS_OK;
1867
1868         /* make these things */
1869         newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1870         list = YMALLOC(sizeof(yaffs_ObjectList));
1871
1872         if (!newObjects || !list) {
1873                 if(newObjects)
1874                         YFREE(newObjects);
1875                 if(list)
1876                         YFREE(list);
1877                 T(YAFFS_TRACE_ALLOCATE,
1878                   (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1879                 return YAFFS_FAIL;
1880         }
1881         
1882         /* Hook them into the free list */
1883         for (i = 0; i < nObjects - 1; i++) {
1884                 newObjects[i].siblings.next =
1885                     (struct ylist_head *)(&newObjects[i + 1]);
1886         }
1887
1888         newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1889         dev->freeObjects = newObjects;
1890         dev->nFreeObjects += nObjects;
1891         dev->nObjectsCreated += nObjects;
1892
1893         /* Now add this bunch of Objects to a list for freeing up. */
1894
1895         list->objects = newObjects;
1896         list->next = dev->allocatedObjectList;
1897         dev->allocatedObjectList = list;
1898
1899         return YAFFS_OK;
1900 }
1901
1902
1903 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1904 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1905 {
1906         yaffs_Object *tn = NULL;
1907
1908 #ifdef VALGRIND_TEST
1909         tn = YMALLOC(sizeof(yaffs_Object));
1910 #else
1911         /* If there are none left make more */
1912         if (!dev->freeObjects) {
1913                 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1914         }
1915
1916         if (dev->freeObjects) {
1917                 tn = dev->freeObjects;
1918                 dev->freeObjects =
1919                     (yaffs_Object *) (dev->freeObjects->siblings.next);
1920                 dev->nFreeObjects--;
1921         }
1922 #endif
1923         if(tn){
1924                 /* Now sweeten it up... */
1925
1926                 memset(tn, 0, sizeof(yaffs_Object));
1927                 tn->myDev = dev;
1928                 tn->hdrChunk = 0;
1929                 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1930                 YINIT_LIST_HEAD(&(tn->hardLinks));
1931                 YINIT_LIST_HEAD(&(tn->hashLink));
1932                 YINIT_LIST_HEAD(&tn->siblings);
1933                 
1934
1935                 /* Now make the directory sane */
1936                 if(dev->rootDir){
1937                         tn->parent = dev->rootDir;
1938                         ylist_add(&(tn->siblings),&dev->rootDir->variant.directoryVariant.children);
1939                 }
1940
1941                 /* Add it to the lost and found directory.
1942                  * NB Can't put root or lostNFound in lostNFound so
1943                  * check if lostNFound exists first
1944                  */
1945                 if (dev->lostNFoundDir) {
1946                         yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1947                 }
1948         }
1949         
1950         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1951
1952         return tn;
1953 }
1954
1955 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1956                                                __u32 mode)
1957 {
1958
1959         yaffs_Object *obj =
1960             yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1961         if (obj) {
1962                 obj->fake = 1;          /* it is fake so it might have no NAND presence... */
1963                 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1964                 obj->unlinkAllowed = 0; /* ... or unlink it */
1965                 obj->deleted = 0;
1966                 obj->unlinked = 0;
1967                 obj->yst_mode = mode;
1968                 obj->myDev = dev;
1969                 obj->hdrChunk = 0;      /* Not a valid chunk. */
1970         }
1971
1972         return obj;
1973
1974 }
1975
1976 static void yaffs_UnhashObject(yaffs_Object * tn)
1977 {
1978         int bucket;
1979         yaffs_Device *dev = tn->myDev;
1980
1981         /* If it is still linked into the bucket list, free from the list */
1982         if (!ylist_empty(&tn->hashLink)) {
1983                 ylist_del_init(&tn->hashLink);
1984                 bucket = yaffs_HashFunction(tn->objectId);
1985                 dev->objectBucket[bucket].count--;
1986         }
1987
1988 }
1989
1990 /*  FreeObject frees up a Object and puts it back on the free list */
1991 static void yaffs_FreeObject(yaffs_Object * tn)
1992 {
1993
1994         yaffs_Device *dev = tn->myDev;
1995
1996         
1997         if(tn->parent)
1998                 YBUG();
1999         if(!ylist_empty(&tn->siblings))
2000                 YBUG();
2001
2002
2003 #ifdef  __KERNEL__
2004         if (tn->myInode) {
2005                 /* We're still hooked up to a cached inode.
2006                  * Don't delete now, but mark for later deletion
2007                  */
2008                 tn->deferedFree = 1;
2009                 return;
2010         }
2011 #endif
2012
2013         yaffs_UnhashObject(tn);
2014
2015 #ifdef VALGRIND_TEST
2016         YFREE(tn);
2017 #else
2018         /* Link into the free list. */
2019         tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2020         dev->freeObjects = tn;
2021         dev->nFreeObjects++;
2022 #endif
2023         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2024
2025 }
2026
2027 #ifdef __KERNEL__
2028
2029 void yaffs_HandleDeferedFree(yaffs_Object * obj)
2030 {
2031         if (obj->deferedFree) {
2032                 yaffs_FreeObject(obj);
2033         }
2034 }
2035
2036 #endif
2037
2038 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
2039 {
2040         /* Free the list of allocated Objects */
2041
2042         yaffs_ObjectList *tmp;
2043
2044         while (dev->allocatedObjectList) {
2045                 tmp = dev->allocatedObjectList->next;
2046                 YFREE(dev->allocatedObjectList->objects);
2047                 YFREE(dev->allocatedObjectList);
2048
2049                 dev->allocatedObjectList = tmp;
2050         }
2051
2052         dev->freeObjects = NULL;
2053         dev->nFreeObjects = 0;
2054 }
2055
2056 static void yaffs_InitialiseObjects(yaffs_Device * dev)
2057 {
2058         int i;
2059
2060         dev->allocatedObjectList = NULL;
2061         dev->freeObjects = NULL;
2062         dev->nFreeObjects = 0;
2063
2064         for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2065                 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2066                 dev->objectBucket[i].count = 0;
2067         }
2068
2069 }
2070
2071 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
2072 {
2073         static int x = 0;
2074         int i;
2075         int l = 999;
2076         int lowest = 999999;
2077
2078         /* First let's see if we can find one that's empty. */
2079
2080         for (i = 0; i < 10 && lowest > 0; i++) {
2081                 x++;
2082                 x %= YAFFS_NOBJECT_BUCKETS;
2083                 if (dev->objectBucket[x].count < lowest) {
2084                         lowest = dev->objectBucket[x].count;
2085                         l = x;
2086                 }
2087
2088         }
2089
2090         /* If we didn't find an empty list, then try
2091          * looking a bit further for a short one
2092          */
2093
2094         for (i = 0; i < 10 && lowest > 3; i++) {
2095                 x++;
2096                 x %= YAFFS_NOBJECT_BUCKETS;
2097                 if (dev->objectBucket[x].count < lowest) {
2098                         lowest = dev->objectBucket[x].count;
2099                         l = x;
2100                 }
2101
2102         }
2103
2104         return l;
2105 }
2106
2107 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
2108 {
2109         int bucket = yaffs_FindNiceObjectBucket(dev);
2110
2111         /* Now find an object value that has not already been taken
2112          * by scanning the list.
2113          */
2114
2115         int found = 0;
2116         struct ylist_head *i;
2117
2118         __u32 n = (__u32) bucket;
2119
2120         /* yaffs_CheckObjectHashSanity();  */
2121
2122         while (!found) {
2123                 found = 1;
2124                 n += YAFFS_NOBJECT_BUCKETS;
2125                 if (1 || dev->objectBucket[bucket].count > 0) {
2126                         ylist_for_each(i, &dev->objectBucket[bucket].list) {
2127                                 /* If there is already one in the list */
2128                                 if (i
2129                                     && ylist_entry(i, yaffs_Object,
2130                                                   hashLink)->objectId == n) {
2131                                         found = 0;
2132                                 }
2133                         }
2134                 }
2135         }
2136
2137
2138         return n;
2139 }
2140
2141 static void yaffs_HashObject(yaffs_Object * in)
2142 {
2143         int bucket = yaffs_HashFunction(in->objectId);
2144         yaffs_Device *dev = in->myDev;
2145
2146         ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2147         dev->objectBucket[bucket].count++;
2148
2149 }
2150
2151 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
2152 {
2153         int bucket = yaffs_HashFunction(number);
2154         struct ylist_head *i;
2155         yaffs_Object *in;
2156
2157         ylist_for_each(i, &dev->objectBucket[bucket].list) {
2158                 /* Look if it is in the list */
2159                 if (i) {
2160                         in = ylist_entry(i, yaffs_Object, hashLink);
2161                         if (in->objectId == number) {
2162 #ifdef __KERNEL__
2163                                 /* Don't tell the VFS about this one if it is defered free */
2164                                 if (in->deferedFree)
2165                                         return NULL;
2166 #endif
2167
2168                                 return in;
2169                         }
2170                 }
2171         }
2172
2173         return NULL;
2174 }
2175
2176 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
2177                                     yaffs_ObjectType type)
2178 {
2179
2180         yaffs_Object *theObject;
2181         yaffs_Tnode *tn = NULL;
2182
2183         if (number < 0) {
2184                 number = yaffs_CreateNewObjectNumber(dev);
2185         }
2186
2187         theObject = yaffs_AllocateEmptyObject(dev);
2188         if(!theObject)
2189                 return NULL;
2190                 
2191         if(type == YAFFS_OBJECT_TYPE_FILE){
2192                 tn = yaffs_GetTnode(dev);
2193                 if(!tn){
2194                         yaffs_FreeObject(theObject);
2195                         return NULL;
2196                 }
2197         }
2198                 
2199         
2200
2201         if (theObject) {
2202                 theObject->fake = 0;
2203                 theObject->renameAllowed = 1;
2204                 theObject->unlinkAllowed = 1;
2205                 theObject->objectId = number;
2206                 yaffs_HashObject(theObject);
2207                 theObject->variantType = type;
2208 #ifdef CONFIG_YAFFS_WINCE
2209                 yfsd_WinFileTimeNow(theObject->win_atime);
2210                 theObject->win_ctime[0] = theObject->win_mtime[0] =
2211                     theObject->win_atime[0];
2212                 theObject->win_ctime[1] = theObject->win_mtime[1] =
2213                     theObject->win_atime[1];
2214
2215 #else
2216
2217                 theObject->yst_atime = theObject->yst_mtime =
2218                     theObject->yst_ctime = Y_CURRENT_TIME;
2219 #endif
2220
2221 #if 0
2222                 theObject->sum_prev = 12345;
2223                 theObject->sum_trailer = 6789;
2224 #endif
2225
2226                 switch (type) {
2227                 case YAFFS_OBJECT_TYPE_FILE:
2228                         theObject->variant.fileVariant.fileSize = 0;
2229                         theObject->variant.fileVariant.scannedFileSize = 0;
2230                         theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2231                         theObject->variant.fileVariant.topLevel = 0;
2232                         theObject->variant.fileVariant.top = tn;
2233                         break;
2234                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2235                         YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2236                                        children);
2237                         break;
2238                 case YAFFS_OBJECT_TYPE_SYMLINK:
2239                 case YAFFS_OBJECT_TYPE_HARDLINK:
2240                 case YAFFS_OBJECT_TYPE_SPECIAL:
2241                         /* No action required */
2242                         break;
2243                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2244                         /* todo this should not happen */
2245                         break;
2246                 }
2247         }
2248
2249         return theObject;
2250 }
2251
2252 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
2253                                                       int number,
2254                                                       yaffs_ObjectType type)
2255 {
2256         yaffs_Object *theObject = NULL;
2257
2258         if (number > 0) {
2259                 theObject = yaffs_FindObjectByNumber(dev, number);
2260         }
2261
2262         if (!theObject) {
2263                 theObject = yaffs_CreateNewObject(dev, number, type);
2264         }
2265
2266         return theObject;
2267
2268 }
2269                         
2270
2271 static YCHAR *yaffs_CloneString(const YCHAR * str)
2272 {
2273         YCHAR *newStr = NULL;
2274
2275         if (str && *str) {
2276                 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2277                 if(newStr)
2278                         yaffs_strcpy(newStr, str);
2279         }
2280
2281         return newStr;
2282
2283 }
2284
2285 /*
2286  * Mknod (create) a new object.
2287  * equivalentObject only has meaning for a hard link;
2288  * aliasString only has meaning for a sumlink.
2289  * rdev only has meaning for devices (a subset of special objects)
2290  */
2291  
2292 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2293                                        yaffs_Object * parent,
2294                                        const YCHAR * name,
2295                                        __u32 mode,
2296                                        __u32 uid,
2297                                        __u32 gid,
2298                                        yaffs_Object * equivalentObject,
2299                                        const YCHAR * aliasString, __u32 rdev)
2300 {
2301         yaffs_Object *in;
2302         YCHAR *str = NULL;
2303
2304         yaffs_Device *dev = parent->myDev;
2305
2306         /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2307         if (yaffs_FindObjectByName(parent, name)) {
2308                 return NULL;
2309         }
2310
2311         in = yaffs_CreateNewObject(dev, -1, type);
2312
2313         if(!in)
2314                 return YAFFS_FAIL;
2315         
2316         if(type == YAFFS_OBJECT_TYPE_SYMLINK){
2317                 str = yaffs_CloneString(aliasString);
2318                 if(!str){
2319                         yaffs_FreeObject(in);
2320                         return NULL;
2321                 }
2322         }
2323         
2324         
2325
2326         if (in) {
2327                 in->hdrChunk = 0;
2328                 in->valid = 1;
2329                 in->variantType = type;
2330
2331                 in->yst_mode = mode;
2332
2333 #ifdef CONFIG_YAFFS_WINCE
2334                 yfsd_WinFileTimeNow(in->win_atime);
2335                 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2336                 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2337
2338 #else
2339                 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2340
2341                 in->yst_rdev = rdev;
2342                 in->yst_uid = uid;
2343                 in->yst_gid = gid;
2344 #endif
2345                 in->nDataChunks = 0;
2346
2347                 yaffs_SetObjectName(in, name);
2348                 in->dirty = 1;
2349
2350                 yaffs_AddObjectToDirectory(parent, in);
2351
2352                 in->myDev = parent->myDev;
2353
2354                 switch (type) {
2355                 case YAFFS_OBJECT_TYPE_SYMLINK:
2356                         in->variant.symLinkVariant.alias = str;
2357                         break;
2358                 case YAFFS_OBJECT_TYPE_HARDLINK:
2359                         in->variant.hardLinkVariant.equivalentObject =
2360                             equivalentObject;
2361                         in->variant.hardLinkVariant.equivalentObjectId =
2362                             equivalentObject->objectId;
2363                         ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2364                         break;
2365                 case YAFFS_OBJECT_TYPE_FILE:    
2366                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2367                 case YAFFS_OBJECT_TYPE_SPECIAL:
2368                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2369                         /* do nothing */
2370                         break;
2371                 }
2372
2373                 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2374                         /* Could not create the object header, fail the creation */
2375                         yaffs_DestroyObject(in);
2376                         in = NULL;
2377                 }
2378
2379         }
2380
2381         return in;
2382 }
2383
2384 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
2385                               __u32 mode, __u32 uid, __u32 gid)
2386 {
2387         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2388                                  uid, gid, NULL, NULL, 0);
2389 }
2390
2391 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
2392                                    __u32 mode, __u32 uid, __u32 gid)
2393 {
2394         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2395                                  mode, uid, gid, NULL, NULL, 0);
2396 }
2397
2398 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
2399                                  __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2400 {
2401         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2402                                  uid, gid, NULL, NULL, rdev);
2403 }
2404
2405 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
2406                                  __u32 mode, __u32 uid, __u32 gid,
2407                                  const YCHAR * alias)
2408 {
2409         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2410                                  uid, gid, NULL, alias, 0);
2411 }
2412
2413 /* yaffs_Link returns the object id of the equivalent object.*/
2414 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
2415                          yaffs_Object * equivalentObject)
2416 {
2417         /* Get the real object in case we were fed a hard link as an equivalent object */
2418         equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2419
2420         if (yaffs_MknodObject
2421             (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2422              equivalentObject, NULL, 0)) {
2423                 return equivalentObject;
2424         } else {
2425                 return NULL;
2426         }
2427
2428 }
2429
2430 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
2431                                   const YCHAR * newName, int force, int shadows)
2432 {
2433         int unlinkOp;
2434         int deleteOp;
2435
2436         yaffs_Object *existingTarget;
2437
2438         if (newDir == NULL) {
2439                 newDir = obj->parent;   /* use the old directory */
2440         }
2441
2442         if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2443                 T(YAFFS_TRACE_ALWAYS,
2444                   (TSTR
2445                    ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2446                     TENDSTR)));
2447                 YBUG();
2448         }
2449         
2450         /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2451         if (obj->myDev->isYaffs2) {
2452                 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2453         } else {
2454                 unlinkOp = (newDir == obj->myDev->unlinkedDir
2455                             && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2456         }
2457
2458         deleteOp = (newDir == obj->myDev->deletedDir);
2459
2460         existingTarget = yaffs_FindObjectByName(newDir, newName);
2461
2462         /* If the object is a file going into the unlinked directory, 
2463          *   then it is OK to just stuff it in since duplicate names are allowed.
2464          *   else only proceed if the new name does not exist and if we're putting 
2465          *   it into a directory.
2466          */
2467         if ((unlinkOp ||
2468              deleteOp ||
2469              force ||
2470              (shadows > 0) ||
2471              !existingTarget) &&
2472             newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2473                 yaffs_SetObjectName(obj, newName);
2474                 obj->dirty = 1;
2475
2476                 yaffs_AddObjectToDirectory(newDir, obj);
2477
2478                 if (unlinkOp)
2479                         obj->unlinked = 1;
2480
2481                 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2482                 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
2483                         return YAFFS_OK;
2484         }
2485
2486         return YAFFS_FAIL;
2487 }
2488
2489 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
2490                        yaffs_Object * newDir, const YCHAR * newName)
2491 {
2492         yaffs_Object *obj=NULL;
2493         yaffs_Object *existingTarget=NULL;
2494         int force = 0;
2495         
2496         
2497         if(!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2498                 YBUG();
2499         if(!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2500                 YBUG();
2501
2502 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2503         /* Special case for case insemsitive systems (eg. WinCE).
2504          * While look-up is case insensitive, the name isn't.
2505          * Therefore we might want to change x.txt to X.txt
2506         */
2507         if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
2508                 force = 1;
2509         }
2510 #endif
2511
2512         else if (yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2513           /* ENAMETOOLONG */
2514           return YAFFS_FAIL;
2515
2516         obj = yaffs_FindObjectByName(oldDir, oldName);
2517
2518         if (obj && obj->renameAllowed) {
2519
2520                 /* Now do the handling for an existing target, if there is one */
2521
2522                 existingTarget = yaffs_FindObjectByName(newDir, newName);
2523                 if (existingTarget &&
2524                     existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2525                     !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2526                         /* There is a target that is a non-empty directory, so we fail */
2527                         return YAFFS_FAIL;      /* EEXIST or ENOTEMPTY */
2528                 } else if (existingTarget && existingTarget != obj) {
2529                         /* Nuke the target first, using shadowing, 
2530                          * but only if it isn't the same object
2531                          */
2532                         yaffs_ChangeObjectName(obj, newDir, newName, force,
2533                                                existingTarget->objectId);
2534                         yaffs_UnlinkObject(existingTarget);
2535                 }
2536
2537                 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2538         }
2539         return YAFFS_FAIL;
2540 }
2541
2542 /*------------------------- Block Management and Page Allocation ----------------*/
2543
2544 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
2545 {
2546         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2547         
2548         dev->blockInfo = NULL;
2549         dev->chunkBits = NULL;
2550         
2551         dev->allocationBlock = -1;      /* force it to get a new one */
2552
2553         /* If the first allocation strategy fails, thry the alternate one */
2554         dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2555         if(!dev->blockInfo){
2556                 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2557                 dev->blockInfoAlt = 1;
2558         }
2559         else
2560                 dev->blockInfoAlt = 0;
2561                 
2562         if(dev->blockInfo){
2563         
2564                 /* Set up dynamic blockinfo stuff. */
2565                 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2566                 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2567                 if(!dev->chunkBits){
2568                         dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2569                         dev->chunkBitsAlt = 1;
2570                 }
2571                 else
2572                         dev->chunkBitsAlt = 0;
2573         }
2574         
2575         if (dev->blockInfo && dev->chunkBits) {
2576                 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2577                 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2578                 return YAFFS_OK;
2579         }
2580
2581         return YAFFS_FAIL;
2582
2583 }
2584
2585 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
2586 {
2587         if(dev->blockInfoAlt && dev->blockInfo)
2588                 YFREE_ALT(dev->blockInfo);
2589         else if(dev->blockInfo)
2590                 YFREE(dev->blockInfo);
2591
2592         dev->blockInfoAlt = 0;
2593
2594         dev->blockInfo = NULL;
2595         
2596         if(dev->chunkBitsAlt && dev->chunkBits)
2597                 YFREE_ALT(dev->chunkBits);
2598         else if(dev->chunkBits)
2599                 YFREE(dev->chunkBits);
2600         dev->chunkBitsAlt = 0;
2601         dev->chunkBits = NULL;
2602 }
2603
2604 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
2605                                             yaffs_BlockInfo * bi)
2606 {
2607         int i;
2608         __u32 seq;
2609         yaffs_BlockInfo *b;
2610
2611         if (!dev->isYaffs2)
2612                 return 1;       /* disqualification only applies to yaffs2. */
2613
2614         if (!bi->hasShrinkHeader)
2615                 return 1;       /* can gc */
2616
2617         /* Find the oldest dirty sequence number if we don't know it and save it
2618          * so we don't have to keep recomputing it.
2619          */
2620         if (!dev->oldestDirtySequence) {
2621                 seq = dev->sequenceNumber;
2622
2623                 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2624                      i++) {
2625                         b = yaffs_GetBlockInfo(dev, i);
2626                         if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2627                             (b->pagesInUse - b->softDeletions) <
2628                             dev->nChunksPerBlock && b->sequenceNumber < seq) {
2629                                 seq = b->sequenceNumber;
2630                         }
2631                 }
2632                 dev->oldestDirtySequence = seq;
2633         }
2634
2635         /* Can't do gc of this block if there are any blocks older than this one that have
2636          * discarded pages.
2637          */
2638         return (bi->sequenceNumber <= dev->oldestDirtySequence);
2639
2640 }
2641
2642 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2643  * for garbage collection.
2644  */
2645
2646 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2647                                                int aggressive)
2648 {
2649
2650         int b = dev->currentDirtyChecker;
2651
2652         int i;
2653         int iterations;
2654         int dirtiest = -1;
2655         int pagesInUse = 0;
2656         int prioritised=0;
2657         yaffs_BlockInfo *bi;
2658         int pendingPrioritisedExist = 0;
2659         
2660         /* First let's see if we need to grab a prioritised block */
2661         if(dev->hasPendingPrioritisedGCs){
2662                 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2663
2664                         bi = yaffs_GetBlockInfo(dev, i);
2665                         //yaffs_VerifyBlock(dev,bi,i);
2666                         
2667                         if(bi->gcPrioritise) {
2668                                 pendingPrioritisedExist = 1;
2669                                 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2670                                    yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2671                                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
2672                                         dirtiest = i;
2673                                         prioritised = 1;
2674                                         aggressive = 1; /* Fool the non-aggressive skip logiv below */
2675                                 }
2676                         }
2677                 }
2678                 
2679                 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2680                         dev->hasPendingPrioritisedGCs = 0;
2681         }
2682
2683         /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2684          * search harder.
2685          * else (we're doing a leasurely gc), then we only bother to do this if the
2686          * block has only a few pages in use.
2687          */
2688
2689         dev->nonAggressiveSkip--;
2690
2691         if (!aggressive && (dev->nonAggressiveSkip > 0)) {
2692                 return -1;
2693         }
2694
2695         if(!prioritised)
2696                 pagesInUse =
2697                         (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2698
2699         if (aggressive) {
2700                 iterations =
2701                     dev->internalEndBlock - dev->internalStartBlock + 1;
2702         } else {
2703                 iterations =
2704                     dev->internalEndBlock - dev->internalStartBlock + 1;
2705                 iterations = iterations / 16;
2706                 if (iterations > 200) {
2707                         iterations = 200;
2708                 }
2709         }
2710
2711         for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2712                 b++;
2713                 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2714                         b = dev->internalStartBlock;
2715                 }
2716
2717                 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2718                         T(YAFFS_TRACE_ERROR,
2719                           (TSTR("**>> Block %d is not valid" TENDSTR), b));
2720                         YBUG();
2721                 }
2722
2723                 bi = yaffs_GetBlockInfo(dev, b);
2724
2725 #if 0
2726                 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2727                         dirtiest = b;
2728                         pagesInUse = 0;
2729                 }
2730                 else 
2731 #endif
2732
2733                 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2734                        (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2735                         yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2736                         dirtiest = b;
2737                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
2738                 }
2739         }
2740
2741         dev->currentDirtyChecker = b;
2742
2743         if (dirtiest > 0) {
2744                 T(YAFFS_TRACE_GC,
2745                   (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2746                    dev->nChunksPerBlock - pagesInUse,prioritised));
2747         }
2748
2749         dev->oldestDirtySequence = 0;
2750
2751         if (dirtiest > 0) {
2752                 dev->nonAggressiveSkip = 4;
2753         }
2754
2755         return dirtiest;
2756 }
2757
2758 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2759 {
2760         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2761
2762         int erasedOk = 0;
2763
2764         /* If the block is still healthy erase it and mark as clean.
2765          * If the block has had a data failure, then retire it.
2766          */
2767          
2768         T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2769                 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2770                 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2771                 
2772         bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2773
2774         if (!bi->needsRetiring) {
2775                 yaffs_InvalidateCheckpoint(dev);
2776                 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2777                 if (!erasedOk) {
2778                         dev->nErasureFailures++;
2779                         T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2780                           (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2781                 }
2782         }
2783
2784         if (erasedOk && 
2785             ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2786                 int i;
2787                 for (i = 0; i < dev->nChunksPerBlock; i++) {
2788                         if (!yaffs_CheckChunkErased
2789                             (dev, blockNo * dev->nChunksPerBlock + i)) {
2790                                 T(YAFFS_TRACE_ERROR,
2791                                   (TSTR
2792                                    (">>Block %d erasure supposedly OK, but chunk %d not erased"
2793                                     TENDSTR), blockNo, i));
2794                         }
2795                 }
2796         }
2797
2798         if (erasedOk) {
2799                 /* Clean it up... */
2800                 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2801                 dev->nErasedBlocks++;
2802                 bi->pagesInUse = 0;
2803                 bi->softDeletions = 0;
2804                 bi->hasShrinkHeader = 0;
2805                 bi->skipErasedCheck = 1;  /* This is clean, so no need to check */
2806                 bi->gcPrioritise = 0;
2807                 yaffs_ClearChunkBits(dev, blockNo);
2808
2809                 T(YAFFS_TRACE_ERASE,
2810                   (TSTR("Erased block %d" TENDSTR), blockNo));
2811         } else {
2812                 dev->nFreeChunks -= dev->nChunksPerBlock;       /* We lost a block of free space */
2813
2814                 yaffs_RetireBlock(dev, blockNo);
2815                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2816                   (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2817         }
2818 }
2819
2820 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2821 {
2822         int i;
2823
2824         yaffs_BlockInfo *bi;
2825
2826         if (dev->nErasedBlocks < 1) {
2827                 /* Hoosterman we've got a problem.
2828                  * Can't get space to gc
2829                  */
2830                 T(YAFFS_TRACE_ERROR,
2831                   (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2832
2833                 return -1;
2834         }
2835         
2836         /* Find an empty block. */
2837
2838         for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2839                 dev->allocationBlockFinder++;
2840                 if (dev->allocationBlockFinder < dev->internalStartBlock
2841                     || dev->allocationBlockFinder > dev->internalEndBlock) {
2842                         dev->allocationBlockFinder = dev->internalStartBlock;
2843                 }
2844
2845                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2846
2847                 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2848                         bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2849                         dev->sequenceNumber++;
2850                         bi->sequenceNumber = dev->sequenceNumber;
2851                         dev->nErasedBlocks--;
2852                         T(YAFFS_TRACE_ALLOCATE,
2853                           (TSTR("Allocated block %d, seq  %d, %d left" TENDSTR),
2854                            dev->allocationBlockFinder, dev->sequenceNumber,
2855                            dev->nErasedBlocks));
2856                         return dev->allocationBlockFinder;
2857                 }
2858         }
2859
2860         T(YAFFS_TRACE_ALWAYS,
2861           (TSTR
2862            ("yaffs tragedy: no more erased blocks, but there should have been %d"
2863             TENDSTR), dev->nErasedBlocks));
2864
2865         return -1;
2866 }
2867
2868
2869
2870 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2871 {
2872         if(!dev->nCheckpointBlocksRequired &&
2873            dev->isYaffs2){
2874                 /* Not a valid value so recalculate */
2875                 int nBytes = 0;
2876                 int nBlocks;
2877                 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2878                 int tnodeSize;
2879
2880                 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2881
2882                 if(tnodeSize < sizeof(yaffs_Tnode))
2883                         tnodeSize = sizeof(yaffs_Tnode);
2884                 
2885                 nBytes += sizeof(yaffs_CheckpointValidity);
2886                 nBytes += sizeof(yaffs_CheckpointDevice);
2887                 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2888                 nBytes += devBlocks * dev->chunkBitmapStride;
2889                 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2890                 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2891                 nBytes += sizeof(yaffs_CheckpointValidity);
2892                 nBytes += sizeof(__u32); /* checksum*/
2893         
2894                 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2895         
2896                 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2897         
2898                 dev->nCheckpointBlocksRequired = nBlocks;
2899         }
2900
2901         return dev->nCheckpointBlocksRequired;
2902 }
2903
2904 // Check if there's space to allocate...
2905 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2906 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2907 {
2908         int reservedChunks;
2909         int reservedBlocks = dev->nReservedBlocks;
2910         int checkpointBlocks;
2911         
2912         if(dev->isYaffs2){
2913                 checkpointBlocks =  yaffs_CalcCheckpointBlocksRequired(dev) - 
2914                                     dev->blocksInCheckpoint;
2915                 if(checkpointBlocks < 0)
2916                         checkpointBlocks = 0;
2917         } else {
2918                 checkpointBlocks =0;
2919         }
2920         
2921         reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2922         
2923         return (dev->nFreeChunks > reservedChunks);
2924 }
2925
2926 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2927 {
2928         int retVal;
2929         yaffs_BlockInfo *bi;
2930
2931         if (dev->allocationBlock < 0) {
2932                 /* Get next block to allocate off */
2933                 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2934                 dev->allocationPage = 0;
2935         }
2936
2937         if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2938                 /* Not enough space to allocate unless we're allowed to use the reserve. */
2939                 return -1;
2940         }
2941
2942         if (dev->nErasedBlocks < dev->nReservedBlocks
2943             && dev->allocationPage == 0) {
2944                 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2945         }
2946
2947         /* Next page please.... */
2948         if (dev->allocationBlock >= 0) {
2949                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2950
2951                 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2952                     dev->allocationPage;
2953                 bi->pagesInUse++;
2954                 yaffs_SetChunkBit(dev, dev->allocationBlock,
2955                                   dev->allocationPage);
2956
2957                 dev->allocationPage++;
2958
2959                 dev->nFreeChunks--;
2960
2961                 /* If the block is full set the state to full */
2962                 if (dev->allocationPage >= dev->nChunksPerBlock) {
2963                         bi->blockState = YAFFS_BLOCK_STATE_FULL;
2964                         dev->allocationBlock = -1;
2965                 }
2966
2967                 if(blockUsedPtr)
2968                         *blockUsedPtr = bi;
2969                         
2970                 return retVal;
2971         }
2972         
2973         T(YAFFS_TRACE_ERROR,
2974           (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2975
2976         return -1;
2977 }
2978
2979 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2980 {
2981         int n;
2982
2983         n = dev->nErasedBlocks * dev->nChunksPerBlock;
2984
2985         if (dev->allocationBlock > 0) {
2986                 n += (dev->nChunksPerBlock - dev->allocationPage);
2987         }
2988
2989         return n;
2990
2991 }
2992
2993 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block, int wholeBlock)
2994 {
2995         int oldChunk;
2996         int newChunk;
2997         int markNAND;
2998         int retVal = YAFFS_OK;
2999         int cleanups = 0;
3000         int i;
3001         int isCheckpointBlock;
3002         int matchingChunk;
3003         int maxCopies;
3004
3005         int chunksBefore = yaffs_GetErasedChunks(dev);
3006         int chunksAfter;
3007
3008         yaffs_ExtendedTags tags;
3009
3010         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3011
3012         yaffs_Object *object;
3013
3014         isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3015         
3016         bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3017
3018         T(YAFFS_TRACE_TRACING,
3019           (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR), 
3020           block,
3021           bi->pagesInUse,
3022           bi->hasShrinkHeader,
3023           wholeBlock));
3024
3025         /*yaffs_VerifyFreeChunks(dev); */
3026
3027         bi->hasShrinkHeader = 0;        /* clear the flag so that the block can erase */
3028
3029         /* Take off the number of soft deleted entries because
3030          * they're going to get really deleted during GC.
3031          */
3032         dev->nFreeChunks -= bi->softDeletions;
3033
3034         dev->isDoingGC = 1;
3035
3036         if (isCheckpointBlock ||
3037             !yaffs_StillSomeChunkBits(dev, block)) {
3038                 T(YAFFS_TRACE_TRACING,
3039                   (TSTR
3040                    ("Collecting block %d that has no chunks in use" TENDSTR),
3041                    block));
3042                 yaffs_BlockBecameDirty(dev, block);
3043         } else {
3044
3045                 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3046                 
3047                 yaffs_VerifyBlock(dev,bi,block);
3048
3049                 maxCopies = (wholeBlock) ? dev->nChunksPerBlock : 10;
3050                 oldChunk = block * dev->nChunksPerBlock + dev->gcChunk;
3051                 
3052                 for ( /* init already done */;
3053                      retVal == YAFFS_OK &&
3054                      dev->gcChunk < dev->nChunksPerBlock &&
3055                      (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING)&&
3056                      maxCopies > 0;
3057                      dev->gcChunk++, oldChunk++) {
3058                         if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3059
3060                                 /* This page is in use and might need to be copied off */
3061                                 
3062                                 maxCopies--;
3063
3064                                 markNAND = 1;
3065
3066                                 yaffs_InitialiseTags(&tags);
3067
3068                                 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3069                                                                 buffer, &tags);
3070
3071                                 object =
3072                                     yaffs_FindObjectByNumber(dev,
3073                                                              tags.objectId);
3074
3075                                 T(YAFFS_TRACE_GC_DETAIL,
3076                                   (TSTR
3077                                    ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3078                                    dev->gcChunk, tags.objectId, tags.chunkId,
3079                                    tags.byteCount));
3080                                    
3081                                 if(object && !yaffs_SkipVerification(dev)){
3082                                         if(tags.chunkId == 0)
3083                                                 matchingChunk = object->hdrChunk;
3084                                         else if(object->softDeleted)
3085                                                 matchingChunk = oldChunk; /* Defeat the test */
3086                                         else
3087                                                 matchingChunk = yaffs_FindChunkInFile(object,tags.chunkId,NULL);
3088                                         
3089                                         if(oldChunk != matchingChunk)
3090                                                 T(YAFFS_TRACE_ERROR,
3091                                                   (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3092                                                   oldChunk,matchingChunk,tags.objectId, tags.chunkId));
3093                                                 
3094                                 }
3095
3096                                 if (!object) {
3097                                         T(YAFFS_TRACE_ERROR,
3098                                           (TSTR
3099                                            ("page %d in gc has no object: %d %d %d "
3100                                             TENDSTR), oldChunk,
3101                                             tags.objectId, tags.chunkId, tags.byteCount));
3102                                 }
3103
3104                                 if (object && 
3105                                     object->deleted &&
3106                                     object->softDeleted &&
3107                                     tags.chunkId != 0) {
3108                                         /* Data chunk in a soft deleted file, throw it away
3109                                          * It's a soft deleted data chunk,
3110                                          * No need to copy this, just forget about it and 
3111                                          * fix up the object.
3112                                          */
3113
3114                                         object->nDataChunks--;
3115
3116                                         if (object->nDataChunks <= 0) {
3117                                                 /* remeber to clean up the object */
3118                                                 dev->gcCleanupList[cleanups] =
3119                                                     tags.objectId;
3120                                                 cleanups++;
3121                                         }
3122                                         markNAND = 0;
3123                                 } else if (0
3124                                            /* Todo object && object->deleted && object->nDataChunks == 0 */
3125                                            ) {
3126                                         /* Deleted object header with no data chunks.
3127                                          * Can be discarded and the file deleted.
3128                                          */
3129                                         object->hdrChunk = 0;
3130                                         yaffs_FreeTnode(object->myDev,
3131                                                         object->variant.
3132                                                         fileVariant.top);
3133                                         object->variant.fileVariant.top = NULL;
3134                                         yaffs_DoGenericObjectDeletion(object);
3135
3136                                 } else if (object) {
3137                                         /* It's either a data chunk in a live file or
3138                                          * an ObjectHeader, so we're interested in it.
3139                                          * NB Need to keep the ObjectHeaders of deleted files
3140                                          * until the whole file has been deleted off
3141                                          */
3142                                         tags.serialNumber++;
3143
3144                                         dev->nGCCopies++;
3145
3146                                         if (tags.chunkId == 0) {
3147                                                 /* It is an object Id,
3148                                                  * We need to nuke the shrinkheader flags first
3149                                                  * We no longer want the shrinkHeader flag since its work is done
3150                                                  * and if it is left in place it will mess up scanning.
3151                                                  * Also, clear out any shadowing stuff
3152                                                  */
3153
3154                                                 yaffs_ObjectHeader *oh;
3155                                                 oh = (yaffs_ObjectHeader *)buffer;
3156                                                 oh->isShrink = 0;
3157                                                 tags.extraShadows = 0;
3158                                                 tags.extraIsShrinkHeader = 0;
3159                                                 
3160                                                 yaffs_VerifyObjectHeader(object,oh,&tags,1);
3161                                         }
3162
3163                                         newChunk =
3164                                             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3165
3166                                         if (newChunk < 0) {
3167                                                 retVal = YAFFS_FAIL;
3168                                         } else {
3169
3170                                                 /* Ok, now fix up the Tnodes etc. */
3171
3172                                                 if (tags.chunkId == 0) {
3173                                                         /* It's a header */
3174                                                         object->hdrChunk =  newChunk;
3175                                                         object->serial =   tags.serialNumber;
3176                                                 } else {
3177                                                         /* It's a data chunk */
3178                                                         yaffs_PutChunkIntoFile
3179                                                             (object,
3180                                                              tags.chunkId,
3181                                                              newChunk, 0);
3182                                                 }
3183                                         }
3184                                 }
3185
3186                                 if(retVal == YAFFS_OK)
3187                                         yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3188
3189                         }
3190                 }
3191
3192                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3193                 
3194
3195
3196                 /* Do any required cleanups */
3197                 for (i = 0; i < cleanups; i++) {
3198                         /* Time to delete the file too */
3199                         object =
3200                             yaffs_FindObjectByNumber(dev,
3201                                                      dev->gcCleanupList[i]);
3202                         if (object) {
3203                                 yaffs_FreeTnode(dev,
3204                                                 object->variant.fileVariant.
3205                                                 top);
3206                                 object->variant.fileVariant.top = NULL;
3207                                 T(YAFFS_TRACE_GC,
3208                                   (TSTR
3209                                    ("yaffs: About to finally delete object %d"
3210                                     TENDSTR), object->objectId));
3211                                 yaffs_DoGenericObjectDeletion(object);
3212                                 object->myDev->nDeletedFiles--;
3213                         }
3214
3215                 }
3216
3217         }
3218
3219         yaffs_VerifyCollectedBlock(dev,bi,block);
3220           
3221         if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
3222                 T(YAFFS_TRACE_GC,
3223                   (TSTR
3224                    ("gc did not increase free chunks before %d after %d"
3225                     TENDSTR), chunksBefore, chunksAfter));
3226         }
3227
3228         /* If the gc completed then clear the current gcBlock so that we find another. */
3229         if(bi->blockState != YAFFS_BLOCK_STATE_COLLECTING){
3230                 dev->gcBlock = -1;
3231                 dev->gcChunk = 0;
3232         }
3233         
3234         dev->isDoingGC = 0;
3235
3236         return retVal;
3237 }
3238
3239 /* New garbage collector
3240  * If we're very low on erased blocks then we do aggressive garbage collection
3241  * otherwise we do "leasurely" garbage collection.
3242  * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3243  * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3244  *
3245  * The idea is to help clear out space in a more spread-out manner.
3246  * Dunno if it really does anything useful.
3247  */
3248 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
3249 {
3250         int block;
3251         int aggressive;
3252         int gcOk = YAFFS_OK;
3253         int maxTries = 0;
3254         
3255         int checkpointBlockAdjust;
3256
3257         if (dev->isDoingGC) {
3258                 /* Bail out so we don't get recursive gc */
3259                 return YAFFS_OK;
3260         }
3261         
3262         /* This loop should pass the first time.
3263          * We'll only see looping here if the erase of the collected block fails.
3264          */
3265
3266         do {
3267                 maxTries++;
3268                 
3269                 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3270                 if(checkpointBlockAdjust < 0)
3271                         checkpointBlockAdjust = 0;
3272
3273                 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3274                         /* We need a block soon...*/
3275                         aggressive = 1;
3276                 } else {
3277                         /* We're in no hurry */
3278                         aggressive = 0;
3279                 }
3280
3281                 if(dev->gcBlock <= 0){
3282                         dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3283                         dev->gcChunk = 0;
3284                 }
3285                 
3286                 block = dev->gcBlock;
3287
3288                 if (block > 0) {
3289                         dev->garbageCollections++;
3290                         if (!aggressive) {
3291                                 dev->passiveGarbageCollections++;
3292                         }
3293
3294                         T(YAFFS_TRACE_GC,
3295                           (TSTR
3296                            ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3297                            dev->nErasedBlocks, aggressive));
3298
3299                         gcOk = yaffs_GarbageCollectBlock(dev,block,aggressive);
3300                 }
3301
3302                 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3303                         T(YAFFS_TRACE_GC,
3304                           (TSTR
3305                            ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3306                             TENDSTR), dev->nErasedBlocks, maxTries, block));
3307                 }
3308         } while ((dev->nErasedBlocks < dev->nReservedBlocks) && 
3309                  (block > 0) &&
3310                  (maxTries < 2));
3311
3312         return aggressive ? gcOk : YAFFS_OK;
3313 }
3314
3315 /*-------------------------  TAGS --------------------------------*/
3316
3317 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
3318                            int chunkInObject)
3319 {
3320         return (tags->chunkId == chunkInObject &&
3321                 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3322
3323 }
3324
3325
3326 /*-------------------- Data file manipulation -----------------*/
3327
3328 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
3329                                  yaffs_ExtendedTags * tags)
3330 {
3331         /*Get the Tnode, then get the level 0 offset chunk offset */
3332         yaffs_Tnode *tn;
3333         int theChunk = -1;
3334         yaffs_ExtendedTags localTags;
3335         int retVal = -1;
3336
3337         yaffs_Device *dev = in->myDev;
3338
3339         if (!tags) {
3340                 /* Passed a NULL, so use our own tags space */
3341                 tags = &localTags;
3342         }
3343
3344         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3345
3346         if (tn) {
3347                 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3348
3349                 retVal =
3350                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3351                                            chunkInInode);
3352         }
3353         return retVal;
3354 }
3355
3356 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
3357                                           yaffs_ExtendedTags * tags)
3358 {
3359         /* Get the Tnode, then get the level 0 offset chunk offset */
3360         yaffs_Tnode *tn;
3361         int theChunk = -1;
3362         yaffs_ExtendedTags localTags;
3363
3364         yaffs_Device *dev = in->myDev;
3365         int retVal = -1;
3366
3367         if (!tags) {
3368                 /* Passed a NULL, so use our own tags space */
3369                 tags = &localTags;
3370         }
3371
3372         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3373
3374         if (tn) {
3375
3376                 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3377
3378                 retVal =
3379                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3380                                            chunkInInode);
3381
3382                 /* Delete the entry in the filestructure (if found) */
3383                 if (retVal != -1) {
3384                         yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
3385                 }
3386         } else {
3387                 /*T(("No level 0 found for %d\n", chunkInInode)); */
3388         }
3389
3390         if (retVal == -1) {
3391                 /* T(("Could not find %d to delete\n",chunkInInode)); */
3392         }
3393         return retVal;
3394 }
3395
3396 #ifdef YAFFS_PARANOID
3397
3398 static int yaffs_CheckFileSanity(yaffs_Object * in)
3399 {
3400         int chunk;
3401         int nChunks;
3402         int fSize;
3403         int failed = 0;
3404         int objId;
3405         yaffs_Tnode *tn;
3406         yaffs_Tags localTags;
3407         yaffs_Tags *tags = &localTags;
3408         int theChunk;
3409         int chunkDeleted;
3410
3411         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3412                 /* T(("Object not a file\n")); */
3413                 return YAFFS_FAIL;
3414         }
3415
3416         objId = in->objectId;
3417         fSize = in->variant.fileVariant.fileSize;
3418         nChunks =
3419             (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3420
3421         for (chunk = 1; chunk <= nChunks; chunk++) {
3422                 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3423                                            chunk);
3424
3425                 if (tn) {
3426
3427                         theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
3428
3429                         if (yaffs_CheckChunkBits
3430                             (dev, theChunk / dev->nChunksPerBlock,
3431                              theChunk % dev->nChunksPerBlock)) {
3432
3433                                 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3434                                                             tags,
3435                                                             &chunkDeleted);
3436                                 if (yaffs_TagsMatch
3437                                     (tags, in->objectId, chunk, chunkDeleted)) {
3438                                         /* found it; */
3439
3440                                 }
3441                         } else {
3442
3443                                 failed = 1;
3444                         }
3445
3446                 } else {
3447                         /* T(("No level 0 found for %d\n", chunk)); */
3448                 }
3449         }
3450
3451         return failed ? YAFFS_FAIL : YAFFS_OK;
3452 }
3453
3454 #endif
3455
3456 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
3457                                   int chunkInNAND, int inScan)
3458 {
3459         /* NB inScan is zero unless scanning. 
3460          * For forward scanning, inScan is > 0; 
3461          * for backward scanning inScan is < 0
3462          */
3463          
3464         yaffs_Tnode *tn;
3465         yaffs_Device *dev = in->myDev;
3466         int existingChunk;
3467         yaffs_ExtendedTags existingTags;
3468         yaffs_ExtendedTags newTags;
3469         unsigned existingSerial, newSerial;
3470
3471         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3472                 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3473                  * If it is not during Scanning then something went wrong!
3474                  */
3475                 if (!inScan) {
3476                         T(YAFFS_TRACE_ERROR,
3477                           (TSTR
3478                            ("yaffs tragedy:attempt to put data chunk into a non-file"
3479                             TENDSTR)));
3480                         YBUG();
3481                 }
3482
3483                 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3484                 return YAFFS_OK;
3485         }
3486
3487         tn = yaffs_AddOrFindLevel0Tnode(dev, 
3488                                         &in->variant.fileVariant,
3489                                         chunkInInode,
3490                                         NULL);
3491         if (!tn) {
3492                 return YAFFS_FAIL;
3493         }
3494
3495         existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3496
3497         if (inScan != 0) {
3498                 /* If we're scanning then we need to test for duplicates
3499                  * NB This does not need to be efficient since it should only ever 
3500                  * happen when the power fails during a write, then only one
3501                  * chunk should ever be affected.
3502                  *
3503                  * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3504                  * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3505                  */
3506
3507                 if (existingChunk > 0) {
3508                         /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3509                          *    thus we have to do a FindChunkInFile to get the real chunk id.
3510                          *
3511                          * We have a duplicate now we need to decide which one to use:
3512                          *
3513                          * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3514                          * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3515                          * YAFFS1: Get both sets of tags and compare serial numbers.
3516                          */
3517
3518                         if (inScan > 0) {
3519                                 /* Only do this for forward scanning */
3520                                 yaffs_ReadChunkWithTagsFromNAND(dev,
3521                                                                 chunkInNAND,
3522                                                                 NULL, &newTags);
3523
3524                                 /* Do a proper find */
3525                                 existingChunk =
3526                                     yaffs_FindChunkInFile(in, chunkInInode,
3527                                                           &existingTags);
3528                         }
3529
3530                         if (existingChunk <= 0) {
3531                                 /*Hoosterman - how did this happen? */
3532
3533                                 T(YAFFS_TRACE_ERROR,
3534                                   (TSTR
3535                                    ("yaffs tragedy: existing chunk < 0 in scan"
3536                                     TENDSTR)));
3537
3538                         }
3539
3540                         /* NB The deleted flags should be false, otherwise the chunks will 
3541                          * not be loaded during a scan
3542                          */
3543
3544                         if(inScan > 0) {
3545                                 newSerial = newTags.serialNumber;
3546                                 existingSerial = existingTags.serialNumber;
3547                         }
3548
3549                         if ((inScan > 0) &&
3550                             (in->myDev->isYaffs2 ||
3551                              existingChunk <= 0 ||
3552                              ((existingSerial + 1) & 3) == newSerial)) {
3553                                 /* Forward scanning.                            
3554                                  * Use new
3555                                  * Delete the old one and drop through to update the tnode
3556                                  */
3557                                 yaffs_DeleteChunk(dev, existingChunk, 1,
3558                                                   __LINE__);
3559                         } else {
3560                                 /* Backward scanning or we want to use the existing one
3561                                  * Use existing.
3562                                  * Delete the new one and return early so that the tnode isn't changed
3563                                  */
3564                                 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3565                                                   __LINE__);
3566                                 return YAFFS_OK;
3567                         }
3568                 }
3569
3570         }
3571
3572         if (existingChunk == 0) {
3573                 in->nDataChunks++;
3574         }
3575
3576         yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
3577
3578         return YAFFS_OK;
3579 }
3580
3581 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
3582                                          __u8 * buffer)
3583 {
3584         int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3585
3586         if (chunkInNAND >= 0) {
3587                 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3588                                                        buffer,NULL);
3589         } else {
3590                 T(YAFFS_TRACE_NANDACCESS,
3591                   (TSTR("Chunk %d not found zero instead" TENDSTR),
3592                    chunkInNAND));
3593                 /* get sane (zero) data if you read a hole */
3594                 memset(buffer, 0, in->myDev->nDataBytesPerChunk);       
3595                 return 0;
3596         }
3597
3598 }
3599
3600 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
3601 {
3602         int block;
3603         int page;
3604         yaffs_ExtendedTags tags;
3605         yaffs_BlockInfo *bi;
3606
3607         if (chunkId <= 0)
3608                 return;
3609                 
3610
3611         dev->nDeletions++;
3612         block = chunkId / dev->nChunksPerBlock;
3613         page = chunkId % dev->nChunksPerBlock;
3614
3615
3616         if(!yaffs_CheckChunkBit(dev,block,page))
3617                 T(YAFFS_TRACE_VERIFY,
3618                         (TSTR("Deleting invalid chunk %d"TENDSTR),
3619                          chunkId));
3620
3621         bi = yaffs_GetBlockInfo(dev, block);
3622
3623         T(YAFFS_TRACE_DELETION,
3624           (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3625
3626         if (markNAND &&
3627             bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3628
3629                 yaffs_InitialiseTags(&tags);
3630
3631                 tags.chunkDeleted = 1;
3632
3633                 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3634                 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3635         } else {
3636                 dev->nUnmarkedDeletions++;
3637         }
3638
3639         /* Pull out of the management area.
3640          * If the whole block became dirty, this will kick off an erasure.
3641          */
3642         if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3643             bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3644             bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3645             bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3646                 dev->nFreeChunks++;
3647
3648                 yaffs_ClearChunkBit(dev, block, page);
3649
3650                 bi->pagesInUse--;
3651
3652                 if (bi->pagesInUse == 0 &&
3653                     !bi->hasShrinkHeader &&
3654                     bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3655                     bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3656                         yaffs_BlockBecameDirty(dev, block);
3657                 }
3658
3659         } else {
3660                 /* T(("Bad news deleting chunk %d\n",chunkId)); */
3661         }
3662
3663 }
3664
3665 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
3666                                         const __u8 * buffer, int nBytes,
3667                                         int useReserve)
3668 {
3669         /* Find old chunk Need to do this to get serial number
3670          * Write new one and patch into tree.
3671          * Invalidate old tags.
3672          */
3673
3674         int prevChunkId;
3675         yaffs_ExtendedTags prevTags;
3676
3677         int newChunkId;
3678         yaffs_ExtendedTags newTags;
3679
3680         yaffs_Device *dev = in->myDev;
3681
3682         yaffs_CheckGarbageCollection(dev);
3683
3684         /* Get the previous chunk at this location in the file if it exists */
3685         prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3686
3687         /* Set up new tags */
3688         yaffs_InitialiseTags(&newTags);
3689
3690         newTags.chunkId = chunkInInode;
3691         newTags.objectId = in->objectId;
3692         newTags.serialNumber =
3693             (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
3694         newTags.byteCount = nBytes;
3695         
3696         if(nBytes < 1 || nBytes > dev->totalBytesPerChunk){
3697           T(YAFFS_TRACE_ERROR,
3698           (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3699           while(1){}
3700         }
3701         
3702         
3703
3704         newChunkId =
3705             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3706                                               useReserve);
3707
3708         if (newChunkId >= 0) {
3709                 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3710
3711                 if (prevChunkId >= 0) {
3712                         yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3713
3714                 }
3715
3716                 yaffs_CheckFileSanity(in);
3717         }
3718         return newChunkId;
3719
3720 }
3721
3722 /* UpdateObjectHeader updates the header on NAND for an object.
3723  * If name is not NULL, then that new name is used.
3724  */
3725 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
3726                              int isShrink, int shadows)
3727 {
3728
3729         yaffs_BlockInfo *bi;
3730
3731         yaffs_Device *dev = in->myDev;
3732
3733         int prevChunkId;
3734         int retVal = 0;
3735         int result = 0;
3736
3737         int newChunkId;
3738         yaffs_ExtendedTags newTags;
3739         yaffs_ExtendedTags oldTags;
3740
3741         __u8 *buffer = NULL;
3742         YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3743
3744         yaffs_ObjectHeader *oh = NULL;
3745         
3746         yaffs_strcpy(oldName,_Y("silly old name"));
3747
3748
3749         if (!in->fake || 
3750             in == dev->rootDir || /* The rootDir should also be saved */
3751             force) {
3752
3753                 yaffs_CheckGarbageCollection(dev);
3754                 yaffs_CheckObjectDetailsLoaded(in);
3755
3756                 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3757                 oh = (yaffs_ObjectHeader *) buffer;
3758
3759                 prevChunkId = in->hdrChunk;
3760
3761                 if (prevChunkId > 0) {
3762                         result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3763                                                         buffer, &oldTags);
3764                         
3765                         yaffs_VerifyObjectHeader(in,oh,&oldTags,0);
3766                                                                                 
3767                         memcpy(oldName, oh->name, sizeof(oh->name));
3768                 }
3769
3770                 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3771
3772                 oh->type = in->variantType;
3773                 oh->yst_mode = in->yst_mode;
3774                 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3775
3776 #ifdef CONFIG_YAFFS_WINCE
3777                 oh->win_atime[0] = in->win_atime[0];
3778                 oh->win_ctime[0] = in->win_ctime[0];
3779                 oh->win_mtime[0] = in->win_mtime[0];
3780                 oh->win_atime[1] = in->win_atime[1];
3781                 oh->win_ctime[1] = in->win_ctime[1];
3782                 oh->win_mtime[1] = in->win_mtime[1];
3783 #else
3784                 oh->yst_uid = in->yst_uid;
3785                 oh->yst_gid = in->yst_gid;
3786                 oh->yst_atime = in->yst_atime;
3787                 oh->yst_mtime = in->yst_mtime;
3788                 oh->yst_ctime = in->yst_ctime;
3789                 oh->yst_rdev = in->yst_rdev;
3790 #endif
3791                 if (in->parent) {
3792                         oh->parentObjectId = in->parent->objectId;
3793                 } else {
3794                         oh->parentObjectId = 0;
3795                 }
3796
3797                 if (name && *name) {
3798                         memset(oh->name, 0, sizeof(oh->name));
3799                         yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3800                 } else if (prevChunkId>=0) {
3801                         memcpy(oh->name, oldName, sizeof(oh->name));
3802                 } else {
3803                         memset(oh->name, 0, sizeof(oh->name));
3804                 }
3805
3806                 oh->isShrink = isShrink;
3807
3808                 switch (in->variantType) {
3809                 case YAFFS_OBJECT_TYPE_UNKNOWN:
3810                         /* Should not happen */
3811                         break;
3812                 case YAFFS_OBJECT_TYPE_FILE:
3813                         oh->fileSize =
3814                             (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3815                              || oh->parentObjectId ==
3816                              YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3817                             fileVariant.fileSize;
3818                         break;
3819                 case YAFFS_OBJECT_TYPE_HARDLINK:
3820                         oh->equivalentObjectId =
3821                             in->variant.hardLinkVariant.equivalentObjectId;
3822                         break;
3823                 case YAFFS_OBJECT_TYPE_SPECIAL:
3824                         /* Do nothing */
3825                         break;
3826                 case YAFFS_OBJECT_TYPE_DIRECTORY:
3827                         /* Do nothing */
3828                         break;
3829                 case YAFFS_OBJECT_TYPE_SYMLINK:
3830                         yaffs_strncpy(oh->alias,
3831                                       in->variant.symLinkVariant.alias,
3832                                       YAFFS_MAX_ALIAS_LENGTH);
3833                         oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3834                         break;
3835                 }
3836
3837                 /* Tags */
3838                 yaffs_InitialiseTags(&newTags);
3839                 in->serial++;
3840                 newTags.chunkId = 0;
3841                 newTags.objectId = in->objectId;
3842                 newTags.serialNumber = in->serial;
3843
3844                 /* Add extra info for file header */
3845
3846                 newTags.extraHeaderInfoAvailable = 1;
3847                 newTags.extraParentObjectId = oh->parentObjectId;
3848                 newTags.extraFileLength = oh->fileSize;
3849                 newTags.extraIsShrinkHeader = oh->isShrink;
3850                 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3851                 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3852                 newTags.extraObjectType = in->variantType;
3853
3854                 yaffs_VerifyObjectHeader(in,oh,&newTags,1);
3855
3856                 /* Create new chunk in NAND */
3857                 newChunkId =
3858                     yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3859                                                       (prevChunkId >= 0) ? 1 : 0);
3860
3861                 if (newChunkId >= 0) {
3862
3863                         in->hdrChunk = newChunkId;
3864
3865                         if (prevChunkId >= 0) {
3866                                 yaffs_DeleteChunk(dev, prevChunkId, 1,
3867                                                   __LINE__);
3868                         }
3869
3870                         if(!yaffs_ObjectHasCachedWriteData(in))
3871                                 in->dirty = 0;
3872
3873                         /* If this was a shrink, then mark the block that the chunk lives on */
3874                         if (isShrink) {
3875                                 bi = yaffs_GetBlockInfo(in->myDev,
3876                                                         newChunkId /in->myDev-> nChunksPerBlock);
3877                                 bi->hasShrinkHeader = 1;
3878                         }
3879
3880                 }
3881
3882                 retVal = newChunkId;
3883
3884         }
3885
3886         if (buffer)
3887                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3888
3889         return retVal;
3890 }
3891
3892 /*------------------------ Short Operations Cache ----------------------------------------
3893  *   In many situations where there is no high level buffering (eg WinCE) a lot of
3894  *   reads might be short sequential reads, and a lot of writes may be short 
3895  *   sequential writes. eg. scanning/writing a jpeg file.
3896  *   In these cases, a short read/write cache can provide a huge perfomance benefit 
3897  *   with dumb-as-a-rock code.
3898  *   In Linux, the page cache provides read buffering aand the short op cache provides write 
3899  *   buffering.
3900  *
3901  *   There are a limited number (~10) of cache chunks per device so that we don't
3902  *   need a very intelligent search.
3903  */
3904
3905 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3906 {
3907         yaffs_Device *dev = obj->myDev;
3908         int i;
3909         yaffs_ChunkCache *cache;
3910         int nCaches = obj->myDev->nShortOpCaches;
3911         
3912         for(i = 0; i < nCaches; i++){
3913                 cache = &dev->srCache[i];
3914                 if (cache->object == obj &&
3915                     cache->dirty)
3916                         return 1;
3917         }
3918         
3919         return 0;
3920 }
3921
3922
3923 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3924 {
3925         yaffs_Device *dev = obj->myDev;
3926         int lowest = -99;       /* Stop compiler whining. */
3927         int i;
3928         yaffs_ChunkCache *cache;
3929         int chunkWritten = 0;
3930         int nCaches = obj->myDev->nShortOpCaches;
3931
3932         if (nCaches > 0) {
3933                 do {
3934                         cache = NULL;
3935
3936                         /* Find the dirty cache for this object with the lowest chunk id. */
3937                         for (i = 0; i < nCaches; i++) {
3938                                 if (dev->srCache[i].object == obj &&
3939                                     dev->srCache[i].dirty) {
3940                                         if (!cache
3941                                             || dev->srCache[i].chunkId <
3942                                             lowest) {
3943                                                 cache = &dev->srCache[i];
3944                                                 lowest = cache->chunkId;
3945                                         }
3946                                 }
3947                         }
3948
3949                         if (cache && !cache->locked) {
3950                                 /* Write it out and free it up */
3951
3952                                 chunkWritten =
3953                                     yaffs_WriteChunkDataToObject(cache->object,
3954                                                                  cache->chunkId,
3955                                                                  cache->data,
3956                                                                  cache->nBytes,
3957                                                                  1);
3958                                 cache->dirty = 0;
3959                                 cache->object = NULL;
3960                         }
3961
3962                 } while (cache && chunkWritten > 0);
3963
3964                 if (cache) {
3965                         /* Hoosterman, disk full while writing cache out. */
3966                         T(YAFFS_TRACE_ERROR,
3967                           (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3968
3969                 }
3970         }
3971
3972 }
3973
3974 /*yaffs_FlushEntireDeviceCache(dev)
3975  *
3976  *
3977  */
3978
3979 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3980 {
3981         yaffs_Object *obj;
3982         int nCaches = dev->nShortOpCaches;
3983         int i;
3984         
3985         /* Find a dirty object in the cache and flush it...
3986          * until there are no further dirty objects.
3987          */
3988         do {
3989                 obj = NULL;
3990                 for( i = 0; i < nCaches && !obj; i++) {
3991                         if (dev->srCache[i].object &&
3992                             dev->srCache[i].dirty)
3993                                 obj = dev->srCache[i].object;
3994                             
3995                 }
3996                 if(obj)
3997                         yaffs_FlushFilesChunkCache(obj);
3998                         
3999         } while(obj);
4000         
4001 }
4002
4003
4004 /* Grab us a cache chunk for use.
4005  * First look for an empty one. 
4006  * Then look for the least recently used non-dirty one.
4007  * Then look for the least recently used dirty one...., flush and look again.
4008  */
4009 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device * dev)
4010 {
4011         int i;
4012
4013         if (dev->nShortOpCaches > 0) {
4014                 for (i = 0; i < dev->nShortOpCaches; i++) {
4015                         if (!dev->srCache[i].object) 
4016                                 return &dev->srCache[i];
4017                 }
4018         }
4019
4020         return NULL;
4021 }
4022
4023 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device * dev)
4024 {
4025         yaffs_ChunkCache *cache;
4026         yaffs_Object *theObj;
4027         int usage;
4028         int i;
4029         int pushout;
4030
4031         if (dev->nShortOpCaches > 0) {
4032                 /* Try find a non-dirty one... */
4033
4034                 cache = yaffs_GrabChunkCacheWorker(dev);
4035
4036                 if (!cache) {
4037                         /* They were all dirty, find the last recently used object and flush
4038                          * its cache, then  find again.
4039                          * NB what's here is not very accurate, we actually flush the object
4040                          * the last recently used page.
4041                          */
4042
4043                         /* With locking we can't assume we can use entry zero */
4044
4045                         theObj = NULL;
4046                         usage = -1;
4047                         cache = NULL;
4048                         pushout = -1;
4049
4050                         for (i = 0; i < dev->nShortOpCaches; i++) {
4051                                 if (dev->srCache[i].object &&
4052                                     !dev->srCache[i].locked &&
4053                                     (dev->srCache[i].lastUse < usage || !cache))
4054                                 {
4055                                         usage = dev->srCache[i].lastUse;
4056                                         theObj = dev->srCache[i].object;
4057                                         cache = &dev->srCache[i];
4058                                         pushout = i;
4059                                 }
4060                         }
4061
4062                         if (!cache || cache->dirty) {
4063                                 /* Flush and try again */
4064                                 yaffs_FlushFilesChunkCache(theObj);
4065                                 cache = yaffs_GrabChunkCacheWorker(dev);
4066                         }
4067
4068                 }
4069                 return cache;
4070         } else
4071                 return NULL;
4072
4073 }
4074
4075 /* Find a cached chunk */
4076 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object * obj,
4077                                               int chunkId)
4078 {
4079         yaffs_Device *dev = obj->myDev;
4080         int i;
4081         if (dev->nShortOpCaches > 0) {
4082                 for (i = 0; i < dev->nShortOpCaches; i++) {
4083                         if (dev->srCache[i].object == obj &&
4084                             dev->srCache[i].chunkId == chunkId) {
4085                                 dev->cacheHits++;
4086
4087                                 return &dev->srCache[i];
4088                         }
4089                 }
4090         }
4091         return NULL;
4092 }
4093
4094 /* Mark the chunk for the least recently used algorithym */
4095 static void yaffs_UseChunkCache(yaffs_Device * dev, yaffs_ChunkCache * cache,
4096                                 int isAWrite)
4097 {
4098
4099         if (dev->nShortOpCaches > 0) {
4100                 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4101                         /* Reset the cache usages */
4102                         int i;
4103                         for (i = 1; i < dev->nShortOpCaches; i++) {
4104                                 dev->srCache[i].lastUse = 0;
4105                         }
4106                         dev->srLastUse = 0;
4107                 }
4108
4109                 dev->srLastUse++;
4110
4111                 cache->lastUse = dev->srLastUse;
4112
4113                 if (isAWrite) {
4114                         cache->dirty = 1;
4115                 }
4116         }
4117 }
4118
4119 /* Invalidate a single cache page.
4120  * Do this when a whole page gets written,
4121  * ie the short cache for this page is no longer valid.
4122  */
4123 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId)
4124 {
4125         if (object->myDev->nShortOpCaches > 0) {
4126                 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4127
4128                 if (cache) {
4129                         cache->object = NULL;
4130                 }
4131         }
4132 }
4133
4134 /* Invalidate all the cache pages associated with this object
4135  * Do this whenever ther file is deleted or resized.
4136  */
4137 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in)
4138 {
4139         int i;
4140         yaffs_Device *dev = in->myDev;
4141
4142         if (dev->nShortOpCaches > 0) {
4143                 /* Invalidate it. */
4144                 for (i = 0; i < dev->nShortOpCaches; i++) {
4145                         if (dev->srCache[i].object == in) {
4146                                 dev->srCache[i].object = NULL;
4147                         }
4148                 }
4149         }
4150 }
4151
4152 /*--------------------- Checkpointing --------------------*/
4153
4154
4155 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev,int head)
4156 {
4157         yaffs_CheckpointValidity cp;
4158         
4159         memset(&cp,0,sizeof(cp));
4160         
4161         cp.structType = sizeof(cp);
4162         cp.magic = YAFFS_MAGIC;
4163         cp.version = YAFFS_CHECKPOINT_VERSION;
4164         cp.head = (head) ? 1 : 0;
4165         
4166         return (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp))?
4167                 1 : 0;
4168 }
4169
4170 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4171 {
4172         yaffs_CheckpointValidity cp;
4173         int ok;
4174         
4175         ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4176         
4177         if(ok)
4178                 ok = (cp.structType == sizeof(cp)) &&
4179                      (cp.magic == YAFFS_MAGIC) &&
4180                      (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4181                      (cp.head == ((head) ? 1 : 0));
4182         return ok ? 1 : 0;
4183 }
4184
4185 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp, 
4186                                            yaffs_Device *dev)
4187 {
4188         cp->nErasedBlocks = dev->nErasedBlocks;
4189         cp->allocationBlock = dev->allocationBlock;
4190         cp->allocationPage = dev->allocationPage;
4191         cp->nFreeChunks = dev->nFreeChunks;
4192         
4193         cp->nDeletedFiles = dev->nDeletedFiles;
4194         cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4195         cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4196         cp->sequenceNumber = dev->sequenceNumber;
4197         cp->oldestDirtySequence = dev->oldestDirtySequence;
4198         
4199 }
4200
4201 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4202                                            yaffs_CheckpointDevice *cp)
4203 {
4204         dev->nErasedBlocks = cp->nErasedBlocks;
4205         dev->allocationBlock = cp->allocationBlock;
4206         dev->allocationPage = cp->allocationPage;
4207         dev->nFreeChunks = cp->nFreeChunks;
4208         
4209         dev->nDeletedFiles = cp->nDeletedFiles;
4210         dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4211         dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4212         dev->sequenceNumber = cp->sequenceNumber;
4213         dev->oldestDirtySequence = cp->oldestDirtySequence;
4214 }
4215
4216
4217 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4218 {
4219         yaffs_CheckpointDevice cp;
4220         __u32 nBytes;
4221         __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4222
4223         int ok;
4224                 
4225         /* Write device runtime values*/
4226         yaffs_DeviceToCheckpointDevice(&cp,dev);
4227         cp.structType = sizeof(cp);
4228         
4229         ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4230         
4231         /* Write block info */
4232         if(ok) {
4233                 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4234                 ok = (yaffs_CheckpointWrite(dev,dev->blockInfo,nBytes) == nBytes);
4235         }
4236                 
4237         /* Write chunk bits */          
4238         if(ok) {
4239                 nBytes = nBlocks * dev->chunkBitmapStride;
4240                 ok = (yaffs_CheckpointWrite(dev,dev->chunkBits,nBytes) == nBytes);
4241         }
4242         return   ok ? 1 : 0;
4243
4244 }
4245
4246 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4247 {
4248         yaffs_CheckpointDevice cp;
4249         __u32 nBytes;
4250         __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4251
4252         int ok; 
4253         
4254         ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4255         if(!ok)
4256                 return 0;
4257                 
4258         if(cp.structType != sizeof(cp))
4259                 return 0;
4260                 
4261         
4262         yaffs_CheckpointDeviceToDevice(dev,&cp);
4263         
4264         nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4265         
4266         ok = (yaffs_CheckpointRead(dev,dev->blockInfo,nBytes) == nBytes);
4267         
4268         if(!ok)
4269                 return 0;
4270         nBytes = nBlocks * dev->chunkBitmapStride;
4271         
4272         ok = (yaffs_CheckpointRead(dev,dev->chunkBits,nBytes) == nBytes);
4273         
4274         return ok ? 1 : 0;
4275 }
4276
4277 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4278                                            yaffs_Object *obj)
4279 {
4280
4281         cp->objectId = obj->objectId;
4282         cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4283         cp->hdrChunk = obj->hdrChunk;
4284         cp->variantType = obj->variantType;
4285         cp->deleted = obj->deleted;
4286         cp->softDeleted = obj->softDeleted;
4287         cp->unlinked = obj->unlinked;
4288         cp->fake = obj->fake;
4289         cp->renameAllowed = obj->renameAllowed;
4290         cp->unlinkAllowed = obj->unlinkAllowed;
4291         cp->serial = obj->serial;
4292         cp->nDataChunks = obj->nDataChunks;
4293         
4294         if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4295                 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4296         else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4297                 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4298 }
4299
4300 static void yaffs_CheckpointObjectToObject( yaffs_Object *obj,yaffs_CheckpointObject *cp)
4301 {
4302
4303         yaffs_Object *parent;
4304         
4305         obj->objectId = cp->objectId;
4306         
4307         if(cp->parentId)
4308                 parent = yaffs_FindOrCreateObjectByNumber(
4309                                         obj->myDev,
4310                                         cp->parentId,
4311                                         YAFFS_OBJECT_TYPE_DIRECTORY);
4312         else
4313                 parent = NULL;
4314                 
4315         if(parent)
4316                 yaffs_AddObjectToDirectory(parent, obj);
4317
4318         obj->hdrChunk = cp->hdrChunk;
4319         obj->variantType = cp->variantType;
4320         obj->deleted = cp->deleted;
4321         obj->softDeleted = cp->softDeleted;
4322         obj->unlinked = cp->unlinked;
4323         obj->fake = cp->fake;
4324         obj->renameAllowed = cp->renameAllowed;
4325         obj->unlinkAllowed = cp->unlinkAllowed;
4326         obj->serial = cp->serial;
4327         obj->nDataChunks = cp->nDataChunks;
4328         
4329         if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4330                 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4331         else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4332                 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4333
4334         if(obj->hdrChunk > 0)
4335                 obj->lazyLoaded = 1;
4336 }
4337
4338
4339
4340 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
4341                                         __u32 level, int chunkOffset)
4342 {
4343         int i;
4344         yaffs_Device *dev = in->myDev;
4345         int ok = 1;
4346         int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4347
4348         if(tnodeSize < sizeof(yaffs_Tnode))
4349                 tnodeSize = sizeof(yaffs_Tnode);
4350         
4351
4352         if (tn) {
4353                 if (level > 0) {
4354
4355                         for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
4356                                 if (tn->internal[i]) {
4357                                         ok = yaffs_CheckpointTnodeWorker(in,
4358                                                         tn->internal[i],
4359                                                         level - 1,
4360                                                         (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4361                                 }
4362                         }
4363                 } else if (level == 0) {
4364                         __u32 baseOffset = chunkOffset <<  YAFFS_TNODES_LEVEL0_BITS;
4365                         /* printf("write tnode at %d\n",baseOffset); */
4366                         ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
4367                         if(ok)
4368                                 ok = (yaffs_CheckpointWrite(dev,tn,tnodeSize) == tnodeSize);
4369                 }
4370         }
4371
4372         return ok;
4373
4374 }
4375
4376 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4377 {
4378         __u32 endMarker = ~0;
4379         int ok = 1;
4380         
4381         if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4382                 ok = yaffs_CheckpointTnodeWorker(obj,
4383                                             obj->variant.fileVariant.top,
4384                                             obj->variant.fileVariant.topLevel,
4385                                             0);
4386                 if(ok)
4387                         ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) == 
4388                                 sizeof(endMarker));
4389         }
4390         
4391         return ok ? 1 : 0;
4392 }
4393
4394 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4395 {
4396         __u32 baseChunk;
4397         int ok = 1;
4398         yaffs_Device *dev = obj->myDev;
4399         yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4400         yaffs_Tnode *tn;
4401         int nread = 0;
4402         int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4403
4404         if(tnodeSize < sizeof(yaffs_Tnode))
4405                 tnodeSize = sizeof(yaffs_Tnode);
4406
4407         ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4408         
4409         while(ok && (~baseChunk)){
4410                 nread++;
4411                 /* Read level 0 tnode */
4412                 
4413                 
4414                 /* printf("read  tnode at %d\n",baseChunk); */
4415                 tn = yaffs_GetTnodeRaw(dev);
4416                 if(tn)
4417                         ok = (yaffs_CheckpointRead(dev,tn,tnodeSize) == tnodeSize);
4418                 else
4419                         ok = 0;
4420                         
4421                 if(tn && ok){
4422                         ok = yaffs_AddOrFindLevel0Tnode(dev,
4423                                                         fileStructPtr,
4424                                                         baseChunk,
4425                                                         tn) ? 1 : 0;
4426                                                         
4427                 }
4428                         
4429                 if(ok)
4430                         ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4431                 
4432         }
4433
4434         T(YAFFS_TRACE_CHECKPOINT,(
4435                 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4436                 nread,baseChunk,ok));
4437
4438         return ok ? 1 : 0;      
4439 }
4440  
4441
4442 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4443 {
4444         yaffs_Object *obj;
4445         yaffs_CheckpointObject cp;
4446         int i;
4447         int ok = 1;
4448         struct ylist_head *lh;
4449
4450         
4451         /* Iterate through the objects in each hash entry,
4452          * dumping them to the checkpointing stream.
4453          */
4454          
4455          for(i = 0; ok &&  i <  YAFFS_NOBJECT_BUCKETS; i++){
4456                 ylist_for_each(lh, &dev->objectBucket[i].list) {
4457                         if (lh) {
4458                                 obj = ylist_entry(lh, yaffs_Object, hashLink);
4459                                 if (!obj->deferedFree) {
4460                                         yaffs_ObjectToCheckpointObject(&cp,obj);
4461                                         cp.structType = sizeof(cp);
4462
4463                                         T(YAFFS_TRACE_CHECKPOINT,(
4464                                                 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
4465                                                 cp.objectId,cp.parentId,cp.variantType,cp.hdrChunk,(unsigned) obj));
4466
4467                                         ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4468                                         
4469                                         if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4470                                                 ok = yaffs_WriteCheckpointTnodes(obj);
4471                                         }
4472                                 }
4473                         }
4474                 }
4475          }
4476          
4477          /* Dump end of list */
4478         memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
4479         cp.structType = sizeof(cp);
4480         
4481         if(ok)
4482                 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4483                 
4484         return ok ? 1 : 0;
4485 }
4486
4487 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4488 {
4489         yaffs_Object *obj;
4490         yaffs_CheckpointObject cp;
4491         int ok = 1;
4492         int done = 0;
4493         yaffs_Object *hardList = NULL;
4494         
4495         while(ok && !done) {
4496                 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4497                 if(cp.structType != sizeof(cp)) {
4498                         T(YAFFS_TRACE_CHECKPOINT,(TSTR("struct size %d instead of %d ok %d"TENDSTR),
4499                                 cp.structType,sizeof(cp),ok));
4500                         ok = 0;
4501                 }
4502                         
4503                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4504                         cp.objectId,cp.parentId,cp.variantType,cp.hdrChunk));
4505
4506                 if(ok && cp.objectId == ~0)
4507                         done = 1;
4508                 else if(ok){
4509                         obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
4510                         if(obj) {
4511                                 yaffs_CheckpointObjectToObject(obj,&cp);
4512                                 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4513                                         ok = yaffs_ReadCheckpointTnodes(obj);
4514                                 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4515                                         obj->hardLinks.next =
4516                                                     (struct ylist_head *)
4517                                                     hardList;
4518                                         hardList = obj;
4519                                 }
4520                            
4521                         }
4522                 }
4523         }
4524         
4525         if(ok)
4526                 yaffs_HardlinkFixup(dev,hardList);
4527         
4528         return ok ? 1 : 0;
4529 }
4530
4531 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4532 {
4533         __u32 checkpointSum;
4534         int ok;
4535         
4536         yaffs_GetCheckpointSum(dev,&checkpointSum);
4537         
4538         ok = (yaffs_CheckpointWrite(dev,&checkpointSum,sizeof(checkpointSum)) == sizeof(checkpointSum));
4539         
4540         if(!ok)
4541                 return 0;
4542         
4543         return 1;
4544 }
4545
4546 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4547 {
4548         __u32 checkpointSum0;
4549         __u32 checkpointSum1;
4550         int ok;
4551         
4552         yaffs_GetCheckpointSum(dev,&checkpointSum0);
4553         
4554         ok = (yaffs_CheckpointRead(dev,&checkpointSum1,sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4555         
4556         if(!ok)
4557                 return 0;
4558                 
4559         if(checkpointSum0 != checkpointSum1)
4560                 return 0;
4561         
4562         return 1;
4563 }
4564
4565
4566 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4567 {
4568
4569         int ok = 1;
4570         
4571         if(dev->skipCheckpointWrite || !dev->isYaffs2){
4572                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint write" TENDSTR)));
4573                 ok = 0;
4574         }
4575                 
4576         if(ok)
4577                 ok = yaffs_CheckpointOpen(dev,1);
4578         
4579         if(ok){
4580                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4581                 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
4582         }
4583         if(ok){
4584                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint device" TENDSTR)));
4585                 ok = yaffs_WriteCheckpointDevice(dev);
4586         }
4587         if(ok){
4588                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint objects" TENDSTR)));
4589                 ok = yaffs_WriteCheckpointObjects(dev);
4590         }
4591         if(ok){
4592                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4593                 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
4594         }
4595         
4596         if(ok){
4597                 ok = yaffs_WriteCheckpointSum(dev);
4598         }
4599         
4600         
4601         if(!yaffs_CheckpointClose(dev))
4602                  ok = 0;
4603                  
4604         if(ok)
4605                 dev->isCheckpointed = 1;
4606          else 
4607                 dev->isCheckpointed = 0;
4608
4609         return dev->isCheckpointed;
4610 }
4611
4612 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4613 {
4614         int ok = 1;
4615         
4616         if(dev->skipCheckpointRead || !dev->isYaffs2){
4617                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint read" TENDSTR)));
4618                 ok = 0;
4619         }
4620         
4621         if(ok)
4622                 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
4623         
4624         if(ok){
4625                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));   
4626                 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
4627         }
4628         if(ok){
4629                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint device" TENDSTR)));
4630                 ok = yaffs_ReadCheckpointDevice(dev);
4631         }
4632         if(ok){
4633                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint objects" TENDSTR)));    
4634                 ok = yaffs_ReadCheckpointObjects(dev);
4635         }
4636         if(ok){
4637                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4638                 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
4639         }
4640         
4641         if(ok){
4642                 ok = yaffs_ReadCheckpointSum(dev);
4643                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint checksum %d" TENDSTR),ok));
4644         }
4645
4646         if(!yaffs_CheckpointClose(dev))
4647                 ok = 0;
4648
4649         if(ok)
4650                 dev->isCheckpointed = 1;
4651          else 
4652                 dev->isCheckpointed = 0;
4653
4654         return ok ? 1 : 0;
4655
4656 }
4657
4658 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4659 {
4660         if(dev->isCheckpointed || 
4661            dev->blocksInCheckpoint > 0){
4662                 dev->isCheckpointed = 0;
4663                 yaffs_CheckpointInvalidateStream(dev);
4664                 if(dev->superBlock && dev->markSuperBlockDirty)
4665                         dev->markSuperBlockDirty(dev->superBlock);
4666         }
4667 }
4668
4669
4670 int yaffs_CheckpointSave(yaffs_Device *dev)
4671 {
4672
4673         T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4674
4675         yaffs_VerifyObjects(dev);
4676         yaffs_VerifyBlocks(dev);
4677         yaffs_VerifyFreeChunks(dev);
4678
4679         if(!dev->isCheckpointed) {
4680                 yaffs_InvalidateCheckpoint(dev);
4681                 yaffs_WriteCheckpointData(dev);
4682         }
4683         
4684         T(YAFFS_TRACE_ALWAYS,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4685
4686         return dev->isCheckpointed;
4687 }
4688
4689 int yaffs_CheckpointRestore(yaffs_Device *dev)
4690 {
4691         int retval;
4692         T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4693                 
4694         retval = yaffs_ReadCheckpointData(dev);
4695
4696         if(dev->isCheckpointed){
4697                 yaffs_VerifyObjects(dev);
4698                 yaffs_VerifyBlocks(dev);
4699                 yaffs_VerifyFreeChunks(dev);
4700         }
4701
4702         T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4703         
4704         return retval;
4705 }
4706
4707 /*--------------------- File read/write ------------------------
4708  * Read and write have very similar structures.
4709  * In general the read/write has three parts to it
4710  * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4711  * Some complete chunks
4712  * An incomplete chunk to end off with
4713  *
4714  * Curve-balls: the first chunk might also be the last chunk.
4715  */
4716
4717 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, loff_t offset,
4718                            int nBytes)
4719 {
4720
4721         int chunk;
4722         __u32 start;
4723         int nToCopy;
4724         int n = nBytes;
4725         int nDone = 0;
4726         yaffs_ChunkCache *cache;
4727
4728         yaffs_Device *dev;
4729
4730         dev = in->myDev;
4731
4732         while (n > 0) {
4733                 //chunk = offset / dev->nDataBytesPerChunk + 1;
4734                 //start = offset % dev->nDataBytesPerChunk;
4735                 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4736                 chunk++;
4737
4738                 /* OK now check for the curveball where the start and end are in
4739                  * the same chunk.      
4740                  */
4741                 if ((start + n) < dev->nDataBytesPerChunk) {
4742                         nToCopy = n;
4743                 } else {
4744                         nToCopy = dev->nDataBytesPerChunk - start;
4745                 }
4746
4747                 cache = yaffs_FindChunkCache(in, chunk);
4748
4749                 /* If the chunk is already in the cache or it is less than a whole chunk
4750                  * or we're using inband tags then use the cache (if there is caching)
4751                  * else bypass the cache.
4752                  */
4753                 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4754                         if (dev->nShortOpCaches > 0) {
4755
4756                                 /* If we can't find the data in the cache, then load it up. */
4757
4758                                 if (!cache) {
4759                                         cache = yaffs_GrabChunkCache(in->myDev);
4760                                         cache->object = in;
4761                                         cache->chunkId = chunk;
4762                                         cache->dirty = 0;
4763                                         cache->locked = 0;
4764                                         yaffs_ReadChunkDataFromObject(in, chunk,
4765                                                                       cache->
4766                                                                       data);
4767                                         cache->nBytes = 0;
4768                                 }
4769
4770                                 yaffs_UseChunkCache(dev, cache, 0);
4771
4772                                 cache->locked = 1;
4773
4774 #ifdef CONFIG_YAFFS_WINCE
4775                                 yfsd_UnlockYAFFS(TRUE);
4776 #endif
4777                                 memcpy(buffer, &cache->data[start], nToCopy);
4778
4779 #ifdef CONFIG_YAFFS_WINCE
4780                                 yfsd_LockYAFFS(TRUE);
4781 #endif
4782                                 cache->locked = 0;
4783                         } else {
4784                                 /* Read into the local buffer then copy..*/
4785
4786                                 __u8 *localBuffer =
4787                                     yaffs_GetTempBuffer(dev, __LINE__);
4788                                 yaffs_ReadChunkDataFromObject(in, chunk,
4789                                                               localBuffer);
4790 #ifdef CONFIG_YAFFS_WINCE
4791                                 yfsd_UnlockYAFFS(TRUE);
4792 #endif
4793                                 memcpy(buffer, &localBuffer[start], nToCopy);
4794
4795 #ifdef CONFIG_YAFFS_WINCE
4796                                 yfsd_LockYAFFS(TRUE);
4797 #endif
4798                                 yaffs_ReleaseTempBuffer(dev, localBuffer,
4799                                                         __LINE__);
4800                         }
4801
4802                 } else {
4803 #ifdef CONFIG_YAFFS_WINCE
4804                         __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4805
4806                         /* Under WinCE can't do direct transfer. Need to use a local buffer.
4807                          * This is because we otherwise screw up WinCE's memory mapper
4808                          */
4809                         yaffs_ReadChunkDataFromObject(in, chunk, localBuffer);
4810
4811 #ifdef CONFIG_YAFFS_WINCE
4812                         yfsd_UnlockYAFFS(TRUE);
4813 #endif
4814                         memcpy(buffer, localBuffer, dev->nDataBytesPerChunk);
4815
4816 #ifdef CONFIG_YAFFS_WINCE
4817                         yfsd_LockYAFFS(TRUE);
4818                         yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
4819 #endif
4820
4821 #else
4822                         /* A full chunk. Read directly into the supplied buffer. */
4823                         yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4824 #endif
4825                 }
4826
4827                 n -= nToCopy;
4828                 offset += nToCopy;
4829                 buffer += nToCopy;
4830                 nDone += nToCopy;
4831
4832         }
4833
4834         return nDone;
4835 }
4836
4837 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, loff_t offset,
4838                           int nBytes, int writeThrough)
4839 {
4840
4841         int chunk;
4842         __u32 start;
4843         int nToCopy;
4844         int n = nBytes;
4845         int nDone = 0;
4846         int nToWriteBack;
4847         int startOfWrite = offset;
4848         int chunkWritten = 0;
4849         int nBytesRead;
4850
4851         yaffs_Device *dev;
4852
4853         dev = in->myDev;
4854
4855         while (n > 0 && chunkWritten >= 0) {
4856                 //chunk = offset / dev->nDataBytesPerChunk + 1;
4857                 //start = offset % dev->nDataBytesPerChunk;
4858                 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4859                 
4860                 if(chunk * dev->nDataBytesPerChunk + start != offset ||
4861                    start >= dev->nDataBytesPerChunk){
4862                    T(YAFFS_TRACE_ERROR,(TSTR("AddrToChunk of offset %d gives chunk %d start %d"TENDSTR),
4863                                         (int)offset, chunk,start));
4864                 }
4865                 chunk++;
4866
4867                 /* OK now check for the curveball where the start and end are in
4868                  * the same chunk.
4869                  */
4870
4871                 if ((start + n) < dev->nDataBytesPerChunk) {
4872                         nToCopy = n;
4873
4874                         /* Now folks, to calculate how many bytes to write back....
4875                          * If we're overwriting and not writing to then end of file then
4876                          * we need to write back as much as was there before.
4877                          */
4878
4879                         nBytesRead =
4880                             in->variant.fileVariant.fileSize -
4881                             ((chunk - 1) * dev->nDataBytesPerChunk);
4882
4883                         if (nBytesRead > dev->nDataBytesPerChunk) {
4884                                 nBytesRead = dev->nDataBytesPerChunk;
4885                         }
4886
4887                         nToWriteBack =
4888                             (nBytesRead >
4889                              ((int)start + n)) ? nBytesRead : (start + n);
4890
4891                 } else {
4892                         nToCopy = dev->nDataBytesPerChunk - start;
4893                         nToWriteBack = dev->nDataBytesPerChunk;
4894                 }
4895
4896                 if (nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4897                         /* An incomplete start or end chunk (or maybe both start and end chunk), 
4898                          * or we're using inband tags, so we want to use the cache buffers.
4899                          */
4900                         if (dev->nShortOpCaches > 0) {
4901                                 yaffs_ChunkCache *cache;
4902                                 /* If we can't find the data in the cache, then load the cache */
4903                                 cache = yaffs_FindChunkCache(in, chunk);
4904                                 
4905                                 if (!cache
4906                                     && yaffs_CheckSpaceForAllocation(in->
4907                                                                      myDev)) {
4908                                         cache = yaffs_GrabChunkCache(in->myDev);
4909                                         cache->object = in;
4910                                         cache->chunkId = chunk;
4911                                         cache->dirty = 0;
4912                                         cache->locked = 0;
4913                                         yaffs_ReadChunkDataFromObject(in, chunk,
4914                                                                       cache->
4915                                                                       data);
4916                                 }
4917                                 else if(cache && 
4918                                         !cache->dirty &&
4919                                         !yaffs_CheckSpaceForAllocation(in->myDev)){
4920                                         /* Drop the cache if it was a read cache item and
4921                                          * no space check has been made for it.
4922                                          */ 
4923                                          cache = NULL;
4924                                 }
4925
4926                                 if (cache) {
4927                                         yaffs_UseChunkCache(dev, cache, 1);
4928                                         cache->locked = 1;
4929 #ifdef CONFIG_YAFFS_WINCE
4930                                         yfsd_UnlockYAFFS(TRUE);
4931 #endif
4932
4933                                         memcpy(&cache->data[start], buffer,
4934                                                nToCopy);
4935
4936 #ifdef CONFIG_YAFFS_WINCE
4937                                         yfsd_LockYAFFS(TRUE);
4938 #endif
4939                                         cache->locked = 0;
4940                                         cache->nBytes = nToWriteBack;
4941
4942                                         if (writeThrough) {
4943                                                 chunkWritten =
4944                                                     yaffs_WriteChunkDataToObject
4945                                                     (cache->object,
4946                                                      cache->chunkId,
4947                                                      cache->data, cache->nBytes,
4948                                                      1);
4949                                                 cache->dirty = 0;
4950                                         }
4951
4952                                 } else {
4953                                         chunkWritten = -1;      /* fail the write */
4954                                 }
4955                         } else {
4956                                 /* An incomplete start or end chunk (or maybe both start and end chunk)
4957                                  * Read into the local buffer then copy, then copy over and write back.
4958                                  */
4959
4960                                 __u8 *localBuffer =
4961                                     yaffs_GetTempBuffer(dev, __LINE__);
4962
4963                                 yaffs_ReadChunkDataFromObject(in, chunk,
4964                                                               localBuffer);
4965
4966 #ifdef CONFIG_YAFFS_WINCE
4967                                 yfsd_UnlockYAFFS(TRUE);
4968 #endif
4969
4970                                 memcpy(&localBuffer[start], buffer, nToCopy);
4971
4972 #ifdef CONFIG_YAFFS_WINCE
4973                                 yfsd_LockYAFFS(TRUE);
4974 #endif
4975                                 chunkWritten =
4976                                     yaffs_WriteChunkDataToObject(in, chunk,
4977                                                                  localBuffer,
4978                                                                  nToWriteBack,
4979                                                                  0);
4980
4981                                 yaffs_ReleaseTempBuffer(dev, localBuffer,
4982                                                         __LINE__);
4983
4984                         }
4985
4986                 } else {
4987                         /* A full chunk. Write directly from the supplied buffer. */
4988                         
4989 #ifdef CONFIG_YAFFS_WINCE
4990                         /* Under WinCE can't do direct transfer. Need to use a local buffer.
4991                          * This is because we otherwise screw up WinCE's memory mapper
4992                          */
4993                         __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
4994 #ifdef CONFIG_YAFFS_WINCE
4995                         yfsd_UnlockYAFFS(TRUE);
4996 #endif
4997                         memcpy(localBuffer, buffer, dev->nDataBytesPerChunk);
4998 #ifdef CONFIG_YAFFS_WINCE
4999                         yfsd_LockYAFFS(TRUE);
5000 #endif
5001                         chunkWritten =
5002                             yaffs_WriteChunkDataToObject(in, chunk, localBuffer,
5003                                                          dev->nDataBytesPerChunk,
5004                                                          0);
5005                         yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5006 #else
5007
5008                         chunkWritten =
5009                             yaffs_WriteChunkDataToObject(in, chunk, buffer,
5010                                                          dev->nDataBytesPerChunk,
5011                                                          0);
5012 #endif
5013                         /* Since we've overwritten the cached data, we better invalidate it. */
5014                         yaffs_InvalidateChunkCache(in, chunk);
5015                 }
5016
5017                 if (chunkWritten >= 0) {
5018                         n -= nToCopy;
5019                         offset += nToCopy;
5020                         buffer += nToCopy;
5021                         nDone += nToCopy;
5022                 }
5023
5024         }
5025
5026         /* Update file object */
5027
5028         if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
5029                 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
5030         }
5031
5032         in->dirty = 1;
5033
5034         return nDone;
5035 }
5036
5037
5038 /* ---------------------- File resizing stuff ------------------ */
5039
5040 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
5041 {
5042
5043         yaffs_Device *dev = in->myDev;
5044         int oldFileSize = in->variant.fileVariant.fileSize;
5045
5046         int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
5047
5048         int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
5049             dev->nDataBytesPerChunk;
5050         int i;
5051         int chunkId;
5052
5053         /* Delete backwards so that we don't end up with holes if
5054          * power is lost part-way through the operation.
5055          */
5056         for (i = lastDel; i >= startDel; i--) {
5057                 /* NB this could be optimised somewhat,
5058                  * eg. could retrieve the tags and write them without
5059                  * using yaffs_DeleteChunk
5060                  */
5061
5062                 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5063                 if (chunkId > 0) {
5064                         if (chunkId <
5065                             (dev->internalStartBlock * dev->nChunksPerBlock)
5066                             || chunkId >=
5067                             ((dev->internalEndBlock +
5068                               1) * dev->nChunksPerBlock)) {
5069                                 T(YAFFS_TRACE_ALWAYS,
5070                                   (TSTR("Found daft chunkId %d for %d" TENDSTR),
5071                                    chunkId, i));
5072                         } else {
5073                                 in->nDataChunks--;
5074                                 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5075                         }
5076                 }
5077         }
5078
5079 }
5080
5081 int yaffs_ResizeFile(yaffs_Object * in, loff_t newSize)
5082 {
5083
5084         int oldFileSize = in->variant.fileVariant.fileSize;
5085         __u32 newSizeOfPartialChunk;
5086         int newFullChunks;
5087         
5088         yaffs_Device *dev = in->myDev;
5089
5090         yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5091
5092         yaffs_FlushFilesChunkCache(in);
5093         yaffs_InvalidateWholeChunkCache(in);
5094
5095         yaffs_CheckGarbageCollection(dev);
5096
5097         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
5098                 return YAFFS_FAIL;
5099         }
5100
5101         if (newSize == oldFileSize) {
5102                 return YAFFS_OK;
5103         }
5104
5105         if (newSize < oldFileSize) {
5106
5107                 yaffs_PruneResizedChunks(in, newSize);
5108
5109                 if (newSizeOfPartialChunk != 0) {
5110                         int lastChunk = 1 + newFullChunks;
5111                         
5112                         __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5113
5114                         /* Got to read and rewrite the last chunk with its new size and zero pad */
5115                         yaffs_ReadChunkDataFromObject(in, lastChunk,
5116                                                       localBuffer);
5117
5118                         memset(localBuffer + newSizeOfPartialChunk, 0,
5119                                dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5120
5121                         yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5122                                                      newSizeOfPartialChunk, 1);
5123
5124                         yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5125                 }
5126
5127                 in->variant.fileVariant.fileSize = newSize;
5128
5129                 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5130         } else {
5131                 /* newsSize > oldFileSize */
5132                 in->variant.fileVariant.fileSize = newSize;
5133         }
5134
5135                 
5136         
5137         /* Write a new object header.
5138          * show we've shrunk the file, if need be
5139          * Do this only if the file is not in the deleted directories.
5140          */
5141         if (in->parent &&
5142             in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5143             in->parent->objectId != YAFFS_OBJECTID_DELETED) {
5144                 yaffs_UpdateObjectHeader(in, NULL, 0,
5145                                          (newSize < oldFileSize) ? 1 : 0, 0);
5146         }
5147
5148         return YAFFS_OK;
5149 }
5150
5151 loff_t yaffs_GetFileSize(yaffs_Object * obj)
5152 {
5153         obj = yaffs_GetEquivalentObject(obj);
5154
5155         switch (obj->variantType) {
5156         case YAFFS_OBJECT_TYPE_FILE:
5157                 return obj->variant.fileVariant.fileSize;
5158         case YAFFS_OBJECT_TYPE_SYMLINK:
5159                 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5160         default:
5161                 return 0;
5162         }
5163 }
5164
5165
5166
5167 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
5168 {
5169         int retVal;
5170         if (in->dirty) {
5171                 yaffs_FlushFilesChunkCache(in);
5172                 if (updateTime) {
5173 #ifdef CONFIG_YAFFS_WINCE
5174                         yfsd_WinFileTimeNow(in->win_mtime);
5175 #else
5176
5177                         in->yst_mtime = Y_CURRENT_TIME;
5178
5179 #endif
5180                 }
5181
5182                 retVal =
5183                     (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5184                      0) ? YAFFS_OK : YAFFS_FAIL;
5185         } else {
5186                 retVal = YAFFS_OK;
5187         }
5188
5189         return retVal;
5190
5191 }
5192
5193 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
5194 {
5195
5196         /* First off, invalidate the file's data in the cache, without flushing. */
5197         yaffs_InvalidateWholeChunkCache(in);
5198
5199         if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5200                 /* Move to the unlinked directory so we have a record that it was deleted. */
5201                 yaffs_ChangeObjectName(in, in->myDev->deletedDir,_Y("deleted"), 0, 0);
5202
5203         }
5204
5205         yaffs_RemoveObjectFromDirectory(in);
5206         yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5207         in->hdrChunk = 0;
5208
5209         yaffs_FreeObject(in);
5210         return YAFFS_OK;
5211
5212 }
5213
5214 /* yaffs_DeleteFile deletes the whole file data
5215  * and the inode associated with the file.
5216  * It does not delete the links associated with the file.
5217  */
5218  
5219 static int yaffs_UnlinkFile(yaffs_Object * in)
5220 {
5221
5222         int retVal;
5223         int immediateDeletion = 0;
5224
5225 #ifdef __KERNEL__
5226         if (!in->myInode) {
5227                 immediateDeletion = 1;
5228         }
5229 #else
5230         if (in->inUse <= 0) {
5231                 immediateDeletion = 1;
5232         }
5233 #endif
5234
5235         if (immediateDeletion) {
5236                 retVal =
5237                     yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5238                                            _Y("deleted"), 0, 0);
5239                 T(YAFFS_TRACE_TRACING,
5240                   (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5241                    in->objectId));
5242                 in->deleted = 1;
5243                 in->myDev->nDeletedFiles++;
5244                 if (1 || in->myDev->isYaffs2) {
5245                         yaffs_ResizeFile(in, 0);
5246                 }
5247                 yaffs_SoftDeleteFile(in);
5248         } else {
5249                 retVal =
5250                     yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5251                                            _Y("unlinked"), 0, 0);
5252         }
5253
5254
5255         return retVal;
5256 }
5257
5258 int yaffs_DeleteFile(yaffs_Object * in)
5259 {
5260         int retVal = YAFFS_OK;
5261         int deleted = in->deleted;
5262         
5263         yaffs_ResizeFile(in,0);
5264
5265         if (in->nDataChunks > 0) {
5266                 /* Use soft deletion if there is data in the file.
5267                  * That won't be the case if it has been resized to zero.
5268                  */
5269                 if (!in->unlinked) {
5270                         retVal = yaffs_UnlinkFile(in);
5271                 }
5272                 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5273                         in->deleted = deleted = 1;
5274                         in->myDev->nDeletedFiles++;
5275                         yaffs_SoftDeleteFile(in);
5276                 }
5277                 return deleted ? YAFFS_OK : YAFFS_FAIL;
5278         } else {
5279                 /* The file has no data chunks so we toss it immediately */
5280                 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5281                 in->variant.fileVariant.top = NULL;
5282                 yaffs_DoGenericObjectDeletion(in);
5283
5284                 return YAFFS_OK;
5285         }
5286 }
5287
5288 static int yaffs_DeleteDirectory(yaffs_Object * in)
5289 {
5290         /* First check that the directory is empty. */
5291         if (ylist_empty(&in->variant.directoryVariant.children)) {
5292                 return yaffs_DoGenericObjectDeletion(in);
5293         }
5294
5295         return YAFFS_FAIL;
5296
5297 }
5298
5299 static int yaffs_DeleteSymLink(yaffs_Object * in)
5300 {
5301         YFREE(in->variant.symLinkVariant.alias);
5302
5303         return yaffs_DoGenericObjectDeletion(in);
5304 }
5305
5306 static int yaffs_DeleteHardLink(yaffs_Object * in)
5307 {
5308         /* remove this hardlink from the list assocaited with the equivalent
5309          * object
5310          */
5311         ylist_del_init(&in->hardLinks);
5312         return yaffs_DoGenericObjectDeletion(in);
5313 }
5314
5315 static void yaffs_DestroyObject(yaffs_Object * obj)
5316 {
5317         switch (obj->variantType) {
5318         case YAFFS_OBJECT_TYPE_FILE:
5319                 yaffs_DeleteFile(obj);
5320                 break;
5321         case YAFFS_OBJECT_TYPE_DIRECTORY:
5322                 yaffs_DeleteDirectory(obj);
5323                 break;
5324         case YAFFS_OBJECT_TYPE_SYMLINK:
5325                 yaffs_DeleteSymLink(obj);
5326                 break;
5327         case YAFFS_OBJECT_TYPE_HARDLINK:
5328                 yaffs_DeleteHardLink(obj);
5329                 break;
5330         case YAFFS_OBJECT_TYPE_SPECIAL:
5331                 yaffs_DoGenericObjectDeletion(obj);
5332                 break;
5333         case YAFFS_OBJECT_TYPE_UNKNOWN:
5334                 break;          /* should not happen. */
5335         }
5336 }
5337
5338 static int yaffs_UnlinkWorker(yaffs_Object * obj)
5339 {
5340
5341         if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5342                 return yaffs_DeleteHardLink(obj);
5343         } else if (!ylist_empty(&obj->hardLinks)) {
5344                 /* Curve ball: We're unlinking an object that has a hardlink.
5345                  *
5346                  * This problem arises because we are not strictly following
5347                  * The Linux link/inode model.
5348                  *
5349                  * We can't really delete the object.
5350                  * Instead, we do the following:
5351                  * - Select a hardlink.
5352                  * - Unhook it from the hard links
5353                  * - Unhook it from its parent directory (so that the rename can work)
5354                  * - Rename the object to the hardlink's name.
5355                  * - Delete the hardlink
5356                  */
5357
5358                 yaffs_Object *hl;
5359                 int retVal;
5360                 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5361
5362                 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5363
5364                 ylist_del_init(&hl->hardLinks);
5365                 ylist_del_init(&hl->siblings);
5366
5367                 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5368
5369                 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
5370
5371                 if (retVal == YAFFS_OK) {
5372                         retVal = yaffs_DoGenericObjectDeletion(hl);
5373                 }
5374                 return retVal;
5375
5376         } else {
5377                 switch (obj->variantType) {
5378                 case YAFFS_OBJECT_TYPE_FILE:
5379                         return yaffs_UnlinkFile(obj);
5380                         break;
5381                 case YAFFS_OBJECT_TYPE_DIRECTORY:
5382                         return yaffs_DeleteDirectory(obj);
5383                         break;
5384                 case YAFFS_OBJECT_TYPE_SYMLINK:
5385                         return yaffs_DeleteSymLink(obj);
5386                         break;
5387                 case YAFFS_OBJECT_TYPE_SPECIAL:
5388                         return yaffs_DoGenericObjectDeletion(obj);
5389                         break;
5390                 case YAFFS_OBJECT_TYPE_HARDLINK:
5391                 case YAFFS_OBJECT_TYPE_UNKNOWN:
5392                 default:
5393                         return YAFFS_FAIL;
5394                 }
5395         }
5396 }
5397
5398
5399 static int yaffs_UnlinkObject( yaffs_Object *obj)
5400 {
5401
5402         if (obj && obj->unlinkAllowed) {
5403                 return yaffs_UnlinkWorker(obj);
5404         }
5405
5406         return YAFFS_FAIL;
5407
5408 }
5409 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
5410 {
5411         yaffs_Object *obj;
5412
5413         obj = yaffs_FindObjectByName(dir, name);
5414         return yaffs_UnlinkObject(obj);
5415 }
5416
5417 /*----------------------- Initialisation Scanning ---------------------- */
5418
5419 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
5420                                        int backwardScanning)
5421 {
5422         yaffs_Object *obj;
5423
5424         if (!backwardScanning) {
5425                 /* Handle YAFFS1 forward scanning case
5426                  * For YAFFS1 we always do the deletion
5427                  */
5428
5429         } else {
5430                 /* Handle YAFFS2 case (backward scanning)
5431                  * If the shadowed object exists then ignore.
5432                  */
5433                 if (yaffs_FindObjectByNumber(dev, objId)) {
5434                         return;
5435                 }
5436         }
5437
5438         /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5439          * We put it in unlinked dir to be cleaned up after the scanning
5440          */
5441         obj =
5442             yaffs_FindOrCreateObjectByNumber(dev, objId,
5443                                              YAFFS_OBJECT_TYPE_FILE);
5444         yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5445         obj->variant.fileVariant.shrinkSize = 0;
5446         obj->valid = 1;         /* So that we don't read any other info for this file */
5447
5448 }
5449
5450 typedef struct {
5451         int seq;
5452         int block;
5453 } yaffs_BlockIndex;
5454
5455
5456 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5457 {
5458         yaffs_Object *hl;
5459         yaffs_Object *in;
5460         
5461         while (hardList) {
5462                 hl = hardList;
5463                 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5464
5465                 in = yaffs_FindObjectByNumber(dev,
5466                                               hl->variant.hardLinkVariant.
5467                                               equivalentObjectId);
5468
5469                 if (in) {
5470                         /* Add the hardlink pointers */
5471                         hl->variant.hardLinkVariant.equivalentObject = in;
5472                         ylist_add(&hl->hardLinks, &in->hardLinks);
5473                 } else {
5474                         /* Todo Need to report/handle this better.
5475                          * Got a problem... hardlink to a non-existant object
5476                          */
5477                         hl->variant.hardLinkVariant.equivalentObject = NULL;
5478                         YINIT_LIST_HEAD(&hl->hardLinks);
5479
5480                 }
5481
5482         }
5483
5484 }
5485
5486
5487
5488
5489
5490 static int ybicmp(const void *a, const void *b){
5491     register int aseq = ((yaffs_BlockIndex *)a)->seq;
5492     register int bseq = ((yaffs_BlockIndex *)b)->seq;
5493     register int ablock = ((yaffs_BlockIndex *)a)->block;
5494     register int bblock = ((yaffs_BlockIndex *)b)->block;
5495     if( aseq == bseq )
5496         return ablock - bblock;
5497     else
5498         return aseq - bseq;
5499
5500 }
5501
5502
5503 struct yaffs_ShadowFixerStruct {
5504         int objectId;
5505         int shadowedId;
5506         struct yaffs_ShadowFixerStruct *next;
5507 };
5508
5509 static int yaffs_Scan(yaffs_Device * dev)
5510 {
5511         yaffs_ExtendedTags tags;
5512         int blk;
5513         int blockIterator;
5514         int startIterator;
5515         int endIterator;
5516         int result;
5517
5518         int chunk;
5519         int c;
5520         int deleted;
5521         yaffs_BlockState state;
5522         yaffs_Object *hardList = NULL;
5523         yaffs_BlockInfo *bi;
5524         __u32 sequenceNumber;
5525         yaffs_ObjectHeader *oh;
5526         yaffs_Object *in;
5527         yaffs_Object *parent;
5528         
5529         int alloc_failed = 0;
5530         
5531         struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5532         
5533
5534         __u8 *chunkData;
5535
5536         
5537         
5538         T(YAFFS_TRACE_SCAN,
5539           (TSTR("yaffs_Scan starts  intstartblk %d intendblk %d..." TENDSTR),
5540            dev->internalStartBlock, dev->internalEndBlock));
5541
5542         chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5543
5544         dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5545
5546         /* Scan all the blocks to determine their state */
5547         for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5548                 bi = yaffs_GetBlockInfo(dev, blk);
5549                 yaffs_ClearChunkBits(dev, blk);
5550                 bi->pagesInUse = 0;
5551                 bi->softDeletions = 0;
5552
5553                 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5554
5555                 bi->blockState = state;
5556                 bi->sequenceNumber = sequenceNumber;
5557
5558                 T(YAFFS_TRACE_SCAN_DEBUG,
5559                   (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5560                    state, sequenceNumber));
5561
5562                 if (state == YAFFS_BLOCK_STATE_DEAD) {
5563                         T(YAFFS_TRACE_BAD_BLOCKS,
5564                           (TSTR("block %d is bad" TENDSTR), blk));
5565                 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5566                         T(YAFFS_TRACE_SCAN_DEBUG,
5567                           (TSTR("Block empty " TENDSTR)));
5568                         dev->nErasedBlocks++;
5569                         dev->nFreeChunks += dev->nChunksPerBlock;
5570                 } 
5571         }
5572
5573         startIterator = dev->internalStartBlock;
5574         endIterator = dev->internalEndBlock;
5575
5576         /* For each block.... */
5577         for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5578              blockIterator++) {
5579                 
5580                 YYIELD();
5581
5582                 YYIELD();
5583                 
5584                 blk = blockIterator;
5585
5586                 bi = yaffs_GetBlockInfo(dev, blk);
5587                 state = bi->blockState;
5588
5589                 deleted = 0;
5590
5591                 /* For each chunk in each block that needs scanning....*/
5592                 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5593                      state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5594                         /* Read the tags and decide what to do */
5595                         chunk = blk * dev->nChunksPerBlock + c;
5596
5597                         result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5598                                                         &tags);
5599
5600                         /* Let's have a good look at this chunk... */
5601
5602                         if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
5603                                 /* YAFFS1 only...
5604                                  * A deleted chunk
5605                                  */
5606                                 deleted++;
5607                                 dev->nFreeChunks++;
5608                                 /*T((" %d %d deleted\n",blk,c)); */
5609                         } else if (!tags.chunkUsed) {
5610                                 /* An unassigned chunk in the block
5611                                  * This means that either the block is empty or 
5612                                  * this is the one being allocated from
5613                                  */
5614
5615                                 if (c == 0) {
5616                                         /* We're looking at the first chunk in the block so the block is unused */
5617                                         state = YAFFS_BLOCK_STATE_EMPTY;
5618                                         dev->nErasedBlocks++;
5619                                 } else {
5620                                         /* this is the block being allocated from */
5621                                         T(YAFFS_TRACE_SCAN,
5622                                           (TSTR
5623                                            (" Allocating from %d %d" TENDSTR),
5624                                            blk, c));
5625                                         state = YAFFS_BLOCK_STATE_ALLOCATING;
5626                                         dev->allocationBlock = blk;
5627                                         dev->allocationPage = c;
5628                                         dev->allocationBlockFinder = blk;       
5629                                         /* Set it to here to encourage the allocator to go forth from here. */
5630                                         
5631                                 }
5632
5633                                 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5634                         } else if (tags.chunkId > 0) {
5635                                 /* chunkId > 0 so it is a data chunk... */
5636                                 unsigned int endpos;
5637
5638                                 yaffs_SetChunkBit(dev, blk, c);
5639                                 bi->pagesInUse++;
5640
5641                                 in = yaffs_FindOrCreateObjectByNumber(dev,
5642                                                                       tags.
5643                                                                       objectId,
5644                                                                       YAFFS_OBJECT_TYPE_FILE);
5645                                 /* PutChunkIntoFile checks for a clash (two data chunks with
5646                                  * the same chunkId).
5647                                  */
5648                                  
5649                                 if(!in)
5650                                         alloc_failed = 1;
5651
5652                                 if(in){
5653                                         if(!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,1))
5654                                                 alloc_failed = 1;
5655                                 }
5656                                 
5657                                 endpos =
5658                                     (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5659                                     tags.byteCount;
5660                                 if (in && 
5661                                     in->variantType == YAFFS_OBJECT_TYPE_FILE
5662                                     && in->variant.fileVariant.scannedFileSize <
5663                                     endpos) {
5664                                         in->variant.fileVariant.
5665                                             scannedFileSize = endpos;
5666                                         if (!dev->useHeaderFileSize) {
5667                                                 in->variant.fileVariant.
5668                                                     fileSize =
5669                                                     in->variant.fileVariant.
5670                                                     scannedFileSize;
5671                                         }
5672
5673                                 }
5674                                 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));   */
5675                         } else {
5676                                 /* chunkId == 0, so it is an ObjectHeader.
5677                                  * Thus, we read in the object header and make the object
5678                                  */
5679                                 yaffs_SetChunkBit(dev, blk, c);
5680                                 bi->pagesInUse++;
5681
5682                                 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5683                                                                 chunkData,
5684                                                                 NULL);
5685
5686                                 oh = (yaffs_ObjectHeader *) chunkData;
5687
5688                                 in = yaffs_FindObjectByNumber(dev,
5689                                                               tags.objectId);
5690                                 if (in && in->variantType != oh->type) {
5691                                         /* This should not happen, but somehow
5692                                          * Wev'e ended up with an objectId that has been reused but not yet 
5693                                          * deleted, and worse still it has changed type. Delete the old object.
5694                                          */
5695
5696                                         yaffs_DestroyObject(in);
5697
5698                                         in = 0;
5699                                 }
5700
5701                                 in = yaffs_FindOrCreateObjectByNumber(dev,
5702                                                                       tags.
5703                                                                       objectId,
5704                                                                       oh->type);
5705
5706                                 if(!in)
5707                                         alloc_failed = 1;
5708                                         
5709                                 if (in && oh->shadowsObject > 0) {
5710                                 
5711                                         struct yaffs_ShadowFixerStruct *fixer;
5712                                         fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
5713                                         if(fixer){
5714                                                 fixer-> next = shadowFixerList;
5715                                                 shadowFixerList = fixer;
5716                                                 fixer->objectId = tags.objectId;
5717                                                 fixer->shadowedId = oh->shadowsObject;
5718                                         }
5719                                         
5720                                 }
5721
5722                                 if (in && in->valid) {
5723                                         /* We have already filled this one. We have a duplicate and need to resolve it. */
5724
5725                                         unsigned existingSerial = in->serial;
5726                                         unsigned newSerial = tags.serialNumber;
5727
5728                                         if (((existingSerial + 1) & 3) == newSerial) {
5729                                                 /* Use new one - destroy the exisiting one */
5730                                                 yaffs_DeleteChunk(dev,
5731                                                                   in->hdrChunk,
5732                                                                   1, __LINE__);
5733                                                 in->valid = 0;
5734                                         } else {
5735                                                 /* Use existing - destroy this one. */
5736                                                 yaffs_DeleteChunk(dev, chunk, 1,
5737                                                                   __LINE__);
5738                                         }
5739                                 }
5740
5741                                 if (in && !in->valid &&
5742                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
5743                                      tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5744                                         /* We only load some info, don't fiddle with directory structure */
5745                                         in->valid = 1;
5746                                         in->variantType = oh->type;
5747
5748                                         in->yst_mode = oh->yst_mode;
5749 #ifdef CONFIG_YAFFS_WINCE
5750                                         in->win_atime[0] = oh->win_atime[0];
5751                                         in->win_ctime[0] = oh->win_ctime[0];
5752                                         in->win_mtime[0] = oh->win_mtime[0];
5753                                         in->win_atime[1] = oh->win_atime[1];
5754                                         in->win_ctime[1] = oh->win_ctime[1];
5755                                         in->win_mtime[1] = oh->win_mtime[1];
5756 #else
5757                                         in->yst_uid = oh->yst_uid;
5758                                         in->yst_gid = oh->yst_gid;
5759                                         in->yst_atime = oh->yst_atime;
5760                                         in->yst_mtime = oh->yst_mtime;
5761                                         in->yst_ctime = oh->yst_ctime;
5762                                         in->yst_rdev = oh->yst_rdev;
5763 #endif
5764                                         in->hdrChunk = chunk;
5765                                         in->serial = tags.serialNumber;
5766
5767                                 } else if (in && !in->valid) {
5768                                         /* we need to load this info */
5769
5770                                         in->valid = 1;
5771                                         in->variantType = oh->type;
5772
5773                                         in->yst_mode = oh->yst_mode;
5774 #ifdef CONFIG_YAFFS_WINCE
5775                                         in->win_atime[0] = oh->win_atime[0];
5776                                         in->win_ctime[0] = oh->win_ctime[0];
5777                                         in->win_mtime[0] = oh->win_mtime[0];
5778                                         in->win_atime[1] = oh->win_atime[1];
5779                                         in->win_ctime[1] = oh->win_ctime[1];
5780                                         in->win_mtime[1] = oh->win_mtime[1];
5781 #else
5782                                         in->yst_uid = oh->yst_uid;
5783                                         in->yst_gid = oh->yst_gid;
5784                                         in->yst_atime = oh->yst_atime;
5785                                         in->yst_mtime = oh->yst_mtime;
5786                                         in->yst_ctime = oh->yst_ctime;
5787                                         in->yst_rdev = oh->yst_rdev;
5788 #endif
5789                                         in->hdrChunk = chunk;
5790                                         in->serial = tags.serialNumber;
5791
5792                                         yaffs_SetObjectName(in, oh->name);
5793                                         in->dirty = 0;
5794
5795                                         /* directory stuff...
5796                                          * hook up to parent
5797                                          */
5798
5799                                         parent =
5800                                             yaffs_FindOrCreateObjectByNumber
5801                                             (dev, oh->parentObjectId,
5802                                              YAFFS_OBJECT_TYPE_DIRECTORY);
5803                                         if (parent->variantType ==
5804                                             YAFFS_OBJECT_TYPE_UNKNOWN) {
5805                                                 /* Set up as a directory */
5806                                                 parent->variantType =
5807                                                     YAFFS_OBJECT_TYPE_DIRECTORY;
5808                                                 YINIT_LIST_HEAD(&parent->variant.
5809                                                                directoryVariant.
5810                                                                children);
5811                                         } else if (parent->variantType !=
5812                                                    YAFFS_OBJECT_TYPE_DIRECTORY)
5813                                         {
5814                                                 /* Hoosterman, another problem....
5815                                                  * We're trying to use a non-directory as a directory
5816                                                  */
5817
5818                                                 T(YAFFS_TRACE_ERROR,
5819                                                   (TSTR
5820                                                    ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
5821                                                     TENDSTR)));
5822                                                 parent = dev->lostNFoundDir;
5823                                         }
5824
5825                                         yaffs_AddObjectToDirectory(parent, in);
5826
5827                                         if (0 && (parent == dev->deletedDir ||
5828                                                   parent == dev->unlinkedDir)) {
5829                                                 in->deleted = 1;        /* If it is unlinked at start up then it wants deleting */
5830                                                 dev->nDeletedFiles++;
5831                                         }
5832                                         /* Note re hardlinks.
5833                                          * Since we might scan a hardlink before its equivalent object is scanned
5834                                          * we put them all in a list.
5835                                          * After scanning is complete, we should have all the objects, so we run through this
5836                                          * list and fix up all the chains.              
5837                                          */
5838
5839                                         switch (in->variantType) {
5840                                         case YAFFS_OBJECT_TYPE_UNKNOWN: 
5841                                                 /* Todo got a problem */
5842                                                 break;
5843                                         case YAFFS_OBJECT_TYPE_FILE:
5844                                                 if (dev->useHeaderFileSize)
5845
5846                                                         in->variant.fileVariant.
5847                                                             fileSize =
5848                                                             oh->fileSize;
5849
5850                                                 break;
5851                                         case YAFFS_OBJECT_TYPE_HARDLINK:
5852                                                 in->variant.hardLinkVariant.
5853                                                     equivalentObjectId =
5854                                                     oh->equivalentObjectId;
5855                                                 in->hardLinks.next =
5856                                                     (struct ylist_head *)
5857                                                     hardList;
5858                                                 hardList = in;
5859                                                 break;
5860                                         case YAFFS_OBJECT_TYPE_DIRECTORY:
5861                                                 /* Do nothing */
5862                                                 break;
5863                                         case YAFFS_OBJECT_TYPE_SPECIAL:
5864                                                 /* Do nothing */
5865                                                 break;
5866                                         case YAFFS_OBJECT_TYPE_SYMLINK: 
5867                                                 in->variant.symLinkVariant.alias =
5868                                                     yaffs_CloneString(oh->alias);
5869                                                 if(!in->variant.symLinkVariant.alias)
5870                                                         alloc_failed = 1;
5871                                                 break;
5872                                         }
5873
5874 /*
5875                                         if (parent == dev->deletedDir) {
5876                                                 yaffs_DestroyObject(in);
5877                                                 bi->hasShrinkHeader = 1;
5878                                         }
5879 */
5880                                 }
5881                         }
5882                 }
5883
5884                 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5885                         /* If we got this far while scanning, then the block is fully allocated.*/
5886                         state = YAFFS_BLOCK_STATE_FULL;
5887                 }
5888
5889                 bi->blockState = state;
5890
5891                 /* Now let's see if it was dirty */
5892                 if (bi->pagesInUse == 0 &&
5893                     !bi->hasShrinkHeader &&
5894                     bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5895                         yaffs_BlockBecameDirty(dev, blk);
5896                 }
5897
5898         }
5899
5900         
5901         /* Ok, we've done all the scanning.
5902          * Fix up the hard link chains.
5903          * We should now have scanned all the objects, now it's time to add these 
5904          * hardlinks.
5905          */
5906
5907         yaffs_HardlinkFixup(dev,hardList);
5908         
5909         /* Handle the unlinked files. Since they were left in an unlinked state we should
5910          * just delete them.
5911          */
5912         {
5913                 struct ylist_head *i;
5914                 struct ylist_head *n;
5915
5916                 yaffs_Object *l;
5917                 /* Soft delete all the unlinked files */
5918                 ylist_for_each_safe(i, n,
5919                                    &dev->unlinkedDir->variant.directoryVariant.
5920                                    children) {
5921                         if (i) {
5922                                 l = ylist_entry(i, yaffs_Object, siblings);
5923                                 yaffs_DestroyObject(l);
5924                         }
5925                 }
5926         }
5927
5928         /* Fix up any shadowed objects */
5929         {
5930                 struct yaffs_ShadowFixerStruct *fixer;
5931                 yaffs_Object *obj;
5932                 
5933                 while(shadowFixerList){
5934                         fixer = shadowFixerList;
5935                         shadowFixerList = fixer->next;
5936                         /* Complete the rename transaction by deleting the shadowed object
5937                          * then setting the object header to unshadowed.
5938                          */
5939                         obj = yaffs_FindObjectByNumber(dev,fixer->shadowedId);
5940                         if(obj)
5941                                 yaffs_DestroyObject(obj);
5942         
5943                         obj = yaffs_FindObjectByNumber(dev,fixer->objectId);
5944                         if(obj){
5945                                 yaffs_UpdateObjectHeader(obj,NULL,1,0,0);
5946                         }
5947                         
5948                         YFREE(fixer);
5949                 }
5950         }
5951
5952         yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5953
5954         if(alloc_failed){
5955                 return YAFFS_FAIL;
5956         }
5957         
5958         T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5959         
5960
5961         return YAFFS_OK;
5962 }
5963
5964 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5965 {
5966         __u8 *chunkData;
5967         yaffs_ObjectHeader *oh;
5968         yaffs_Device *dev;
5969         yaffs_ExtendedTags tags;
5970         int result;
5971         int alloc_failed = 0;
5972
5973         if(!in)
5974                 return;
5975                 
5976         dev = in->myDev;
5977                 
5978 #if 0
5979         T(YAFFS_TRACE_SCAN,(TSTR("details for object %d %s loaded" TENDSTR),
5980                 in->objectId,
5981                 in->lazyLoaded ? "not yet" : "already"));
5982 #endif
5983
5984         if(in->lazyLoaded && in->hdrChunk > 0){
5985                 in->lazyLoaded = 0;
5986                 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5987
5988                 result = yaffs_ReadChunkWithTagsFromNAND(dev,in->hdrChunk,chunkData,&tags);
5989                 oh = (yaffs_ObjectHeader *) chunkData;
5990
5991                 in->yst_mode = oh->yst_mode;
5992 #ifdef CONFIG_YAFFS_WINCE
5993                 in->win_atime[0] = oh->win_atime[0];
5994                 in->win_ctime[0] = oh->win_ctime[0];
5995                 in->win_mtime[0] = oh->win_mtime[0];
5996                 in->win_atime[1] = oh->win_atime[1];
5997                 in->win_ctime[1] = oh->win_ctime[1];
5998                 in->win_mtime[1] = oh->win_mtime[1];
5999 #else
6000                 in->yst_uid = oh->yst_uid;
6001                 in->yst_gid = oh->yst_gid;
6002                 in->yst_atime = oh->yst_atime;
6003                 in->yst_mtime = oh->yst_mtime;
6004                 in->yst_ctime = oh->yst_ctime;
6005                 in->yst_rdev = oh->yst_rdev;
6006                 
6007 #endif
6008                 yaffs_SetObjectName(in, oh->name);
6009                 
6010                 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
6011                          in->variant.symLinkVariant.alias =
6012                                                     yaffs_CloneString(oh->alias);
6013                         if(!in->variant.symLinkVariant.alias)
6014                                 alloc_failed = 1; /* Not returned to caller */
6015                 }
6016                                                     
6017                 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
6018         }
6019 }
6020
6021 static int yaffs_ScanBackwards(yaffs_Device * dev)
6022 {
6023         yaffs_ExtendedTags tags;
6024         int blk;
6025         int blockIterator;
6026         int startIterator;
6027         int endIterator;
6028         int nBlocksToScan = 0;
6029
6030         int chunk;
6031         int result;
6032         int c;
6033         int deleted;
6034         yaffs_BlockState state;
6035         yaffs_Object *hardList = NULL;
6036         yaffs_BlockInfo *bi;
6037         __u32 sequenceNumber;
6038         yaffs_ObjectHeader *oh;
6039         yaffs_Object *in;
6040         yaffs_Object *parent;
6041         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6042         int itsUnlinked;
6043         __u8 *chunkData;
6044         
6045         int fileSize;
6046         int isShrink;
6047         int foundChunksInBlock;
6048         int equivalentObjectId;
6049         int alloc_failed = 0;
6050         
6051
6052         yaffs_BlockIndex *blockIndex = NULL;
6053         int altBlockIndex = 0;
6054
6055         if (!dev->isYaffs2) {
6056                 T(YAFFS_TRACE_SCAN,
6057                   (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6058                 return YAFFS_FAIL;
6059         }
6060
6061         T(YAFFS_TRACE_SCAN,
6062           (TSTR
6063            ("yaffs_ScanBackwards starts  intstartblk %d intendblk %d..."
6064             TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6065
6066
6067         dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6068
6069         blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6070         
6071         if(!blockIndex) {
6072                 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6073                 altBlockIndex = 1;
6074         }
6075         
6076         if(!blockIndex) {
6077                 T(YAFFS_TRACE_SCAN,
6078                   (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6079                 return YAFFS_FAIL;
6080         }
6081         
6082         dev->blocksInCheckpoint = 0;
6083         
6084         chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6085
6086         /* Scan all the blocks to determine their state */
6087         for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6088                 bi = yaffs_GetBlockInfo(dev, blk);
6089                 yaffs_ClearChunkBits(dev, blk);
6090                 bi->pagesInUse = 0;
6091                 bi->softDeletions = 0;
6092
6093                 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6094
6095                 bi->blockState = state;
6096                 bi->sequenceNumber = sequenceNumber;
6097
6098                 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6099                         bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6100                         
6101                 T(YAFFS_TRACE_SCAN_DEBUG,
6102                   (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6103                    state, sequenceNumber));
6104
6105                 
6106                 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
6107                         dev->blocksInCheckpoint++;
6108                         
6109                 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6110                         T(YAFFS_TRACE_BAD_BLOCKS,
6111                           (TSTR("block %d is bad" TENDSTR), blk));
6112                 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6113                         T(YAFFS_TRACE_SCAN_DEBUG,
6114                           (TSTR("Block empty " TENDSTR)));
6115                         dev->nErasedBlocks++;
6116                         dev->nFreeChunks += dev->nChunksPerBlock;
6117                 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6118
6119                         /* Determine the highest sequence number */
6120                         if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6121                             sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6122
6123                                 blockIndex[nBlocksToScan].seq = sequenceNumber;
6124                                 blockIndex[nBlocksToScan].block = blk;
6125
6126                                 nBlocksToScan++;
6127
6128                                 if (sequenceNumber >= dev->sequenceNumber) {
6129                                         dev->sequenceNumber = sequenceNumber;
6130                                 }
6131                         } else {
6132                                 /* TODO: Nasty sequence number! */
6133                                 T(YAFFS_TRACE_SCAN,
6134                                   (TSTR
6135                                    ("Block scanning block %d has bad sequence number %d"
6136                                     TENDSTR), blk, sequenceNumber));
6137
6138                         }
6139                 }
6140         }
6141
6142         T(YAFFS_TRACE_SCAN,
6143         (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6144
6145
6146
6147         YYIELD();
6148
6149         /* Sort the blocks */
6150 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6151         {
6152                 /* Use qsort now. */
6153                 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6154         }
6155 #else
6156         {
6157                 /* Dungy old bubble sort... */
6158                 
6159                 yaffs_BlockIndex temp;
6160                 int i;
6161                 int j;
6162
6163                 for (i = 0; i < nBlocksToScan; i++)
6164                         for (j = i + 1; j < nBlocksToScan; j++)
6165                                 if (blockIndex[i].seq > blockIndex[j].seq) {
6166                                         temp = blockIndex[j];
6167                                         blockIndex[j] = blockIndex[i];
6168                                         blockIndex[i] = temp;
6169                                 }
6170         }
6171 #endif
6172
6173         YYIELD();
6174
6175         T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6176
6177         /* Now scan the blocks looking at the data. */
6178         startIterator = 0;
6179         endIterator = nBlocksToScan - 1;
6180         T(YAFFS_TRACE_SCAN_DEBUG,
6181           (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6182
6183         /* For each block.... backwards */
6184         for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6185              blockIterator--) {
6186                 /* Cooperative multitasking! This loop can run for so
6187                    long that watchdog timers expire. */
6188                 YYIELD();
6189
6190                 /* get the block to scan in the correct order */
6191                 blk = blockIndex[blockIterator].block;
6192
6193                 bi = yaffs_GetBlockInfo(dev, blk);
6194                 
6195                 
6196                 state = bi->blockState;
6197
6198                 deleted = 0;
6199
6200                 /* For each chunk in each block that needs scanning.... */
6201                 foundChunksInBlock = 0;
6202                 for (c = dev->nChunksPerBlock - 1; 
6203                      !alloc_failed && c >= 0 &&
6204                      (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6205                       state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6206                         /* Scan backwards... 
6207                          * Read the tags and decide what to do
6208                          */
6209                         
6210                         chunk = blk * dev->nChunksPerBlock + c;
6211
6212                         result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6213                                                         &tags);
6214
6215                         /* Let's have a good look at this chunk... */
6216
6217                         if (!tags.chunkUsed) {
6218                                 /* An unassigned chunk in the block.
6219                                  * If there are used chunks after this one, then
6220                                  * it is a chunk that was skipped due to failing the erased
6221                                  * check. Just skip it so that it can be deleted.
6222                                  * But, more typically, We get here when this is an unallocated
6223                                  * chunk and his means that either the block is empty or 
6224                                  * this is the one being allocated from
6225                                  */
6226
6227                                 if(foundChunksInBlock)
6228                                 {
6229                                         /* This is a chunk that was skipped due to failing the erased check */
6230                                         
6231                                 } else if (c == 0) {
6232                                         /* We're looking at the first chunk in the block so the block is unused */
6233                                         state = YAFFS_BLOCK_STATE_EMPTY;
6234                                         dev->nErasedBlocks++;
6235                                 } else {
6236                                         if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6237                                             state == YAFFS_BLOCK_STATE_ALLOCATING) {
6238                                                 if(dev->sequenceNumber == bi->sequenceNumber) {
6239                                                         /* this is the block being allocated from */
6240                                                 
6241                                                         T(YAFFS_TRACE_SCAN,
6242                                                           (TSTR
6243                                                            (" Allocating from %d %d"
6244                                                             TENDSTR), blk, c));
6245
6246                                                         state = YAFFS_BLOCK_STATE_ALLOCATING;
6247                                                         dev->allocationBlock = blk;
6248                                                         dev->allocationPage = c;
6249                                                         dev->allocationBlockFinder = blk;       
6250                                                 }
6251                                                 else {
6252                                                         /* This is a partially written block that is not
6253                                                          * the current allocation block. This block must have
6254                                                          * had a write failure, so set up for retirement.
6255                                                          */
6256                                                   
6257                                                          /* bi->needsRetiring = 1; ??? TODO */
6258                                                          bi->gcPrioritise = 1;
6259                                                                                                          
6260                                                          T(YAFFS_TRACE_ALWAYS,
6261                                                          (TSTR("Partially written block %d detected" TENDSTR),
6262                                                          blk));
6263                                                 }
6264
6265                                         }
6266                                          
6267                                 }
6268
6269                                 dev->nFreeChunks++;
6270                                 
6271                         } else if (tags.chunkId > 0) {
6272                                 /* chunkId > 0 so it is a data chunk... */
6273                                 unsigned int endpos;
6274                                 __u32 chunkBase =
6275                                     (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6276                                                                 
6277                                 foundChunksInBlock = 1;
6278
6279
6280                                 yaffs_SetChunkBit(dev, blk, c);
6281                                 bi->pagesInUse++;
6282
6283                                 in = yaffs_FindOrCreateObjectByNumber(dev,
6284                                                                       tags.
6285                                                                       objectId,
6286                                                                       YAFFS_OBJECT_TYPE_FILE);
6287                                 if(!in){
6288                                         /* Out of memory */
6289                                         alloc_failed = 1;
6290                                 }
6291                                 
6292                                 if (in &&
6293                                     in->variantType == YAFFS_OBJECT_TYPE_FILE
6294                                     && chunkBase <
6295                                     in->variant.fileVariant.shrinkSize) {
6296                                         /* This has not been invalidated by a resize */
6297                                         if(!yaffs_PutChunkIntoFile(in, tags.chunkId,
6298                                                                chunk, -1)){
6299                                                 alloc_failed = 1;
6300                                         }
6301
6302                                         /* File size is calculated by looking at the data chunks if we have not 
6303                                          * seen an object header yet. Stop this practice once we find an object header.
6304                                          */
6305                                         endpos =
6306                                             (tags.chunkId -
6307                                              1) * dev->nDataBytesPerChunk +
6308                                             tags.byteCount;
6309                                             
6310                                         if (!in->valid &&       /* have not got an object header yet */
6311                                             in->variant.fileVariant.
6312                                             scannedFileSize < endpos) {
6313                                                 in->variant.fileVariant.
6314                                                     scannedFileSize = endpos;
6315                                                 in->variant.fileVariant.
6316                                                     fileSize =
6317                                                     in->variant.fileVariant.
6318                                                     scannedFileSize;
6319                                         }
6320
6321                                 } else if(in) {
6322                                         /* This chunk has been invalidated by a resize, so delete */
6323                                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6324
6325                                 }
6326                         } else {
6327                                 /* chunkId == 0, so it is an ObjectHeader.
6328                                  * Thus, we read in the object header and make the object
6329                                  */
6330                                 foundChunksInBlock = 1;
6331
6332                                 yaffs_SetChunkBit(dev, blk, c);
6333                                 bi->pagesInUse++;
6334
6335                                 oh = NULL;
6336                                 in = NULL;
6337
6338                                 if (tags.extraHeaderInfoAvailable) {
6339                                         in = yaffs_FindOrCreateObjectByNumber
6340                                             (dev, tags.objectId,
6341                                              tags.extraObjectType);
6342                                 }
6343
6344                                 if (!in ||
6345 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
6346                                     !in->valid ||
6347 #endif
6348                                     tags.extraShadows ||
6349                                     (!in->valid &&
6350                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
6351                                      tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
6352                                     ) {
6353
6354                                         /* If we don't have  valid info then we need to read the chunk
6355                                          * TODO In future we can probably defer reading the chunk and 
6356                                          * living with invalid data until needed.
6357                                          */
6358
6359                                         result = yaffs_ReadChunkWithTagsFromNAND(dev,
6360                                                                         chunk,
6361                                                                         chunkData,
6362                                                                         NULL);
6363
6364                                         oh = (yaffs_ObjectHeader *) chunkData;
6365                                         
6366                                         if(dev->inbandTags){
6367                                                 /* Fix up the header if they got corrupted by inband tags */
6368                                                 oh->shadowsObject = oh->inbandShadowsObject;
6369                                                 oh->isShrink = oh->inbandIsShrink;
6370                                         }
6371
6372                                         if (!in)
6373                                                 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6374
6375                                 }
6376
6377                                 if (!in) {
6378                                         /* TODO Hoosterman we have a problem! */
6379                                         T(YAFFS_TRACE_ERROR,
6380                                           (TSTR
6381                                            ("yaffs tragedy: Could not make object for object  %d at chunk %d during scan"
6382                                             TENDSTR), tags.objectId, chunk));
6383
6384                                 }
6385
6386                                 if (in->valid) {
6387                                         /* We have already filled this one.
6388                                          * We have a duplicate that will be discarded, but 
6389                                          * we first have to suck out resize info if it is a file.
6390                                          */
6391
6392                                         if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) && 
6393                                              ((oh && 
6394                                                oh-> type == YAFFS_OBJECT_TYPE_FILE)||
6395                                               (tags.extraHeaderInfoAvailable  &&
6396                                                tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
6397                                             ) {
6398                                                 __u32 thisSize =
6399                                                     (oh) ? oh->fileSize : tags.
6400                                                     extraFileLength;
6401                                                 __u32 parentObjectId =
6402                                                     (oh) ? oh->
6403                                                     parentObjectId : tags.
6404                                                     extraParentObjectId;
6405                                                 
6406                                                 
6407                                                 isShrink =
6408                                                     (oh) ? oh->isShrink : tags.
6409                                                     extraIsShrinkHeader;
6410
6411                                                 /* If it is deleted (unlinked at start also means deleted)
6412                                                  * we treat the file size as being zeroed at this point.
6413                                                  */
6414                                                 if (parentObjectId ==
6415                                                     YAFFS_OBJECTID_DELETED
6416                                                     || parentObjectId ==
6417                                                     YAFFS_OBJECTID_UNLINKED) {
6418                                                         thisSize = 0;
6419                                                         isShrink = 1;
6420                                                 }
6421
6422                                                 if (isShrink &&
6423                                                     in->variant.fileVariant.
6424                                                     shrinkSize > thisSize) {
6425                                                         in->variant.fileVariant.
6426                                                             shrinkSize =
6427                                                             thisSize;
6428                                                 }
6429
6430                                                 if (isShrink) {
6431                                                         bi->hasShrinkHeader = 1;
6432                                                 }
6433
6434                                         }
6435                                         /* Use existing - destroy this one. */
6436                                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6437
6438                                 }
6439
6440                                 if (!in->valid &&
6441                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
6442                                      tags.objectId ==
6443                                      YAFFS_OBJECTID_LOSTNFOUND)) {
6444                                         /* We only load some info, don't fiddle with directory structure */
6445                                         in->valid = 1;
6446                                         
6447                                         if(oh) {
6448                                                 in->variantType = oh->type;
6449
6450                                                 in->yst_mode = oh->yst_mode;
6451 #ifdef CONFIG_YAFFS_WINCE
6452                                                 in->win_atime[0] = oh->win_atime[0];
6453                                                 in->win_ctime[0] = oh->win_ctime[0];
6454                                                 in->win_mtime[0] = oh->win_mtime[0];
6455                                                 in->win_atime[1] = oh->win_atime[1];
6456                                                 in->win_ctime[1] = oh->win_ctime[1];
6457                                                 in->win_mtime[1] = oh->win_mtime[1];
6458 #else
6459                                                 in->yst_uid = oh->yst_uid;
6460                                                 in->yst_gid = oh->yst_gid;
6461                                                 in->yst_atime = oh->yst_atime;
6462                                                 in->yst_mtime = oh->yst_mtime;
6463                                                 in->yst_ctime = oh->yst_ctime;
6464                                                 in->yst_rdev = oh->yst_rdev;
6465                 
6466 #endif
6467                                         } else {
6468                                                 in->variantType = tags.extraObjectType;
6469                                                 in->lazyLoaded = 1;
6470                                         }
6471
6472                                         in->hdrChunk = chunk;
6473
6474                                 } else if (!in->valid) {
6475                                         /* we need to load this info */
6476
6477                                         in->valid = 1;
6478                                         in->hdrChunk = chunk;
6479
6480                                         if(oh) {
6481                                                 in->variantType = oh->type;
6482
6483                                                 in->yst_mode = oh->yst_mode;
6484 #ifdef CONFIG_YAFFS_WINCE
6485                                                 in->win_atime[0] = oh->win_atime[0];
6486                                                 in->win_ctime[0] = oh->win_ctime[0];
6487                                                 in->win_mtime[0] = oh->win_mtime[0];
6488                                                 in->win_atime[1] = oh->win_atime[1];
6489                                                 in->win_ctime[1] = oh->win_ctime[1];
6490                                                 in->win_mtime[1] = oh->win_mtime[1];
6491 #else
6492                                                 in->yst_uid = oh->yst_uid;
6493                                                 in->yst_gid = oh->yst_gid;
6494                                                 in->yst_atime = oh->yst_atime;
6495                                                 in->yst_mtime = oh->yst_mtime;
6496                                                 in->yst_ctime = oh->yst_ctime;
6497                                                 in->yst_rdev = oh->yst_rdev;
6498 #endif
6499
6500                                                 if (oh->shadowsObject > 0) 
6501                                                         yaffs_HandleShadowedObject(dev,
6502                                                                            oh->
6503                                                                            shadowsObject,
6504                                                                            1);
6505                                         
6506
6507                                                 yaffs_SetObjectName(in, oh->name);
6508                                                 parent =
6509                                                     yaffs_FindOrCreateObjectByNumber
6510                                                         (dev, oh->parentObjectId,
6511                                                          YAFFS_OBJECT_TYPE_DIRECTORY);
6512
6513                                                  fileSize = oh->fileSize;
6514                                                  isShrink = oh->isShrink;
6515                                                  equivalentObjectId = oh->equivalentObjectId;
6516
6517                                         }
6518                                         else {
6519                                                 in->variantType = tags.extraObjectType;
6520                                                 parent =
6521                                                     yaffs_FindOrCreateObjectByNumber
6522                                                         (dev, tags.extraParentObjectId,
6523                                                          YAFFS_OBJECT_TYPE_DIRECTORY);
6524                                                  fileSize = tags.extraFileLength;
6525                                                  isShrink = tags.extraIsShrinkHeader;
6526                                                  equivalentObjectId = tags.extraEquivalentObjectId;
6527                                                 in->lazyLoaded = 1;
6528
6529                                         }
6530                                         in->dirty = 0;
6531
6532                                         /* directory stuff...
6533                                          * hook up to parent
6534                                          */
6535
6536                                         if (parent->variantType ==
6537                                             YAFFS_OBJECT_TYPE_UNKNOWN) {
6538                                                 /* Set up as a directory */
6539                                                 parent->variantType =
6540                                                     YAFFS_OBJECT_TYPE_DIRECTORY;
6541                                                 YINIT_LIST_HEAD(&parent->variant.
6542                                                                directoryVariant.
6543                                                                children);
6544                                         } else if (parent->variantType !=
6545                                                    YAFFS_OBJECT_TYPE_DIRECTORY)
6546                                         {
6547                                                 /* Hoosterman, another problem....
6548                                                  * We're trying to use a non-directory as a directory
6549                                                  */
6550
6551                                                 T(YAFFS_TRACE_ERROR,
6552                                                   (TSTR
6553                                                    ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6554                                                     TENDSTR)));
6555                                                 parent = dev->lostNFoundDir;
6556                                         }
6557
6558                                         yaffs_AddObjectToDirectory(parent, in);
6559
6560                                         itsUnlinked = (parent == dev->deletedDir) ||
6561                                                       (parent == dev->unlinkedDir);
6562
6563                                         if (isShrink) {
6564                                                 /* Mark the block as having a shrinkHeader */
6565                                                 bi->hasShrinkHeader = 1;
6566                                         }
6567
6568                                         /* Note re hardlinks.
6569                                          * Since we might scan a hardlink before its equivalent object is scanned
6570                                          * we put them all in a list.
6571                                          * After scanning is complete, we should have all the objects, so we run
6572                                          * through this list and fix up all the chains.              
6573                                          */
6574
6575                                         switch (in->variantType) {
6576                                         case YAFFS_OBJECT_TYPE_UNKNOWN: 
6577                                                 /* Todo got a problem */
6578                                                 break;
6579                                         case YAFFS_OBJECT_TYPE_FILE:
6580
6581                                                 if (in->variant.fileVariant.
6582                                                     scannedFileSize < fileSize) {
6583                                                         /* This covers the case where the file size is greater
6584                                                          * than where the data is
6585                                                          * This will happen if the file is resized to be larger 
6586                                                          * than its current data extents.
6587                                                          */
6588                                                         in->variant.fileVariant.fileSize = fileSize;
6589                                                         in->variant.fileVariant.scannedFileSize =
6590                                                             in->variant.fileVariant.fileSize;
6591                                                 }
6592
6593                                                 if (isShrink &&
6594                                                     in->variant.fileVariant.shrinkSize > fileSize) {
6595                                                         in->variant.fileVariant.shrinkSize = fileSize;
6596                                                 }
6597
6598                                                 break;
6599                                         case YAFFS_OBJECT_TYPE_HARDLINK:
6600                                                 if(!itsUnlinked) {
6601                                                   in->variant.hardLinkVariant.equivalentObjectId =
6602                                                     equivalentObjectId;
6603                                                   in->hardLinks.next =
6604                                                     (struct ylist_head *) hardList;
6605                                                   hardList = in;
6606                                                 }
6607                                                 break;
6608                                         case YAFFS_OBJECT_TYPE_DIRECTORY:
6609                                                 /* Do nothing */
6610                                                 break;
6611                                         case YAFFS_OBJECT_TYPE_SPECIAL:
6612                                                 /* Do nothing */
6613                                                 break;
6614                                         case YAFFS_OBJECT_TYPE_SYMLINK:
6615                                                 if(oh){
6616                                                    in->variant.symLinkVariant.alias =
6617                                                     yaffs_CloneString(oh->
6618                                                                       alias);
6619                                                    if(!in->variant.symLinkVariant.alias)
6620                                                         alloc_failed = 1;
6621                                                 }
6622                                                 break;
6623                                         }
6624
6625                                 }
6626                                 
6627                         }
6628
6629                 } /* End of scanning for each chunk */
6630
6631                 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6632                         /* If we got this far while scanning, then the block is fully allocated. */
6633                         state = YAFFS_BLOCK_STATE_FULL;
6634                 }
6635
6636                 bi->blockState = state;
6637
6638                 /* Now let's see if it was dirty */
6639                 if (bi->pagesInUse == 0 &&
6640                     !bi->hasShrinkHeader &&
6641                     bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6642                         yaffs_BlockBecameDirty(dev, blk);
6643                 }
6644
6645         }
6646
6647         if (altBlockIndex) 
6648                 YFREE_ALT(blockIndex);
6649         else
6650                 YFREE(blockIndex);
6651         
6652         /* Ok, we've done all the scanning.
6653          * Fix up the hard link chains.
6654          * We should now have scanned all the objects, now it's time to add these 
6655          * hardlinks.
6656          */
6657         yaffs_HardlinkFixup(dev,hardList);
6658         
6659         
6660         /*
6661         *  Sort out state of unlinked and deleted objects.
6662         */
6663         {
6664                 struct ylist_head *i;
6665                 struct ylist_head *n;
6666
6667                 yaffs_Object *l;
6668
6669                 /* Soft delete all the unlinked files */
6670                 ylist_for_each_safe(i, n,
6671                                    &dev->unlinkedDir->variant.directoryVariant.
6672                                    children) {
6673                         if (i) {
6674                                 l = ylist_entry(i, yaffs_Object, siblings);
6675                                 yaffs_DestroyObject(l);
6676                         }
6677                 }
6678
6679                 /* Soft delete all the deletedDir files */
6680                 ylist_for_each_safe(i, n,
6681                                    &dev->deletedDir->variant.directoryVariant.
6682                                    children) {
6683                         if (i) {
6684                                 l = ylist_entry(i, yaffs_Object, siblings);
6685                                 yaffs_DestroyObject(l);
6686
6687                         }
6688                 }
6689         }
6690
6691         yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6692         
6693         if(alloc_failed){
6694                 return YAFFS_FAIL;
6695         }
6696
6697         T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6698
6699         return YAFFS_OK;
6700 }
6701
6702 /*------------------------------  Directory Functions ----------------------------- */
6703
6704 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
6705 {
6706         struct ylist_head *lh;
6707         yaffs_Object *listObj;
6708         
6709         int count = 0;
6710
6711         if(!obj){
6712                 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
6713                 YBUG();
6714         }
6715
6716         if(yaffs_SkipVerification(obj->myDev))
6717                 return;
6718
6719         if(!obj->parent){
6720                 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
6721                 YBUG();
6722         }
6723                 
6724         if(obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
6725                 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
6726                 YBUG();
6727         }
6728         
6729         /* Iterate through the objects in each hash entry */
6730          
6731         ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
6732                 if (lh) {
6733                         listObj = ylist_entry(lh, yaffs_Object, siblings);
6734                         yaffs_VerifyObject(listObj);
6735                         if(obj == listObj)
6736                                 count ++;
6737                 }
6738          }
6739          
6740          if(count != 1){
6741                 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR),count));
6742                 YBUG();
6743         }
6744
6745 }
6746
6747 static void yaffs_VerifyDirectory(yaffs_Object *directory)
6748 {
6749
6750         struct ylist_head *lh;
6751         yaffs_Object *listObj;
6752         
6753         if(!directory)
6754                 YBUG();
6755
6756         if(yaffs_SkipFullVerification(directory->myDev))
6757                 return;
6758
6759                 
6760         if(directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
6761                 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR),directory->variantType));
6762                 YBUG();
6763         }
6764         
6765         /* Iterate through the objects in each hash entry */
6766          
6767         ylist_for_each(lh, &directory->variant.directoryVariant.children) {
6768                 if (lh) {
6769                         listObj = ylist_entry(lh, yaffs_Object, siblings);
6770                         if(listObj->parent != directory){
6771                                 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent" TENDSTR),listObj->parent));
6772                                 YBUG();
6773                         }
6774                         yaffs_VerifyObjectInDirectory(listObj);
6775                 }
6776          }
6777          
6778 }
6779
6780
6781 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
6782 {
6783         yaffs_Device *dev = obj->myDev;
6784         yaffs_Object *parent;
6785         
6786         yaffs_VerifyObjectInDirectory(obj);
6787         parent = obj->parent;
6788         
6789         yaffs_VerifyDirectory(parent);
6790
6791         if(dev && dev->removeObjectCallback)
6792                 dev->removeObjectCallback(obj);
6793
6794            
6795         ylist_del_init(&obj->siblings);
6796         obj->parent = NULL;
6797
6798         yaffs_VerifyDirectory(parent);
6799
6800 }
6801
6802
6803 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
6804                                        yaffs_Object * obj)
6805 {
6806
6807         if (!directory) {
6808                 T(YAFFS_TRACE_ALWAYS,
6809                   (TSTR
6810                    ("tragedy: Trying to add an object to a null pointer directory"
6811                     TENDSTR)));
6812                 YBUG();
6813         }
6814         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6815                 T(YAFFS_TRACE_ALWAYS,
6816                   (TSTR
6817                    ("tragedy: Trying to add an object to a non-directory"
6818                     TENDSTR)));
6819                 YBUG();
6820         }
6821
6822         if (obj->siblings.prev == NULL) {
6823                 /* Not initialised */
6824                 YBUG();
6825
6826         } else if (ylist_empty(&obj->siblings)) {
6827                 YBUG();
6828         } 
6829
6830
6831         yaffs_VerifyDirectory(directory);
6832
6833         yaffs_RemoveObjectFromDirectory(obj);
6834         
6835         
6836         /* Now add it */
6837         ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
6838         obj->parent = directory;
6839
6840         if (directory == obj->myDev->unlinkedDir
6841             || directory == obj->myDev->deletedDir) {
6842                 obj->unlinked = 1;
6843                 obj->myDev->nUnlinkedFiles++;
6844                 obj->renameAllowed = 0;
6845         }
6846
6847         yaffs_VerifyDirectory(directory);
6848         yaffs_VerifyObjectInDirectory(obj);
6849
6850
6851 }
6852
6853 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
6854                                      const YCHAR * name)
6855 {
6856         int sum;
6857
6858         struct ylist_head *i;
6859         YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
6860
6861         yaffs_Object *l;
6862
6863         if (!name) {
6864                 return NULL;
6865         }
6866
6867         if (!directory) {
6868                 T(YAFFS_TRACE_ALWAYS,
6869                   (TSTR
6870                    ("tragedy: yaffs_FindObjectByName: null pointer directory"
6871                     TENDSTR)));
6872                 YBUG();
6873         }
6874         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6875                 T(YAFFS_TRACE_ALWAYS,
6876                   (TSTR
6877                    ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6878                 YBUG();
6879         }
6880
6881         sum = yaffs_CalcNameSum(name);
6882
6883         ylist_for_each(i, &directory->variant.directoryVariant.children) {
6884                 if (i) {
6885                         l = ylist_entry(i, yaffs_Object, siblings);
6886                         
6887                         if(l->parent != directory)
6888                                 YBUG();
6889                         
6890                         yaffs_CheckObjectDetailsLoaded(l);
6891
6892                         /* Special case for lost-n-found */
6893                         if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6894                                 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
6895                                         return l;
6896                                 }
6897                         } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0){
6898                                 /* LostnFound chunk called Objxxx
6899                                  * Do a real check
6900                                  */
6901                                 yaffs_GetObjectName(l, buffer,
6902                                                     YAFFS_MAX_NAME_LENGTH);
6903                                 if (yaffs_strncmp(name, buffer,YAFFS_MAX_NAME_LENGTH) == 0) {
6904                                         return l;
6905                                 }
6906
6907                         }
6908                 }
6909         }
6910
6911         return NULL;
6912 }
6913
6914
6915 #if 0
6916 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
6917                                    int (*fn) (yaffs_Object *))
6918 {
6919         struct ylist_head *i;
6920         yaffs_Object *l;
6921
6922         if (!theDir) {
6923                 T(YAFFS_TRACE_ALWAYS,
6924                   (TSTR
6925                    ("tragedy: yaffs_FindObjectByName: null pointer directory"
6926                     TENDSTR)));
6927                 YBUG();
6928         }
6929         if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6930                 T(YAFFS_TRACE_ALWAYS,
6931                   (TSTR
6932                    ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6933                 YBUG();
6934         }
6935
6936         ylist_for_each(i, &theDir->variant.directoryVariant.children) {
6937                 if (i) {
6938                         l = ylist_entry(i, yaffs_Object, siblings);
6939                         if (l && !fn(l)) {
6940                                 return YAFFS_FAIL;
6941                         }
6942                 }
6943         }
6944
6945         return YAFFS_OK;
6946
6947 }
6948 #endif
6949
6950 /* GetEquivalentObject dereferences any hard links to get to the
6951  * actual object.
6952  */
6953
6954 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
6955 {
6956         if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
6957                 /* We want the object id of the equivalent object, not this one */
6958                 obj = obj->variant.hardLinkVariant.equivalentObject;
6959                 yaffs_CheckObjectDetailsLoaded(obj);
6960         }
6961         return obj;
6962
6963 }
6964
6965 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
6966 {
6967         memset(name, 0, buffSize * sizeof(YCHAR));
6968         
6969         yaffs_CheckObjectDetailsLoaded(obj);
6970
6971         if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6972                 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
6973         } else if (obj->hdrChunk <= 0) {
6974                 YCHAR locName[20];
6975                 YCHAR numString[20];
6976                 YCHAR *x = &numString[19];
6977                 unsigned v = obj->objectId;
6978                 numString[19] = 0;
6979                 while(v>0){
6980                         x--;
6981                         *x = '0' + (v % 10);
6982                         v /= 10;
6983                 }
6984                 /* make up a name */
6985                 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
6986                 yaffs_strcat(locName,x);
6987                 yaffs_strncpy(name, locName, buffSize - 1);
6988
6989         }
6990 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
6991         else if (obj->shortName[0]) {
6992                 yaffs_strcpy(name, obj->shortName);
6993         }
6994 #endif
6995         else {
6996                 int result;
6997                 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
6998
6999                 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
7000
7001                 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
7002
7003                 if (obj->hdrChunk > 0) {
7004                         result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
7005                                                         obj->hdrChunk, buffer,
7006                                                         NULL);
7007                 }
7008                 yaffs_strncpy(name, oh->name, buffSize - 1);
7009
7010                 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
7011         }
7012
7013         return yaffs_strlen(name);
7014 }
7015
7016 int yaffs_GetObjectFileLength(yaffs_Object * obj)
7017 {
7018
7019         /* Dereference any hard linking */
7020         obj = yaffs_GetEquivalentObject(obj);
7021
7022         if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
7023                 return obj->variant.fileVariant.fileSize;
7024         }
7025         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
7026                 return yaffs_strlen(obj->variant.symLinkVariant.alias);
7027         } else {
7028                 /* Only a directory should drop through to here */
7029                 return obj->myDev->nDataBytesPerChunk;
7030         }
7031 }
7032
7033 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
7034 {
7035         int count = 0;
7036         struct ylist_head *i;
7037
7038         if (!obj->unlinked) {
7039                 count++;        /* the object itself */
7040         }
7041         ylist_for_each(i, &obj->hardLinks) {
7042                 count++;        /* add the hard links; */
7043         }
7044         return count;
7045
7046 }
7047
7048 int yaffs_GetObjectInode(yaffs_Object * obj)
7049 {
7050         obj = yaffs_GetEquivalentObject(obj);
7051
7052         return obj->objectId;
7053 }
7054
7055 unsigned yaffs_GetObjectType(yaffs_Object * obj)
7056 {
7057         obj = yaffs_GetEquivalentObject(obj);
7058
7059         switch (obj->variantType) {
7060         case YAFFS_OBJECT_TYPE_FILE:
7061                 return DT_REG;
7062                 break;
7063         case YAFFS_OBJECT_TYPE_DIRECTORY:
7064                 return DT_DIR;
7065                 break;
7066         case YAFFS_OBJECT_TYPE_SYMLINK:
7067                 return DT_LNK;
7068                 break;
7069         case YAFFS_OBJECT_TYPE_HARDLINK:
7070                 return DT_REG;
7071                 break;
7072         case YAFFS_OBJECT_TYPE_SPECIAL:
7073                 if (S_ISFIFO(obj->yst_mode))
7074                         return DT_FIFO;
7075                 if (S_ISCHR(obj->yst_mode))
7076                         return DT_CHR;
7077                 if (S_ISBLK(obj->yst_mode))
7078                         return DT_BLK;
7079                 if (S_ISSOCK(obj->yst_mode))
7080                         return DT_SOCK;
7081         default:
7082                 return DT_REG;
7083                 break;
7084         }
7085 }
7086
7087 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
7088 {
7089         obj = yaffs_GetEquivalentObject(obj);
7090         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
7091                 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7092         } else {
7093                 return yaffs_CloneString(_Y(""));
7094         }
7095 }
7096
7097 #ifndef CONFIG_YAFFS_WINCE
7098
7099 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
7100 {
7101         unsigned int valid = attr->ia_valid;
7102
7103         if (valid & ATTR_MODE)
7104                 obj->yst_mode = attr->ia_mode;
7105         if (valid & ATTR_UID)
7106                 obj->yst_uid = attr->ia_uid;
7107         if (valid & ATTR_GID)
7108                 obj->yst_gid = attr->ia_gid;
7109
7110         if (valid & ATTR_ATIME)
7111                 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7112         if (valid & ATTR_CTIME)
7113                 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7114         if (valid & ATTR_MTIME)
7115                 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7116
7117         if (valid & ATTR_SIZE)
7118                 yaffs_ResizeFile(obj, attr->ia_size);
7119
7120         yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7121
7122         return YAFFS_OK;
7123
7124 }
7125 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
7126 {
7127         unsigned int valid = 0;
7128
7129         attr->ia_mode = obj->yst_mode;
7130         valid |= ATTR_MODE;
7131         attr->ia_uid = obj->yst_uid;
7132         valid |= ATTR_UID;
7133         attr->ia_gid = obj->yst_gid;
7134         valid |= ATTR_GID;
7135
7136         Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7137         valid |= ATTR_ATIME;
7138         Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7139         valid |= ATTR_CTIME;
7140         Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7141         valid |= ATTR_MTIME;
7142
7143         attr->ia_size = yaffs_GetFileSize(obj);
7144         valid |= ATTR_SIZE;
7145
7146         attr->ia_valid = valid;
7147
7148         return YAFFS_OK;
7149
7150 }
7151
7152 #endif
7153
7154 #if 0
7155 int yaffs_DumpObject(yaffs_Object * obj)
7156 {
7157         YCHAR name[257];
7158
7159         yaffs_GetObjectName(obj, name, 256);
7160
7161         T(YAFFS_TRACE_ALWAYS,
7162           (TSTR
7163            ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7164             " chunk %d type %d size %d\n"
7165             TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7166            obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7167            yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7168
7169         return YAFFS_OK;
7170 }
7171 #endif
7172
7173 /*---------------------------- Initialisation code -------------------------------------- */
7174
7175 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
7176 {
7177
7178         /* Common functions, gotta have */
7179         if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
7180                 return 0;
7181
7182 #ifdef CONFIG_YAFFS_YAFFS2
7183
7184         /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7185         if (dev->writeChunkWithTagsToNAND &&
7186             dev->readChunkWithTagsFromNAND &&
7187             !dev->writeChunkToNAND &&
7188             !dev->readChunkFromNAND &&
7189             dev->markNANDBlockBad && dev->queryNANDBlock)
7190                 return 1;
7191 #endif
7192
7193         /* Can use the "spare" style interface for yaffs1 */
7194         if (!dev->isYaffs2 &&
7195             !dev->writeChunkWithTagsToNAND &&
7196             !dev->readChunkWithTagsFromNAND &&
7197             dev->writeChunkToNAND &&
7198             dev->readChunkFromNAND &&
7199             !dev->markNANDBlockBad && !dev->queryNANDBlock)
7200                 return 1;
7201
7202         return 0;               /* bad */
7203 }
7204
7205
7206 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7207 {
7208         /* Initialise the unlinked, deleted, root and lost and found directories */
7209         
7210         dev->lostNFoundDir = dev->rootDir =  NULL;
7211         dev->unlinkedDir = dev->deletedDir = NULL;
7212
7213         dev->unlinkedDir =
7214             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7215         
7216         dev->deletedDir =
7217             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7218
7219         dev->rootDir =
7220             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7221                                       YAFFS_ROOT_MODE | S_IFDIR);
7222         dev->lostNFoundDir =
7223             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7224                                       YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7225         
7226         if(dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir){
7227                 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7228                 return YAFFS_OK;
7229         }
7230         
7231         return YAFFS_FAIL;
7232 }
7233
7234 int yaffs_GutsInitialise(yaffs_Device * dev)
7235 {
7236         int init_failed = 0;
7237         unsigned x;
7238         int bits;
7239
7240         T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7241
7242         /* Check stuff that must be set */
7243
7244         if (!dev) {
7245                 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7246                 return YAFFS_FAIL;
7247         }
7248
7249         dev->internalStartBlock = dev->startBlock;
7250         dev->internalEndBlock = dev->endBlock;
7251         dev->blockOffset = 0;
7252         dev->chunkOffset = 0;
7253         dev->nFreeChunks = 0;
7254         
7255         dev->gcBlock = -1;
7256
7257         if (dev->startBlock == 0) {
7258                 dev->internalStartBlock = dev->startBlock + 1;
7259                 dev->internalEndBlock = dev->endBlock + 1;
7260                 dev->blockOffset = 1;
7261                 dev->chunkOffset = dev->nChunksPerBlock;
7262         }
7263
7264         /* Check geometry parameters. */
7265
7266         if ((!dev->inbandTags && dev->isYaffs2 && dev->totalBytesPerChunk < 1024) || 
7267             (!dev->isYaffs2 && dev->totalBytesPerChunk < 512) || 
7268             (dev->inbandTags && !dev->isYaffs2 ) ||
7269              dev->nChunksPerBlock < 2 || 
7270              dev->nReservedBlocks < 2 || 
7271              dev->internalStartBlock <= 0 || 
7272              dev->internalEndBlock <= 0 || 
7273              dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2)      // otherwise it is too small
7274             ) {
7275                 T(YAFFS_TRACE_ALWAYS,
7276                   (TSTR
7277                    ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7278                     TENDSTR), dev->totalBytesPerChunk, dev->isYaffs2 ? "2" : "", dev->inbandTags));
7279                 return YAFFS_FAIL;
7280         }
7281
7282         if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7283                 T(YAFFS_TRACE_ALWAYS,
7284                   (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7285                 return YAFFS_FAIL;
7286         }
7287         
7288         /* Sort out space for inband tags, if required */
7289         if(dev->inbandTags)
7290                 dev->nDataBytesPerChunk = dev->totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7291         else 
7292                 dev->nDataBytesPerChunk = dev->totalBytesPerChunk;
7293
7294         /* Got the right mix of functions? */
7295         if (!yaffs_CheckDevFunctions(dev)) {
7296                 /* Function missing */
7297                 T(YAFFS_TRACE_ALWAYS,
7298                   (TSTR
7299                    ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7300
7301                 return YAFFS_FAIL;
7302         }
7303
7304         /* This is really a compilation check. */
7305         if (!yaffs_CheckStructures()) {
7306                 T(YAFFS_TRACE_ALWAYS,
7307                   (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7308                 return YAFFS_FAIL;
7309         }
7310
7311         if (dev->isMounted) {
7312                 T(YAFFS_TRACE_ALWAYS,
7313                   (TSTR("yaffs: device already mounted\n" TENDSTR)));
7314                 return YAFFS_FAIL;
7315         }
7316
7317         /* Finished with most checks. One or two more checks happen later on too. */
7318
7319         dev->isMounted = 1;
7320
7321         /* OK now calculate a few things for the device */
7322         
7323         /*
7324          *  Calculate all the chunk size manipulation numbers:   
7325          */
7326         x = dev->nDataBytesPerChunk;
7327         /* We always use dev->chunkShift and dev->chunkDiv */
7328         dev->chunkShift = Shifts(x);
7329         x >>= dev->chunkShift;
7330         dev->chunkDiv = x;
7331         /* We only use chunk mask if chunkDiv is 1 */
7332         dev->chunkMask = (1<<dev->chunkShift) - 1;
7333                 
7334         /*
7335          * Calculate chunkGroupBits.
7336          * We need to find the next power of 2 > than internalEndBlock
7337          */
7338
7339         x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7340         
7341         bits = ShiftsGE(x);
7342         
7343         /* Set up tnode width if wide tnodes are enabled. */
7344         if(!dev->wideTnodesDisabled){
7345                 /* bits must be even so that we end up with 32-bit words */
7346                 if(bits & 1)
7347                         bits++;
7348                 if(bits < 16)
7349                         dev->tnodeWidth = 16;
7350                 else
7351                         dev->tnodeWidth = bits;
7352         }
7353         else
7354                 dev->tnodeWidth = 16;
7355  
7356         dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7357                 
7358         /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7359          * so if the bitwidth of the
7360          * chunk range we're using is greater than 16 we need
7361          * to figure out chunk shift and chunkGroupSize
7362          */
7363                  
7364         if (bits <= dev->tnodeWidth)
7365                 dev->chunkGroupBits = 0;
7366         else
7367                 dev->chunkGroupBits = bits - dev->tnodeWidth;
7368                 
7369
7370         dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7371
7372         if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7373                 /* We have a problem because the soft delete won't work if
7374                  * the chunk group size > chunks per block.
7375                  * This can be remedied by using larger "virtual blocks".
7376                  */
7377                 T(YAFFS_TRACE_ALWAYS,
7378                   (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7379
7380                 return YAFFS_FAIL;
7381         }
7382
7383         /* OK, we've finished verifying the device, lets continue with initialisation */
7384
7385         /* More device initialisation */
7386         dev->garbageCollections = 0;
7387         dev->passiveGarbageCollections = 0;
7388         dev->currentDirtyChecker = 0;
7389         dev->bufferedBlock = -1;
7390         dev->doingBufferedBlockRewrite = 0;
7391         dev->nDeletedFiles = 0;
7392         dev->nBackgroundDeletions = 0;
7393         dev->nUnlinkedFiles = 0;
7394         dev->eccFixed = 0;
7395         dev->eccUnfixed = 0;
7396         dev->tagsEccFixed = 0;
7397         dev->tagsEccUnfixed = 0;
7398         dev->nErasureFailures = 0;
7399         dev->nErasedBlocks = 0;
7400         dev->isDoingGC = 0;
7401         dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7402
7403         /* Initialise temporary buffers and caches. */
7404         if(!yaffs_InitialiseTempBuffers(dev))
7405                 init_failed = 1;
7406         
7407         dev->srCache = NULL;
7408         dev->gcCleanupList = NULL;
7409         
7410         
7411         if (!init_failed &&
7412             dev->nShortOpCaches > 0) {
7413                 int i;
7414                 void *buf;
7415                 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7416
7417                 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
7418                         dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7419                 }
7420
7421                 dev->srCache =  YMALLOC(srCacheBytes);
7422                 
7423                 buf = (__u8 *) dev->srCache;
7424                     
7425                 if(dev->srCache)
7426                         memset(dev->srCache,0,srCacheBytes);
7427                    
7428                 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7429                         dev->srCache[i].object = NULL;
7430                         dev->srCache[i].lastUse = 0;
7431                         dev->srCache[i].dirty = 0;
7432                         dev->srCache[i].data = buf = YMALLOC_DMA(dev->totalBytesPerChunk);
7433                 }
7434                 if(!buf)
7435                         init_failed = 1;
7436                         
7437                 dev->srLastUse = 0;
7438         }
7439
7440         dev->cacheHits = 0;
7441         
7442         if(!init_failed){
7443                 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7444                 if(!dev->gcCleanupList)
7445                         init_failed = 1;
7446         }
7447
7448         if (dev->isYaffs2) {
7449                 dev->useHeaderFileSize = 1;
7450         }
7451         if(!init_failed && !yaffs_InitialiseBlocks(dev))
7452                 init_failed = 1;
7453                 
7454         yaffs_InitialiseTnodes(dev);
7455         yaffs_InitialiseObjects(dev);
7456
7457         if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7458                 init_failed = 1;
7459
7460
7461         if(!init_failed){
7462                 /* Now scan the flash. */
7463                 if (dev->isYaffs2) {
7464                         if(yaffs_CheckpointRestore(dev)) {
7465                                 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7466                                 T(YAFFS_TRACE_ALWAYS,
7467                                   (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7468                         } else {
7469
7470                                 /* Clean up the mess caused by an aborted checkpoint load 
7471                                  * and scan backwards. 
7472                                  */
7473                                 yaffs_DeinitialiseBlocks(dev);
7474                                 yaffs_DeinitialiseTnodes(dev);
7475                                 yaffs_DeinitialiseObjects(dev);
7476                                 
7477                         
7478                                 dev->nErasedBlocks = 0;
7479                                 dev->nFreeChunks = 0;
7480                                 dev->allocationBlock = -1;
7481                                 dev->allocationPage = -1;
7482                                 dev->nDeletedFiles = 0;
7483                                 dev->nUnlinkedFiles = 0;
7484                                 dev->nBackgroundDeletions = 0;
7485                                 dev->oldestDirtySequence = 0;
7486
7487                                 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7488                                         init_failed = 1;
7489                                         
7490                                 yaffs_InitialiseTnodes(dev);
7491                                 yaffs_InitialiseObjects(dev);
7492
7493                                 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7494                                         init_failed = 1;
7495
7496                                 if(!init_failed && !yaffs_ScanBackwards(dev))
7497                                         init_failed = 1;
7498                         }
7499                 }else
7500                         if(!yaffs_Scan(dev))
7501                                 init_failed = 1;
7502         }
7503                 
7504         if(init_failed){
7505                 /* Clean up the mess */
7506                 T(YAFFS_TRACE_TRACING,
7507                   (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7508
7509                 yaffs_Deinitialise(dev);
7510                 return YAFFS_FAIL;
7511         }
7512
7513         /* Zero out stats */
7514         dev->nPageReads = 0;
7515         dev->nPageWrites = 0;
7516         dev->nBlockErasures = 0;
7517         dev->nGCCopies = 0;
7518         dev->nRetriedWrites = 0;
7519
7520         dev->nRetiredBlocks = 0;
7521
7522         yaffs_VerifyFreeChunks(dev);
7523         yaffs_VerifyBlocks(dev);
7524         
7525
7526         T(YAFFS_TRACE_TRACING,
7527           (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7528         return YAFFS_OK;
7529
7530 }
7531
7532 void yaffs_Deinitialise(yaffs_Device * dev)
7533 {
7534         if (dev->isMounted) {
7535                 int i;
7536
7537                 yaffs_DeinitialiseBlocks(dev);
7538                 yaffs_DeinitialiseTnodes(dev);
7539                 yaffs_DeinitialiseObjects(dev);
7540                 if (dev->nShortOpCaches > 0 &&
7541                     dev->srCache) {
7542
7543                         for (i = 0; i < dev->nShortOpCaches; i++) {
7544                                 if(dev->srCache[i].data)
7545                                         YFREE(dev->srCache[i].data);
7546                                 dev->srCache[i].data = NULL;
7547                         }
7548
7549                         YFREE(dev->srCache);
7550                         dev->srCache = NULL;
7551                 }
7552
7553                 YFREE(dev->gcCleanupList);
7554
7555                 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
7556                         YFREE(dev->tempBuffer[i].buffer);
7557                 }
7558
7559
7560                 dev->isMounted = 0;
7561                 
7562                 if(dev->deinitialiseNAND)
7563                         dev->deinitialiseNAND(dev);
7564         }
7565
7566 }
7567
7568 static int yaffs_CountFreeChunks(yaffs_Device * dev)
7569 {
7570         int nFree;
7571         int b;
7572
7573         yaffs_BlockInfo *blk;
7574
7575         for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7576              b++) {
7577                 blk = yaffs_GetBlockInfo(dev, b);
7578
7579                 switch (blk->blockState) {
7580                 case YAFFS_BLOCK_STATE_EMPTY:
7581                 case YAFFS_BLOCK_STATE_ALLOCATING:
7582                 case YAFFS_BLOCK_STATE_COLLECTING:
7583                 case YAFFS_BLOCK_STATE_FULL:
7584                         nFree +=
7585                             (dev->nChunksPerBlock - blk->pagesInUse +
7586                              blk->softDeletions);
7587                         break;
7588                 default:
7589                         break;
7590                 }
7591
7592         }
7593
7594         return nFree;
7595 }
7596
7597 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
7598 {
7599         /* This is what we report to the outside world */
7600
7601         int nFree;
7602         int nDirtyCacheChunks;
7603         int blocksForCheckpoint;
7604
7605 #if 1
7606         nFree = dev->nFreeChunks;
7607 #else
7608         nFree = yaffs_CountFreeChunks(dev);
7609 #endif
7610
7611         nFree += dev->nDeletedFiles;
7612         
7613         /* Now count the number of dirty chunks in the cache and subtract those */
7614
7615         {
7616                 int i;
7617                 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7618                         if (dev->srCache[i].dirty)
7619                                 nDirtyCacheChunks++;
7620                 }
7621         }
7622
7623         nFree -= nDirtyCacheChunks;
7624
7625         nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7626         
7627         /* Now we figure out how much to reserve for the checkpoint and report that... */
7628         blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7629         if(blocksForCheckpoint < 0)
7630                 blocksForCheckpoint = 0;
7631                 
7632         nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7633
7634         if (nFree < 0)
7635                 nFree = 0;
7636
7637         return nFree;
7638
7639 }
7640
7641 static int yaffs_freeVerificationFailures;
7642
7643 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
7644 {
7645         int counted;
7646         int difference;
7647         
7648         if(yaffs_SkipVerification(dev))
7649                 return;
7650         
7651         counted = yaffs_CountFreeChunks(dev);
7652
7653         difference = dev->nFreeChunks - counted;
7654
7655         if (difference) {
7656                 T(YAFFS_TRACE_ALWAYS,
7657                   (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7658                    dev->nFreeChunks, counted, difference));
7659                 yaffs_freeVerificationFailures++;
7660         }
7661 }
7662
7663 /*---------------------------------------- YAFFS test code ----------------------*/
7664
7665 #define yaffs_CheckStruct(structure,syze, name) \
7666         do { \
7667            if(sizeof(structure) != syze) \
7668                { \
7669                  T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
7670                  name,syze,sizeof(structure))); \
7671                  return YAFFS_FAIL; \
7672                 } \
7673         } while(0)
7674
7675 static int yaffs_CheckStructures(void)
7676 {
7677 /*      yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
7678 /*      yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
7679 /*      yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
7680 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7681         yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode");
7682 #endif
7683 #ifndef CONFIG_YAFFS_WINCE
7684                 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");
7685 #endif
7686             return YAFFS_OK;
7687 }