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