Consolidate with Android fixes
[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.77 2009-01-27 02:00:42 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                                         "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           while(1){}
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                         "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 chunk %d Parent type, %d, not directory"TENDSTR),
4347                                 cp->objectId,cp->parentId,cp->variantType,cp->hdrChunk,parent->variantType));
4348                         return 0;
4349                 }
4350                 yaffs_AddObjectToDirectory(parent, obj);
4351         }
4352
4353         obj->hdrChunk = cp->hdrChunk;
4354         obj->variantType = cp->variantType;
4355         obj->deleted = cp->deleted;
4356         obj->softDeleted = cp->softDeleted;
4357         obj->unlinked = cp->unlinked;
4358         obj->fake = cp->fake;
4359         obj->renameAllowed = cp->renameAllowed;
4360         obj->unlinkAllowed = cp->unlinkAllowed;
4361         obj->serial = cp->serial;
4362         obj->nDataChunks = cp->nDataChunks;
4363         
4364         if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4365                 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4366         else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4367                 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4368
4369         if(obj->hdrChunk > 0)
4370                 obj->lazyLoaded = 1;
4371         return 1;
4372 }
4373
4374
4375
4376 static int yaffs_CheckpointTnodeWorker(yaffs_Object * in, yaffs_Tnode * tn,
4377                                         __u32 level, int chunkOffset)
4378 {
4379         int i;
4380         yaffs_Device *dev = in->myDev;
4381         int ok = 1;
4382         int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4383
4384         if(tnodeSize < sizeof(yaffs_Tnode))
4385                 tnodeSize = sizeof(yaffs_Tnode);
4386         
4387
4388         if (tn) {
4389                 if (level > 0) {
4390
4391                         for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
4392                                 if (tn->internal[i]) {
4393                                         ok = yaffs_CheckpointTnodeWorker(in,
4394                                                         tn->internal[i],
4395                                                         level - 1,
4396                                                         (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4397                                 }
4398                         }
4399                 } else if (level == 0) {
4400                         __u32 baseOffset = chunkOffset <<  YAFFS_TNODES_LEVEL0_BITS;
4401                         ok = (yaffs_CheckpointWrite(dev,&baseOffset,sizeof(baseOffset)) == sizeof(baseOffset));
4402                         if(ok)
4403                                 ok = (yaffs_CheckpointWrite(dev,tn,tnodeSize) == tnodeSize);
4404                 }
4405         }
4406
4407         return ok;
4408
4409 }
4410
4411 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4412 {
4413         __u32 endMarker = ~0;
4414         int ok = 1;
4415         
4416         if(obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4417                 ok = yaffs_CheckpointTnodeWorker(obj,
4418                                             obj->variant.fileVariant.top,
4419                                             obj->variant.fileVariant.topLevel,
4420                                             0);
4421                 if(ok)
4422                         ok = (yaffs_CheckpointWrite(obj->myDev,&endMarker,sizeof(endMarker)) == 
4423                                 sizeof(endMarker));
4424         }
4425         
4426         return ok ? 1 : 0;
4427 }
4428
4429 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4430 {
4431         __u32 baseChunk;
4432         int ok = 1;
4433         yaffs_Device *dev = obj->myDev;
4434         yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4435         yaffs_Tnode *tn;
4436         int nread = 0;
4437         int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4438
4439         if(tnodeSize < sizeof(yaffs_Tnode))
4440                 tnodeSize = sizeof(yaffs_Tnode);
4441
4442         ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4443         
4444         while(ok && (~baseChunk)){
4445                 nread++;
4446                 /* Read level 0 tnode */
4447                 
4448                 
4449                 tn = yaffs_GetTnodeRaw(dev);
4450                 if(tn)
4451                         ok = (yaffs_CheckpointRead(dev,tn,tnodeSize) == tnodeSize);
4452                 else
4453                         ok = 0;
4454                         
4455                 if(tn && ok){
4456                         ok = yaffs_AddOrFindLevel0Tnode(dev,
4457                                                         fileStructPtr,
4458                                                         baseChunk,
4459                                                         tn) ? 1 : 0;
4460                                                         
4461                 }
4462                         
4463                 if(ok)
4464                         ok = (yaffs_CheckpointRead(dev,&baseChunk,sizeof(baseChunk)) == sizeof(baseChunk));
4465                 
4466         }
4467
4468         T(YAFFS_TRACE_CHECKPOINT,(
4469                 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4470                 nread,baseChunk,ok));
4471
4472         return ok ? 1 : 0;      
4473 }
4474  
4475
4476 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4477 {
4478         yaffs_Object *obj;
4479         yaffs_CheckpointObject cp;
4480         int i;
4481         int ok = 1;
4482         struct ylist_head *lh;
4483
4484         
4485         /* Iterate through the objects in each hash entry,
4486          * dumping them to the checkpointing stream.
4487          */
4488          
4489          for(i = 0; ok &&  i <  YAFFS_NOBJECT_BUCKETS; i++){
4490                 ylist_for_each(lh, &dev->objectBucket[i].list) {
4491                         if (lh) {
4492                                 obj = ylist_entry(lh, yaffs_Object, hashLink);
4493                                 if (!obj->deferedFree) {
4494                                         yaffs_ObjectToCheckpointObject(&cp,obj);
4495                                         cp.structType = sizeof(cp);
4496
4497                                         T(YAFFS_TRACE_CHECKPOINT,(
4498                                                 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
4499                                                 cp.objectId,cp.parentId,cp.variantType,cp.hdrChunk,(unsigned) obj));
4500
4501                                         ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4502                                         
4503                                         if(ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE){
4504                                                 ok = yaffs_WriteCheckpointTnodes(obj);
4505                                         }
4506                                 }
4507                         }
4508                 }
4509          }
4510          
4511          /* Dump end of list */
4512         memset(&cp,0xFF,sizeof(yaffs_CheckpointObject));
4513         cp.structType = sizeof(cp);
4514         
4515         if(ok)
4516                 ok = (yaffs_CheckpointWrite(dev,&cp,sizeof(cp)) == sizeof(cp));
4517                 
4518         return ok ? 1 : 0;
4519 }
4520
4521 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4522 {
4523         yaffs_Object *obj;
4524         yaffs_CheckpointObject cp;
4525         int ok = 1;
4526         int done = 0;
4527         yaffs_Object *hardList = NULL;
4528         
4529         while(ok && !done) {
4530                 ok = (yaffs_CheckpointRead(dev,&cp,sizeof(cp)) == sizeof(cp));
4531                 if(cp.structType != sizeof(cp)) {
4532                         T(YAFFS_TRACE_CHECKPOINT,(TSTR("struct size %d instead of %d ok %d"TENDSTR),
4533                                 cp.structType,sizeof(cp),ok));
4534                         ok = 0;
4535                 }
4536                         
4537                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4538                         cp.objectId,cp.parentId,cp.variantType,cp.hdrChunk));
4539
4540                 if(ok && cp.objectId == ~0)
4541                         done = 1;
4542                 else if(ok){
4543                         obj = yaffs_FindOrCreateObjectByNumber(dev,cp.objectId, cp.variantType);
4544                         if(obj) {
4545                                 ok = yaffs_CheckpointObjectToObject(obj,&cp);
4546                                 if (!ok)
4547                                         break;
4548                                 if(obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4549                                         ok = yaffs_ReadCheckpointTnodes(obj);
4550                                 } else if(obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4551                                         obj->hardLinks.next =
4552                                                     (struct ylist_head *)
4553                                                     hardList;
4554                                         hardList = obj;
4555                                 }
4556                            
4557                         }
4558                         else
4559                                 ok = 0;
4560                 }
4561         }
4562         
4563         if(ok)
4564                 yaffs_HardlinkFixup(dev,hardList);
4565         
4566         return ok ? 1 : 0;
4567 }
4568
4569 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4570 {
4571         __u32 checkpointSum;
4572         int ok;
4573         
4574         yaffs_GetCheckpointSum(dev,&checkpointSum);
4575         
4576         ok = (yaffs_CheckpointWrite(dev,&checkpointSum,sizeof(checkpointSum)) == sizeof(checkpointSum));
4577         
4578         if(!ok)
4579                 return 0;
4580         
4581         return 1;
4582 }
4583
4584 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4585 {
4586         __u32 checkpointSum0;
4587         __u32 checkpointSum1;
4588         int ok;
4589         
4590         yaffs_GetCheckpointSum(dev,&checkpointSum0);
4591         
4592         ok = (yaffs_CheckpointRead(dev,&checkpointSum1,sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4593         
4594         if(!ok)
4595                 return 0;
4596                 
4597         if(checkpointSum0 != checkpointSum1)
4598                 return 0;
4599         
4600         return 1;
4601 }
4602
4603
4604 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4605 {
4606
4607         int ok = 1;
4608         
4609         if(dev->skipCheckpointWrite || !dev->isYaffs2){
4610                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint write" TENDSTR)));
4611                 ok = 0;
4612         }
4613                 
4614         if(ok)
4615                 ok = yaffs_CheckpointOpen(dev,1);
4616         
4617         if(ok){
4618                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4619                 ok = yaffs_WriteCheckpointValidityMarker(dev,1);
4620         }
4621         if(ok){
4622                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint device" TENDSTR)));
4623                 ok = yaffs_WriteCheckpointDevice(dev);
4624         }
4625         if(ok){
4626                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint objects" TENDSTR)));
4627                 ok = yaffs_WriteCheckpointObjects(dev);
4628         }
4629         if(ok){
4630                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("write checkpoint validity" TENDSTR)));
4631                 ok = yaffs_WriteCheckpointValidityMarker(dev,0);
4632         }
4633         
4634         if(ok){
4635                 ok = yaffs_WriteCheckpointSum(dev);
4636         }
4637         
4638         
4639         if(!yaffs_CheckpointClose(dev))
4640                  ok = 0;
4641                  
4642         if(ok)
4643                 dev->isCheckpointed = 1;
4644          else 
4645                 dev->isCheckpointed = 0;
4646
4647         return dev->isCheckpointed;
4648 }
4649
4650 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4651 {
4652         int ok = 1;
4653         
4654         if(dev->skipCheckpointRead || !dev->isYaffs2){
4655                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("skipping checkpoint read" TENDSTR)));
4656                 ok = 0;
4657         }
4658         
4659         if(ok)
4660                 ok = yaffs_CheckpointOpen(dev,0); /* open for read */
4661         
4662         if(ok){
4663                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));   
4664                 ok = yaffs_ReadCheckpointValidityMarker(dev,1);
4665         }
4666         if(ok){
4667                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint device" TENDSTR)));
4668                 ok = yaffs_ReadCheckpointDevice(dev);
4669         }
4670         if(ok){
4671                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint objects" TENDSTR)));    
4672                 ok = yaffs_ReadCheckpointObjects(dev);
4673         }
4674         if(ok){
4675                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint validity" TENDSTR)));
4676                 ok = yaffs_ReadCheckpointValidityMarker(dev,0);
4677         }
4678         
4679         if(ok){
4680                 ok = yaffs_ReadCheckpointSum(dev);
4681                 T(YAFFS_TRACE_CHECKPOINT,(TSTR("read checkpoint checksum %d" TENDSTR),ok));
4682         }
4683
4684         if(!yaffs_CheckpointClose(dev))
4685                 ok = 0;
4686
4687         if(ok)
4688                 dev->isCheckpointed = 1;
4689          else 
4690                 dev->isCheckpointed = 0;
4691
4692         return ok ? 1 : 0;
4693
4694 }
4695
4696 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4697 {
4698         if(dev->isCheckpointed || 
4699            dev->blocksInCheckpoint > 0){
4700                 dev->isCheckpointed = 0;
4701                 yaffs_CheckpointInvalidateStream(dev);
4702                 if(dev->superBlock && dev->markSuperBlockDirty)
4703                         dev->markSuperBlockDirty(dev->superBlock);
4704         }
4705 }
4706
4707
4708 int yaffs_CheckpointSave(yaffs_Device *dev)
4709 {
4710
4711         T(YAFFS_TRACE_CHECKPOINT,(TSTR("save entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4712
4713         yaffs_VerifyObjects(dev);
4714         yaffs_VerifyBlocks(dev);
4715         yaffs_VerifyFreeChunks(dev);
4716
4717         if(!dev->isCheckpointed) {
4718                 yaffs_InvalidateCheckpoint(dev);
4719                 yaffs_WriteCheckpointData(dev);
4720         }
4721         
4722         T(YAFFS_TRACE_ALWAYS,(TSTR("save exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4723
4724         return dev->isCheckpointed;
4725 }
4726
4727 int yaffs_CheckpointRestore(yaffs_Device *dev)
4728 {
4729         int retval;
4730         T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore entry: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4731                 
4732         retval = yaffs_ReadCheckpointData(dev);
4733
4734         if(dev->isCheckpointed){
4735                 yaffs_VerifyObjects(dev);
4736                 yaffs_VerifyBlocks(dev);
4737                 yaffs_VerifyFreeChunks(dev);
4738         }
4739
4740         T(YAFFS_TRACE_CHECKPOINT,(TSTR("restore exit: isCheckpointed %d"TENDSTR),dev->isCheckpointed));
4741         
4742         return retval;
4743 }
4744
4745 /*--------------------- File read/write ------------------------
4746  * Read and write have very similar structures.
4747  * In general the read/write has three parts to it
4748  * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4749  * Some complete chunks
4750  * An incomplete chunk to end off with
4751  *
4752  * Curve-balls: the first chunk might also be the last chunk.
4753  */
4754
4755 int yaffs_ReadDataFromFile(yaffs_Object * in, __u8 * buffer, loff_t offset,
4756                            int nBytes)
4757 {
4758
4759         int chunk;
4760         __u32 start;
4761         int nToCopy;
4762         int n = nBytes;
4763         int nDone = 0;
4764         yaffs_ChunkCache *cache;
4765
4766         yaffs_Device *dev;
4767
4768         dev = in->myDev;
4769
4770         while (n > 0) {
4771                 //chunk = offset / dev->nDataBytesPerChunk + 1;
4772                 //start = offset % dev->nDataBytesPerChunk;
4773                 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4774                 chunk++;
4775
4776                 /* OK now check for the curveball where the start and end are in
4777                  * the same chunk.      
4778                  */
4779                 if ((start + n) < dev->nDataBytesPerChunk) {
4780                         nToCopy = n;
4781                 } else {
4782                         nToCopy = dev->nDataBytesPerChunk - start;
4783                 }
4784
4785                 cache = yaffs_FindChunkCache(in, chunk);
4786
4787                 /* If the chunk is already in the cache or it is less than a whole chunk
4788                  * or we're using inband tags then use the cache (if there is caching)
4789                  * else bypass the cache.
4790                  */
4791                 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4792                         if (dev->nShortOpCaches > 0) {
4793
4794                                 /* If we can't find the data in the cache, then load it up. */
4795
4796                                 if (!cache) {
4797                                         cache = yaffs_GrabChunkCache(in->myDev);
4798                                         cache->object = in;
4799                                         cache->chunkId = chunk;
4800                                         cache->dirty = 0;
4801                                         cache->locked = 0;
4802                                         yaffs_ReadChunkDataFromObject(in, chunk,
4803                                                                       cache->
4804                                                                       data);
4805                                         cache->nBytes = 0;
4806                                 }
4807
4808                                 yaffs_UseChunkCache(dev, cache, 0);
4809
4810                                 cache->locked = 1;
4811
4812
4813                                 memcpy(buffer, &cache->data[start], nToCopy);
4814
4815                                 cache->locked = 0;
4816                         } else {
4817                                 /* Read into the local buffer then copy..*/
4818
4819                                 __u8 *localBuffer =
4820                                     yaffs_GetTempBuffer(dev, __LINE__);
4821                                 yaffs_ReadChunkDataFromObject(in, chunk,
4822                                                               localBuffer);
4823
4824                                 memcpy(buffer, &localBuffer[start], nToCopy);
4825
4826
4827                                 yaffs_ReleaseTempBuffer(dev, localBuffer,
4828                                                         __LINE__);
4829                         }
4830
4831                 } else {
4832
4833                         /* A full chunk. Read directly into the supplied buffer. */
4834                         yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4835
4836                 }
4837
4838                 n -= nToCopy;
4839                 offset += nToCopy;
4840                 buffer += nToCopy;
4841                 nDone += nToCopy;
4842
4843         }
4844
4845         return nDone;
4846 }
4847
4848 int yaffs_WriteDataToFile(yaffs_Object * in, const __u8 * buffer, loff_t offset,
4849                           int nBytes, int writeThrough)
4850 {
4851
4852         int chunk;
4853         __u32 start;
4854         int nToCopy;
4855         int n = nBytes;
4856         int nDone = 0;
4857         int nToWriteBack;
4858         int startOfWrite = offset;
4859         int chunkWritten = 0;
4860         __u32 nBytesRead;
4861         __u32 chunkStart;
4862
4863         yaffs_Device *dev;
4864
4865         dev = in->myDev;
4866
4867         while (n > 0 && chunkWritten >= 0) {
4868                 //chunk = offset / dev->nDataBytesPerChunk + 1;
4869                 //start = offset % dev->nDataBytesPerChunk;
4870                 yaffs_AddrToChunk(dev,offset,&chunk,&start);
4871                 
4872                 if(chunk * dev->nDataBytesPerChunk + start != offset ||
4873                    start >= dev->nDataBytesPerChunk){
4874                    T(YAFFS_TRACE_ERROR,(TSTR("AddrToChunk of offset %d gives chunk %d start %d"TENDSTR),
4875                                         (int)offset, chunk,start));
4876                 }
4877                 chunk++;
4878
4879                 /* OK now check for the curveball where the start and end are in
4880                  * the same chunk.
4881                  */
4882
4883                 if ((start + n) < dev->nDataBytesPerChunk) {
4884                         nToCopy = n;
4885
4886                         /* Now folks, to calculate how many bytes to write back....
4887                          * If we're overwriting and not writing to then end of file then
4888                          * we need to write back as much as was there before.
4889                          */
4890
4891                         chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
4892
4893                         if(chunkStart > in->variant.fileVariant.fileSize)
4894                                 nBytesRead = 0; /* Past end of file */
4895                         else
4896                                 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
4897
4898                         if (nBytesRead > dev->nDataBytesPerChunk) {
4899                                 nBytesRead = dev->nDataBytesPerChunk;
4900                         }
4901
4902                         nToWriteBack =
4903                             (nBytesRead >
4904                              (start + n)) ? nBytesRead : (start + n);
4905                         
4906                         if(nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
4907                                 YBUG();
4908
4909                 } else {
4910                         nToCopy = dev->nDataBytesPerChunk - start;
4911                         nToWriteBack = dev->nDataBytesPerChunk;
4912                 }
4913
4914                 if (nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4915                         /* An incomplete start or end chunk (or maybe both start and end chunk), 
4916                          * or we're using inband tags, so we want to use the cache buffers.
4917                          */
4918                         if (dev->nShortOpCaches > 0) {
4919                                 yaffs_ChunkCache *cache;
4920                                 /* If we can't find the data in the cache, then load the cache */
4921                                 cache = yaffs_FindChunkCache(in, chunk);
4922                                 
4923                                 if (!cache
4924                                     && yaffs_CheckSpaceForAllocation(in->
4925                                                                      myDev)) {
4926                                         cache = yaffs_GrabChunkCache(in->myDev);
4927                                         cache->object = in;
4928                                         cache->chunkId = chunk;
4929                                         cache->dirty = 0;
4930                                         cache->locked = 0;
4931                                         yaffs_ReadChunkDataFromObject(in, chunk,
4932                                                                       cache->
4933                                                                       data);
4934                                 }
4935                                 else if(cache && 
4936                                         !cache->dirty &&
4937                                         !yaffs_CheckSpaceForAllocation(in->myDev)){
4938                                         /* Drop the cache if it was a read cache item and
4939                                          * no space check has been made for it.
4940                                          */ 
4941                                          cache = NULL;
4942                                 }
4943
4944                                 if (cache) {
4945                                         yaffs_UseChunkCache(dev, cache, 1);
4946                                         cache->locked = 1;
4947
4948
4949                                         memcpy(&cache->data[start], buffer,
4950                                                nToCopy);
4951
4952
4953                                         cache->locked = 0;
4954                                         cache->nBytes = nToWriteBack;
4955
4956                                         if (writeThrough) {
4957                                                 chunkWritten =
4958                                                     yaffs_WriteChunkDataToObject
4959                                                     (cache->object,
4960                                                      cache->chunkId,
4961                                                      cache->data, cache->nBytes,
4962                                                      1);
4963                                                 cache->dirty = 0;
4964                                         }
4965
4966                                 } else {
4967                                         chunkWritten = -1;      /* fail the write */
4968                                 }
4969                         } else {
4970                                 /* An incomplete start or end chunk (or maybe both start and end chunk)
4971                                  * Read into the local buffer then copy, then copy over and write back.
4972                                  */
4973
4974                                 __u8 *localBuffer =
4975                                     yaffs_GetTempBuffer(dev, __LINE__);
4976
4977                                 yaffs_ReadChunkDataFromObject(in, chunk,
4978                                                               localBuffer);
4979
4980
4981
4982                                 memcpy(&localBuffer[start], buffer, nToCopy);
4983
4984                                 chunkWritten =
4985                                     yaffs_WriteChunkDataToObject(in, chunk,
4986                                                                  localBuffer,
4987                                                                  nToWriteBack,
4988                                                                  0);
4989
4990                                 yaffs_ReleaseTempBuffer(dev, localBuffer,
4991                                                         __LINE__);
4992
4993                         }
4994
4995                 } else {
4996                         /* A full chunk. Write directly from the supplied buffer. */
4997                         
4998
4999
5000                         chunkWritten =
5001                             yaffs_WriteChunkDataToObject(in, chunk, buffer,
5002                                                          dev->nDataBytesPerChunk,
5003                                                          0);
5004
5005                         /* Since we've overwritten the cached data, we better invalidate it. */
5006                         yaffs_InvalidateChunkCache(in, chunk);
5007                 }
5008
5009                 if (chunkWritten >= 0) {
5010                         n -= nToCopy;
5011                         offset += nToCopy;
5012                         buffer += nToCopy;
5013                         nDone += nToCopy;
5014                 }
5015
5016         }
5017
5018         /* Update file object */
5019
5020         if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize) {
5021                 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
5022         }
5023
5024         in->dirty = 1;
5025
5026         return nDone;
5027 }
5028
5029
5030 /* ---------------------- File resizing stuff ------------------ */
5031
5032 static void yaffs_PruneResizedChunks(yaffs_Object * in, int newSize)
5033 {
5034
5035         yaffs_Device *dev = in->myDev;
5036         int oldFileSize = in->variant.fileVariant.fileSize;
5037
5038         int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
5039
5040         int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
5041             dev->nDataBytesPerChunk;
5042         int i;
5043         int chunkId;
5044
5045         /* Delete backwards so that we don't end up with holes if
5046          * power is lost part-way through the operation.
5047          */
5048         for (i = lastDel; i >= startDel; i--) {
5049                 /* NB this could be optimised somewhat,
5050                  * eg. could retrieve the tags and write them without
5051                  * using yaffs_DeleteChunk
5052                  */
5053
5054                 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5055                 if (chunkId > 0) {
5056                         if (chunkId <
5057                             (dev->internalStartBlock * dev->nChunksPerBlock)
5058                             || chunkId >=
5059                             ((dev->internalEndBlock +
5060                               1) * dev->nChunksPerBlock)) {
5061                                 T(YAFFS_TRACE_ALWAYS,
5062                                   (TSTR("Found daft chunkId %d for %d" TENDSTR),
5063                                    chunkId, i));
5064                         } else {
5065                                 in->nDataChunks--;
5066                                 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5067                         }
5068                 }
5069         }
5070
5071 }
5072
5073 int yaffs_ResizeFile(yaffs_Object * in, loff_t newSize)
5074 {
5075
5076         int oldFileSize = in->variant.fileVariant.fileSize;
5077         __u32 newSizeOfPartialChunk;
5078         int newFullChunks;
5079         
5080         yaffs_Device *dev = in->myDev;
5081
5082         yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5083
5084         yaffs_FlushFilesChunkCache(in);
5085         yaffs_InvalidateWholeChunkCache(in);
5086
5087         yaffs_CheckGarbageCollection(dev);
5088
5089         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
5090                 return YAFFS_FAIL;
5091         }
5092
5093         if (newSize == oldFileSize) {
5094                 return YAFFS_OK;
5095         }
5096
5097         if (newSize < oldFileSize) {
5098
5099                 yaffs_PruneResizedChunks(in, newSize);
5100
5101                 if (newSizeOfPartialChunk != 0) {
5102                         int lastChunk = 1 + newFullChunks;
5103                         
5104                         __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5105
5106                         /* Got to read and rewrite the last chunk with its new size and zero pad */
5107                         yaffs_ReadChunkDataFromObject(in, lastChunk,
5108                                                       localBuffer);
5109
5110                         memset(localBuffer + newSizeOfPartialChunk, 0,
5111                                dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5112
5113                         yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5114                                                      newSizeOfPartialChunk, 1);
5115
5116                         yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5117                 }
5118
5119                 in->variant.fileVariant.fileSize = newSize;
5120
5121                 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5122         } else {
5123                 /* newsSize > oldFileSize */
5124                 in->variant.fileVariant.fileSize = newSize;
5125         }
5126
5127                 
5128         
5129         /* Write a new object header.
5130          * show we've shrunk the file, if need be
5131          * Do this only if the file is not in the deleted directories.
5132          */
5133         if (in->parent &&
5134             in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5135             in->parent->objectId != YAFFS_OBJECTID_DELETED) {
5136                 yaffs_UpdateObjectHeader(in, NULL, 0,
5137                                          (newSize < oldFileSize) ? 1 : 0, 0);
5138         }
5139
5140         return YAFFS_OK;
5141 }
5142
5143 loff_t yaffs_GetFileSize(yaffs_Object * obj)
5144 {
5145         obj = yaffs_GetEquivalentObject(obj);
5146
5147         switch (obj->variantType) {
5148         case YAFFS_OBJECT_TYPE_FILE:
5149                 return obj->variant.fileVariant.fileSize;
5150         case YAFFS_OBJECT_TYPE_SYMLINK:
5151                 return yaffs_strlen(obj->variant.symLinkVariant.alias);
5152         default:
5153                 return 0;
5154         }
5155 }
5156
5157
5158
5159 int yaffs_FlushFile(yaffs_Object * in, int updateTime)
5160 {
5161         int retVal;
5162         if (in->dirty) {
5163                 yaffs_FlushFilesChunkCache(in);
5164                 if (updateTime) {
5165 #ifdef CONFIG_YAFFS_WINCE
5166                         yfsd_WinFileTimeNow(in->win_mtime);
5167 #else
5168
5169                         in->yst_mtime = Y_CURRENT_TIME;
5170
5171 #endif
5172                 }
5173
5174                 retVal =
5175                     (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5176                      0) ? YAFFS_OK : YAFFS_FAIL;
5177         } else {
5178                 retVal = YAFFS_OK;
5179         }
5180
5181         return retVal;
5182
5183 }
5184
5185 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in)
5186 {
5187
5188         /* First off, invalidate the file's data in the cache, without flushing. */
5189         yaffs_InvalidateWholeChunkCache(in);
5190
5191         if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5192                 /* Move to the unlinked directory so we have a record that it was deleted. */
5193                 yaffs_ChangeObjectName(in, in->myDev->deletedDir,_Y("deleted"), 0, 0);
5194
5195         }
5196
5197         yaffs_RemoveObjectFromDirectory(in);
5198         yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5199         in->hdrChunk = 0;
5200
5201         yaffs_FreeObject(in);
5202         return YAFFS_OK;
5203
5204 }
5205
5206 /* yaffs_DeleteFile deletes the whole file data
5207  * and the inode associated with the file.
5208  * It does not delete the links associated with the file.
5209  */
5210 static int yaffs_UnlinkFile(yaffs_Object * in)
5211 {
5212
5213         int retVal;
5214         int immediateDeletion = 0;
5215
5216 #ifdef __KERNEL__
5217         if (!in->myInode) {
5218                 immediateDeletion = 1;
5219         }
5220 #else
5221         if (in->inUse <= 0) {
5222                 immediateDeletion = 1;
5223         }
5224 #endif
5225
5226         if (immediateDeletion) {
5227                 retVal =
5228                     yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5229                                            _Y("deleted"), 0, 0);
5230                 T(YAFFS_TRACE_TRACING,
5231                   (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5232                    in->objectId));
5233                 in->deleted = 1;
5234                 in->myDev->nDeletedFiles++;
5235                 if (1 || in->myDev->isYaffs2) {
5236                         yaffs_ResizeFile(in, 0);
5237                 }
5238                 yaffs_SoftDeleteFile(in);
5239         } else {
5240                 retVal =
5241                     yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5242                                            _Y("unlinked"), 0, 0);
5243         }
5244
5245
5246         return retVal;
5247 }
5248
5249 int yaffs_DeleteFile(yaffs_Object * in)
5250 {
5251         int retVal = YAFFS_OK;
5252         int deleted = in->deleted;
5253         
5254         yaffs_ResizeFile(in,0);
5255
5256         if (in->nDataChunks > 0) {
5257                 /* Use soft deletion if there is data in the file.
5258                  * That won't be the case if it has been resized to zero.
5259                  */
5260                 if (!in->unlinked) {
5261                         retVal = yaffs_UnlinkFile(in);
5262                 }
5263                 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5264                         in->deleted = deleted = 1;
5265                         in->myDev->nDeletedFiles++;
5266                         yaffs_SoftDeleteFile(in);
5267                 }
5268                 return deleted ? YAFFS_OK : YAFFS_FAIL;
5269         } else {
5270                 /* The file has no data chunks so we toss it immediately */
5271                 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5272                 in->variant.fileVariant.top = NULL;
5273                 yaffs_DoGenericObjectDeletion(in);
5274
5275                 return YAFFS_OK;
5276         }
5277 }
5278
5279 static int yaffs_DeleteDirectory(yaffs_Object * in)
5280 {
5281         /* First check that the directory is empty. */
5282         if (ylist_empty(&in->variant.directoryVariant.children)) {
5283                 return yaffs_DoGenericObjectDeletion(in);
5284         }
5285
5286         return YAFFS_FAIL;
5287
5288 }
5289
5290 static int yaffs_DeleteSymLink(yaffs_Object * in)
5291 {
5292         YFREE(in->variant.symLinkVariant.alias);
5293
5294         return yaffs_DoGenericObjectDeletion(in);
5295 }
5296
5297 static int yaffs_DeleteHardLink(yaffs_Object * in)
5298 {
5299         /* remove this hardlink from the list assocaited with the equivalent
5300          * object
5301          */
5302         ylist_del_init(&in->hardLinks);
5303         return yaffs_DoGenericObjectDeletion(in);
5304 }
5305
5306 static void yaffs_DestroyObject(yaffs_Object * obj)
5307 {
5308         switch (obj->variantType) {
5309         case YAFFS_OBJECT_TYPE_FILE:
5310                 yaffs_DeleteFile(obj);
5311                 break;
5312         case YAFFS_OBJECT_TYPE_DIRECTORY:
5313                 yaffs_DeleteDirectory(obj);
5314                 break;
5315         case YAFFS_OBJECT_TYPE_SYMLINK:
5316                 yaffs_DeleteSymLink(obj);
5317                 break;
5318         case YAFFS_OBJECT_TYPE_HARDLINK:
5319                 yaffs_DeleteHardLink(obj);
5320                 break;
5321         case YAFFS_OBJECT_TYPE_SPECIAL:
5322                 yaffs_DoGenericObjectDeletion(obj);
5323                 break;
5324         case YAFFS_OBJECT_TYPE_UNKNOWN:
5325                 break;          /* should not happen. */
5326         }
5327 }
5328
5329 static int yaffs_UnlinkWorker(yaffs_Object * obj)
5330 {
5331
5332         if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5333                 return yaffs_DeleteHardLink(obj);
5334         } else if (!ylist_empty(&obj->hardLinks)) {
5335                 /* Curve ball: We're unlinking an object that has a hardlink.
5336                  *
5337                  * This problem arises because we are not strictly following
5338                  * The Linux link/inode model.
5339                  *
5340                  * We can't really delete the object.
5341                  * Instead, we do the following:
5342                  * - Select a hardlink.
5343                  * - Unhook it from the hard links
5344                  * - Unhook it from its parent directory (so that the rename can work)
5345                  * - Rename the object to the hardlink's name.
5346                  * - Delete the hardlink
5347                  */
5348
5349                 yaffs_Object *hl;
5350                 int retVal;
5351                 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5352
5353                 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5354
5355                 ylist_del_init(&hl->hardLinks);
5356                 ylist_del_init(&hl->siblings);
5357
5358                 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5359
5360                 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
5361
5362                 if (retVal == YAFFS_OK) {
5363                         retVal = yaffs_DoGenericObjectDeletion(hl);
5364                 }
5365                 return retVal;
5366
5367         } else {
5368                 switch (obj->variantType) {
5369                 case YAFFS_OBJECT_TYPE_FILE:
5370                         return yaffs_UnlinkFile(obj);
5371                         break;
5372                 case YAFFS_OBJECT_TYPE_DIRECTORY:
5373                         return yaffs_DeleteDirectory(obj);
5374                         break;
5375                 case YAFFS_OBJECT_TYPE_SYMLINK:
5376                         return yaffs_DeleteSymLink(obj);
5377                         break;
5378                 case YAFFS_OBJECT_TYPE_SPECIAL:
5379                         return yaffs_DoGenericObjectDeletion(obj);
5380                         break;
5381                 case YAFFS_OBJECT_TYPE_HARDLINK:
5382                 case YAFFS_OBJECT_TYPE_UNKNOWN:
5383                 default:
5384                         return YAFFS_FAIL;
5385                 }
5386         }
5387 }
5388
5389
5390 static int yaffs_UnlinkObject( yaffs_Object *obj)
5391 {
5392
5393         if (obj && obj->unlinkAllowed) {
5394                 return yaffs_UnlinkWorker(obj);
5395         }
5396
5397         return YAFFS_FAIL;
5398
5399 }
5400 int yaffs_Unlink(yaffs_Object * dir, const YCHAR * name)
5401 {
5402         yaffs_Object *obj;
5403
5404         obj = yaffs_FindObjectByName(dir, name);
5405         return yaffs_UnlinkObject(obj);
5406 }
5407
5408 /*----------------------- Initialisation Scanning ---------------------- */
5409
5410 static void yaffs_HandleShadowedObject(yaffs_Device * dev, int objId,
5411                                        int backwardScanning)
5412 {
5413         yaffs_Object *obj;
5414
5415         if (!backwardScanning) {
5416                 /* Handle YAFFS1 forward scanning case
5417                  * For YAFFS1 we always do the deletion
5418                  */
5419
5420         } else {
5421                 /* Handle YAFFS2 case (backward scanning)
5422                  * If the shadowed object exists then ignore.
5423                  */
5424                 if (yaffs_FindObjectByNumber(dev, objId)) {
5425                         return;
5426                 }
5427         }
5428
5429         /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5430          * We put it in unlinked dir to be cleaned up after the scanning
5431          */
5432         obj =
5433             yaffs_FindOrCreateObjectByNumber(dev, objId,
5434                                              YAFFS_OBJECT_TYPE_FILE);
5435         if (!obj)
5436                 return;
5437         yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5438         obj->variant.fileVariant.shrinkSize = 0;
5439         obj->valid = 1;         /* So that we don't read any other info for this file */
5440
5441 }
5442
5443 typedef struct {
5444         int seq;
5445         int block;
5446 } yaffs_BlockIndex;
5447
5448
5449 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5450 {
5451         yaffs_Object *hl;
5452         yaffs_Object *in;
5453         
5454         while (hardList) {
5455                 hl = hardList;
5456                 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5457
5458                 in = yaffs_FindObjectByNumber(dev,
5459                                               hl->variant.hardLinkVariant.
5460                                               equivalentObjectId);
5461
5462                 if (in) {
5463                         /* Add the hardlink pointers */
5464                         hl->variant.hardLinkVariant.equivalentObject = in;
5465                         ylist_add(&hl->hardLinks, &in->hardLinks);
5466                 } else {
5467                         /* Todo Need to report/handle this better.
5468                          * Got a problem... hardlink to a non-existant object
5469                          */
5470                         hl->variant.hardLinkVariant.equivalentObject = NULL;
5471                         YINIT_LIST_HEAD(&hl->hardLinks);
5472
5473                 }
5474
5475         }
5476
5477 }
5478
5479
5480
5481
5482
5483 static int ybicmp(const void *a, const void *b){
5484     register int aseq = ((yaffs_BlockIndex *)a)->seq;
5485     register int bseq = ((yaffs_BlockIndex *)b)->seq;
5486     register int ablock = ((yaffs_BlockIndex *)a)->block;
5487     register int bblock = ((yaffs_BlockIndex *)b)->block;
5488     if( aseq == bseq )
5489         return ablock - bblock;
5490     else
5491         return aseq - bseq;
5492
5493 }
5494
5495
5496 struct yaffs_ShadowFixerStruct {
5497         int objectId;
5498         int shadowedId;
5499         struct yaffs_ShadowFixerStruct *next;
5500 };
5501
5502
5503 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5504 {
5505         /*
5506         *  Sort out state of unlinked and deleted objects after scanning.
5507         */
5508         struct ylist_head *i;
5509         struct ylist_head *n;
5510         yaffs_Object *l;
5511
5512         /* Soft delete all the unlinked files */
5513         ylist_for_each_safe(i, n,
5514                 &dev->unlinkedDir->variant.directoryVariant.children) {
5515                 if (i) {
5516                         l = ylist_entry(i, yaffs_Object, siblings);
5517                         yaffs_DestroyObject(l);
5518                 }
5519         }
5520         
5521         ylist_for_each_safe(i, n,
5522                 &dev->deletedDir->variant.directoryVariant.children) {
5523                 if (i) {
5524                         l = ylist_entry(i, yaffs_Object, siblings);
5525                         yaffs_DestroyObject(l);
5526                 }
5527         }
5528
5529 }
5530
5531 static int yaffs_Scan(yaffs_Device * dev)
5532 {
5533         yaffs_ExtendedTags tags;
5534         int blk;
5535         int blockIterator;
5536         int startIterator;
5537         int endIterator;
5538         int result;
5539
5540         int chunk;
5541         int c;
5542         int deleted;
5543         yaffs_BlockState state;
5544         yaffs_Object *hardList = NULL;
5545         yaffs_BlockInfo *bi;
5546         __u32 sequenceNumber;
5547         yaffs_ObjectHeader *oh;
5548         yaffs_Object *in;
5549         yaffs_Object *parent;
5550         
5551         int alloc_failed = 0;
5552         
5553         struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5554         
5555
5556         __u8 *chunkData;
5557
5558         
5559         
5560         T(YAFFS_TRACE_SCAN,
5561           (TSTR("yaffs_Scan starts  intstartblk %d intendblk %d..." TENDSTR),
5562            dev->internalStartBlock, dev->internalEndBlock));
5563
5564         chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5565
5566         dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5567
5568         /* Scan all the blocks to determine their state */
5569         for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5570                 bi = yaffs_GetBlockInfo(dev, blk);
5571                 yaffs_ClearChunkBits(dev, blk);
5572                 bi->pagesInUse = 0;
5573                 bi->softDeletions = 0;
5574
5575                 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5576
5577                 bi->blockState = state;
5578                 bi->sequenceNumber = sequenceNumber;
5579
5580                 if(bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
5581                         bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
5582
5583                 T(YAFFS_TRACE_SCAN_DEBUG,
5584                   (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5585                    state, sequenceNumber));
5586
5587                 if (state == YAFFS_BLOCK_STATE_DEAD) {
5588                         T(YAFFS_TRACE_BAD_BLOCKS,
5589                           (TSTR("block %d is bad" TENDSTR), blk));
5590                 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5591                         T(YAFFS_TRACE_SCAN_DEBUG,
5592                           (TSTR("Block empty " TENDSTR)));
5593                         dev->nErasedBlocks++;
5594                         dev->nFreeChunks += dev->nChunksPerBlock;
5595                 } 
5596         }
5597
5598         startIterator = dev->internalStartBlock;
5599         endIterator = dev->internalEndBlock;
5600
5601         /* For each block.... */
5602         for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5603              blockIterator++) {
5604                 
5605                 YYIELD();
5606
5607                 YYIELD();
5608                 
5609                 blk = blockIterator;
5610
5611                 bi = yaffs_GetBlockInfo(dev, blk);
5612                 state = bi->blockState;
5613
5614                 deleted = 0;
5615
5616                 /* For each chunk in each block that needs scanning....*/
5617                 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5618                      state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5619                         /* Read the tags and decide what to do */
5620                         chunk = blk * dev->nChunksPerBlock + c;
5621
5622                         result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5623                                                         &tags);
5624
5625                         /* Let's have a good look at this chunk... */
5626
5627                         if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
5628                                 /* YAFFS1 only...
5629                                  * A deleted chunk
5630                                  */
5631                                 deleted++;
5632                                 dev->nFreeChunks++;
5633                                 /*T((" %d %d deleted\n",blk,c)); */
5634                         } else if (!tags.chunkUsed) {
5635                                 /* An unassigned chunk in the block
5636                                  * This means that either the block is empty or 
5637                                  * this is the one being allocated from
5638                                  */
5639
5640                                 if (c == 0) {
5641                                         /* We're looking at the first chunk in the block so the block is unused */
5642                                         state = YAFFS_BLOCK_STATE_EMPTY;
5643                                         dev->nErasedBlocks++;
5644                                 } else {
5645                                         /* this is the block being allocated from */
5646                                         T(YAFFS_TRACE_SCAN,
5647                                           (TSTR
5648                                            (" Allocating from %d %d" TENDSTR),
5649                                            blk, c));
5650                                         state = YAFFS_BLOCK_STATE_ALLOCATING;
5651                                         dev->allocationBlock = blk;
5652                                         dev->allocationPage = c;
5653                                         dev->allocationBlockFinder = blk;       
5654                                         /* Set it to here to encourage the allocator to go forth from here. */
5655                                         
5656                                 }
5657
5658                                 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5659                         } else if (tags.chunkId > 0) {
5660                                 /* chunkId > 0 so it is a data chunk... */
5661                                 unsigned int endpos;
5662
5663                                 yaffs_SetChunkBit(dev, blk, c);
5664                                 bi->pagesInUse++;
5665
5666                                 in = yaffs_FindOrCreateObjectByNumber(dev,
5667                                                                       tags.
5668                                                                       objectId,
5669                                                                       YAFFS_OBJECT_TYPE_FILE);
5670                                 /* PutChunkIntoFile checks for a clash (two data chunks with
5671                                  * the same chunkId).
5672                                  */
5673                                  
5674                                 if(!in)
5675                                         alloc_failed = 1;
5676
5677                                 if(in){
5678                                         if(!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk,1))
5679                                                 alloc_failed = 1;
5680                                 }
5681                                 
5682                                 endpos =
5683                                     (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5684                                     tags.byteCount;
5685                                 if (in && 
5686                                     in->variantType == YAFFS_OBJECT_TYPE_FILE
5687                                     && in->variant.fileVariant.scannedFileSize <
5688                                     endpos) {
5689                                         in->variant.fileVariant.
5690                                             scannedFileSize = endpos;
5691                                         if (!dev->useHeaderFileSize) {
5692                                                 in->variant.fileVariant.
5693                                                     fileSize =
5694                                                     in->variant.fileVariant.
5695                                                     scannedFileSize;
5696                                         }
5697
5698                                 }
5699                                 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));   */
5700                         } else {
5701                                 /* chunkId == 0, so it is an ObjectHeader.
5702                                  * Thus, we read in the object header and make the object
5703                                  */
5704                                 yaffs_SetChunkBit(dev, blk, c);
5705                                 bi->pagesInUse++;
5706
5707                                 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5708                                                                 chunkData,
5709                                                                 NULL);
5710
5711                                 oh = (yaffs_ObjectHeader *) chunkData;
5712
5713                                 in = yaffs_FindObjectByNumber(dev,
5714                                                               tags.objectId);
5715                                 if (in && in->variantType != oh->type) {
5716                                         /* This should not happen, but somehow
5717                                          * Wev'e ended up with an objectId that has been reused but not yet 
5718                                          * deleted, and worse still it has changed type. Delete the old object.
5719                                          */
5720
5721                                         yaffs_DestroyObject(in);
5722
5723                                         in = 0;
5724                                 }
5725
5726                                 in = yaffs_FindOrCreateObjectByNumber(dev,
5727                                                                       tags.
5728                                                                       objectId,
5729                                                                       oh->type);
5730
5731                                 if(!in)
5732                                         alloc_failed = 1;
5733                                         
5734                                 if (in && oh->shadowsObject > 0) {
5735                                 
5736                                         struct yaffs_ShadowFixerStruct *fixer;
5737                                         fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
5738                                         if(fixer){
5739                                                 fixer-> next = shadowFixerList;
5740                                                 shadowFixerList = fixer;
5741                                                 fixer->objectId = tags.objectId;
5742                                                 fixer->shadowedId = oh->shadowsObject;
5743                                         }
5744                                         
5745                                 }
5746
5747                                 if (in && in->valid) {
5748                                         /* We have already filled this one. We have a duplicate and need to resolve it. */
5749
5750                                         unsigned existingSerial = in->serial;
5751                                         unsigned newSerial = tags.serialNumber;
5752
5753                                         if (((existingSerial + 1) & 3) == newSerial) {
5754                                                 /* Use new one - destroy the exisiting one */
5755                                                 yaffs_DeleteChunk(dev,
5756                                                                   in->hdrChunk,
5757                                                                   1, __LINE__);
5758                                                 in->valid = 0;
5759                                         } else {
5760                                                 /* Use existing - destroy this one. */
5761                                                 yaffs_DeleteChunk(dev, chunk, 1,
5762                                                                   __LINE__);
5763                                         }
5764                                 }
5765
5766                                 if (in && !in->valid &&
5767                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
5768                                      tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5769                                         /* We only load some info, don't fiddle with directory structure */
5770                                         in->valid = 1;
5771                                         in->variantType = oh->type;
5772
5773                                         in->yst_mode = oh->yst_mode;
5774 #ifdef CONFIG_YAFFS_WINCE
5775                                         in->win_atime[0] = oh->win_atime[0];
5776                                         in->win_ctime[0] = oh->win_ctime[0];
5777                                         in->win_mtime[0] = oh->win_mtime[0];
5778                                         in->win_atime[1] = oh->win_atime[1];
5779                                         in->win_ctime[1] = oh->win_ctime[1];
5780                                         in->win_mtime[1] = oh->win_mtime[1];
5781 #else
5782                                         in->yst_uid = oh->yst_uid;
5783                                         in->yst_gid = oh->yst_gid;
5784                                         in->yst_atime = oh->yst_atime;
5785                                         in->yst_mtime = oh->yst_mtime;
5786                                         in->yst_ctime = oh->yst_ctime;
5787                                         in->yst_rdev = oh->yst_rdev;
5788 #endif
5789                                         in->hdrChunk = chunk;
5790                                         in->serial = tags.serialNumber;
5791
5792                                 } else if (in && !in->valid) {
5793                                         /* we need to load this info */
5794
5795                                         in->valid = 1;
5796                                         in->variantType = oh->type;
5797
5798                                         in->yst_mode = oh->yst_mode;
5799 #ifdef CONFIG_YAFFS_WINCE
5800                                         in->win_atime[0] = oh->win_atime[0];
5801                                         in->win_ctime[0] = oh->win_ctime[0];
5802                                         in->win_mtime[0] = oh->win_mtime[0];
5803                                         in->win_atime[1] = oh->win_atime[1];
5804                                         in->win_ctime[1] = oh->win_ctime[1];
5805                                         in->win_mtime[1] = oh->win_mtime[1];
5806 #else
5807                                         in->yst_uid = oh->yst_uid;
5808                                         in->yst_gid = oh->yst_gid;
5809                                         in->yst_atime = oh->yst_atime;
5810                                         in->yst_mtime = oh->yst_mtime;
5811                                         in->yst_ctime = oh->yst_ctime;
5812                                         in->yst_rdev = oh->yst_rdev;
5813 #endif
5814                                         in->hdrChunk = chunk;
5815                                         in->serial = tags.serialNumber;
5816
5817                                         yaffs_SetObjectName(in, oh->name);
5818                                         in->dirty = 0;
5819
5820                                         /* directory stuff...
5821                                          * hook up to parent
5822                                          */
5823
5824                                         parent =
5825                                             yaffs_FindOrCreateObjectByNumber
5826                                             (dev, oh->parentObjectId,
5827                                              YAFFS_OBJECT_TYPE_DIRECTORY);
5828                                         if(!parent)
5829                                                 alloc_failed = 1;
5830                                         if (parent && parent->variantType ==
5831                                             YAFFS_OBJECT_TYPE_UNKNOWN) {
5832                                                 /* Set up as a directory */
5833                                                 parent->variantType =
5834                                                     YAFFS_OBJECT_TYPE_DIRECTORY;
5835                                                 YINIT_LIST_HEAD(&parent->variant.
5836                                                                directoryVariant.
5837                                                                children);
5838                                         } else if (!parent || parent->variantType !=
5839                                                    YAFFS_OBJECT_TYPE_DIRECTORY)
5840                                         {
5841                                                 /* Hoosterman, another problem....
5842                                                  * We're trying to use a non-directory as a directory
5843                                                  */
5844
5845                                                 T(YAFFS_TRACE_ERROR,
5846                                                   (TSTR
5847                                                    ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
5848                                                     TENDSTR)));
5849                                                 parent = dev->lostNFoundDir;
5850                                         }
5851
5852                                         yaffs_AddObjectToDirectory(parent, in);
5853
5854                                         if (0 && (parent == dev->deletedDir ||
5855                                                   parent == dev->unlinkedDir)) {
5856                                                 in->deleted = 1;        /* If it is unlinked at start up then it wants deleting */
5857                                                 dev->nDeletedFiles++;
5858                                         }
5859                                         /* Note re hardlinks.
5860                                          * Since we might scan a hardlink before its equivalent object is scanned
5861                                          * we put them all in a list.
5862                                          * After scanning is complete, we should have all the objects, so we run through this
5863                                          * list and fix up all the chains.              
5864                                          */
5865
5866                                         switch (in->variantType) {
5867                                         case YAFFS_OBJECT_TYPE_UNKNOWN: 
5868                                                 /* Todo got a problem */
5869                                                 break;
5870                                         case YAFFS_OBJECT_TYPE_FILE:
5871                                                 if (dev->useHeaderFileSize)
5872
5873                                                         in->variant.fileVariant.
5874                                                             fileSize =
5875                                                             oh->fileSize;
5876
5877                                                 break;
5878                                         case YAFFS_OBJECT_TYPE_HARDLINK:
5879                                                 in->variant.hardLinkVariant.
5880                                                     equivalentObjectId =
5881                                                     oh->equivalentObjectId;
5882                                                 in->hardLinks.next =
5883                                                     (struct ylist_head *)
5884                                                     hardList;
5885                                                 hardList = in;
5886                                                 break;
5887                                         case YAFFS_OBJECT_TYPE_DIRECTORY:
5888                                                 /* Do nothing */
5889                                                 break;
5890                                         case YAFFS_OBJECT_TYPE_SPECIAL:
5891                                                 /* Do nothing */
5892                                                 break;
5893                                         case YAFFS_OBJECT_TYPE_SYMLINK: 
5894                                                 in->variant.symLinkVariant.alias =
5895                                                     yaffs_CloneString(oh->alias);
5896                                                 if(!in->variant.symLinkVariant.alias)
5897                                                         alloc_failed = 1;
5898                                                 break;
5899                                         }
5900
5901 /*
5902                                         if (parent == dev->deletedDir) {
5903                                                 yaffs_DestroyObject(in);
5904                                                 bi->hasShrinkHeader = 1;
5905                                         }
5906 */
5907                                 }
5908                         }
5909                 }
5910
5911                 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
5912                         /* If we got this far while scanning, then the block is fully allocated.*/
5913                         state = YAFFS_BLOCK_STATE_FULL;
5914                 }
5915
5916                 bi->blockState = state;
5917
5918                 /* Now let's see if it was dirty */
5919                 if (bi->pagesInUse == 0 &&
5920                     !bi->hasShrinkHeader &&
5921                     bi->blockState == YAFFS_BLOCK_STATE_FULL) {
5922                         yaffs_BlockBecameDirty(dev, blk);
5923                 }
5924
5925         }
5926
5927         
5928         /* Ok, we've done all the scanning.
5929          * Fix up the hard link chains.
5930          * We should now have scanned all the objects, now it's time to add these 
5931          * hardlinks.
5932          */
5933
5934         yaffs_HardlinkFixup(dev,hardList);
5935         
5936         /* Fix up any shadowed objects */
5937         {
5938                 struct yaffs_ShadowFixerStruct *fixer;
5939                 yaffs_Object *obj;
5940                 
5941                 while(shadowFixerList){
5942                         fixer = shadowFixerList;
5943                         shadowFixerList = fixer->next;
5944                         /* Complete the rename transaction by deleting the shadowed object
5945                          * then setting the object header to unshadowed.
5946                          */
5947                         obj = yaffs_FindObjectByNumber(dev,fixer->shadowedId);
5948                         if(obj)
5949                                 yaffs_DestroyObject(obj);
5950         
5951                         obj = yaffs_FindObjectByNumber(dev,fixer->objectId);
5952                         if(obj){
5953                                 yaffs_UpdateObjectHeader(obj,NULL,1,0,0);
5954                         }
5955                         
5956                         YFREE(fixer);
5957                 }
5958         }
5959
5960         yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
5961
5962         if(alloc_failed){
5963                 return YAFFS_FAIL;
5964         }
5965         
5966         T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
5967         
5968
5969         return YAFFS_OK;
5970 }
5971
5972 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
5973 {
5974         __u8 *chunkData;
5975         yaffs_ObjectHeader *oh;
5976         yaffs_Device *dev;
5977         yaffs_ExtendedTags tags;
5978         int result;
5979         int alloc_failed = 0;
5980
5981         if(!in)
5982                 return;
5983                 
5984         dev = in->myDev;
5985                 
5986 #if 0
5987         T(YAFFS_TRACE_SCAN,(TSTR("details for object %d %s loaded" TENDSTR),
5988                 in->objectId,
5989                 in->lazyLoaded ? "not yet" : "already"));
5990 #endif
5991
5992         if(in->lazyLoaded && in->hdrChunk > 0){
5993                 in->lazyLoaded = 0;
5994                 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5995
5996                 result = yaffs_ReadChunkWithTagsFromNAND(dev,in->hdrChunk,chunkData,&tags);
5997                 oh = (yaffs_ObjectHeader *) chunkData;
5998
5999                 in->yst_mode = oh->yst_mode;
6000 #ifdef CONFIG_YAFFS_WINCE
6001                 in->win_atime[0] = oh->win_atime[0];
6002                 in->win_ctime[0] = oh->win_ctime[0];
6003                 in->win_mtime[0] = oh->win_mtime[0];
6004                 in->win_atime[1] = oh->win_atime[1];
6005                 in->win_ctime[1] = oh->win_ctime[1];
6006                 in->win_mtime[1] = oh->win_mtime[1];
6007 #else
6008                 in->yst_uid = oh->yst_uid;
6009                 in->yst_gid = oh->yst_gid;
6010                 in->yst_atime = oh->yst_atime;
6011                 in->yst_mtime = oh->yst_mtime;
6012                 in->yst_ctime = oh->yst_ctime;
6013                 in->yst_rdev = oh->yst_rdev;
6014                 
6015 #endif
6016                 yaffs_SetObjectName(in, oh->name);
6017                 
6018                 if(in->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
6019                          in->variant.symLinkVariant.alias =
6020                                                     yaffs_CloneString(oh->alias);
6021                         if(!in->variant.symLinkVariant.alias)
6022                                 alloc_failed = 1; /* Not returned to caller */
6023                 }
6024                                                     
6025                 yaffs_ReleaseTempBuffer(dev,chunkData, __LINE__);
6026         }
6027 }
6028
6029 static int yaffs_ScanBackwards(yaffs_Device * dev)
6030 {
6031         yaffs_ExtendedTags tags;
6032         int blk;
6033         int blockIterator;
6034         int startIterator;
6035         int endIterator;
6036         int nBlocksToScan = 0;
6037
6038         int chunk;
6039         int result;
6040         int c;
6041         int deleted;
6042         yaffs_BlockState state;
6043         yaffs_Object *hardList = NULL;
6044         yaffs_BlockInfo *bi;
6045         __u32 sequenceNumber;
6046         yaffs_ObjectHeader *oh;
6047         yaffs_Object *in;
6048         yaffs_Object *parent;
6049         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6050         int itsUnlinked;
6051         __u8 *chunkData;
6052         
6053         int fileSize;
6054         int isShrink;
6055         int foundChunksInBlock;
6056         int equivalentObjectId;
6057         int alloc_failed = 0;
6058         
6059
6060         yaffs_BlockIndex *blockIndex = NULL;
6061         int altBlockIndex = 0;
6062
6063         if (!dev->isYaffs2) {
6064                 T(YAFFS_TRACE_SCAN,
6065                   (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6066                 return YAFFS_FAIL;
6067         }
6068
6069         T(YAFFS_TRACE_SCAN,
6070           (TSTR
6071            ("yaffs_ScanBackwards starts  intstartblk %d intendblk %d..."
6072             TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6073
6074
6075         dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6076
6077         blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6078         
6079         if(!blockIndex) {
6080                 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6081                 altBlockIndex = 1;
6082         }
6083         
6084         if(!blockIndex) {
6085                 T(YAFFS_TRACE_SCAN,
6086                   (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6087                 return YAFFS_FAIL;
6088         }
6089         
6090         dev->blocksInCheckpoint = 0;
6091         
6092         chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6093
6094         /* Scan all the blocks to determine their state */
6095         for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6096                 bi = yaffs_GetBlockInfo(dev, blk);
6097                 yaffs_ClearChunkBits(dev, blk);
6098                 bi->pagesInUse = 0;
6099                 bi->softDeletions = 0;
6100
6101                 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6102
6103                 bi->blockState = state;
6104                 bi->sequenceNumber = sequenceNumber;
6105
6106                 if(bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6107                         bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6108                 if(bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6109                         bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6110                         
6111                 T(YAFFS_TRACE_SCAN_DEBUG,
6112                   (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6113                    state, sequenceNumber));
6114
6115                 
6116                 if(state == YAFFS_BLOCK_STATE_CHECKPOINT){
6117                         dev->blocksInCheckpoint++;
6118                         
6119                 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6120                         T(YAFFS_TRACE_BAD_BLOCKS,
6121                           (TSTR("block %d is bad" TENDSTR), blk));
6122                 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6123                         T(YAFFS_TRACE_SCAN_DEBUG,
6124                           (TSTR("Block empty " TENDSTR)));
6125                         dev->nErasedBlocks++;
6126                         dev->nFreeChunks += dev->nChunksPerBlock;
6127                 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6128
6129                         /* Determine the highest sequence number */
6130                         if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6131                             sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6132
6133                                 blockIndex[nBlocksToScan].seq = sequenceNumber;
6134                                 blockIndex[nBlocksToScan].block = blk;
6135
6136                                 nBlocksToScan++;
6137
6138                                 if (sequenceNumber >= dev->sequenceNumber) {
6139                                         dev->sequenceNumber = sequenceNumber;
6140                                 }
6141                         } else {
6142                                 /* TODO: Nasty sequence number! */
6143                                 T(YAFFS_TRACE_SCAN,
6144                                   (TSTR
6145                                    ("Block scanning block %d has bad sequence number %d"
6146                                     TENDSTR), blk, sequenceNumber));
6147
6148                         }
6149                 }
6150         }
6151
6152         T(YAFFS_TRACE_SCAN,
6153         (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6154
6155
6156
6157         YYIELD();
6158
6159         /* Sort the blocks */
6160 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6161         {
6162                 /* Use qsort now. */
6163                 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6164         }
6165 #else
6166         {
6167                 /* Dungy old bubble sort... */
6168                 
6169                 yaffs_BlockIndex temp;
6170                 int i;
6171                 int j;
6172
6173                 for (i = 0; i < nBlocksToScan; i++)
6174                         for (j = i + 1; j < nBlocksToScan; j++)
6175                                 if (blockIndex[i].seq > blockIndex[j].seq) {
6176                                         temp = blockIndex[j];
6177                                         blockIndex[j] = blockIndex[i];
6178                                         blockIndex[i] = temp;
6179                                 }
6180         }
6181 #endif
6182
6183         YYIELD();
6184
6185         T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6186
6187         /* Now scan the blocks looking at the data. */
6188         startIterator = 0;
6189         endIterator = nBlocksToScan - 1;
6190         T(YAFFS_TRACE_SCAN_DEBUG,
6191           (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6192
6193         /* For each block.... backwards */
6194         for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6195              blockIterator--) {
6196                 /* Cooperative multitasking! This loop can run for so
6197                    long that watchdog timers expire. */
6198                 YYIELD();
6199
6200                 /* get the block to scan in the correct order */
6201                 blk = blockIndex[blockIterator].block;
6202
6203                 bi = yaffs_GetBlockInfo(dev, blk);
6204                 
6205                 
6206                 state = bi->blockState;
6207
6208                 deleted = 0;
6209
6210                 /* For each chunk in each block that needs scanning.... */
6211                 foundChunksInBlock = 0;
6212                 for (c = dev->nChunksPerBlock - 1; 
6213                      !alloc_failed && c >= 0 &&
6214                      (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6215                       state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6216                         /* Scan backwards... 
6217                          * Read the tags and decide what to do
6218                          */
6219                         
6220                         chunk = blk * dev->nChunksPerBlock + c;
6221
6222                         result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6223                                                         &tags);
6224
6225                         /* Let's have a good look at this chunk... */
6226
6227                         if (!tags.chunkUsed) {
6228                                 /* An unassigned chunk in the block.
6229                                  * If there are used chunks after this one, then
6230                                  * it is a chunk that was skipped due to failing the erased
6231                                  * check. Just skip it so that it can be deleted.
6232                                  * But, more typically, We get here when this is an unallocated
6233                                  * chunk and his means that either the block is empty or 
6234                                  * this is the one being allocated from
6235                                  */
6236
6237                                 if(foundChunksInBlock)
6238                                 {
6239                                         /* This is a chunk that was skipped due to failing the erased check */
6240                                         
6241                                 } else if (c == 0) {
6242                                         /* We're looking at the first chunk in the block so the block is unused */
6243                                         state = YAFFS_BLOCK_STATE_EMPTY;
6244                                         dev->nErasedBlocks++;
6245                                 } else {
6246                                         if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6247                                             state == YAFFS_BLOCK_STATE_ALLOCATING) {
6248                                                 if(dev->sequenceNumber == bi->sequenceNumber) {
6249                                                         /* this is the block being allocated from */
6250                                                 
6251                                                         T(YAFFS_TRACE_SCAN,
6252                                                           (TSTR
6253                                                            (" Allocating from %d %d"
6254                                                             TENDSTR), blk, c));
6255
6256                                                         state = YAFFS_BLOCK_STATE_ALLOCATING;
6257                                                         dev->allocationBlock = blk;
6258                                                         dev->allocationPage = c;
6259                                                         dev->allocationBlockFinder = blk;       
6260                                                 }
6261                                                 else {
6262                                                         /* This is a partially written block that is not
6263                                                          * the current allocation block. This block must have
6264                                                          * had a write failure, so set up for retirement.
6265                                                          */
6266                                                   
6267                                                          /* bi->needsRetiring = 1; ??? TODO */
6268                                                          bi->gcPrioritise = 1;
6269                                                                                                          
6270                                                          T(YAFFS_TRACE_ALWAYS,
6271                                                          (TSTR("Partially written block %d detected" TENDSTR),
6272                                                          blk));
6273                                                 }
6274
6275                                         }
6276                                          
6277                                 }
6278
6279                                 dev->nFreeChunks++;
6280                                 
6281                         } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED){
6282                                 T(YAFFS_TRACE_SCAN,
6283                                   (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
6284                                   blk, c));
6285
6286                                   dev->nFreeChunks++;
6287
6288                         }else if (tags.chunkId > 0) {
6289                                 /* chunkId > 0 so it is a data chunk... */
6290                                 unsigned int endpos;
6291                                 __u32 chunkBase =
6292                                     (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6293                                                                 
6294                                 foundChunksInBlock = 1;
6295
6296
6297                                 yaffs_SetChunkBit(dev, blk, c);
6298                                 bi->pagesInUse++;
6299
6300                                 in = yaffs_FindOrCreateObjectByNumber(dev,
6301                                                                       tags.
6302                                                                       objectId,
6303                                                                       YAFFS_OBJECT_TYPE_FILE);
6304                                 if(!in){
6305                                         /* Out of memory */
6306                                         alloc_failed = 1;
6307                                 }
6308                                 
6309                                 if (in &&
6310                                     in->variantType == YAFFS_OBJECT_TYPE_FILE
6311                                     && chunkBase <
6312                                     in->variant.fileVariant.shrinkSize) {
6313                                         /* This has not been invalidated by a resize */
6314                                         if(!yaffs_PutChunkIntoFile(in, tags.chunkId,
6315                                                                chunk, -1)){
6316                                                 alloc_failed = 1;
6317                                         }
6318
6319                                         /* File size is calculated by looking at the data chunks if we have not 
6320                                          * seen an object header yet. Stop this practice once we find an object header.
6321                                          */
6322                                         endpos =
6323                                             (tags.chunkId -
6324                                              1) * dev->nDataBytesPerChunk +
6325                                             tags.byteCount;
6326                                             
6327                                         if (!in->valid &&       /* have not got an object header yet */
6328                                             in->variant.fileVariant.
6329                                             scannedFileSize < endpos) {
6330                                                 in->variant.fileVariant.
6331                                                     scannedFileSize = endpos;
6332                                                 in->variant.fileVariant.
6333                                                     fileSize =
6334                                                     in->variant.fileVariant.
6335                                                     scannedFileSize;
6336                                         }
6337
6338                                 } else if(in) {
6339                                         /* This chunk has been invalidated by a resize, so delete */
6340                                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6341
6342                                 }
6343                         } else {
6344                                 /* chunkId == 0, so it is an ObjectHeader.
6345                                  * Thus, we read in the object header and make the object
6346                                  */
6347                                 foundChunksInBlock = 1;
6348
6349                                 yaffs_SetChunkBit(dev, blk, c);
6350                                 bi->pagesInUse++;
6351
6352                                 oh = NULL;
6353                                 in = NULL;
6354
6355                                 if (tags.extraHeaderInfoAvailable) {
6356                                         in = yaffs_FindOrCreateObjectByNumber
6357                                             (dev, tags.objectId,
6358                                              tags.extraObjectType);
6359                                         if (!in)
6360                                                 alloc_failed = 1;
6361                                 }
6362
6363                                 if (!in ||
6364 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
6365                                     !in->valid ||
6366 #endif
6367                                     tags.extraShadows ||
6368                                     (!in->valid &&
6369                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
6370                                      tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))
6371                                     ) {
6372
6373                                         /* If we don't have  valid info then we need to read the chunk
6374                                          * TODO In future we can probably defer reading the chunk and 
6375                                          * living with invalid data until needed.
6376                                          */
6377
6378                                         result = yaffs_ReadChunkWithTagsFromNAND(dev,
6379                                                                         chunk,
6380                                                                         chunkData,
6381                                                                         NULL);
6382
6383                                         oh = (yaffs_ObjectHeader *) chunkData;
6384                                         
6385                                         if(dev->inbandTags){
6386                                                 /* Fix up the header if they got corrupted by inband tags */
6387                                                 oh->shadowsObject = oh->inbandShadowsObject;
6388                                                 oh->isShrink = oh->inbandIsShrink;
6389                                         }
6390
6391                                         if (!in) {
6392                                                 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6393                                                 if (!in)
6394                                                         alloc_failed = 1;
6395                                         }
6396
6397                                 }
6398
6399                                 if (!in) {
6400                                         /* TODO Hoosterman we have a problem! */
6401                                         T(YAFFS_TRACE_ERROR,
6402                                           (TSTR
6403                                            ("yaffs tragedy: Could not make object for object  %d at chunk %d during scan"
6404                                             TENDSTR), tags.objectId, chunk));
6405                                         continue;
6406                                 }
6407
6408                                 if (in->valid) {
6409                                         /* We have already filled this one.
6410                                          * We have a duplicate that will be discarded, but 
6411                                          * we first have to suck out resize info if it is a file.
6412                                          */
6413
6414                                         if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) && 
6415                                              ((oh && 
6416                                                oh-> type == YAFFS_OBJECT_TYPE_FILE)||
6417                                               (tags.extraHeaderInfoAvailable  &&
6418                                                tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))
6419                                             ) {
6420                                                 __u32 thisSize =
6421                                                     (oh) ? oh->fileSize : tags.
6422                                                     extraFileLength;
6423                                                 __u32 parentObjectId =
6424                                                     (oh) ? oh->
6425                                                     parentObjectId : tags.
6426                                                     extraParentObjectId;
6427                                                 
6428                                                 
6429                                                 isShrink =
6430                                                     (oh) ? oh->isShrink : tags.
6431                                                     extraIsShrinkHeader;
6432
6433                                                 /* If it is deleted (unlinked at start also means deleted)
6434                                                  * we treat the file size as being zeroed at this point.
6435                                                  */
6436                                                 if (parentObjectId ==
6437                                                     YAFFS_OBJECTID_DELETED
6438                                                     || parentObjectId ==
6439                                                     YAFFS_OBJECTID_UNLINKED) {
6440                                                         thisSize = 0;
6441                                                         isShrink = 1;
6442                                                 }
6443
6444                                                 if (isShrink &&
6445                                                     in->variant.fileVariant.
6446                                                     shrinkSize > thisSize) {
6447                                                         in->variant.fileVariant.
6448                                                             shrinkSize =
6449                                                             thisSize;
6450                                                 }
6451
6452                                                 if (isShrink) {
6453                                                         bi->hasShrinkHeader = 1;
6454                                                 }
6455
6456                                         }
6457                                         /* Use existing - destroy this one. */
6458                                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6459
6460                                 }
6461
6462                                 if (!in->valid && in->variantType !=
6463                                     (oh ? oh->type : tags.extraObjectType))
6464                                         T(YAFFS_TRACE_ERROR, (TSTR
6465                                            ("yaffs tragedy: Bad object type, "
6466                                             "%d != %d, for object %d at chunk "
6467                                             "%d during scan" TENDSTR), oh ?
6468                                             oh->type : tags.extraObjectType,
6469                                             in->variantType, tags.objectId,
6470                                             chunk));
6471
6472                                 if (!in->valid &&
6473                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
6474                                      tags.objectId ==
6475                                      YAFFS_OBJECTID_LOSTNFOUND)) {
6476                                         /* We only load some info, don't fiddle with directory structure */
6477                                         in->valid = 1;
6478                                         
6479                                         if(oh) {
6480                                                 in->variantType = oh->type;
6481
6482                                                 in->yst_mode = oh->yst_mode;
6483 #ifdef CONFIG_YAFFS_WINCE
6484                                                 in->win_atime[0] = oh->win_atime[0];
6485                                                 in->win_ctime[0] = oh->win_ctime[0];
6486                                                 in->win_mtime[0] = oh->win_mtime[0];
6487                                                 in->win_atime[1] = oh->win_atime[1];
6488                                                 in->win_ctime[1] = oh->win_ctime[1];
6489                                                 in->win_mtime[1] = oh->win_mtime[1];
6490 #else
6491                                                 in->yst_uid = oh->yst_uid;
6492                                                 in->yst_gid = oh->yst_gid;
6493                                                 in->yst_atime = oh->yst_atime;
6494                                                 in->yst_mtime = oh->yst_mtime;
6495                                                 in->yst_ctime = oh->yst_ctime;
6496                                                 in->yst_rdev = oh->yst_rdev;
6497                 
6498 #endif
6499                                         } else {
6500                                                 in->variantType = tags.extraObjectType;
6501                                                 in->lazyLoaded = 1;
6502                                         }
6503
6504                                         in->hdrChunk = chunk;
6505
6506                                 } else if (!in->valid) {
6507                                         /* we need to load this info */
6508
6509                                         in->valid = 1;
6510                                         in->hdrChunk = chunk;
6511
6512                                         if(oh) {
6513                                                 in->variantType = oh->type;
6514
6515                                                 in->yst_mode = oh->yst_mode;
6516 #ifdef CONFIG_YAFFS_WINCE
6517                                                 in->win_atime[0] = oh->win_atime[0];
6518                                                 in->win_ctime[0] = oh->win_ctime[0];
6519                                                 in->win_mtime[0] = oh->win_mtime[0];
6520                                                 in->win_atime[1] = oh->win_atime[1];
6521                                                 in->win_ctime[1] = oh->win_ctime[1];
6522                                                 in->win_mtime[1] = oh->win_mtime[1];
6523 #else
6524                                                 in->yst_uid = oh->yst_uid;
6525                                                 in->yst_gid = oh->yst_gid;
6526                                                 in->yst_atime = oh->yst_atime;
6527                                                 in->yst_mtime = oh->yst_mtime;
6528                                                 in->yst_ctime = oh->yst_ctime;
6529                                                 in->yst_rdev = oh->yst_rdev;
6530 #endif
6531
6532                                                 if (oh->shadowsObject > 0) 
6533                                                         yaffs_HandleShadowedObject(dev,
6534                                                                            oh->
6535                                                                            shadowsObject,
6536                                                                            1);
6537                                         
6538
6539                                                 yaffs_SetObjectName(in, oh->name);
6540                                                 parent =
6541                                                     yaffs_FindOrCreateObjectByNumber
6542                                                         (dev, oh->parentObjectId,
6543                                                          YAFFS_OBJECT_TYPE_DIRECTORY);
6544
6545                                                  fileSize = oh->fileSize;
6546                                                  isShrink = oh->isShrink;
6547                                                  equivalentObjectId = oh->equivalentObjectId;
6548
6549                                         }
6550                                         else {
6551                                                 in->variantType = tags.extraObjectType;
6552                                                 parent =
6553                                                     yaffs_FindOrCreateObjectByNumber
6554                                                         (dev, tags.extraParentObjectId,
6555                                                          YAFFS_OBJECT_TYPE_DIRECTORY);
6556                                                  fileSize = tags.extraFileLength;
6557                                                  isShrink = tags.extraIsShrinkHeader;
6558                                                  equivalentObjectId = tags.extraEquivalentObjectId;
6559                                                 in->lazyLoaded = 1;
6560
6561                                         }
6562                                         in->dirty = 0;
6563
6564                                         if (!parent)
6565                                                 alloc_failed = 1;
6566
6567                                         /* directory stuff...
6568                                          * hook up to parent
6569                                          */
6570
6571                                         if (parent && parent->variantType ==
6572                                             YAFFS_OBJECT_TYPE_UNKNOWN) {
6573                                                 /* Set up as a directory */
6574                                                 parent->variantType =
6575                                                     YAFFS_OBJECT_TYPE_DIRECTORY;
6576                                                 YINIT_LIST_HEAD(&parent->variant.
6577                                                                directoryVariant.
6578                                                                children);
6579                                         } else if (!parent || parent->variantType !=
6580                                                    YAFFS_OBJECT_TYPE_DIRECTORY)
6581                                         {
6582                                                 /* Hoosterman, another problem....
6583                                                  * We're trying to use a non-directory as a directory
6584                                                  */
6585
6586                                                 T(YAFFS_TRACE_ERROR,
6587                                                   (TSTR
6588                                                    ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6589                                                     TENDSTR)));
6590                                                 parent = dev->lostNFoundDir;
6591                                         }
6592
6593                                         yaffs_AddObjectToDirectory(parent, in);
6594
6595                                         itsUnlinked = (parent == dev->deletedDir) ||
6596                                                       (parent == dev->unlinkedDir);
6597
6598                                         if (isShrink) {
6599                                                 /* Mark the block as having a shrinkHeader */
6600                                                 bi->hasShrinkHeader = 1;
6601                                         }
6602
6603                                         /* Note re hardlinks.
6604                                          * Since we might scan a hardlink before its equivalent object is scanned
6605                                          * we put them all in a list.
6606                                          * After scanning is complete, we should have all the objects, so we run
6607                                          * through this list and fix up all the chains.              
6608                                          */
6609
6610                                         switch (in->variantType) {
6611                                         case YAFFS_OBJECT_TYPE_UNKNOWN: 
6612                                                 /* Todo got a problem */
6613                                                 break;
6614                                         case YAFFS_OBJECT_TYPE_FILE:
6615
6616                                                 if (in->variant.fileVariant.
6617                                                     scannedFileSize < fileSize) {
6618                                                         /* This covers the case where the file size is greater
6619                                                          * than where the data is
6620                                                          * This will happen if the file is resized to be larger 
6621                                                          * than its current data extents.
6622                                                          */
6623                                                         in->variant.fileVariant.fileSize = fileSize;
6624                                                         in->variant.fileVariant.scannedFileSize =
6625                                                             in->variant.fileVariant.fileSize;
6626                                                 }
6627
6628                                                 if (isShrink &&
6629                                                     in->variant.fileVariant.shrinkSize > fileSize) {
6630                                                         in->variant.fileVariant.shrinkSize = fileSize;
6631                                                 }
6632
6633                                                 break;
6634                                         case YAFFS_OBJECT_TYPE_HARDLINK:
6635                                                 if(!itsUnlinked) {
6636                                                   in->variant.hardLinkVariant.equivalentObjectId =
6637                                                     equivalentObjectId;
6638                                                   in->hardLinks.next =
6639                                                     (struct ylist_head *) hardList;
6640                                                   hardList = in;
6641                                                 }
6642                                                 break;
6643                                         case YAFFS_OBJECT_TYPE_DIRECTORY:
6644                                                 /* Do nothing */
6645                                                 break;
6646                                         case YAFFS_OBJECT_TYPE_SPECIAL:
6647                                                 /* Do nothing */
6648                                                 break;
6649                                         case YAFFS_OBJECT_TYPE_SYMLINK:
6650                                                 if(oh){
6651                                                    in->variant.symLinkVariant.alias =
6652                                                     yaffs_CloneString(oh->
6653                                                                       alias);
6654                                                    if(!in->variant.symLinkVariant.alias)
6655                                                         alloc_failed = 1;
6656                                                 }
6657                                                 break;
6658                                         }
6659
6660                                 }
6661                                 
6662                         }
6663
6664                 } /* End of scanning for each chunk */
6665
6666                 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6667                         /* If we got this far while scanning, then the block is fully allocated. */
6668                         state = YAFFS_BLOCK_STATE_FULL;
6669                 }
6670
6671                 bi->blockState = state;
6672
6673                 /* Now let's see if it was dirty */
6674                 if (bi->pagesInUse == 0 &&
6675                     !bi->hasShrinkHeader &&
6676                     bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6677                         yaffs_BlockBecameDirty(dev, blk);
6678                 }
6679
6680         }
6681
6682         if (altBlockIndex) 
6683                 YFREE_ALT(blockIndex);
6684         else
6685                 YFREE(blockIndex);
6686         
6687         /* Ok, we've done all the scanning.
6688          * Fix up the hard link chains.
6689          * We should now have scanned all the objects, now it's time to add these 
6690          * hardlinks.
6691          */
6692         yaffs_HardlinkFixup(dev,hardList);
6693         
6694
6695         yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6696         
6697         if(alloc_failed){
6698                 return YAFFS_FAIL;
6699         }
6700
6701         T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6702
6703         return YAFFS_OK;
6704 }
6705
6706 /*------------------------------  Directory Functions ----------------------------- */
6707
6708 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
6709 {
6710         struct ylist_head *lh;
6711         yaffs_Object *listObj;
6712         
6713         int count = 0;
6714
6715         if(!obj){
6716                 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
6717                 YBUG();
6718         }
6719
6720         if(yaffs_SkipVerification(obj->myDev))
6721                 return;
6722
6723         if(!obj->parent){
6724                 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
6725                 YBUG();
6726         }
6727                 
6728         if(obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
6729                 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
6730                 YBUG();
6731         }
6732         
6733         /* Iterate through the objects in each hash entry */
6734          
6735         ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
6736                 if (lh) {
6737                         listObj = ylist_entry(lh, yaffs_Object, siblings);
6738                         yaffs_VerifyObject(listObj);
6739                         if(obj == listObj)
6740                                 count ++;
6741                 }
6742          }
6743          
6744          if(count != 1){
6745                 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR),count));
6746                 YBUG();
6747         }
6748
6749 }
6750
6751 static void yaffs_VerifyDirectory(yaffs_Object *directory)
6752 {
6753
6754         struct ylist_head *lh;
6755         yaffs_Object *listObj;
6756         
6757         if(!directory)
6758                 YBUG();
6759
6760         if(yaffs_SkipFullVerification(directory->myDev))
6761                 return;
6762
6763                 
6764         if(directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
6765                 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR),directory->variantType));
6766                 YBUG();
6767         }
6768         
6769         /* Iterate through the objects in each hash entry */
6770          
6771         ylist_for_each(lh, &directory->variant.directoryVariant.children) {
6772                 if (lh) {
6773                         listObj = ylist_entry(lh, yaffs_Object, siblings);
6774                         if(listObj->parent != directory){
6775                                 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR),listObj->parent));
6776                                 YBUG();
6777                         }
6778                         yaffs_VerifyObjectInDirectory(listObj);
6779                 }
6780          }
6781          
6782 }
6783
6784
6785 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj)
6786 {
6787         yaffs_Device *dev = obj->myDev;
6788         yaffs_Object *parent;
6789         
6790         yaffs_VerifyObjectInDirectory(obj);
6791         parent = obj->parent;
6792         
6793         yaffs_VerifyDirectory(parent);
6794
6795         if(dev && dev->removeObjectCallback)
6796                 dev->removeObjectCallback(obj);
6797
6798            
6799         ylist_del_init(&obj->siblings);
6800         obj->parent = NULL;
6801
6802         yaffs_VerifyDirectory(parent);
6803
6804 }
6805
6806
6807 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
6808                                        yaffs_Object * obj)
6809 {
6810
6811         if (!directory) {
6812                 T(YAFFS_TRACE_ALWAYS,
6813                   (TSTR
6814                    ("tragedy: Trying to add an object to a null pointer directory"
6815                     TENDSTR)));
6816                 YBUG();
6817         }
6818         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6819                 T(YAFFS_TRACE_ALWAYS,
6820                   (TSTR
6821                    ("tragedy: Trying to add an object to a non-directory"
6822                     TENDSTR)));
6823                 YBUG();
6824         }
6825
6826         if (obj->siblings.prev == NULL) {
6827                 /* Not initialised */
6828                 YBUG();
6829
6830         } else if (ylist_empty(&obj->siblings)) {
6831                 YBUG();
6832         } 
6833
6834
6835         yaffs_VerifyDirectory(directory);
6836
6837         yaffs_RemoveObjectFromDirectory(obj);
6838         
6839         
6840         /* Now add it */
6841         ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
6842         obj->parent = directory;
6843
6844         if (directory == obj->myDev->unlinkedDir
6845             || directory == obj->myDev->deletedDir) {
6846                 obj->unlinked = 1;
6847                 obj->myDev->nUnlinkedFiles++;
6848                 obj->renameAllowed = 0;
6849         }
6850
6851         yaffs_VerifyDirectory(directory);
6852         yaffs_VerifyObjectInDirectory(obj);
6853
6854
6855 }
6856
6857 yaffs_Object *yaffs_FindObjectByName(yaffs_Object * directory,
6858                                      const YCHAR * name)
6859 {
6860         int sum;
6861
6862         struct ylist_head *i;
6863         YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
6864
6865         yaffs_Object *l;
6866
6867         if (!name) {
6868                 return NULL;
6869         }
6870
6871         if (!directory) {
6872                 T(YAFFS_TRACE_ALWAYS,
6873                   (TSTR
6874                    ("tragedy: yaffs_FindObjectByName: null pointer directory"
6875                     TENDSTR)));
6876                 YBUG();
6877         }
6878         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6879                 T(YAFFS_TRACE_ALWAYS,
6880                   (TSTR
6881                    ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6882                 YBUG();
6883         }
6884
6885         sum = yaffs_CalcNameSum(name);
6886
6887         ylist_for_each(i, &directory->variant.directoryVariant.children) {
6888                 if (i) {
6889                         l = ylist_entry(i, yaffs_Object, siblings);
6890                         
6891                         if(l->parent != directory)
6892                                 YBUG();
6893                         
6894                         yaffs_CheckObjectDetailsLoaded(l);
6895
6896                         /* Special case for lost-n-found */
6897                         if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6898                                 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0) {
6899                                         return l;
6900                                 }
6901                         } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0){
6902                                 /* LostnFound chunk called Objxxx
6903                                  * Do a real check
6904                                  */
6905                                 yaffs_GetObjectName(l, buffer,
6906                                                     YAFFS_MAX_NAME_LENGTH);
6907                                 if (yaffs_strncmp(name, buffer,YAFFS_MAX_NAME_LENGTH) == 0) {
6908                                         return l;
6909                                 }
6910
6911                         }
6912                 }
6913         }
6914
6915         return NULL;
6916 }
6917
6918
6919 #if 0
6920 int yaffs_ApplyToDirectoryChildren(yaffs_Object * theDir,
6921                                    int (*fn) (yaffs_Object *))
6922 {
6923         struct ylist_head *i;
6924         yaffs_Object *l;
6925
6926         if (!theDir) {
6927                 T(YAFFS_TRACE_ALWAYS,
6928                   (TSTR
6929                    ("tragedy: yaffs_FindObjectByName: null pointer directory"
6930                     TENDSTR)));
6931                 YBUG();
6932         }
6933         if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6934                 T(YAFFS_TRACE_ALWAYS,
6935                   (TSTR
6936                    ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6937                 YBUG();
6938         }
6939
6940         ylist_for_each(i, &theDir->variant.directoryVariant.children) {
6941                 if (i) {
6942                         l = ylist_entry(i, yaffs_Object, siblings);
6943                         if (l && !fn(l)) {
6944                                 return YAFFS_FAIL;
6945                         }
6946                 }
6947         }
6948
6949         return YAFFS_OK;
6950
6951 }
6952 #endif
6953
6954 /* GetEquivalentObject dereferences any hard links to get to the
6955  * actual object.
6956  */
6957
6958 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object * obj)
6959 {
6960         if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
6961                 /* We want the object id of the equivalent object, not this one */
6962                 obj = obj->variant.hardLinkVariant.equivalentObject;
6963                 yaffs_CheckObjectDetailsLoaded(obj);
6964         }
6965         return obj;
6966
6967 }
6968
6969 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
6970 {
6971         memset(name, 0, buffSize * sizeof(YCHAR));
6972         
6973         yaffs_CheckObjectDetailsLoaded(obj);
6974
6975         if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6976                 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
6977         } else if (obj->hdrChunk <= 0) {
6978                 YCHAR locName[20];
6979                 YCHAR numString[20];
6980                 YCHAR *x = &numString[19];
6981                 unsigned v = obj->objectId;
6982                 numString[19] = 0;
6983                 while(v>0){
6984                         x--;
6985                         *x = '0' + (v % 10);
6986                         v /= 10;
6987                 }
6988                 /* make up a name */
6989                 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
6990                 yaffs_strcat(locName,x);
6991                 yaffs_strncpy(name, locName, buffSize - 1);
6992
6993         }
6994 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
6995         else if (obj->shortName[0]) {
6996                 yaffs_strcpy(name, obj->shortName);
6997         }
6998 #endif
6999         else {
7000                 int result;
7001                 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
7002
7003                 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
7004
7005                 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
7006
7007                 if (obj->hdrChunk > 0) {
7008                         result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
7009                                                         obj->hdrChunk, buffer,
7010                                                         NULL);
7011                 }
7012                 yaffs_strncpy(name, oh->name, buffSize - 1);
7013
7014                 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
7015         }
7016
7017         return yaffs_strlen(name);
7018 }
7019
7020 int yaffs_GetObjectFileLength(yaffs_Object * obj)
7021 {
7022
7023         /* Dereference any hard linking */
7024         obj = yaffs_GetEquivalentObject(obj);
7025
7026         if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
7027                 return obj->variant.fileVariant.fileSize;
7028         }
7029         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
7030                 return yaffs_strlen(obj->variant.symLinkVariant.alias);
7031         } else {
7032                 /* Only a directory should drop through to here */
7033                 return obj->myDev->nDataBytesPerChunk;
7034         }
7035 }
7036
7037 int yaffs_GetObjectLinkCount(yaffs_Object * obj)
7038 {
7039         int count = 0;
7040         struct ylist_head *i;
7041
7042         if (!obj->unlinked) {
7043                 count++;        /* the object itself */
7044         }
7045         ylist_for_each(i, &obj->hardLinks) {
7046                 count++;        /* add the hard links; */
7047         }
7048         return count;
7049
7050 }
7051
7052 int yaffs_GetObjectInode(yaffs_Object * obj)
7053 {
7054         obj = yaffs_GetEquivalentObject(obj);
7055
7056         return obj->objectId;
7057 }
7058
7059 unsigned yaffs_GetObjectType(yaffs_Object * obj)
7060 {
7061         obj = yaffs_GetEquivalentObject(obj);
7062
7063         switch (obj->variantType) {
7064         case YAFFS_OBJECT_TYPE_FILE:
7065                 return DT_REG;
7066                 break;
7067         case YAFFS_OBJECT_TYPE_DIRECTORY:
7068                 return DT_DIR;
7069                 break;
7070         case YAFFS_OBJECT_TYPE_SYMLINK:
7071                 return DT_LNK;
7072                 break;
7073         case YAFFS_OBJECT_TYPE_HARDLINK:
7074                 return DT_REG;
7075                 break;
7076         case YAFFS_OBJECT_TYPE_SPECIAL:
7077                 if (S_ISFIFO(obj->yst_mode))
7078                         return DT_FIFO;
7079                 if (S_ISCHR(obj->yst_mode))
7080                         return DT_CHR;
7081                 if (S_ISBLK(obj->yst_mode))
7082                         return DT_BLK;
7083                 if (S_ISSOCK(obj->yst_mode))
7084                         return DT_SOCK;
7085         default:
7086                 return DT_REG;
7087                 break;
7088         }
7089 }
7090
7091 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object * obj)
7092 {
7093         obj = yaffs_GetEquivalentObject(obj);
7094         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
7095                 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7096         } else {
7097                 return yaffs_CloneString(_Y(""));
7098         }
7099 }
7100
7101 #ifndef CONFIG_YAFFS_WINCE
7102
7103 int yaffs_SetAttributes(yaffs_Object * obj, struct iattr *attr)
7104 {
7105         unsigned int valid = attr->ia_valid;
7106
7107         if (valid & ATTR_MODE)
7108                 obj->yst_mode = attr->ia_mode;
7109         if (valid & ATTR_UID)
7110                 obj->yst_uid = attr->ia_uid;
7111         if (valid & ATTR_GID)
7112                 obj->yst_gid = attr->ia_gid;
7113
7114         if (valid & ATTR_ATIME)
7115                 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7116         if (valid & ATTR_CTIME)
7117                 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7118         if (valid & ATTR_MTIME)
7119                 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7120
7121         if (valid & ATTR_SIZE)
7122                 yaffs_ResizeFile(obj, attr->ia_size);
7123
7124         yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7125
7126         return YAFFS_OK;
7127
7128 }
7129 int yaffs_GetAttributes(yaffs_Object * obj, struct iattr *attr)
7130 {
7131         unsigned int valid = 0;
7132
7133         attr->ia_mode = obj->yst_mode;
7134         valid |= ATTR_MODE;
7135         attr->ia_uid = obj->yst_uid;
7136         valid |= ATTR_UID;
7137         attr->ia_gid = obj->yst_gid;
7138         valid |= ATTR_GID;
7139
7140         Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7141         valid |= ATTR_ATIME;
7142         Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7143         valid |= ATTR_CTIME;
7144         Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7145         valid |= ATTR_MTIME;
7146
7147         attr->ia_size = yaffs_GetFileSize(obj);
7148         valid |= ATTR_SIZE;
7149
7150         attr->ia_valid = valid;
7151
7152         return YAFFS_OK;
7153
7154 }
7155
7156 #endif
7157
7158 #if 0
7159 int yaffs_DumpObject(yaffs_Object * obj)
7160 {
7161         YCHAR name[257];
7162
7163         yaffs_GetObjectName(obj, name, 256);
7164
7165         T(YAFFS_TRACE_ALWAYS,
7166           (TSTR
7167            ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7168             " chunk %d type %d size %d\n"
7169             TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7170            obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7171            yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7172
7173         return YAFFS_OK;
7174 }
7175 #endif
7176
7177 /*---------------------------- Initialisation code -------------------------------------- */
7178
7179 static int yaffs_CheckDevFunctions(const yaffs_Device * dev)
7180 {
7181
7182         /* Common functions, gotta have */
7183         if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
7184                 return 0;
7185
7186 #ifdef CONFIG_YAFFS_YAFFS2
7187
7188         /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7189         if (dev->writeChunkWithTagsToNAND &&
7190             dev->readChunkWithTagsFromNAND &&
7191             !dev->writeChunkToNAND &&
7192             !dev->readChunkFromNAND &&
7193             dev->markNANDBlockBad && dev->queryNANDBlock)
7194                 return 1;
7195 #endif
7196
7197         /* Can use the "spare" style interface for yaffs1 */
7198         if (!dev->isYaffs2 &&
7199             !dev->writeChunkWithTagsToNAND &&
7200             !dev->readChunkWithTagsFromNAND &&
7201             dev->writeChunkToNAND &&
7202             dev->readChunkFromNAND &&
7203             !dev->markNANDBlockBad && !dev->queryNANDBlock)
7204                 return 1;
7205
7206         return 0;               /* bad */
7207 }
7208
7209
7210 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7211 {
7212         /* Initialise the unlinked, deleted, root and lost and found directories */
7213         
7214         dev->lostNFoundDir = dev->rootDir =  NULL;
7215         dev->unlinkedDir = dev->deletedDir = NULL;
7216
7217         dev->unlinkedDir =
7218             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7219         
7220         dev->deletedDir =
7221             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7222
7223         dev->rootDir =
7224             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7225                                       YAFFS_ROOT_MODE | S_IFDIR);
7226         dev->lostNFoundDir =
7227             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7228                                       YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7229         
7230         if(dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir){
7231                 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7232                 return YAFFS_OK;
7233         }
7234         
7235         return YAFFS_FAIL;
7236 }
7237
7238 int yaffs_GutsInitialise(yaffs_Device * dev)
7239 {
7240         int init_failed = 0;
7241         unsigned x;
7242         int bits;
7243
7244         T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7245
7246         /* Check stuff that must be set */
7247
7248         if (!dev) {
7249                 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7250                 return YAFFS_FAIL;
7251         }
7252
7253         dev->internalStartBlock = dev->startBlock;
7254         dev->internalEndBlock = dev->endBlock;
7255         dev->blockOffset = 0;
7256         dev->chunkOffset = 0;
7257         dev->nFreeChunks = 0;
7258         
7259         dev->gcBlock = -1;
7260
7261         if (dev->startBlock == 0) {
7262                 dev->internalStartBlock = dev->startBlock + 1;
7263                 dev->internalEndBlock = dev->endBlock + 1;
7264                 dev->blockOffset = 1;
7265                 dev->chunkOffset = dev->nChunksPerBlock;
7266         }
7267
7268         /* Check geometry parameters. */
7269
7270         if ((!dev->inbandTags && dev->isYaffs2 && dev->totalBytesPerChunk < 1024) || 
7271             (!dev->isYaffs2 && dev->totalBytesPerChunk < 512) || 
7272             (dev->inbandTags && !dev->isYaffs2 ) ||
7273              dev->nChunksPerBlock < 2 || 
7274              dev->nReservedBlocks < 2 || 
7275              dev->internalStartBlock <= 0 || 
7276              dev->internalEndBlock <= 0 || 
7277              dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2)      // otherwise it is too small
7278             ) {
7279                 T(YAFFS_TRACE_ALWAYS,
7280                   (TSTR
7281                    ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7282                     TENDSTR), dev->totalBytesPerChunk, dev->isYaffs2 ? "2" : "", dev->inbandTags));
7283                 return YAFFS_FAIL;
7284         }
7285
7286         if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7287                 T(YAFFS_TRACE_ALWAYS,
7288                   (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7289                 return YAFFS_FAIL;
7290         }
7291         
7292         /* Sort out space for inband tags, if required */
7293         if(dev->inbandTags)
7294                 dev->nDataBytesPerChunk = dev->totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7295         else 
7296                 dev->nDataBytesPerChunk = dev->totalBytesPerChunk;
7297
7298         /* Got the right mix of functions? */
7299         if (!yaffs_CheckDevFunctions(dev)) {
7300                 /* Function missing */
7301                 T(YAFFS_TRACE_ALWAYS,
7302                   (TSTR
7303                    ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7304
7305                 return YAFFS_FAIL;
7306         }
7307
7308         /* This is really a compilation check. */
7309         if (!yaffs_CheckStructures()) {
7310                 T(YAFFS_TRACE_ALWAYS,
7311                   (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7312                 return YAFFS_FAIL;
7313         }
7314
7315         if (dev->isMounted) {
7316                 T(YAFFS_TRACE_ALWAYS,
7317                   (TSTR("yaffs: device already mounted\n" TENDSTR)));
7318                 return YAFFS_FAIL;
7319         }
7320
7321         /* Finished with most checks. One or two more checks happen later on too. */
7322
7323         dev->isMounted = 1;
7324
7325         /* OK now calculate a few things for the device */
7326         
7327         /*
7328          *  Calculate all the chunk size manipulation numbers:   
7329          */
7330         x = dev->nDataBytesPerChunk;
7331         /* We always use dev->chunkShift and dev->chunkDiv */
7332         dev->chunkShift = Shifts(x);
7333         x >>= dev->chunkShift;
7334         dev->chunkDiv = x;
7335         /* We only use chunk mask if chunkDiv is 1 */
7336         dev->chunkMask = (1<<dev->chunkShift) - 1;
7337                 
7338         /*
7339          * Calculate chunkGroupBits.
7340          * We need to find the next power of 2 > than internalEndBlock
7341          */
7342
7343         x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7344         
7345         bits = ShiftsGE(x);
7346         
7347         /* Set up tnode width if wide tnodes are enabled. */
7348         if(!dev->wideTnodesDisabled){
7349                 /* bits must be even so that we end up with 32-bit words */
7350                 if(bits & 1)
7351                         bits++;
7352                 if(bits < 16)
7353                         dev->tnodeWidth = 16;
7354                 else
7355                         dev->tnodeWidth = bits;
7356         }
7357         else
7358                 dev->tnodeWidth = 16;
7359  
7360         dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7361                 
7362         /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7363          * so if the bitwidth of the
7364          * chunk range we're using is greater than 16 we need
7365          * to figure out chunk shift and chunkGroupSize
7366          */
7367                  
7368         if (bits <= dev->tnodeWidth)
7369                 dev->chunkGroupBits = 0;
7370         else
7371                 dev->chunkGroupBits = bits - dev->tnodeWidth;
7372                 
7373
7374         dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7375
7376         if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7377                 /* We have a problem because the soft delete won't work if
7378                  * the chunk group size > chunks per block.
7379                  * This can be remedied by using larger "virtual blocks".
7380                  */
7381                 T(YAFFS_TRACE_ALWAYS,
7382                   (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7383
7384                 return YAFFS_FAIL;
7385         }
7386
7387         /* OK, we've finished verifying the device, lets continue with initialisation */
7388
7389         /* More device initialisation */
7390         dev->garbageCollections = 0;
7391         dev->passiveGarbageCollections = 0;
7392         dev->currentDirtyChecker = 0;
7393         dev->bufferedBlock = -1;
7394         dev->doingBufferedBlockRewrite = 0;
7395         dev->nDeletedFiles = 0;
7396         dev->nBackgroundDeletions = 0;
7397         dev->nUnlinkedFiles = 0;
7398         dev->eccFixed = 0;
7399         dev->eccUnfixed = 0;
7400         dev->tagsEccFixed = 0;
7401         dev->tagsEccUnfixed = 0;
7402         dev->nErasureFailures = 0;
7403         dev->nErasedBlocks = 0;
7404         dev->isDoingGC = 0;
7405         dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7406
7407         /* Initialise temporary buffers and caches. */
7408         if(!yaffs_InitialiseTempBuffers(dev))
7409                 init_failed = 1;
7410         
7411         dev->srCache = NULL;
7412         dev->gcCleanupList = NULL;
7413         
7414         
7415         if (!init_failed &&
7416             dev->nShortOpCaches > 0) {
7417                 int i;
7418                 void *buf;
7419                 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7420
7421                 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES) {
7422                         dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7423                 }
7424
7425                 dev->srCache =  YMALLOC(srCacheBytes);
7426                 
7427                 buf = (__u8 *) dev->srCache;
7428                     
7429                 if(dev->srCache)
7430                         memset(dev->srCache,0,srCacheBytes);
7431                    
7432                 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7433                         dev->srCache[i].object = NULL;
7434                         dev->srCache[i].lastUse = 0;
7435                         dev->srCache[i].dirty = 0;
7436                         dev->srCache[i].data = buf = YMALLOC_DMA(dev->totalBytesPerChunk);
7437                 }
7438                 if(!buf)
7439                         init_failed = 1;
7440                         
7441                 dev->srLastUse = 0;
7442         }
7443
7444         dev->cacheHits = 0;
7445         
7446         if(!init_failed){
7447                 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7448                 if(!dev->gcCleanupList)
7449                         init_failed = 1;
7450         }
7451
7452         if (dev->isYaffs2) {
7453                 dev->useHeaderFileSize = 1;
7454         }
7455         if(!init_failed && !yaffs_InitialiseBlocks(dev))
7456                 init_failed = 1;
7457                 
7458         yaffs_InitialiseTnodes(dev);
7459         yaffs_InitialiseObjects(dev);
7460
7461         if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7462                 init_failed = 1;
7463
7464
7465         if(!init_failed){
7466                 /* Now scan the flash. */
7467                 if (dev->isYaffs2) {
7468                         if(yaffs_CheckpointRestore(dev)) {
7469                                 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7470                                 T(YAFFS_TRACE_ALWAYS,
7471                                   (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7472                         } else {
7473
7474                                 /* Clean up the mess caused by an aborted checkpoint load 
7475                                  * and scan backwards. 
7476                                  */
7477                                 yaffs_DeinitialiseBlocks(dev);
7478                                 yaffs_DeinitialiseTnodes(dev);
7479                                 yaffs_DeinitialiseObjects(dev);
7480                                 
7481                         
7482                                 dev->nErasedBlocks = 0;
7483                                 dev->nFreeChunks = 0;
7484                                 dev->allocationBlock = -1;
7485                                 dev->allocationPage = -1;
7486                                 dev->nDeletedFiles = 0;
7487                                 dev->nUnlinkedFiles = 0;
7488                                 dev->nBackgroundDeletions = 0;
7489                                 dev->oldestDirtySequence = 0;
7490
7491                                 if(!init_failed && !yaffs_InitialiseBlocks(dev))
7492                                         init_failed = 1;
7493                                         
7494                                 yaffs_InitialiseTnodes(dev);
7495                                 yaffs_InitialiseObjects(dev);
7496
7497                                 if(!init_failed && !yaffs_CreateInitialDirectories(dev))
7498                                         init_failed = 1;
7499
7500                                 if(!init_failed && !yaffs_ScanBackwards(dev))
7501                                         init_failed = 1;
7502                         }
7503                 }else
7504                         if(!yaffs_Scan(dev))
7505                                 init_failed = 1;
7506
7507                 yaffs_StripDeletedObjects(dev);
7508         }
7509                 
7510         if(init_failed){
7511                 /* Clean up the mess */
7512                 T(YAFFS_TRACE_TRACING,
7513                   (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7514
7515                 yaffs_Deinitialise(dev);
7516                 return YAFFS_FAIL;
7517         }
7518
7519         /* Zero out stats */
7520         dev->nPageReads = 0;
7521         dev->nPageWrites = 0;
7522         dev->nBlockErasures = 0;
7523         dev->nGCCopies = 0;
7524         dev->nRetriedWrites = 0;
7525
7526         dev->nRetiredBlocks = 0;
7527
7528         yaffs_VerifyFreeChunks(dev);
7529         yaffs_VerifyBlocks(dev);
7530         
7531
7532         T(YAFFS_TRACE_TRACING,
7533           (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7534         return YAFFS_OK;
7535
7536 }
7537
7538 void yaffs_Deinitialise(yaffs_Device * dev)
7539 {
7540         if (dev->isMounted) {
7541                 int i;
7542
7543                 yaffs_DeinitialiseBlocks(dev);
7544                 yaffs_DeinitialiseTnodes(dev);
7545                 yaffs_DeinitialiseObjects(dev);
7546                 if (dev->nShortOpCaches > 0 &&
7547                     dev->srCache) {
7548
7549                         for (i = 0; i < dev->nShortOpCaches; i++) {
7550                                 if(dev->srCache[i].data)
7551                                         YFREE(dev->srCache[i].data);
7552                                 dev->srCache[i].data = NULL;
7553                         }
7554
7555                         YFREE(dev->srCache);
7556                         dev->srCache = NULL;
7557                 }
7558
7559                 YFREE(dev->gcCleanupList);
7560
7561                 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
7562                         YFREE(dev->tempBuffer[i].buffer);
7563                 }
7564
7565
7566                 dev->isMounted = 0;
7567                 
7568                 if(dev->deinitialiseNAND)
7569                         dev->deinitialiseNAND(dev);
7570         }
7571
7572 }
7573
7574 static int yaffs_CountFreeChunks(yaffs_Device * dev)
7575 {
7576         int nFree;
7577         int b;
7578
7579         yaffs_BlockInfo *blk;
7580
7581         for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7582              b++) {
7583                 blk = yaffs_GetBlockInfo(dev, b);
7584
7585                 switch (blk->blockState) {
7586                 case YAFFS_BLOCK_STATE_EMPTY:
7587                 case YAFFS_BLOCK_STATE_ALLOCATING:
7588                 case YAFFS_BLOCK_STATE_COLLECTING:
7589                 case YAFFS_BLOCK_STATE_FULL:
7590                         nFree +=
7591                             (dev->nChunksPerBlock - blk->pagesInUse +
7592                              blk->softDeletions);
7593                         break;
7594                 default:
7595                         break;
7596                 }
7597
7598         }
7599
7600         return nFree;
7601 }
7602
7603 int yaffs_GetNumberOfFreeChunks(yaffs_Device * dev)
7604 {
7605         /* This is what we report to the outside world */
7606
7607         int nFree;
7608         int nDirtyCacheChunks;
7609         int blocksForCheckpoint;
7610
7611 #if 1
7612         nFree = dev->nFreeChunks;
7613 #else
7614         nFree = yaffs_CountFreeChunks(dev);
7615 #endif
7616
7617         nFree += dev->nDeletedFiles;
7618         
7619         /* Now count the number of dirty chunks in the cache and subtract those */
7620
7621         {
7622                 int i;
7623                 for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7624                         if (dev->srCache[i].dirty)
7625                                 nDirtyCacheChunks++;
7626                 }
7627         }
7628
7629         nFree -= nDirtyCacheChunks;
7630
7631         nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7632         
7633         /* Now we figure out how much to reserve for the checkpoint and report that... */
7634         blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7635         if(blocksForCheckpoint < 0)
7636                 blocksForCheckpoint = 0;
7637                 
7638         nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7639
7640         if (nFree < 0)
7641                 nFree = 0;
7642
7643         return nFree;
7644
7645 }
7646
7647 static int yaffs_freeVerificationFailures;
7648
7649 static void yaffs_VerifyFreeChunks(yaffs_Device * dev)
7650 {
7651         int counted;
7652         int difference;
7653         
7654         if(yaffs_SkipVerification(dev))
7655                 return;
7656         
7657         counted = yaffs_CountFreeChunks(dev);
7658
7659         difference = dev->nFreeChunks - counted;
7660
7661         if (difference) {
7662                 T(YAFFS_TRACE_ALWAYS,
7663                   (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7664                    dev->nFreeChunks, counted, difference));
7665                 yaffs_freeVerificationFailures++;
7666         }
7667 }
7668
7669 /*---------------------------------------- YAFFS test code ----------------------*/
7670
7671 #define yaffs_CheckStruct(structure,syze, name) \
7672         do { \
7673            if(sizeof(structure) != syze) \
7674                { \
7675                  T(YAFFS_TRACE_ALWAYS,(TSTR("%s should be %d but is %d\n" TENDSTR),\
7676                  name,syze,sizeof(structure))); \
7677                  return YAFFS_FAIL; \
7678                 } \
7679         } while(0)
7680
7681 static int yaffs_CheckStructures(void)
7682 {
7683 /*      yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
7684 /*      yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
7685 /*      yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
7686 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7687         yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode");
7688 #endif
7689 #ifndef CONFIG_YAFFS_WINCE
7690                 yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");
7691 #endif
7692             return YAFFS_OK;
7693 }