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