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