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