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