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