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