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