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