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