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