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