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