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