Merge branch 'master' of ssh://www.aleph1.co.uk/home/aleph1/git/yaffs2
[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 = in->deleted;
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                 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5641                         in->deleted = 1;
5642                         deleted = 1;
5643                         in->myDev->nDeletedFiles++;
5644                         yaffs_SoftDeleteFile(in);
5645                 }
5646                 return deleted ? YAFFS_OK : YAFFS_FAIL;
5647         } else {
5648                 /* The file has no data chunks so we toss it immediately */
5649                 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5650                 in->variant.fileVariant.top = NULL;
5651                 yaffs_DoGenericObjectDeletion(in);
5652
5653                 return YAFFS_OK;
5654         }
5655 }
5656
5657 static int yaffs_IsNonEmptyDirectory(yaffs_Object *obj)
5658 {
5659         return (obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) &&
5660                 !(ylist_empty(&obj->variant.directoryVariant.children));
5661 }
5662
5663 static int yaffs_DeleteDirectory(yaffs_Object *obj)
5664 {
5665         /* First check that the directory is empty. */
5666         if (yaffs_IsNonEmptyDirectory(obj))
5667                 return YAFFS_FAIL;
5668
5669         return yaffs_DoGenericObjectDeletion(obj);
5670 }
5671
5672 static int yaffs_DeleteSymLink(yaffs_Object *in)
5673 {
5674         if(in->variant.symLinkVariant.alias)
5675                 YFREE(in->variant.symLinkVariant.alias);
5676         in->variant.symLinkVariant.alias=NULL;
5677
5678         return yaffs_DoGenericObjectDeletion(in);
5679 }
5680
5681 static int yaffs_DeleteHardLink(yaffs_Object *in)
5682 {
5683         /* remove this hardlink from the list assocaited with the equivalent
5684          * object
5685          */
5686         ylist_del_init(&in->hardLinks);
5687         return yaffs_DoGenericObjectDeletion(in);
5688 }
5689
5690 int yaffs_DeleteObject(yaffs_Object *obj)
5691 {
5692 int retVal = -1;
5693         switch (obj->variantType) {
5694         case YAFFS_OBJECT_TYPE_FILE:
5695                 retVal = yaffs_DeleteFile(obj);
5696                 break;
5697         case YAFFS_OBJECT_TYPE_DIRECTORY:
5698                 if(!ylist_empty(&obj->variant.directoryVariant.dirty)){
5699                         T(YAFFS_TRACE_BACKGROUND, (TSTR("Remove object %d from dirty directories" TENDSTR),obj->objectId));
5700                         ylist_del_init(&obj->variant.directoryVariant.dirty);
5701                 }
5702                 return yaffs_DeleteDirectory(obj);
5703                 break;
5704         case YAFFS_OBJECT_TYPE_SYMLINK:
5705                 retVal = yaffs_DeleteSymLink(obj);
5706                 break;
5707         case YAFFS_OBJECT_TYPE_HARDLINK:
5708                 retVal = yaffs_DeleteHardLink(obj);
5709                 break;
5710         case YAFFS_OBJECT_TYPE_SPECIAL:
5711                 retVal = yaffs_DoGenericObjectDeletion(obj);
5712                 break;
5713         case YAFFS_OBJECT_TYPE_UNKNOWN:
5714                 retVal = 0;
5715                 break;          /* should not happen. */
5716         }
5717
5718         return retVal;
5719 }
5720
5721 static int yaffs_UnlinkWorker(yaffs_Object *obj)
5722 {
5723
5724         int immediateDeletion = 0;
5725
5726         if (!obj->myInode)
5727                 immediateDeletion = 1;
5728
5729         if(obj)
5730                 yaffs_UpdateParent(obj->parent);
5731
5732         if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5733                 return yaffs_DeleteHardLink(obj);
5734         } else if (!ylist_empty(&obj->hardLinks)) {
5735                 /* Curve ball: We're unlinking an object that has a hardlink.
5736                  *
5737                  * This problem arises because we are not strictly following
5738                  * The Linux link/inode model.
5739                  *
5740                  * We can't really delete the object.
5741                  * Instead, we do the following:
5742                  * - Select a hardlink.
5743                  * - Unhook it from the hard links
5744                  * - Move it from its parent directory (so that the rename can work)
5745                  * - Rename the object to the hardlink's name.
5746                  * - Delete the hardlink
5747                  */
5748
5749                 yaffs_Object *hl;
5750                 yaffs_Object *parent;
5751                 int retVal;
5752                 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5753
5754                 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5755
5756                 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5757                 parent = hl->parent;
5758
5759                 ylist_del_init(&hl->hardLinks);
5760
5761                 yaffs_AddObjectToDirectory(obj->myDev->unlinkedDir, hl);
5762
5763                 retVal = yaffs_ChangeObjectName(obj,parent, name, 0, 0);
5764
5765                 if (retVal == YAFFS_OK)
5766                         retVal = yaffs_DoGenericObjectDeletion(hl);
5767
5768                 return retVal;
5769
5770         } else if (immediateDeletion) {
5771                 switch (obj->variantType) {
5772                 case YAFFS_OBJECT_TYPE_FILE:
5773                         return yaffs_DeleteFile(obj);
5774                         break;
5775                 case YAFFS_OBJECT_TYPE_DIRECTORY:
5776                         ylist_del_init(&obj->variant.directoryVariant.dirty);
5777                         return yaffs_DeleteDirectory(obj);
5778                         break;
5779                 case YAFFS_OBJECT_TYPE_SYMLINK:
5780                         return yaffs_DeleteSymLink(obj);
5781                         break;
5782                 case YAFFS_OBJECT_TYPE_SPECIAL:
5783                         return yaffs_DoGenericObjectDeletion(obj);
5784                         break;
5785                 case YAFFS_OBJECT_TYPE_HARDLINK:
5786                 case YAFFS_OBJECT_TYPE_UNKNOWN:
5787                 default:
5788                         return YAFFS_FAIL;
5789                 }
5790         } else if(yaffs_IsNonEmptyDirectory(obj))
5791                 return YAFFS_FAIL;
5792         else
5793                 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
5794                                            _Y("unlinked"), 0, 0);
5795 }
5796
5797
5798 static int yaffs_UnlinkObject(yaffs_Object *obj)
5799 {
5800
5801         if (obj && obj->unlinkAllowed)
5802                 return yaffs_UnlinkWorker(obj);
5803
5804         return YAFFS_FAIL;
5805
5806 }
5807 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
5808 {
5809         yaffs_Object *obj;
5810
5811         obj = yaffs_FindObjectByName(dir, name);
5812         return yaffs_UnlinkObject(obj);
5813 }
5814
5815 /*----------------------- Initialisation Scanning ---------------------- */
5816
5817 static void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
5818                                 int backwardScanning)
5819 {
5820         yaffs_Object *obj;
5821
5822         if (!backwardScanning) {
5823                 /* Handle YAFFS1 forward scanning case
5824                  * For YAFFS1 we always do the deletion
5825                  */
5826
5827         } else {
5828                 /* Handle YAFFS2 case (backward scanning)
5829                  * If the shadowed object exists then ignore.
5830                  */
5831                 obj = yaffs_FindObjectByNumber(dev, objId);
5832                 if(obj)
5833                         return;
5834         }
5835
5836         /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5837          * We put it in unlinked dir to be cleaned up after the scanning
5838          */
5839         obj =
5840             yaffs_FindOrCreateObjectByNumber(dev, objId,
5841                                              YAFFS_OBJECT_TYPE_FILE);
5842         if (!obj)
5843                 return;
5844         obj->isShadowed = 1;
5845         yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5846         obj->variant.fileVariant.shrinkSize = 0;
5847         obj->valid = 1;         /* So that we don't read any other info for this file */
5848
5849 }
5850
5851 typedef struct {
5852         int seq;
5853         int block;
5854 } yaffs_BlockIndex;
5855
5856
5857 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5858 {
5859         yaffs_Object *hl;
5860         yaffs_Object *in;
5861
5862         while (hardList) {
5863                 hl = hardList;
5864                 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5865
5866                 in = yaffs_FindObjectByNumber(dev,
5867                                               hl->variant.hardLinkVariant.
5868                                               equivalentObjectId);
5869
5870                 if (in) {
5871                         /* Add the hardlink pointers */
5872                         hl->variant.hardLinkVariant.equivalentObject = in;
5873                         ylist_add(&hl->hardLinks, &in->hardLinks);
5874                 } else {
5875                         /* Todo Need to report/handle this better.
5876                          * Got a problem... hardlink to a non-existant object
5877                          */
5878                         hl->variant.hardLinkVariant.equivalentObject = NULL;
5879                         YINIT_LIST_HEAD(&hl->hardLinks);
5880
5881                 }
5882         }
5883 }
5884
5885
5886
5887
5888
5889 static int ybicmp(const void *a, const void *b)
5890 {
5891         register int aseq = ((yaffs_BlockIndex *)a)->seq;
5892         register int bseq = ((yaffs_BlockIndex *)b)->seq;
5893         register int ablock = ((yaffs_BlockIndex *)a)->block;
5894         register int bblock = ((yaffs_BlockIndex *)b)->block;
5895         if (aseq == bseq)
5896                 return ablock - bblock;
5897         else
5898                 return aseq - bseq;
5899 }
5900
5901
5902 struct yaffs_ShadowFixerStruct {
5903         int objectId;
5904         int shadowedId;
5905         struct yaffs_ShadowFixerStruct *next;
5906 };
5907
5908
5909 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5910 {
5911         /*
5912         *  Sort out state of unlinked and deleted objects after scanning.
5913         */
5914         struct ylist_head *i;
5915         struct ylist_head *n;
5916         yaffs_Object *l;
5917
5918         /* Soft delete all the unlinked files */
5919         ylist_for_each_safe(i, n,
5920                 &dev->unlinkedDir->variant.directoryVariant.children) {
5921                 if (i) {
5922                         l = ylist_entry(i, yaffs_Object, siblings);
5923                         yaffs_DeleteObject(l);
5924                 }
5925         }
5926
5927         ylist_for_each_safe(i, n,
5928                 &dev->deletedDir->variant.directoryVariant.children) {
5929                 if (i) {
5930                         l = ylist_entry(i, yaffs_Object, siblings);
5931                         yaffs_DeleteObject(l);
5932                 }
5933         }
5934
5935 }
5936
5937 /*
5938  * This code iterates through all the objects making sure that they are rooted.
5939  * Any unrooted objects are re-rooted in lost+found.
5940  * An object needs to be in one of:
5941  * - Directly under deleted, unlinked
5942  * - Directly or indirectly under root.
5943  *
5944  * Note:
5945  *  This code assumes that we don't ever change the current relationships between
5946  *  directories:
5947  *   rootDir->parent == unlinkedDir->parent == deletedDir->parent == NULL
5948  *   lostNfound->parent == rootDir
5949  *
5950  * This fixes the problem where directories might have inadvertently been deleted
5951  * leaving the object "hanging" without being rooted in the directory tree.
5952  */
5953  
5954 static int yaffs_HasNULLParent(yaffs_Device *dev, yaffs_Object *obj)
5955 {
5956         return (obj == dev->deletedDir ||
5957                 obj == dev->unlinkedDir||
5958                 obj == dev->rootDir);
5959 }
5960
5961 static void yaffs_FixHangingObjects(yaffs_Device *dev)
5962 {
5963         yaffs_Object *obj;
5964         yaffs_Object *parent;
5965         int i;
5966         struct ylist_head *lh;
5967         struct ylist_head *n;
5968         int depthLimit;
5969         int hanging;
5970
5971
5972         /* Iterate through the objects in each hash entry,
5973          * looking at each object.
5974          * Make sure it is rooted.
5975          */
5976
5977         for (i = 0; i <  YAFFS_NOBJECT_BUCKETS; i++) {
5978                 ylist_for_each_safe(lh, n, &dev->objectBucket[i].list) {
5979                         if (lh) {
5980                                 obj = ylist_entry(lh, yaffs_Object, hashLink);
5981                                 parent= obj->parent;
5982                                 
5983                                 if(yaffs_HasNULLParent(dev,obj)){
5984                                         /* These directories are not hanging */
5985                                         hanging = 0;
5986                                 }
5987                                 else if(!parent || parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5988                                         hanging = 1;
5989                                 else if(yaffs_HasNULLParent(dev,parent))
5990                                         hanging = 0;
5991                                 else {
5992                                         /*
5993                                          * Need to follow the parent chain to see if it is hanging.
5994                                          */
5995                                         hanging = 0;
5996                                         depthLimit=100;
5997
5998                                         while(parent != dev->rootDir &&
5999                                                 parent->parent &&
6000                                                 parent->parent->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
6001                                                 depthLimit > 0){
6002                                                 parent = parent->parent;
6003                                                 depthLimit--;
6004                                         }
6005                                         if(parent != dev->rootDir)
6006                                                 hanging = 1;
6007                                 }
6008                                 if(hanging){
6009                                         T(YAFFS_TRACE_SCAN,
6010                                           (TSTR("Hanging object %d moved to lost and found" TENDSTR),
6011                                                 obj->objectId));
6012                                         yaffs_AddObjectToDirectory(dev->lostNFoundDir,obj);
6013                                 }
6014                         }
6015                 }
6016         }
6017 }
6018
6019
6020 /*
6021  * Delete directory contents for cleaning up lost and found.
6022  */
6023 static void yaffs_DeleteDirectoryContents(yaffs_Object *dir)
6024 {
6025         yaffs_Object *obj;
6026         struct ylist_head *lh;
6027         struct ylist_head *n;
6028
6029         if(dir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
6030                 YBUG();
6031         
6032         ylist_for_each_safe(lh, n, &dir->variant.directoryVariant.children) {
6033                 if (lh) {
6034                         obj = ylist_entry(lh, yaffs_Object, siblings);
6035                         if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
6036                                 yaffs_DeleteDirectoryContents(obj);
6037
6038                         T(YAFFS_TRACE_SCAN,
6039                                 (TSTR("Deleting lost_found object %d" TENDSTR),
6040                                 obj->objectId));
6041
6042                         /* Need to use UnlinkObject since Delete would not handle
6043                          * hardlinked objects correctly.
6044                          */
6045                         yaffs_UnlinkObject(obj); 
6046                 }
6047         }
6048                         
6049 }
6050
6051 static void yaffs_EmptyLostAndFound(yaffs_Device *dev)
6052 {
6053         yaffs_DeleteDirectoryContents(dev->lostNFoundDir);
6054 }
6055
6056 static int yaffs_Scan(yaffs_Device *dev)
6057 {
6058         yaffs_ExtendedTags tags;
6059         int blk;
6060         int blockIterator;
6061         int startIterator;
6062         int endIterator;
6063         int result;
6064
6065         int chunk;
6066         int c;
6067         int deleted;
6068         yaffs_BlockState state;
6069         yaffs_Object *hardList = NULL;
6070         yaffs_BlockInfo *bi;
6071         __u32 sequenceNumber;
6072         yaffs_ObjectHeader *oh;
6073         yaffs_Object *in;
6074         yaffs_Object *parent;
6075
6076         int alloc_failed = 0;
6077
6078         struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
6079
6080
6081         __u8 *chunkData;
6082
6083
6084
6085         T(YAFFS_TRACE_SCAN,
6086           (TSTR("yaffs_Scan starts  intstartblk %d intendblk %d..." TENDSTR),
6087            dev->internalStartBlock, dev->internalEndBlock));
6088
6089         chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6090
6091         dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6092
6093         /* Scan all the blocks to determine their state */
6094         bi = dev->blockInfo;
6095         for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6096                 yaffs_ClearChunkBits(dev, blk);
6097                 bi->pagesInUse = 0;
6098                 bi->softDeletions = 0;
6099
6100                 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6101
6102                 bi->blockState = state;
6103                 bi->sequenceNumber = sequenceNumber;
6104
6105                 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6106                         bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6107
6108                 T(YAFFS_TRACE_SCAN_DEBUG,
6109                   (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6110                    state, sequenceNumber));
6111
6112                 if (state == YAFFS_BLOCK_STATE_DEAD) {
6113                         T(YAFFS_TRACE_BAD_BLOCKS,
6114                           (TSTR("block %d is bad" TENDSTR), blk));
6115                 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6116                         T(YAFFS_TRACE_SCAN_DEBUG,
6117                           (TSTR("Block empty " TENDSTR)));
6118                         dev->nErasedBlocks++;
6119                         dev->nFreeChunks += dev->param.nChunksPerBlock;
6120                 }
6121                 bi++;
6122         }
6123
6124         startIterator = dev->internalStartBlock;
6125         endIterator = dev->internalEndBlock;
6126
6127         /* For each block.... */
6128         for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
6129              blockIterator++) {
6130
6131                 YYIELD();
6132
6133                 YYIELD();
6134
6135                 blk = blockIterator;
6136
6137                 bi = yaffs_GetBlockInfo(dev, blk);
6138                 state = bi->blockState;
6139
6140                 deleted = 0;
6141
6142                 /* For each chunk in each block that needs scanning....*/
6143                 for (c = 0; !alloc_failed && c < dev->param.nChunksPerBlock &&
6144                      state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
6145                         /* Read the tags and decide what to do */
6146                         chunk = blk * dev->param.nChunksPerBlock + c;
6147
6148                         result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6149                                                         &tags);
6150
6151                         /* Let's have a good look at this chunk... */
6152
6153                         if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
6154                                 /* YAFFS1 only...
6155                                  * A deleted chunk
6156                                  */
6157                                 deleted++;
6158                                 dev->nFreeChunks++;
6159                                 /*T((" %d %d deleted\n",blk,c)); */
6160                         } else if (!tags.chunkUsed) {
6161                                 /* An unassigned chunk in the block
6162                                  * This means that either the block is empty or
6163                                  * this is the one being allocated from
6164                                  */
6165
6166                                 if (c == 0) {
6167                                         /* We're looking at the first chunk in the block so the block is unused */
6168                                         state = YAFFS_BLOCK_STATE_EMPTY;
6169                                         dev->nErasedBlocks++;
6170                                 } else {
6171                                         /* this is the block being allocated from */
6172                                         T(YAFFS_TRACE_SCAN,
6173                                           (TSTR
6174                                            (" Allocating from %d %d" TENDSTR),
6175                                            blk, c));
6176                                         state = YAFFS_BLOCK_STATE_ALLOCATING;
6177                                         dev->allocationBlock = blk;
6178                                         dev->allocationPage = c;
6179                                         dev->allocationBlockFinder = blk;
6180                                         /* Set block finder here to encourage the allocator to go forth from here. */
6181
6182                                 }
6183
6184                                 dev->nFreeChunks += (dev->param.nChunksPerBlock - c);
6185                         } else if (tags.chunkId > 0) {
6186                                 /* chunkId > 0 so it is a data chunk... */
6187                                 unsigned int endpos;
6188
6189                                 yaffs_SetChunkBit(dev, blk, c);
6190                                 bi->pagesInUse++;
6191
6192                                 in = yaffs_FindOrCreateObjectByNumber(dev,
6193                                                                       tags.
6194                                                                       objectId,
6195                                                                       YAFFS_OBJECT_TYPE_FILE);
6196                                 /* PutChunkIntoFile checks for a clash (two data chunks with
6197                                  * the same chunkId).
6198                                  */
6199
6200                                 if (!in)
6201                                         alloc_failed = 1;
6202
6203                                 if (in) {
6204                                         if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, 1))
6205                                                 alloc_failed = 1;
6206                                 }
6207
6208                                 endpos =
6209                                     (tags.chunkId - 1) * dev->nDataBytesPerChunk +
6210                                     tags.byteCount;
6211                                 if (in &&
6212                                     in->variantType == YAFFS_OBJECT_TYPE_FILE
6213                                     && in->variant.fileVariant.scannedFileSize <
6214                                     endpos) {
6215                                         in->variant.fileVariant.
6216                                             scannedFileSize = endpos;
6217                                         if (!dev->param.useHeaderFileSize) {
6218                                                 in->variant.fileVariant.
6219                                                     fileSize =
6220                                                     in->variant.fileVariant.
6221                                                     scannedFileSize;
6222                                         }
6223
6224                                 }
6225                                 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));   */
6226                         } else {
6227                                 /* chunkId == 0, so it is an ObjectHeader.
6228                                  * Thus, we read in the object header and make the object
6229                                  */
6230                                 yaffs_SetChunkBit(dev, blk, c);
6231                                 bi->pagesInUse++;
6232
6233                                 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
6234                                                                 chunkData,
6235                                                                 NULL);
6236
6237                                 oh = (yaffs_ObjectHeader *) chunkData;
6238
6239                                 in = yaffs_FindObjectByNumber(dev,
6240                                                               tags.objectId);
6241                                 if (in && in->variantType != oh->type) {
6242                                         /* This should not happen, but somehow
6243                                          * Wev'e ended up with an objectId that has been reused but not yet
6244                                          * deleted, and worse still it has changed type. Delete the old object.
6245                                          */
6246
6247                                         yaffs_DeleteObject(in);
6248
6249                                         in = 0;
6250                                 }
6251
6252                                 in = yaffs_FindOrCreateObjectByNumber(dev,
6253                                                                       tags.
6254                                                                       objectId,
6255                                                                       oh->type);
6256
6257                                 if (!in)
6258                                         alloc_failed = 1;
6259
6260                                 if (in && oh->shadowsObject > 0) {
6261
6262                                         struct yaffs_ShadowFixerStruct *fixer;
6263                                         fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
6264                                         if (fixer) {
6265                                                 fixer->next = shadowFixerList;
6266                                                 shadowFixerList = fixer;
6267                                                 fixer->objectId = tags.objectId;
6268                                                 fixer->shadowedId = oh->shadowsObject;
6269                                         }
6270
6271                                 }
6272
6273                                 if (in && in->valid) {
6274                                         /* We have already filled this one. We have a duplicate and need to resolve it. */
6275
6276                                         unsigned existingSerial = in->serial;
6277                                         unsigned newSerial = tags.serialNumber;
6278
6279                                         if (((existingSerial + 1) & 3) == newSerial) {
6280                                                 /* Use new one - destroy the exisiting one */
6281                                                 yaffs_DeleteChunk(dev,
6282                                                                   in->hdrChunk,
6283                                                                   1, __LINE__);
6284                                                 in->valid = 0;
6285                                         } else {
6286                                                 /* Use existing - destroy this one. */
6287                                                 yaffs_DeleteChunk(dev, chunk, 1,
6288                                                                   __LINE__);
6289                                         }
6290                                 }
6291
6292                                 if (in && !in->valid &&
6293                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
6294                                      tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
6295                                         /* We only load some info, don't fiddle with directory structure */
6296                                         in->valid = 1;
6297                                         in->variantType = oh->type;
6298
6299                                         in->yst_mode = oh->yst_mode;
6300 #ifdef CONFIG_YAFFS_WINCE
6301                                         in->win_atime[0] = oh->win_atime[0];
6302                                         in->win_ctime[0] = oh->win_ctime[0];
6303                                         in->win_mtime[0] = oh->win_mtime[0];
6304                                         in->win_atime[1] = oh->win_atime[1];
6305                                         in->win_ctime[1] = oh->win_ctime[1];
6306                                         in->win_mtime[1] = oh->win_mtime[1];
6307 #else
6308                                         in->yst_uid = oh->yst_uid;
6309                                         in->yst_gid = oh->yst_gid;
6310                                         in->yst_atime = oh->yst_atime;
6311                                         in->yst_mtime = oh->yst_mtime;
6312                                         in->yst_ctime = oh->yst_ctime;
6313                                         in->yst_rdev = oh->yst_rdev;
6314 #endif
6315                                         in->hdrChunk = chunk;
6316                                         in->serial = tags.serialNumber;
6317
6318                                 } else if (in && !in->valid) {
6319                                         /* we need to load this info */
6320
6321                                         in->valid = 1;
6322                                         in->variantType = oh->type;
6323
6324                                         in->yst_mode = oh->yst_mode;
6325 #ifdef CONFIG_YAFFS_WINCE
6326                                         in->win_atime[0] = oh->win_atime[0];
6327                                         in->win_ctime[0] = oh->win_ctime[0];
6328                                         in->win_mtime[0] = oh->win_mtime[0];
6329                                         in->win_atime[1] = oh->win_atime[1];
6330                                         in->win_ctime[1] = oh->win_ctime[1];
6331                                         in->win_mtime[1] = oh->win_mtime[1];
6332 #else
6333                                         in->yst_uid = oh->yst_uid;
6334                                         in->yst_gid = oh->yst_gid;
6335                                         in->yst_atime = oh->yst_atime;
6336                                         in->yst_mtime = oh->yst_mtime;
6337                                         in->yst_ctime = oh->yst_ctime;
6338                                         in->yst_rdev = oh->yst_rdev;
6339 #endif
6340                                         in->hdrChunk = chunk;
6341                                         in->serial = tags.serialNumber;
6342
6343                                         yaffs_SetObjectName(in, oh->name);
6344                                         in->dirty = 0;
6345
6346                                         /* directory stuff...
6347                                          * hook up to parent
6348                                          */
6349
6350                                         parent =
6351                                             yaffs_FindOrCreateObjectByNumber
6352                                             (dev, oh->parentObjectId,
6353                                              YAFFS_OBJECT_TYPE_DIRECTORY);
6354                                         if (!parent)
6355                                                 alloc_failed = 1;
6356                                         if (parent && parent->variantType ==
6357                                             YAFFS_OBJECT_TYPE_UNKNOWN) {
6358                                                 /* Set up as a directory */
6359                                                 parent->variantType =
6360                                                         YAFFS_OBJECT_TYPE_DIRECTORY;
6361                                                 YINIT_LIST_HEAD(&parent->variant.
6362                                                                 directoryVariant.
6363                                                                 children);
6364                                         } else if (!parent || parent->variantType !=
6365                                                    YAFFS_OBJECT_TYPE_DIRECTORY) {
6366                                                 /* Hoosterman, another problem....
6367                                                  * We're trying to use a non-directory as a directory
6368                                                  */
6369
6370                                                 T(YAFFS_TRACE_ERROR,
6371                                                   (TSTR
6372                                                    ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6373                                                     TENDSTR)));
6374                                                 parent = dev->lostNFoundDir;
6375                                         }
6376
6377                                         yaffs_AddObjectToDirectory(parent, in);
6378
6379                                         if (0 && (parent == dev->deletedDir ||
6380                                                   parent == dev->unlinkedDir)) {
6381                                                 in->deleted = 1;        /* If it is unlinked at start up then it wants deleting */
6382                                                 dev->nDeletedFiles++;
6383                                         }
6384                                         /* Note re hardlinks.
6385                                          * Since we might scan a hardlink before its equivalent object is scanned
6386                                          * we put them all in a list.
6387                                          * After scanning is complete, we should have all the objects, so we run through this
6388                                          * list and fix up all the chains.
6389                                          */
6390
6391                                         switch (in->variantType) {
6392                                         case YAFFS_OBJECT_TYPE_UNKNOWN:
6393                                                 /* Todo got a problem */
6394                                                 break;
6395                                         case YAFFS_OBJECT_TYPE_FILE:
6396                                                 if (dev->param.useHeaderFileSize)
6397
6398                                                         in->variant.fileVariant.
6399                                                             fileSize =
6400                                                             oh->fileSize;
6401
6402                                                 break;
6403                                         case YAFFS_OBJECT_TYPE_HARDLINK:
6404                                                 in->variant.hardLinkVariant.
6405                                                         equivalentObjectId =
6406                                                         oh->equivalentObjectId;
6407                                                 in->hardLinks.next =
6408                                                         (struct ylist_head *)
6409                                                         hardList;
6410                                                 hardList = in;
6411                                                 break;
6412                                         case YAFFS_OBJECT_TYPE_DIRECTORY:
6413                                                 /* Do nothing */
6414                                                 break;
6415                                         case YAFFS_OBJECT_TYPE_SPECIAL:
6416                                                 /* Do nothing */
6417                                                 break;
6418                                         case YAFFS_OBJECT_TYPE_SYMLINK:
6419                                                 in->variant.symLinkVariant.alias =
6420                                                     yaffs_CloneString(oh->alias);
6421                                                 if (!in->variant.symLinkVariant.alias)
6422                                                         alloc_failed = 1;
6423                                                 break;
6424                                         }
6425
6426                                 }
6427                         }
6428                 }
6429
6430                 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6431                         /* If we got this far while scanning, then the block is fully allocated.*/
6432                         state = YAFFS_BLOCK_STATE_FULL;
6433                 }
6434
6435                 if (state == YAFFS_BLOCK_STATE_ALLOCATING) {
6436                         /* If the block was partially allocated then treat it as fully allocated.*/
6437                         state = YAFFS_BLOCK_STATE_FULL;
6438                         dev->allocationBlock = -1;
6439                 }
6440
6441                 bi->blockState = state;
6442
6443                 /* Now let's see if it was dirty */
6444                 if (bi->pagesInUse == 0 &&
6445                     !bi->hasShrinkHeader &&
6446                     bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6447                         yaffs_BlockBecameDirty(dev, blk);
6448                 }
6449
6450         }
6451
6452
6453         /* Ok, we've done all the scanning.
6454          * Fix up the hard link chains.
6455          * We should now have scanned all the objects, now it's time to add these
6456          * hardlinks.
6457          */
6458
6459         yaffs_HardlinkFixup(dev, hardList);
6460
6461         /* Fix up any shadowed objects */
6462         {
6463                 struct yaffs_ShadowFixerStruct *fixer;
6464                 yaffs_Object *obj;
6465
6466                 while (shadowFixerList) {
6467                         fixer = shadowFixerList;
6468                         shadowFixerList = fixer->next;
6469                         /* Complete the rename transaction by deleting the shadowed object
6470                          * then setting the object header to unshadowed.
6471                          */
6472                         obj = yaffs_FindObjectByNumber(dev, fixer->shadowedId);
6473                         if (obj)
6474                                 yaffs_DeleteObject(obj);
6475
6476                         obj = yaffs_FindObjectByNumber(dev, fixer->objectId);
6477
6478                         if (obj)
6479                                 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6480
6481                         YFREE(fixer);
6482                 }
6483         }
6484
6485         yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6486
6487         if (alloc_failed)
6488                 return YAFFS_FAIL;
6489
6490         T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
6491
6492
6493         return YAFFS_OK;
6494 }
6495
6496 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
6497 {
6498         __u8 *chunkData;
6499         yaffs_ObjectHeader *oh;
6500         yaffs_Device *dev;
6501         yaffs_ExtendedTags tags;
6502         int result;
6503         int alloc_failed = 0;
6504
6505         if (!in)
6506                 return;
6507
6508         dev = in->myDev;
6509
6510 #if 0
6511         T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
6512                 in->objectId,
6513                 in->lazyLoaded ? "not yet" : "already"));
6514 #endif
6515
6516         if (in->lazyLoaded && in->hdrChunk > 0) {
6517                 in->lazyLoaded = 0;
6518                 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6519
6520                 result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
6521                 oh = (yaffs_ObjectHeader *) chunkData;
6522
6523                 in->yst_mode = oh->yst_mode;
6524 #ifdef CONFIG_YAFFS_WINCE
6525                 in->win_atime[0] = oh->win_atime[0];
6526                 in->win_ctime[0] = oh->win_ctime[0];
6527                 in->win_mtime[0] = oh->win_mtime[0];
6528                 in->win_atime[1] = oh->win_atime[1];
6529                 in->win_ctime[1] = oh->win_ctime[1];
6530                 in->win_mtime[1] = oh->win_mtime[1];
6531 #else
6532                 in->yst_uid = oh->yst_uid;
6533                 in->yst_gid = oh->yst_gid;
6534                 in->yst_atime = oh->yst_atime;
6535                 in->yst_mtime = oh->yst_mtime;
6536                 in->yst_ctime = oh->yst_ctime;
6537                 in->yst_rdev = oh->yst_rdev;
6538
6539 #endif
6540                 yaffs_SetObjectName(in, oh->name);
6541
6542                 if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6543                         in->variant.symLinkVariant.alias =
6544                                                     yaffs_CloneString(oh->alias);
6545                         if (!in->variant.symLinkVariant.alias)
6546                                 alloc_failed = 1; /* Not returned to caller */
6547                 }
6548
6549                 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6550         }
6551 }
6552
6553 static int yaffs_ScanBackwards(yaffs_Device *dev)
6554 {
6555         yaffs_ExtendedTags tags;
6556         int blk;
6557         int blockIterator;
6558         int startIterator;
6559         int endIterator;
6560         int nBlocksToScan = 0;
6561
6562         int chunk;
6563         int result;
6564         int c;
6565         int deleted;
6566         yaffs_BlockState state;
6567         yaffs_Object *hardList = NULL;
6568         yaffs_BlockInfo *bi;
6569         __u32 sequenceNumber;
6570         yaffs_ObjectHeader *oh;
6571         yaffs_Object *in;
6572         yaffs_Object *parent;
6573         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6574         int itsUnlinked;
6575         __u8 *chunkData;
6576
6577         int fileSize;
6578         int isShrink;
6579         int foundChunksInBlock;
6580         int equivalentObjectId;
6581         int alloc_failed = 0;
6582
6583
6584         yaffs_BlockIndex *blockIndex = NULL;
6585         int altBlockIndex = 0;
6586
6587         if (!dev->param.isYaffs2) {
6588                 T(YAFFS_TRACE_SCAN,
6589                   (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6590                 return YAFFS_FAIL;
6591         }
6592
6593         T(YAFFS_TRACE_SCAN,
6594           (TSTR
6595            ("yaffs_ScanBackwards starts  intstartblk %d intendblk %d..."
6596             TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6597
6598
6599         dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6600
6601         blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6602
6603         if (!blockIndex) {
6604                 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6605                 altBlockIndex = 1;
6606         }
6607
6608         if (!blockIndex) {
6609                 T(YAFFS_TRACE_SCAN,
6610                   (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6611                 return YAFFS_FAIL;
6612         }
6613
6614         dev->blocksInCheckpoint = 0;
6615
6616         chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6617
6618         /* Scan all the blocks to determine their state */
6619         bi = dev->blockInfo;
6620         for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6621                 yaffs_ClearChunkBits(dev, blk);
6622                 bi->pagesInUse = 0;
6623                 bi->softDeletions = 0;
6624
6625                 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6626
6627                 bi->blockState = state;
6628                 bi->sequenceNumber = sequenceNumber;
6629
6630                 if (bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6631                         bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6632                 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6633                         bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6634
6635                 T(YAFFS_TRACE_SCAN_DEBUG,
6636                   (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6637                    state, sequenceNumber));
6638
6639
6640                 if (state == YAFFS_BLOCK_STATE_CHECKPOINT) {
6641                         dev->blocksInCheckpoint++;
6642
6643                 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6644                         T(YAFFS_TRACE_BAD_BLOCKS,
6645                           (TSTR("block %d is bad" TENDSTR), blk));
6646                 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6647                         T(YAFFS_TRACE_SCAN_DEBUG,
6648                           (TSTR("Block empty " TENDSTR)));
6649                         dev->nErasedBlocks++;
6650                         dev->nFreeChunks += dev->param.nChunksPerBlock;
6651                 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6652
6653                         /* Determine the highest sequence number */
6654                         if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6655                             sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6656
6657                                 blockIndex[nBlocksToScan].seq = sequenceNumber;
6658                                 blockIndex[nBlocksToScan].block = blk;
6659
6660                                 nBlocksToScan++;
6661
6662                                 if (sequenceNumber >= dev->sequenceNumber)
6663                                         dev->sequenceNumber = sequenceNumber;
6664                         } else {
6665                                 /* TODO: Nasty sequence number! */
6666                                 T(YAFFS_TRACE_SCAN,
6667                                   (TSTR
6668                                    ("Block scanning block %d has bad sequence number %d"
6669                                     TENDSTR), blk, sequenceNumber));
6670
6671                         }
6672                 }
6673                 bi++;
6674         }
6675
6676         T(YAFFS_TRACE_SCAN,
6677         (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6678
6679
6680
6681         YYIELD();
6682
6683         /* Sort the blocks */
6684 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6685         {
6686                 /* Use qsort now. */
6687                 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6688         }
6689 #else
6690         {
6691                 /* Dungy old bubble sort... */
6692
6693                 yaffs_BlockIndex temp;
6694                 int i;
6695                 int j;
6696
6697                 for (i = 0; i < nBlocksToScan; i++)
6698                         for (j = i + 1; j < nBlocksToScan; j++)
6699                                 if (blockIndex[i].seq > blockIndex[j].seq) {
6700                                         temp = blockIndex[j];
6701                                         blockIndex[j] = blockIndex[i];
6702                                         blockIndex[i] = temp;
6703                                 }
6704         }
6705 #endif
6706
6707         YYIELD();
6708
6709         T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6710
6711         /* Now scan the blocks looking at the data. */
6712         startIterator = 0;
6713         endIterator = nBlocksToScan - 1;
6714         T(YAFFS_TRACE_SCAN_DEBUG,
6715           (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6716
6717         /* For each block.... backwards */
6718         for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6719                         blockIterator--) {
6720                 /* Cooperative multitasking! This loop can run for so
6721                    long that watchdog timers expire. */
6722                 YYIELD();
6723
6724                 /* get the block to scan in the correct order */
6725                 blk = blockIndex[blockIterator].block;
6726
6727                 bi = yaffs_GetBlockInfo(dev, blk);
6728
6729
6730                 state = bi->blockState;
6731
6732                 deleted = 0;
6733
6734                 /* For each chunk in each block that needs scanning.... */
6735                 foundChunksInBlock = 0;
6736                 for (c = dev->param.nChunksPerBlock - 1;
6737                      !alloc_failed && c >= 0 &&
6738                      (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6739                       state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6740                         /* Scan backwards...
6741                          * Read the tags and decide what to do
6742                          */
6743
6744                         chunk = blk * dev->param.nChunksPerBlock + c;
6745
6746                         result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6747                                                         &tags);
6748
6749                         /* Let's have a good look at this chunk... */
6750
6751                         if (!tags.chunkUsed) {
6752                                 /* An unassigned chunk in the block.
6753                                  * If there are used chunks after this one, then
6754                                  * it is a chunk that was skipped due to failing the erased
6755                                  * check. Just skip it so that it can be deleted.
6756                                  * But, more typically, We get here when this is an unallocated
6757                                  * chunk and his means that either the block is empty or
6758                                  * this is the one being allocated from
6759                                  */
6760
6761                                 if (foundChunksInBlock) {
6762                                         /* This is a chunk that was skipped due to failing the erased check */
6763                                 } else if (c == 0) {
6764                                         /* We're looking at the first chunk in the block so the block is unused */
6765                                         state = YAFFS_BLOCK_STATE_EMPTY;
6766                                         dev->nErasedBlocks++;
6767                                 } else {
6768                                         if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6769                                             state == YAFFS_BLOCK_STATE_ALLOCATING) {
6770                                                 if (dev->sequenceNumber == bi->sequenceNumber) {
6771                                                         /* this is the block being allocated from */
6772
6773                                                         T(YAFFS_TRACE_SCAN,
6774                                                           (TSTR
6775                                                            (" Allocating from %d %d"
6776                                                             TENDSTR), blk, c));
6777
6778                                                         state = YAFFS_BLOCK_STATE_ALLOCATING;
6779                                                         dev->allocationBlock = blk;
6780                                                         dev->allocationPage = c;
6781                                                         dev->allocationBlockFinder = blk;
6782                                                 } else {
6783                                                         /* This is a partially written block that is not
6784                                                          * the current allocation block.
6785                                                          */
6786
6787                                                          T(YAFFS_TRACE_SCAN,
6788                                                          (TSTR("Partially written block %d detected" TENDSTR),
6789                                                          blk));
6790                                                 }
6791                                         }
6792                                 }
6793
6794                                 dev->nFreeChunks++;
6795
6796                         } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED) {
6797                                 T(YAFFS_TRACE_SCAN,
6798                                   (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
6799                                   blk, c));
6800
6801                                   dev->nFreeChunks++;
6802
6803                         } else if (tags.chunkId > 0) {
6804                                 /* chunkId > 0 so it is a data chunk... */
6805                                 unsigned int endpos;
6806                                 __u32 chunkBase =
6807                                     (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6808
6809                                 foundChunksInBlock = 1;
6810
6811
6812                                 yaffs_SetChunkBit(dev, blk, c);
6813                                 bi->pagesInUse++;
6814
6815                                 in = yaffs_FindOrCreateObjectByNumber(dev,
6816                                                                       tags.
6817                                                                       objectId,
6818                                                                       YAFFS_OBJECT_TYPE_FILE);
6819                                 if (!in) {
6820                                         /* Out of memory */
6821                                         alloc_failed = 1;
6822                                 }
6823
6824                                 if (in &&
6825                                     in->variantType == YAFFS_OBJECT_TYPE_FILE
6826                                     && chunkBase < in->variant.fileVariant.shrinkSize) {
6827                                         /* This has not been invalidated by a resize */
6828                                         if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, -1)) {
6829                                                 alloc_failed = 1;
6830                                         }
6831
6832                                         /* File size is calculated by looking at the data chunks if we have not
6833                                          * seen an object header yet. Stop this practice once we find an object header.
6834                                          */
6835                                         endpos = chunkBase + tags.byteCount;
6836
6837                                         if (!in->valid &&       /* have not got an object header yet */
6838                                             in->variant.fileVariant.scannedFileSize < endpos) {
6839                                                 in->variant.fileVariant.scannedFileSize = endpos;
6840                                                 in->variant.fileVariant.fileSize = endpos;
6841                                         }
6842
6843                                 } else if (in) {
6844                                         /* This chunk has been invalidated by a resize, or a past file deletion
6845                                          * so delete the chunk*/
6846                                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6847
6848                                 }
6849                         } else {
6850                                 /* chunkId == 0, so it is an ObjectHeader.
6851                                  * Thus, we read in the object header and make the object
6852                                  */
6853                                 foundChunksInBlock = 1;
6854
6855                                 yaffs_SetChunkBit(dev, blk, c);
6856                                 bi->pagesInUse++;
6857
6858                                 oh = NULL;
6859                                 in = NULL;
6860
6861                                 if (tags.extraHeaderInfoAvailable) {
6862                                         in = yaffs_FindOrCreateObjectByNumber(dev,
6863                                                 tags.objectId,
6864                                                 tags.extraObjectType);
6865                                         if (!in)
6866                                                 alloc_failed = 1;
6867                                 }
6868
6869                                 if (!in ||
6870                                     (!in->valid && dev->param.disableLazyLoad) ||
6871                                     tags.extraShadows ||
6872                                     (!in->valid &&
6873                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
6874                                      tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))) {
6875
6876                                         /* If we don't have  valid info then we need to read the chunk
6877                                          * TODO In future we can probably defer reading the chunk and
6878                                          * living with invalid data until needed.
6879                                          */
6880
6881                                         result = yaffs_ReadChunkWithTagsFromNAND(dev,
6882                                                                         chunk,
6883                                                                         chunkData,
6884                                                                         NULL);
6885
6886                                         oh = (yaffs_ObjectHeader *) chunkData;
6887
6888                                         if (dev->param.inbandTags) {
6889                                                 /* Fix up the header if they got corrupted by inband tags */
6890                                                 oh->shadowsObject = oh->inbandShadowsObject;
6891                                                 oh->isShrink = oh->inbandIsShrink;
6892                                         }
6893
6894                                         if (!in) {
6895                                                 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6896                                                 if (!in)
6897                                                         alloc_failed = 1;
6898                                         }
6899
6900                                 }
6901
6902                                 if (!in) {
6903                                         /* TODO Hoosterman we have a problem! */
6904                                         T(YAFFS_TRACE_ERROR,
6905                                           (TSTR
6906                                            ("yaffs tragedy: Could not make object for object  %d at chunk %d during scan"
6907                                             TENDSTR), tags.objectId, chunk));
6908                                         continue;
6909                                 }
6910
6911                                 if (in->valid) {
6912                                         /* We have already filled this one.
6913                                          * We have a duplicate that will be discarded, but
6914                                          * we first have to suck out resize info if it is a file.
6915                                          */
6916
6917                                         if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6918                                              ((oh &&
6919                                                oh->type == YAFFS_OBJECT_TYPE_FILE) ||
6920                                               (tags.extraHeaderInfoAvailable  &&
6921                                                tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))) {
6922                                                 __u32 thisSize =
6923                                                     (oh) ? oh->fileSize : tags.
6924                                                     extraFileLength;
6925                                                 __u32 parentObjectId =
6926                                                     (oh) ? oh->
6927                                                     parentObjectId : tags.
6928                                                     extraParentObjectId;
6929
6930
6931                                                 isShrink =
6932                                                     (oh) ? oh->isShrink : tags.
6933                                                     extraIsShrinkHeader;
6934
6935                                                 /* If it is deleted (unlinked at start also means deleted)
6936                                                  * we treat the file size as being zeroed at this point.
6937                                                  */
6938                                                 if (parentObjectId ==
6939                                                     YAFFS_OBJECTID_DELETED
6940                                                     || parentObjectId ==
6941                                                     YAFFS_OBJECTID_UNLINKED) {
6942                                                         thisSize = 0;
6943                                                         isShrink = 1;
6944                                                 }
6945
6946                                                 if (isShrink && in->variant.fileVariant.shrinkSize > thisSize)
6947                                                         in->variant.fileVariant.shrinkSize = thisSize;
6948
6949                                                 if (isShrink)
6950                                                         bi->hasShrinkHeader = 1;
6951
6952                                         }
6953                                         /* Use existing - destroy this one. */
6954                                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6955
6956                                 }
6957
6958                                 if (!in->valid && in->variantType !=
6959                                     (oh ? oh->type : tags.extraObjectType))
6960                                         T(YAFFS_TRACE_ERROR, (
6961                                                 TSTR("yaffs tragedy: Bad object type, "
6962                                             TCONT("%d != %d, for object %d at chunk ")
6963                                             TCONT("%d during scan")
6964                                                 TENDSTR), oh ?
6965                                             oh->type : tags.extraObjectType,
6966                                             in->variantType, tags.objectId,
6967                                             chunk));
6968
6969                                 if (!in->valid &&
6970                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
6971                                      tags.objectId ==
6972                                      YAFFS_OBJECTID_LOSTNFOUND)) {
6973                                         /* We only load some info, don't fiddle with directory structure */
6974                                         in->valid = 1;
6975
6976                                         if (oh) {
6977                                                 in->variantType = oh->type;
6978
6979                                                 in->yst_mode = oh->yst_mode;
6980 #ifdef CONFIG_YAFFS_WINCE
6981                                                 in->win_atime[0] = oh->win_atime[0];
6982                                                 in->win_ctime[0] = oh->win_ctime[0];
6983                                                 in->win_mtime[0] = oh->win_mtime[0];
6984                                                 in->win_atime[1] = oh->win_atime[1];
6985                                                 in->win_ctime[1] = oh->win_ctime[1];
6986                                                 in->win_mtime[1] = oh->win_mtime[1];
6987 #else
6988                                                 in->yst_uid = oh->yst_uid;
6989                                                 in->yst_gid = oh->yst_gid;
6990                                                 in->yst_atime = oh->yst_atime;
6991                                                 in->yst_mtime = oh->yst_mtime;
6992                                                 in->yst_ctime = oh->yst_ctime;
6993                                                 in->yst_rdev = oh->yst_rdev;
6994
6995 #endif
6996                                         } else {
6997                                                 in->variantType = tags.extraObjectType;
6998                                                 in->lazyLoaded = 1;
6999                                         }
7000
7001                                         in->hdrChunk = chunk;
7002
7003                                 } else if (!in->valid) {
7004                                         /* we need to load this info */
7005
7006                                         in->valid = 1;
7007                                         in->hdrChunk = chunk;
7008
7009                                         if (oh) {
7010                                                 in->variantType = oh->type;
7011
7012                                                 in->yst_mode = oh->yst_mode;
7013 #ifdef CONFIG_YAFFS_WINCE
7014                                                 in->win_atime[0] = oh->win_atime[0];
7015                                                 in->win_ctime[0] = oh->win_ctime[0];
7016                                                 in->win_mtime[0] = oh->win_mtime[0];
7017                                                 in->win_atime[1] = oh->win_atime[1];
7018                                                 in->win_ctime[1] = oh->win_ctime[1];
7019                                                 in->win_mtime[1] = oh->win_mtime[1];
7020 #else
7021                                                 in->yst_uid = oh->yst_uid;
7022                                                 in->yst_gid = oh->yst_gid;
7023                                                 in->yst_atime = oh->yst_atime;
7024                                                 in->yst_mtime = oh->yst_mtime;
7025                                                 in->yst_ctime = oh->yst_ctime;
7026                                                 in->yst_rdev = oh->yst_rdev;
7027 #endif
7028
7029                                                 if (oh->shadowsObject > 0)
7030                                                         yaffs_HandleShadowedObject(dev,
7031                                                                            oh->
7032                                                                            shadowsObject,
7033                                                                            1);
7034                                                         
7035
7036
7037                                                 yaffs_SetObjectName(in, oh->name);
7038                                                 parent =
7039                                                     yaffs_FindOrCreateObjectByNumber
7040                                                         (dev, oh->parentObjectId,
7041                                                          YAFFS_OBJECT_TYPE_DIRECTORY);
7042
7043                                                  fileSize = oh->fileSize;
7044                                                  isShrink = oh->isShrink;
7045                                                  equivalentObjectId = oh->equivalentObjectId;
7046
7047                                         } else {
7048                                                 in->variantType = tags.extraObjectType;
7049                                                 parent =
7050                                                     yaffs_FindOrCreateObjectByNumber
7051                                                         (dev, tags.extraParentObjectId,
7052                                                          YAFFS_OBJECT_TYPE_DIRECTORY);
7053                                                  fileSize = tags.extraFileLength;
7054                                                  isShrink = tags.extraIsShrinkHeader;
7055                                                  equivalentObjectId = tags.extraEquivalentObjectId;
7056                                                 in->lazyLoaded = 1;
7057
7058                                         }
7059                                         in->dirty = 0;
7060
7061                                         if (!parent)
7062                                                 alloc_failed = 1;
7063
7064                                         /* directory stuff...
7065                                          * hook up to parent
7066                                          */
7067
7068                                         if (parent && parent->variantType ==
7069                                             YAFFS_OBJECT_TYPE_UNKNOWN) {
7070                                                 /* Set up as a directory */
7071                                                 parent->variantType =
7072                                                         YAFFS_OBJECT_TYPE_DIRECTORY;
7073                                                 YINIT_LIST_HEAD(&parent->variant.
7074                                                         directoryVariant.
7075                                                         children);
7076                                         } else if (!parent || parent->variantType !=
7077                                                    YAFFS_OBJECT_TYPE_DIRECTORY) {
7078                                                 /* Hoosterman, another problem....
7079                                                  * We're trying to use a non-directory as a directory
7080                                                  */
7081
7082                                                 T(YAFFS_TRACE_ERROR,
7083                                                   (TSTR
7084                                                    ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
7085                                                     TENDSTR)));
7086                                                 parent = dev->lostNFoundDir;
7087                                         }
7088
7089                                         yaffs_AddObjectToDirectory(parent, in);
7090
7091                                         itsUnlinked = (parent == dev->deletedDir) ||
7092                                                       (parent == dev->unlinkedDir);
7093
7094                                         if (isShrink) {
7095                                                 /* Mark the block as having a shrinkHeader */
7096                                                 bi->hasShrinkHeader = 1;
7097                                         }
7098
7099                                         /* Note re hardlinks.
7100                                          * Since we might scan a hardlink before its equivalent object is scanned
7101                                          * we put them all in a list.
7102                                          * After scanning is complete, we should have all the objects, so we run
7103                                          * through this list and fix up all the chains.
7104                                          */
7105
7106                                         switch (in->variantType) {
7107                                         case YAFFS_OBJECT_TYPE_UNKNOWN:
7108                                                 /* Todo got a problem */
7109                                                 break;
7110                                         case YAFFS_OBJECT_TYPE_FILE:
7111
7112                                                 if (in->variant.fileVariant.
7113                                                     scannedFileSize < fileSize) {
7114                                                         /* This covers the case where the file size is greater
7115                                                          * than where the data is
7116                                                          * This will happen if the file is resized to be larger
7117                                                          * than its current data extents.
7118                                                          */
7119                                                         in->variant.fileVariant.fileSize = fileSize;
7120                                                         in->variant.fileVariant.scannedFileSize = fileSize;
7121                                                 }
7122
7123                                                 if (in->variant.fileVariant.shrinkSize > fileSize)
7124                                                         in->variant.fileVariant.shrinkSize = fileSize;
7125                                 
7126
7127                                                 break;
7128                                         case YAFFS_OBJECT_TYPE_HARDLINK:
7129                                                 if (!itsUnlinked) {
7130                                                         in->variant.hardLinkVariant.equivalentObjectId =
7131                                                                 equivalentObjectId;
7132                                                         in->hardLinks.next =
7133                                                                 (struct ylist_head *) hardList;
7134                                                         hardList = in;
7135                                                 }
7136                                                 break;
7137                                         case YAFFS_OBJECT_TYPE_DIRECTORY:
7138                                                 /* Do nothing */
7139                                                 break;
7140                                         case YAFFS_OBJECT_TYPE_SPECIAL:
7141                                                 /* Do nothing */
7142                                                 break;
7143                                         case YAFFS_OBJECT_TYPE_SYMLINK:
7144                                                 if (oh) {
7145                                                         in->variant.symLinkVariant.alias =
7146                                                                 yaffs_CloneString(oh->alias);
7147                                                         if (!in->variant.symLinkVariant.alias)
7148                                                                 alloc_failed = 1;
7149                                                 }
7150                                                 break;
7151                                         }
7152
7153                                 }
7154
7155                         }
7156
7157                 } /* End of scanning for each chunk */
7158
7159                 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
7160                         /* If we got this far while scanning, then the block is fully allocated. */
7161                         state = YAFFS_BLOCK_STATE_FULL;
7162                 }
7163
7164
7165                 bi->blockState = state;
7166
7167                 /* Now let's see if it was dirty */
7168                 if (bi->pagesInUse == 0 &&
7169                     !bi->hasShrinkHeader &&
7170                     bi->blockState == YAFFS_BLOCK_STATE_FULL) {
7171                         yaffs_BlockBecameDirty(dev, blk);
7172                 }
7173
7174         }
7175         
7176         yaffs_SkipRestOfBlock(dev);
7177
7178         if (altBlockIndex)
7179                 YFREE_ALT(blockIndex);
7180         else
7181                 YFREE(blockIndex);
7182
7183         /* Ok, we've done all the scanning.
7184          * Fix up the hard link chains.
7185          * We should now have scanned all the objects, now it's time to add these
7186          * hardlinks.
7187          */
7188         yaffs_HardlinkFixup(dev, hardList);
7189
7190
7191         yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
7192
7193         if (alloc_failed)
7194                 return YAFFS_FAIL;
7195
7196         T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
7197
7198         return YAFFS_OK;
7199 }
7200
7201 /*------------------------------  Directory Functions ----------------------------- */
7202
7203 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
7204 {
7205         struct ylist_head *lh;
7206         yaffs_Object *listObj;
7207
7208         int count = 0;
7209
7210         if (!obj) {
7211                 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
7212                 YBUG();
7213                 return;
7214         }
7215
7216         if (yaffs_SkipVerification(obj->myDev))
7217                 return;
7218
7219         if (!obj->parent) {
7220                 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
7221                 YBUG();
7222                 return;
7223         }
7224
7225         if (obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7226                 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
7227                 YBUG();
7228         }
7229
7230         /* Iterate through the objects in each hash entry */
7231
7232         ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
7233                 if (lh) {
7234                         listObj = ylist_entry(lh, yaffs_Object, siblings);
7235                         yaffs_VerifyObject(listObj);
7236                         if (obj == listObj)
7237                                 count++;
7238                 }
7239          }
7240
7241         if (count != 1) {
7242                 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR), count));
7243                 YBUG();
7244         }
7245 }
7246
7247 static void yaffs_VerifyDirectory(yaffs_Object *directory)
7248 {
7249         struct ylist_head *lh;
7250         yaffs_Object *listObj;
7251
7252         if (!directory) {
7253                 YBUG();
7254                 return;
7255         }
7256
7257         if (yaffs_SkipFullVerification(directory->myDev))
7258                 return;
7259
7260         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7261                 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR), directory->variantType));
7262                 YBUG();
7263         }
7264
7265         /* Iterate through the objects in each hash entry */
7266
7267         ylist_for_each(lh, &directory->variant.directoryVariant.children) {
7268                 if (lh) {
7269                         listObj = ylist_entry(lh, yaffs_Object, siblings);
7270                         if (listObj->parent != directory) {
7271                                 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR), listObj->parent));
7272                                 YBUG();
7273                         }
7274                         yaffs_VerifyObjectInDirectory(listObj);
7275                 }
7276         }
7277 }
7278
7279 /*
7280  *yaffs_UpdateParent() handles fixing a directories mtime and ctime when a new
7281  * link (ie. name) is created or deleted in the directory.
7282  *
7283  * ie.
7284  *   create dir/a : update dir's mtime/ctime
7285  *   rm dir/a:   update dir's mtime/ctime
7286  *   modify dir/a: don't update dir's mtimme/ctime
7287  *
7288  * This can be handled immediately or defered. Defering helps reduce the number
7289  * of updates when many files in a directory are changed within a brief period.
7290  *
7291  * If the directory updating is defered then yaffs_UpdateDirtyDirecories must be
7292  * called periodically.
7293  */
7294  
7295 static void yaffs_UpdateParent(yaffs_Object *obj)
7296 {
7297         yaffs_Device *dev;
7298         if(!obj)
7299                 return;
7300
7301         dev = obj->myDev;
7302         obj->dirty = 1;
7303         obj->yst_mtime = obj->yst_ctime = Y_CURRENT_TIME;
7304         if(dev->param.deferDirectoryUpdate){
7305                 struct ylist_head *link = &obj->variant.directoryVariant.dirty; 
7306         
7307                 if(ylist_empty(link)){
7308                         ylist_add(link,&dev->dirtyDirectories);
7309                         T(YAFFS_TRACE_BACKGROUND, (TSTR("Added object %d to dirty directories" TENDSTR),obj->objectId));
7310                 }
7311
7312         } else
7313                 yaffs_UpdateObjectHeader(obj,NULL,0,0,0);
7314 }
7315
7316 void yaffs_UpdateDirtyDirectories(yaffs_Device *dev)
7317 {
7318         struct ylist_head *link;
7319         yaffs_Object *obj;
7320         yaffs_DirectoryStructure *dS;
7321         yaffs_ObjectVariant *oV;
7322
7323         T(YAFFS_TRACE_BACKGROUND, (TSTR("Update dirty directories" TENDSTR)));
7324
7325         while(!ylist_empty(&dev->dirtyDirectories)){
7326                 link = dev->dirtyDirectories.next;
7327                 ylist_del_init(link);
7328                 
7329                 dS=ylist_entry(link,yaffs_DirectoryStructure,dirty);
7330                 oV = ylist_entry(dS,yaffs_ObjectVariant,directoryVariant);
7331                 obj = ylist_entry(oV,yaffs_Object,variant);
7332
7333                 T(YAFFS_TRACE_BACKGROUND, (TSTR("Update directory %d" TENDSTR), obj->objectId));
7334
7335                 if(obj->dirty)
7336                         yaffs_UpdateObjectHeader(obj,NULL,0,0,0);
7337         }
7338 }
7339
7340 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
7341 {
7342         yaffs_Device *dev = obj->myDev;
7343         yaffs_Object *parent;
7344
7345         yaffs_VerifyObjectInDirectory(obj);
7346         parent = obj->parent;
7347
7348         yaffs_VerifyDirectory(parent);
7349
7350         if (dev && dev->param.removeObjectCallback)
7351                 dev->param.removeObjectCallback(obj);
7352
7353
7354         ylist_del_init(&obj->siblings);
7355         obj->parent = NULL;
7356         
7357         yaffs_VerifyDirectory(parent);
7358 }
7359
7360 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
7361                                         yaffs_Object *obj)
7362 {
7363         if (!directory) {
7364                 T(YAFFS_TRACE_ALWAYS,
7365                   (TSTR
7366                    ("tragedy: Trying to add an object to a null pointer directory"
7367                     TENDSTR)));
7368                 YBUG();
7369                 return;
7370         }
7371         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7372                 T(YAFFS_TRACE_ALWAYS,
7373                   (TSTR
7374                    ("tragedy: Trying to add an object to a non-directory"
7375                     TENDSTR)));
7376                 YBUG();
7377         }
7378
7379         if (obj->siblings.prev == NULL) {
7380                 /* Not initialised */
7381                 YBUG();
7382         }
7383
7384
7385         yaffs_VerifyDirectory(directory);
7386
7387         yaffs_RemoveObjectFromDirectory(obj);
7388
7389
7390         /* Now add it */
7391         ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
7392         obj->parent = directory;
7393
7394         if (directory == obj->myDev->unlinkedDir
7395                         || directory == obj->myDev->deletedDir) {
7396                 obj->unlinked = 1;
7397                 obj->myDev->nUnlinkedFiles++;
7398                 obj->renameAllowed = 0;
7399         }
7400
7401         yaffs_VerifyDirectory(directory);
7402         yaffs_VerifyObjectInDirectory(obj);
7403 }
7404
7405 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
7406                                      const YCHAR *name)
7407 {
7408         int sum;
7409
7410         struct ylist_head *i;
7411         YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
7412
7413         yaffs_Object *l;
7414
7415         if (!name)
7416                 return NULL;
7417
7418         if (!directory) {
7419                 T(YAFFS_TRACE_ALWAYS,
7420                   (TSTR
7421                    ("tragedy: yaffs_FindObjectByName: null pointer directory"
7422                     TENDSTR)));
7423                 YBUG();
7424                 return NULL;
7425         }
7426         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7427                 T(YAFFS_TRACE_ALWAYS,
7428                   (TSTR
7429                    ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7430                 YBUG();
7431         }
7432
7433         sum = yaffs_CalcNameSum(name);
7434
7435         ylist_for_each(i, &directory->variant.directoryVariant.children) {
7436                 if (i) {
7437                         l = ylist_entry(i, yaffs_Object, siblings);
7438
7439                         if (l->parent != directory)
7440                                 YBUG();
7441
7442                         yaffs_CheckObjectDetailsLoaded(l);
7443
7444                         /* Special case for lost-n-found */
7445                         if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7446                                 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
7447                                         return l;
7448                         } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
7449                                 /* LostnFound chunk called Objxxx
7450                                  * Do a real check
7451                                  */
7452                                 yaffs_GetObjectName(l, buffer,
7453                                                     YAFFS_MAX_NAME_LENGTH + 1);
7454                                 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
7455                                         return l;
7456                         }
7457                 }
7458         }
7459
7460         return NULL;
7461 }
7462
7463
7464 #if 0
7465 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
7466                                         int (*fn) (yaffs_Object *))
7467 {
7468         struct ylist_head *i;
7469         yaffs_Object *l;
7470
7471         if (!theDir) {
7472                 T(YAFFS_TRACE_ALWAYS,
7473                   (TSTR
7474                    ("tragedy: yaffs_FindObjectByName: null pointer directory"
7475                     TENDSTR)));
7476                 YBUG();
7477                 return YAFFS_FAIL;
7478         }
7479         if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7480                 T(YAFFS_TRACE_ALWAYS,
7481                   (TSTR
7482                    ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7483                 YBUG();
7484                 return YAFFS_FAIL;
7485         }
7486
7487         ylist_for_each(i, &theDir->variant.directoryVariant.children) {
7488                 if (i) {
7489                         l = ylist_entry(i, yaffs_Object, siblings);
7490                         if (l && !fn(l))
7491                                 return YAFFS_FAIL;
7492                 }
7493         }
7494
7495         return YAFFS_OK;
7496
7497 }
7498 #endif
7499
7500 /* GetEquivalentObject dereferences any hard links to get to the
7501  * actual object.
7502  */
7503
7504 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
7505 {
7506         if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
7507                 /* We want the object id of the equivalent object, not this one */
7508                 obj = obj->variant.hardLinkVariant.equivalentObject;
7509                 yaffs_CheckObjectDetailsLoaded(obj);
7510         }
7511         return obj;
7512 }
7513
7514 int yaffs_GetObjectName(yaffs_Object *obj, YCHAR *name, int buffSize)
7515 {
7516         memset(name, 0, buffSize * sizeof(YCHAR));
7517
7518         yaffs_CheckObjectDetailsLoaded(obj);
7519
7520         if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7521                 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
7522         } else if (obj->hdrChunk <= 0) {
7523                 YCHAR locName[20];
7524                 YCHAR numString[20];
7525                 YCHAR *x = &numString[19];
7526                 unsigned v = obj->objectId;
7527                 numString[19] = 0;
7528                 while (v > 0) {
7529                         x--;
7530                         *x = '0' + (v % 10);
7531                         v /= 10;
7532                 }
7533                 /* make up a name */
7534                 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
7535                 yaffs_strcat(locName, x);
7536                 yaffs_strncpy(name, locName, buffSize - 1);
7537
7538         }
7539 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
7540         else if (obj->shortName[0])
7541                 yaffs_strncpy(name, obj->shortName,YAFFS_SHORT_NAME_LENGTH+1);
7542 #endif
7543         else {
7544                 int result;
7545                 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
7546
7547                 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
7548
7549                 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
7550
7551                 if (obj->hdrChunk > 0) {
7552                         result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
7553                                                         obj->hdrChunk, buffer,
7554                                                         NULL);
7555                 }
7556                 yaffs_strncpy(name, oh->name, buffSize - 1);
7557                 name[buffSize-1]=0;
7558
7559                 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
7560         }
7561
7562         return yaffs_strnlen(name,buffSize-1);
7563 }
7564
7565 int yaffs_GetObjectFileLength(yaffs_Object *obj)
7566 {
7567         /* Dereference any hard linking */
7568         obj = yaffs_GetEquivalentObject(obj);
7569
7570         if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
7571                 return obj->variant.fileVariant.fileSize;
7572         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
7573                 if(!obj->variant.symLinkVariant.alias)
7574                         return 0;
7575                 return yaffs_strnlen(obj->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
7576         } else {
7577                 /* Only a directory should drop through to here */
7578                 return obj->myDev->nDataBytesPerChunk;
7579         }
7580 }
7581
7582 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
7583 {
7584         int count = 0;
7585         struct ylist_head *i;
7586
7587         if (!obj->unlinked)
7588                 count++;                /* the object itself */
7589
7590         ylist_for_each(i, &obj->hardLinks)
7591                 count++;                /* add the hard links; */
7592
7593         return count;
7594 }
7595
7596 int yaffs_GetObjectInode(yaffs_Object *obj)
7597 {
7598         obj = yaffs_GetEquivalentObject(obj);
7599
7600         return obj->objectId;
7601 }
7602
7603 unsigned yaffs_GetObjectType(yaffs_Object *obj)
7604 {
7605         obj = yaffs_GetEquivalentObject(obj);
7606
7607         switch (obj->variantType) {
7608         case YAFFS_OBJECT_TYPE_FILE:
7609                 return DT_REG;
7610                 break;
7611         case YAFFS_OBJECT_TYPE_DIRECTORY:
7612                 return DT_DIR;
7613                 break;
7614         case YAFFS_OBJECT_TYPE_SYMLINK:
7615                 return DT_LNK;
7616                 break;
7617         case YAFFS_OBJECT_TYPE_HARDLINK:
7618                 return DT_REG;
7619                 break;
7620         case YAFFS_OBJECT_TYPE_SPECIAL:
7621                 if (S_ISFIFO(obj->yst_mode))
7622                         return DT_FIFO;
7623                 if (S_ISCHR(obj->yst_mode))
7624                         return DT_CHR;
7625                 if (S_ISBLK(obj->yst_mode))
7626                         return DT_BLK;
7627                 if (S_ISSOCK(obj->yst_mode))
7628                         return DT_SOCK;
7629         default:
7630                 return DT_REG;
7631                 break;
7632         }
7633 }
7634
7635 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
7636 {
7637         obj = yaffs_GetEquivalentObject(obj);
7638         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
7639                 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7640         else
7641                 return yaffs_CloneString(_Y(""));
7642 }
7643
7644 #ifndef CONFIG_YAFFS_WINCE
7645
7646 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
7647 {
7648         unsigned int valid = attr->ia_valid;
7649
7650         if (valid & ATTR_MODE)
7651                 obj->yst_mode = attr->ia_mode;
7652         if (valid & ATTR_UID)
7653                 obj->yst_uid = attr->ia_uid;
7654         if (valid & ATTR_GID)
7655                 obj->yst_gid = attr->ia_gid;
7656
7657         if (valid & ATTR_ATIME)
7658                 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7659         if (valid & ATTR_CTIME)
7660                 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7661         if (valid & ATTR_MTIME)
7662                 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7663
7664         if (valid & ATTR_SIZE)
7665                 yaffs_ResizeFile(obj, attr->ia_size);
7666
7667         yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7668
7669         return YAFFS_OK;
7670
7671 }
7672 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
7673 {
7674         unsigned int valid = 0;
7675
7676         attr->ia_mode = obj->yst_mode;
7677         valid |= ATTR_MODE;
7678         attr->ia_uid = obj->yst_uid;
7679         valid |= ATTR_UID;
7680         attr->ia_gid = obj->yst_gid;
7681         valid |= ATTR_GID;
7682
7683         Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7684         valid |= ATTR_ATIME;
7685         Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7686         valid |= ATTR_CTIME;
7687         Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7688         valid |= ATTR_MTIME;
7689
7690         attr->ia_size = yaffs_GetFileSize(obj);
7691         valid |= ATTR_SIZE;
7692
7693         attr->ia_valid = valid;
7694
7695         return YAFFS_OK;
7696 }
7697
7698 #endif
7699
7700 #if 0
7701 int yaffs_DumpObject(yaffs_Object *obj)
7702 {
7703         YCHAR name[257];
7704
7705         yaffs_GetObjectName(obj, name, YAFFS_MAX_NAME_LENGTH + 1);
7706
7707         T(YAFFS_TRACE_ALWAYS,
7708           (TSTR
7709            ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7710             " chunk %d type %d size %d\n"
7711             TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7712            obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7713            yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7714
7715         return YAFFS_OK;
7716 }
7717 #endif
7718
7719 /*---------------------------- Initialisation code -------------------------------------- */
7720
7721 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
7722 {
7723
7724         /* Common functions, gotta have */
7725         if (!dev->param.eraseBlockInNAND || !dev->param.initialiseNAND)
7726                 return 0;
7727
7728 #ifdef CONFIG_YAFFS_YAFFS2
7729
7730         /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7731         if (dev->param.writeChunkWithTagsToNAND &&
7732             dev->param.readChunkWithTagsFromNAND &&
7733             !dev->param.writeChunkToNAND &&
7734             !dev->param.readChunkFromNAND &&
7735             dev->param.markNANDBlockBad &&
7736             dev->param.queryNANDBlock)
7737                 return 1;
7738 #endif
7739
7740         /* Can use the "spare" style interface for yaffs1 */
7741         if (!dev->param.isYaffs2 &&
7742             !dev->param.writeChunkWithTagsToNAND &&
7743             !dev->param.readChunkWithTagsFromNAND &&
7744             dev->param.writeChunkToNAND &&
7745             dev->param.readChunkFromNAND &&
7746             !dev->param.markNANDBlockBad &&
7747             !dev->param.queryNANDBlock)
7748                 return 1;
7749
7750         return 0;       /* bad */
7751 }
7752
7753
7754 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7755 {
7756         /* Initialise the unlinked, deleted, root and lost and found directories */
7757
7758         dev->lostNFoundDir = dev->rootDir =  NULL;
7759         dev->unlinkedDir = dev->deletedDir = NULL;
7760
7761         dev->unlinkedDir =
7762             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7763
7764         dev->deletedDir =
7765             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7766
7767         dev->rootDir =
7768             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7769                                       YAFFS_ROOT_MODE | S_IFDIR);
7770         dev->lostNFoundDir =
7771             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7772                                       YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7773
7774         if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
7775                 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7776                 return YAFFS_OK;
7777         }
7778
7779         return YAFFS_FAIL;
7780 }
7781
7782 int yaffs_GutsInitialise(yaffs_Device *dev)
7783 {
7784         int init_failed = 0;
7785         unsigned x;
7786         int bits;
7787
7788         T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7789
7790         /* Check stuff that must be set */
7791
7792         if (!dev) {
7793                 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7794                 return YAFFS_FAIL;
7795         }
7796
7797         dev->internalStartBlock = dev->param.startBlock;
7798         dev->internalEndBlock = dev->param.endBlock;
7799         dev->blockOffset = 0;
7800         dev->chunkOffset = 0;
7801         dev->nFreeChunks = 0;
7802
7803         dev->gcBlock = 0;
7804
7805         if (dev->param.startBlock == 0) {
7806                 dev->internalStartBlock = dev->param.startBlock + 1;
7807                 dev->internalEndBlock = dev->param.endBlock + 1;
7808                 dev->blockOffset = 1;
7809                 dev->chunkOffset = dev->param.nChunksPerBlock;
7810         }
7811
7812         /* Check geometry parameters. */
7813
7814         if ((!dev->param.inbandTags && dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 1024) ||
7815             (!dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 512) ||
7816             (dev->param.inbandTags && !dev->param.isYaffs2) ||
7817              dev->param.nChunksPerBlock < 2 ||
7818              dev->param.nReservedBlocks < 2 ||
7819              dev->internalStartBlock <= 0 ||
7820              dev->internalEndBlock <= 0 ||
7821              dev->internalEndBlock <= (dev->internalStartBlock + dev->param.nReservedBlocks + 2)) {     /* otherwise it is too small */
7822                 T(YAFFS_TRACE_ALWAYS,
7823                   (TSTR
7824                    ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7825                     TENDSTR), dev->param.totalBytesPerChunk, dev->param.isYaffs2 ? "2" : "", dev->param.inbandTags));
7826                 return YAFFS_FAIL;
7827         }
7828
7829         if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7830                 T(YAFFS_TRACE_ALWAYS,
7831                   (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7832                 return YAFFS_FAIL;
7833         }
7834
7835         /* Sort out space for inband tags, if required */
7836         if (dev->param.inbandTags)
7837                 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7838         else
7839                 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk;
7840
7841         /* Got the right mix of functions? */
7842         if (!yaffs_CheckDevFunctions(dev)) {
7843                 /* Function missing */
7844                 T(YAFFS_TRACE_ALWAYS,
7845                   (TSTR
7846                    ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7847
7848                 return YAFFS_FAIL;
7849         }
7850
7851         /* This is really a compilation check. */
7852         if (!yaffs_CheckStructures()) {
7853                 T(YAFFS_TRACE_ALWAYS,
7854                   (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7855                 return YAFFS_FAIL;
7856         }
7857
7858         if (dev->isMounted) {
7859                 T(YAFFS_TRACE_ALWAYS,
7860                   (TSTR("yaffs: device already mounted\n" TENDSTR)));
7861                 return YAFFS_FAIL;
7862         }
7863
7864         /* Finished with most checks. One or two more checks happen later on too. */
7865
7866         dev->isMounted = 1;
7867
7868         /* OK now calculate a few things for the device */
7869
7870         /*
7871          *  Calculate all the chunk size manipulation numbers:
7872          */
7873         x = dev->nDataBytesPerChunk;
7874         /* We always use dev->chunkShift and dev->chunkDiv */
7875         dev->chunkShift = Shifts(x);
7876         x >>= dev->chunkShift;
7877         dev->chunkDiv = x;
7878         /* We only use chunk mask if chunkDiv is 1 */
7879         dev->chunkMask = (1<<dev->chunkShift) - 1;
7880
7881         /*
7882          * Calculate chunkGroupBits.
7883          * We need to find the next power of 2 > than internalEndBlock
7884          */
7885
7886         x = dev->param.nChunksPerBlock * (dev->internalEndBlock + 1);
7887
7888         bits = ShiftsGE(x);
7889
7890         /* Set up tnode width if wide tnodes are enabled. */
7891         if (!dev->param.wideTnodesDisabled) {
7892                 /* bits must be even so that we end up with 32-bit words */
7893                 if (bits & 1)
7894                         bits++;
7895                 if (bits < 16)
7896                         dev->tnodeWidth = 16;
7897                 else
7898                         dev->tnodeWidth = bits;
7899         } else
7900                 dev->tnodeWidth = 16;
7901
7902         dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7903
7904         /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7905          * so if the bitwidth of the
7906          * chunk range we're using is greater than 16 we need
7907          * to figure out chunk shift and chunkGroupSize
7908          */
7909
7910         if (bits <= dev->tnodeWidth)
7911                 dev->chunkGroupBits = 0;
7912         else
7913                 dev->chunkGroupBits = bits - dev->tnodeWidth;
7914
7915
7916         dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7917
7918         if (dev->param.nChunksPerBlock < dev->chunkGroupSize) {
7919                 /* We have a problem because the soft delete won't work if
7920                  * the chunk group size > chunks per block.
7921                  * This can be remedied by using larger "virtual blocks".
7922                  */
7923                 T(YAFFS_TRACE_ALWAYS,
7924                   (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7925
7926                 return YAFFS_FAIL;
7927         }
7928
7929         /* OK, we've finished verifying the device, lets continue with initialisation */
7930
7931         /* More device initialisation */
7932         dev->allGCs = 0;
7933         dev->passiveGCs = 0;
7934         dev->oldestDirtyGCs = 0;
7935         dev->backgroundGCs = 0;
7936         dev->gcBlockFinder = 0;
7937         dev->bufferedBlock = -1;
7938         dev->doingBufferedBlockRewrite = 0;
7939         dev->nDeletedFiles = 0;
7940         dev->nBackgroundDeletions = 0;
7941         dev->nUnlinkedFiles = 0;
7942         dev->eccFixed = 0;
7943         dev->eccUnfixed = 0;
7944         dev->tagsEccFixed = 0;
7945         dev->tagsEccUnfixed = 0;
7946         dev->nErasureFailures = 0;
7947         dev->nErasedBlocks = 0;
7948         dev->gcDisable= 0;
7949         dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7950         YINIT_LIST_HEAD(&dev->dirtyDirectories);
7951         dev->oldestDirtySequence = 0;
7952         dev->oldestDirtyBlock = 0;
7953
7954         /* Initialise temporary buffers and caches. */
7955         if (!yaffs_InitialiseTempBuffers(dev))
7956                 init_failed = 1;
7957
7958         dev->srCache = NULL;
7959         dev->gcCleanupList = NULL;
7960
7961
7962         if (!init_failed &&
7963             dev->param.nShortOpCaches > 0) {
7964                 int i;
7965                 void *buf;
7966                 int srCacheBytes = dev->param.nShortOpCaches * sizeof(yaffs_ChunkCache);
7967
7968                 if (dev->param.nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
7969                         dev->param.nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7970
7971                 dev->srCache =  YMALLOC(srCacheBytes);
7972
7973                 buf = (__u8 *) dev->srCache;
7974
7975                 if (dev->srCache)
7976                         memset(dev->srCache, 0, srCacheBytes);
7977
7978                 for (i = 0; i < dev->param.nShortOpCaches && buf; i++) {
7979                         dev->srCache[i].object = NULL;
7980                         dev->srCache[i].lastUse = 0;
7981                         dev->srCache[i].dirty = 0;
7982                         dev->srCache[i].data = buf = YMALLOC_DMA(dev->param.totalBytesPerChunk);
7983                 }
7984                 if (!buf)
7985                         init_failed = 1;
7986
7987                 dev->srLastUse = 0;
7988         }
7989
7990         dev->cacheHits = 0;
7991
7992         if (!init_failed) {
7993                 dev->gcCleanupList = YMALLOC(dev->param.nChunksPerBlock * sizeof(__u32));
7994                 if (!dev->gcCleanupList)
7995                         init_failed = 1;
7996         }
7997
7998         if (dev->param.isYaffs2)
7999                 dev->param.useHeaderFileSize = 1;
8000
8001         if (!init_failed && !yaffs_InitialiseBlocks(dev))
8002                 init_failed = 1;
8003
8004         yaffs_InitialiseTnodes(dev);
8005         yaffs_InitialiseObjects(dev);
8006
8007         if (!init_failed && !yaffs_CreateInitialDirectories(dev))
8008                 init_failed = 1;
8009
8010
8011         if (!init_failed) {
8012                 /* Now scan the flash. */
8013                 if (dev->param.isYaffs2) {
8014                         if (yaffs_CheckpointRestore(dev)) {
8015                                 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
8016                                 T(YAFFS_TRACE_ALWAYS,
8017                                   (TSTR("yaffs: restored from checkpoint" TENDSTR)));
8018                         } else {
8019
8020                                 /* Clean up the mess caused by an aborted checkpoint load
8021                                  * and scan backwards.
8022                                  */
8023                                 yaffs_DeinitialiseBlocks(dev);
8024                                 yaffs_DeinitialiseTnodes(dev);
8025                                 yaffs_DeinitialiseObjects(dev);
8026
8027
8028                                 dev->nErasedBlocks = 0;
8029                                 dev->nFreeChunks = 0;
8030                                 dev->allocationBlock = -1;
8031                                 dev->allocationPage = -1;
8032                                 dev->nDeletedFiles = 0;
8033                                 dev->nUnlinkedFiles = 0;
8034                                 dev->nBackgroundDeletions = 0;
8035
8036                                 if (!init_failed && !yaffs_InitialiseBlocks(dev))
8037                                         init_failed = 1;
8038
8039                                 yaffs_InitialiseTnodes(dev);
8040                                 yaffs_InitialiseObjects(dev);
8041
8042                                 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
8043                                         init_failed = 1;
8044
8045                                 if (!init_failed && !yaffs_ScanBackwards(dev))
8046                                         init_failed = 1;
8047                         }
8048                 } else if (!yaffs_Scan(dev))
8049                                 init_failed = 1;
8050
8051                 yaffs_StripDeletedObjects(dev);
8052                 yaffs_FixHangingObjects(dev);
8053                 if(dev->param.emptyLostAndFound)
8054                         yaffs_EmptyLostAndFound(dev);
8055         }
8056
8057         if (init_failed) {
8058                 /* Clean up the mess */
8059                 T(YAFFS_TRACE_TRACING,
8060                   (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
8061
8062                 yaffs_Deinitialise(dev);
8063                 return YAFFS_FAIL;
8064         }
8065
8066         /* Zero out stats */
8067         dev->nPageReads = 0;
8068         dev->nPageWrites = 0;
8069         dev->nBlockErasures = 0;
8070         dev->nGCCopies = 0;
8071         dev->nRetriedWrites = 0;
8072
8073         dev->nRetiredBlocks = 0;
8074
8075         yaffs_VerifyFreeChunks(dev);
8076         yaffs_VerifyBlocks(dev);
8077
8078         /* Clean up any aborted checkpoint data */
8079         if(!dev->isCheckpointed && dev->blocksInCheckpoint > 0)
8080                 yaffs_InvalidateCheckpoint(dev);
8081
8082         T(YAFFS_TRACE_TRACING,
8083           (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
8084         return YAFFS_OK;
8085
8086 }
8087
8088 void yaffs_Deinitialise(yaffs_Device *dev)
8089 {
8090         if (dev->isMounted) {
8091                 int i;
8092
8093                 yaffs_DeinitialiseBlocks(dev);
8094                 yaffs_DeinitialiseTnodes(dev);
8095                 yaffs_DeinitialiseObjects(dev);
8096                 if (dev->param.nShortOpCaches > 0 &&
8097                     dev->srCache) {
8098
8099                         for (i = 0; i < dev->param.nShortOpCaches; i++) {
8100                                 if (dev->srCache[i].data)
8101                                         YFREE(dev->srCache[i].data);
8102                                 dev->srCache[i].data = NULL;
8103                         }
8104
8105                         YFREE(dev->srCache);
8106                         dev->srCache = NULL;
8107                 }
8108
8109                 YFREE(dev->gcCleanupList);
8110
8111                 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
8112                         YFREE(dev->tempBuffer[i].buffer);
8113
8114                 dev->isMounted = 0;
8115
8116                 if (dev->param.deinitialiseNAND)
8117                         dev->param.deinitialiseNAND(dev);
8118         }
8119 }
8120
8121 static int yaffs_CountFreeChunks(yaffs_Device *dev)
8122 {
8123         int nFree=0;
8124         int b;
8125
8126         yaffs_BlockInfo *blk;
8127
8128         blk = dev->blockInfo;
8129         for (b = dev->internalStartBlock; b <= dev->internalEndBlock; b++) {
8130                 switch (blk->blockState) {
8131                 case YAFFS_BLOCK_STATE_EMPTY:
8132                 case YAFFS_BLOCK_STATE_ALLOCATING:
8133                 case YAFFS_BLOCK_STATE_COLLECTING:
8134                 case YAFFS_BLOCK_STATE_FULL:
8135                         nFree +=
8136                             (dev->param.nChunksPerBlock - blk->pagesInUse +
8137                              blk->softDeletions);
8138                         break;
8139                 default:
8140                         break;
8141                 }
8142                 blk++;
8143         }
8144
8145         return nFree;
8146 }
8147
8148 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
8149 {
8150         /* This is what we report to the outside world */
8151
8152         int nFree;
8153         int nDirtyCacheChunks;
8154         int blocksForCheckpoint;
8155         int i;
8156
8157 #if 1
8158         nFree = dev->nFreeChunks;
8159 #else
8160         nFree = yaffs_CountFreeChunks(dev);
8161 #endif
8162
8163         nFree += dev->nDeletedFiles;
8164
8165         /* Now count the number of dirty chunks in the cache and subtract those */
8166
8167         for (nDirtyCacheChunks = 0, i = 0; i < dev->param.nShortOpCaches; i++) {
8168                 if (dev->srCache[i].dirty)
8169                         nDirtyCacheChunks++;
8170         }
8171
8172         nFree -= nDirtyCacheChunks;
8173
8174         nFree -= ((dev->param.nReservedBlocks + 1) * dev->param.nChunksPerBlock);
8175
8176         /* Now we figure out how much to reserve for the checkpoint and report that... */
8177         blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
8178         if (blocksForCheckpoint < 0)
8179                 blocksForCheckpoint = 0;
8180
8181         nFree -= (blocksForCheckpoint * dev->param.nChunksPerBlock);
8182
8183         if (nFree < 0)
8184                 nFree = 0;
8185
8186         return nFree;
8187
8188 }
8189
8190 static int yaffs_freeVerificationFailures;
8191
8192 static void yaffs_VerifyFreeChunks(yaffs_Device *dev)
8193 {
8194         int counted;
8195         int difference;
8196
8197         if (yaffs_SkipVerification(dev))
8198                 return;
8199
8200         counted = yaffs_CountFreeChunks(dev);
8201
8202         difference = dev->nFreeChunks - counted;
8203
8204         if (difference) {
8205                 T(YAFFS_TRACE_ALWAYS,
8206                   (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
8207                    dev->nFreeChunks, counted, difference));
8208                 yaffs_freeVerificationFailures++;
8209         }
8210 }
8211
8212 /*---------------------------------------- YAFFS test code ----------------------*/
8213
8214 #define yaffs_CheckStruct(structure, syze, name) \
8215         do { \
8216                 if (sizeof(structure) != syze) { \
8217                         T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
8218                                 name, syze, (int) sizeof(structure))); \
8219                         return YAFFS_FAIL; \
8220                 } \
8221         } while (0)
8222
8223 static int yaffs_CheckStructures(void)
8224 {
8225 /*      yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
8226 /*      yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
8227 /*      yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
8228 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
8229 /*      yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode"); */
8230 #endif
8231 #ifndef CONFIG_YAFFS_WINCE
8232         yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");
8233 #endif
8234         return YAFFS_OK;
8235 }