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