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