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