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