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