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