df8efbe3c6371ac22914fc444492775f8cf82c48
[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.107 2010-02-17 02:01:25 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->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->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->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->nChunksPerBlock ||
458            bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
459            actuallyUsed < 0 || actuallyUsed > dev->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->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->nChunksPerBlock;
766         chunkMax = (dev->internalEndBlock+1) * dev->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->nChunksPerBlock,
773                                         obj->hdrChunk % dev->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->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->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->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->nChunksPerBlock,
1602                                 theChunk % dev->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->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 #ifdef __KERNEL__
2096
2097 void yaffs_HandleDeferedFree(yaffs_Object *obj)
2098 {
2099         if (obj->deferedFree)
2100                 yaffs_FreeObject(obj);
2101 }
2102
2103 #endif
2104
2105 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
2106 {
2107         /* Free the list of allocated Objects */
2108
2109         yaffs_ObjectList *tmp;
2110
2111         while (dev->allocatedObjectList) {
2112                 tmp = dev->allocatedObjectList->next;
2113                 YFREE(dev->allocatedObjectList->objects);
2114                 YFREE(dev->allocatedObjectList);
2115
2116                 dev->allocatedObjectList = tmp;
2117         }
2118
2119         dev->freeObjects = NULL;
2120         dev->nFreeObjects = 0;
2121         dev->nObjectsCreated = 0;
2122 }
2123
2124 static void yaffs_InitialiseObjects(yaffs_Device *dev)
2125 {
2126         int i;
2127
2128         dev->allocatedObjectList = NULL;
2129         dev->freeObjects = NULL;
2130         dev->nFreeObjects = 0;
2131
2132         for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2133                 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2134                 dev->objectBucket[i].count = 0;
2135         }
2136 }
2137
2138 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
2139 {
2140         static int x;
2141         int i;
2142         int l = 999;
2143         int lowest = 999999;
2144
2145         /* First let's see if we can find one that's empty. */
2146
2147         for (i = 0; i < 10 && lowest > 0; i++) {
2148                 x++;
2149                 x %= YAFFS_NOBJECT_BUCKETS;
2150                 if (dev->objectBucket[x].count < lowest) {
2151                         lowest = dev->objectBucket[x].count;
2152                         l = x;
2153                 }
2154
2155         }
2156
2157         /* If we didn't find an empty list, then try
2158          * looking a bit further for a short one
2159          */
2160
2161         for (i = 0; i < 10 && lowest > 3; i++) {
2162                 x++;
2163                 x %= YAFFS_NOBJECT_BUCKETS;
2164                 if (dev->objectBucket[x].count < lowest) {
2165                         lowest = dev->objectBucket[x].count;
2166                         l = x;
2167                 }
2168
2169         }
2170
2171         return l;
2172 }
2173
2174 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
2175 {
2176         int bucket = yaffs_FindNiceObjectBucket(dev);
2177
2178         /* Now find an object value that has not already been taken
2179          * by scanning the list.
2180          */
2181
2182         int found = 0;
2183         struct ylist_head *i;
2184
2185         __u32 n = (__u32) bucket;
2186
2187         /* yaffs_CheckObjectHashSanity();  */
2188
2189         while (!found) {
2190                 found = 1;
2191                 n += YAFFS_NOBJECT_BUCKETS;
2192                 if (1 || dev->objectBucket[bucket].count > 0) {
2193                         ylist_for_each(i, &dev->objectBucket[bucket].list) {
2194                                 /* If there is already one in the list */
2195                                 if (i && ylist_entry(i, yaffs_Object,
2196                                                 hashLink)->objectId == n) {
2197                                         found = 0;
2198                                 }
2199                         }
2200                 }
2201         }
2202
2203         return n;
2204 }
2205
2206 static void yaffs_HashObject(yaffs_Object *in)
2207 {
2208         int bucket = yaffs_HashFunction(in->objectId);
2209         yaffs_Device *dev = in->myDev;
2210
2211         ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2212         dev->objectBucket[bucket].count++;
2213 }
2214
2215 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
2216 {
2217         int bucket = yaffs_HashFunction(number);
2218         struct ylist_head *i;
2219         yaffs_Object *in;
2220
2221         ylist_for_each(i, &dev->objectBucket[bucket].list) {
2222                 /* Look if it is in the list */
2223                 if (i) {
2224                         in = ylist_entry(i, yaffs_Object, hashLink);
2225                         if (in->objectId == number) {
2226 #ifdef __KERNEL__
2227                                 /* Don't tell the VFS about this one if it is defered free */
2228                                 if (in->deferedFree)
2229                                         return NULL;
2230 #endif
2231
2232                                 return in;
2233                         }
2234                 }
2235         }
2236
2237         return NULL;
2238 }
2239
2240 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
2241                                     yaffs_ObjectType type)
2242 {
2243         yaffs_Object *theObject=NULL;
2244         yaffs_Tnode *tn = NULL;
2245
2246         if (number < 0)
2247                 number = yaffs_CreateNewObjectNumber(dev);
2248
2249         if (type == YAFFS_OBJECT_TYPE_FILE) {
2250                 tn = yaffs_GetTnode(dev);
2251                 if (!tn)
2252                         return NULL;
2253         }
2254
2255         theObject = yaffs_AllocateEmptyObject(dev);
2256         if (!theObject){
2257                 if(tn)
2258                         yaffs_FreeTnode(dev,tn);
2259                 return NULL;
2260         }
2261
2262
2263         if (theObject) {
2264                 theObject->fake = 0;
2265                 theObject->renameAllowed = 1;
2266                 theObject->unlinkAllowed = 1;
2267                 theObject->objectId = number;
2268                 yaffs_HashObject(theObject);
2269                 theObject->variantType = type;
2270 #ifdef CONFIG_YAFFS_WINCE
2271                 yfsd_WinFileTimeNow(theObject->win_atime);
2272                 theObject->win_ctime[0] = theObject->win_mtime[0] =
2273                     theObject->win_atime[0];
2274                 theObject->win_ctime[1] = theObject->win_mtime[1] =
2275                     theObject->win_atime[1];
2276
2277 #else
2278
2279                 theObject->yst_atime = theObject->yst_mtime =
2280                     theObject->yst_ctime = Y_CURRENT_TIME;
2281 #endif
2282                 switch (type) {
2283                 case YAFFS_OBJECT_TYPE_FILE:
2284                         theObject->variant.fileVariant.fileSize = 0;
2285                         theObject->variant.fileVariant.scannedFileSize = 0;
2286                         theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2287                         theObject->variant.fileVariant.topLevel = 0;
2288                         theObject->variant.fileVariant.top = tn;
2289                         break;
2290                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2291                         YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2292                                         children);
2293                         break;
2294                 case YAFFS_OBJECT_TYPE_SYMLINK:
2295                 case YAFFS_OBJECT_TYPE_HARDLINK:
2296                 case YAFFS_OBJECT_TYPE_SPECIAL:
2297                         /* No action required */
2298                         break;
2299                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2300                         /* todo this should not happen */
2301                         break;
2302                 }
2303         }
2304
2305         return theObject;
2306 }
2307
2308 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
2309                                                       int number,
2310                                                       yaffs_ObjectType type)
2311 {
2312         yaffs_Object *theObject = NULL;
2313
2314         if (number > 0)
2315                 theObject = yaffs_FindObjectByNumber(dev, number);
2316
2317         if (!theObject)
2318                 theObject = yaffs_CreateNewObject(dev, number, type);
2319
2320         return theObject;
2321
2322 }
2323
2324
2325 static YCHAR *yaffs_CloneString(const YCHAR *str)
2326 {
2327         YCHAR *newStr = NULL;
2328         int len;
2329
2330         if (!str)
2331                 str = _Y("");
2332
2333         len = yaffs_strnlen(str,YAFFS_MAX_ALIAS_LENGTH);
2334         newStr = YMALLOC((len + 1) * sizeof(YCHAR));
2335         if (newStr){
2336                 yaffs_strncpy(newStr, str,len);
2337                 newStr[len] = 0;
2338         }
2339         return newStr;
2340
2341 }
2342
2343 /*
2344  * Mknod (create) a new object.
2345  * equivalentObject only has meaning for a hard link;
2346  * aliasString only has meaning for a symlink.
2347  * rdev only has meaning for devices (a subset of special objects)
2348  */
2349
2350 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2351                                        yaffs_Object *parent,
2352                                        const YCHAR *name,
2353                                        __u32 mode,
2354                                        __u32 uid,
2355                                        __u32 gid,
2356                                        yaffs_Object *equivalentObject,
2357                                        const YCHAR *aliasString, __u32 rdev)
2358 {
2359         yaffs_Object *in;
2360         YCHAR *str = NULL;
2361
2362         yaffs_Device *dev = parent->myDev;
2363
2364         /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2365         if (yaffs_FindObjectByName(parent, name))
2366                 return NULL;
2367
2368         if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2369                 str = yaffs_CloneString(aliasString);
2370                 if (!str)
2371                         return NULL;
2372         }
2373
2374         in = yaffs_CreateNewObject(dev, -1, type);
2375
2376         if (!in){
2377                 if(str)
2378                         YFREE(str);
2379                 return NULL;
2380         }
2381
2382
2383
2384
2385
2386         if (in) {
2387                 in->hdrChunk = 0;
2388                 in->valid = 1;
2389                 in->variantType = type;
2390
2391                 in->yst_mode = mode;
2392
2393 #ifdef CONFIG_YAFFS_WINCE
2394                 yfsd_WinFileTimeNow(in->win_atime);
2395                 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2396                 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2397
2398 #else
2399                 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2400
2401                 in->yst_rdev = rdev;
2402                 in->yst_uid = uid;
2403                 in->yst_gid = gid;
2404 #endif
2405                 in->nDataChunks = 0;
2406
2407                 yaffs_SetObjectName(in, name);
2408                 in->dirty = 1;
2409
2410                 yaffs_AddObjectToDirectory(parent, in);
2411
2412                 in->myDev = parent->myDev;
2413
2414                 switch (type) {
2415                 case YAFFS_OBJECT_TYPE_SYMLINK:
2416                         in->variant.symLinkVariant.alias = str;
2417                         break;
2418                 case YAFFS_OBJECT_TYPE_HARDLINK:
2419                         in->variant.hardLinkVariant.equivalentObject =
2420                                 equivalentObject;
2421                         in->variant.hardLinkVariant.equivalentObjectId =
2422                                 equivalentObject->objectId;
2423                         ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2424                         break;
2425                 case YAFFS_OBJECT_TYPE_FILE:
2426                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2427                 case YAFFS_OBJECT_TYPE_SPECIAL:
2428                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2429                         /* do nothing */
2430                         break;
2431                 }
2432
2433                 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2434                         /* Could not create the object header, fail the creation */
2435                         yaffs_DeleteObject(in);
2436                         in = NULL;
2437                 }
2438
2439                 yaffs_UpdateParent(parent);
2440         }
2441
2442         return in;
2443 }
2444
2445 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
2446                         __u32 mode, __u32 uid, __u32 gid)
2447 {
2448         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2449                                 uid, gid, NULL, NULL, 0);
2450 }
2451
2452 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
2453                                 __u32 mode, __u32 uid, __u32 gid)
2454 {
2455         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2456                                  mode, uid, gid, NULL, NULL, 0);
2457 }
2458
2459 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
2460                                 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2461 {
2462         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2463                                  uid, gid, NULL, NULL, rdev);
2464 }
2465
2466 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
2467                                 __u32 mode, __u32 uid, __u32 gid,
2468                                 const YCHAR *alias)
2469 {
2470         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2471                                 uid, gid, NULL, alias, 0);
2472 }
2473
2474 /* yaffs_Link returns the object id of the equivalent object.*/
2475 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
2476                         yaffs_Object *equivalentObject)
2477 {
2478         /* Get the real object in case we were fed a hard link as an equivalent object */
2479         equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2480
2481         if (yaffs_MknodObject
2482             (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2483              equivalentObject, NULL, 0)) {
2484                 return equivalentObject;
2485         } else {
2486                 return NULL;
2487         }
2488
2489 }
2490
2491 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
2492                                 const YCHAR *newName, int force, int shadows)
2493 {
2494         int unlinkOp;
2495         int deleteOp;
2496
2497         yaffs_Object *existingTarget;
2498
2499         if (newDir == NULL)
2500                 newDir = obj->parent;   /* use the old directory */
2501
2502         if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2503                 T(YAFFS_TRACE_ALWAYS,
2504                   (TSTR
2505                    ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2506                     TENDSTR)));
2507                 YBUG();
2508         }
2509
2510         /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2511         if (obj->myDev->isYaffs2)
2512                 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2513         else
2514                 unlinkOp = (newDir == obj->myDev->unlinkedDir
2515                             && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2516
2517         deleteOp = (newDir == obj->myDev->deletedDir);
2518
2519         existingTarget = yaffs_FindObjectByName(newDir, newName);
2520
2521         /* If the object is a file going into the unlinked directory,
2522          *   then it is OK to just stuff it in since duplicate names are allowed.
2523          *   else only proceed if the new name does not exist and if we're putting
2524          *   it into a directory.
2525          */
2526         if ((unlinkOp ||
2527              deleteOp ||
2528              force ||
2529              (shadows > 0) ||
2530              !existingTarget) &&
2531             newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2532                 yaffs_SetObjectName(obj, newName);
2533                 obj->dirty = 1;
2534
2535                 yaffs_AddObjectToDirectory(newDir, obj);
2536
2537                 if (unlinkOp)
2538                         obj->unlinked = 1;
2539
2540                 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2541                 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows) >= 0)
2542                         return YAFFS_OK;
2543         }
2544
2545         return YAFFS_FAIL;
2546 }
2547
2548 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
2549                 yaffs_Object *newDir, const YCHAR *newName)
2550 {
2551         yaffs_Object *obj = NULL;
2552         yaffs_Object *existingTarget = NULL;
2553         int force = 0;
2554         int result;
2555         yaffs_Device *dev;
2556
2557
2558         if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2559                 YBUG();
2560         if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2561                 YBUG();
2562
2563         dev = oldDir->myDev;
2564
2565 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2566         /* Special case for case insemsitive systems (eg. WinCE).
2567          * While look-up is case insensitive, the name isn't.
2568          * Therefore we might want to change x.txt to X.txt
2569         */
2570         if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
2571                 force = 1;
2572 #endif
2573
2574         if(yaffs_strnlen(newName,YAFFS_MAX_NAME_LENGTH+1) > YAFFS_MAX_NAME_LENGTH)
2575                 /* ENAMETOOLONG */
2576                 return YAFFS_FAIL;
2577
2578         obj = yaffs_FindObjectByName(oldDir, oldName);
2579
2580         if (obj && obj->renameAllowed) {
2581
2582                 /* Now do the handling for an existing target, if there is one */
2583
2584                 existingTarget = yaffs_FindObjectByName(newDir, newName);
2585                 if (existingTarget &&
2586                         existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2587                         !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2588                         /* There is a target that is a non-empty directory, so we fail */
2589                         return YAFFS_FAIL;      /* EEXIST or ENOTEMPTY */
2590                 } else if (existingTarget && existingTarget != obj) {
2591                         /* Nuke the target first, using shadowing,
2592                          * but only if it isn't the same object.
2593                          *
2594                          * Note we must disable gc otherwise it can mess up the shadowing.
2595                          *
2596                          */
2597                         dev->isDoingGC=1;
2598                         yaffs_ChangeObjectName(obj, newDir, newName, force,
2599                                                 existingTarget->objectId);
2600                         existingTarget->isShadowed = 1;
2601                         yaffs_UnlinkObject(existingTarget);
2602                         dev->isDoingGC=0;
2603                 }
2604
2605                 result = yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2606
2607                 yaffs_UpdateParent(oldDir);
2608                 if(newDir != oldDir)
2609                         yaffs_UpdateParent(newDir);
2610                 
2611                 return result;
2612         }
2613         return YAFFS_FAIL;
2614 }
2615
2616 /*------------------------- Block Management and Page Allocation ----------------*/
2617
2618 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
2619 {
2620         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2621
2622         dev->blockInfo = NULL;
2623         dev->chunkBits = NULL;
2624
2625         dev->allocationBlock = -1;      /* force it to get a new one */
2626
2627         /* If the first allocation strategy fails, thry the alternate one */
2628         dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2629         if (!dev->blockInfo) {
2630                 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2631                 dev->blockInfoAlt = 1;
2632         } else
2633                 dev->blockInfoAlt = 0;
2634
2635         if (dev->blockInfo) {
2636                 /* Set up dynamic blockinfo stuff. */
2637                 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2638                 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2639                 if (!dev->chunkBits) {
2640                         dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2641                         dev->chunkBitsAlt = 1;
2642                 } else
2643                         dev->chunkBitsAlt = 0;
2644         }
2645
2646         if (dev->blockInfo && dev->chunkBits) {
2647                 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2648                 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2649                 return YAFFS_OK;
2650         }
2651
2652         return YAFFS_FAIL;
2653 }
2654
2655 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2656 {
2657         if (dev->blockInfoAlt && dev->blockInfo)
2658                 YFREE_ALT(dev->blockInfo);
2659         else if (dev->blockInfo)
2660                 YFREE(dev->blockInfo);
2661
2662         dev->blockInfoAlt = 0;
2663
2664         dev->blockInfo = NULL;
2665
2666         if (dev->chunkBitsAlt && dev->chunkBits)
2667                 YFREE_ALT(dev->chunkBits);
2668         else if (dev->chunkBits)
2669                 YFREE(dev->chunkBits);
2670         dev->chunkBitsAlt = 0;
2671         dev->chunkBits = NULL;
2672 }
2673
2674 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
2675                                         yaffs_BlockInfo *bi)
2676 {
2677         int i;
2678         __u32 seq;
2679         yaffs_BlockInfo *b;
2680
2681         if (!dev->isYaffs2)
2682                 return 1;       /* disqualification only applies to yaffs2. */
2683
2684         if (!bi->hasShrinkHeader)
2685                 return 1;       /* can gc */
2686
2687         /* Find the oldest dirty sequence number if we don't know it and save it
2688          * so we don't have to keep recomputing it.
2689          */
2690         if (!dev->oldestDirtySequence) {
2691                 seq = dev->sequenceNumber;
2692
2693                 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2694                                 i++) {
2695                         b = yaffs_GetBlockInfo(dev, i);
2696                         if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2697                             (b->pagesInUse - b->softDeletions) <
2698                             dev->nChunksPerBlock && b->sequenceNumber < seq) {
2699                                 seq = b->sequenceNumber;
2700                         }
2701                 }
2702                 dev->oldestDirtySequence = seq;
2703         }
2704
2705         /* Can't do gc of this block if there are any blocks older than this one that have
2706          * discarded pages.
2707          */
2708         return (bi->sequenceNumber <= dev->oldestDirtySequence);
2709 }
2710
2711 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2712  * for garbage collection.
2713  */
2714
2715 static int yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
2716                                         int aggressive)
2717 {
2718         int b = dev->currentDirtyChecker;
2719
2720         int i;
2721         int iterations;
2722         int dirtiest = -1;
2723         int pagesInUse = 0;
2724         int prioritised = 0;
2725         yaffs_BlockInfo *bi;
2726         int pendingPrioritisedExist = 0;
2727
2728         /* First let's see if we need to grab a prioritised block */
2729         if (dev->hasPendingPrioritisedGCs) {
2730                 for (i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++) {
2731
2732                         bi = yaffs_GetBlockInfo(dev, i);
2733                         /* yaffs_VerifyBlock(dev,bi,i); */
2734
2735                         if (bi->gcPrioritise) {
2736                                 pendingPrioritisedExist = 1;
2737                                 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2738                                    yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2739                                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
2740                                         dirtiest = i;
2741                                         prioritised = 1;
2742                                         aggressive = 1; /* Fool the non-aggressive skip logiv below */
2743                                 }
2744                         }
2745                 }
2746
2747                 if (!pendingPrioritisedExist) /* None found, so we can clear this */
2748                         dev->hasPendingPrioritisedGCs = 0;
2749         }
2750
2751         /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2752          * search harder.
2753          * else (we're doing a leasurely gc), then we only bother to do this if the
2754          * block has only a few pages in use.
2755          */
2756
2757         dev->nonAggressiveSkip--;
2758
2759         if (!aggressive && (dev->nonAggressiveSkip > 0))
2760                 return -1;
2761
2762         if (!prioritised)
2763                 pagesInUse =
2764                         (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2765
2766         if (aggressive)
2767                 iterations =
2768                     dev->internalEndBlock - dev->internalStartBlock + 1;
2769         else {
2770                 iterations =
2771                     dev->internalEndBlock - dev->internalStartBlock + 1;
2772                 iterations = iterations / 16;
2773                 if (iterations > 200)
2774                         iterations = 200;
2775         }
2776
2777         for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2778                 b++;
2779                 if (b < dev->internalStartBlock || b > dev->internalEndBlock)
2780                         b = dev->internalStartBlock;
2781
2782                 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2783                         T(YAFFS_TRACE_ERROR,
2784                           (TSTR("**>> Block %d is not valid" TENDSTR), b));
2785                         YBUG();
2786                 }
2787
2788                 bi = yaffs_GetBlockInfo(dev, b);
2789
2790                 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2791                         (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2792                                 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2793                         dirtiest = b;
2794                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
2795                 }
2796         }
2797
2798         dev->currentDirtyChecker = b;
2799
2800         if (dirtiest > 0) {
2801                 T(YAFFS_TRACE_GC,
2802                   (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2803                    dev->nChunksPerBlock - pagesInUse, prioritised));
2804         }
2805
2806         dev->oldestDirtySequence = 0;
2807
2808         if (dirtiest > 0)
2809                 dev->nonAggressiveSkip = 4;
2810
2811         return dirtiest;
2812 }
2813
2814 static void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
2815 {
2816         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2817
2818         int erasedOk = 0;
2819
2820         /* If the block is still healthy erase it and mark as clean.
2821          * If the block has had a data failure, then retire it.
2822          */
2823
2824         T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2825                 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2826                 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2827
2828         bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2829
2830         if (!bi->needsRetiring) {
2831                 yaffs_InvalidateCheckpoint(dev);
2832                 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2833                 if (!erasedOk) {
2834                         dev->nErasureFailures++;
2835                         T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2836                           (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2837                 }
2838         }
2839
2840         if (erasedOk &&
2841             ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2842                 int i;
2843                 for (i = 0; i < dev->nChunksPerBlock; i++) {
2844                         if (!yaffs_CheckChunkErased
2845                             (dev, blockNo * dev->nChunksPerBlock + i)) {
2846                                 T(YAFFS_TRACE_ERROR,
2847                                   (TSTR
2848                                    (">>Block %d erasure supposedly OK, but chunk %d not erased"
2849                                     TENDSTR), blockNo, i));
2850                         }
2851                 }
2852         }
2853
2854         if (erasedOk) {
2855                 /* Clean it up... */
2856                 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2857                 dev->nErasedBlocks++;
2858                 bi->pagesInUse = 0;
2859                 bi->softDeletions = 0;
2860                 bi->hasShrinkHeader = 0;
2861                 bi->skipErasedCheck = 1;  /* This is clean, so no need to check */
2862                 bi->gcPrioritise = 0;
2863                 yaffs_ClearChunkBits(dev, blockNo);
2864
2865                 T(YAFFS_TRACE_ERASE,
2866                   (TSTR("Erased block %d" TENDSTR), blockNo));
2867         } else {
2868                 dev->nFreeChunks -= dev->nChunksPerBlock;       /* We lost a block of free space */
2869
2870                 yaffs_RetireBlock(dev, blockNo);
2871                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2872                   (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2873         }
2874 }
2875
2876 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2877 {
2878         int i;
2879
2880         yaffs_BlockInfo *bi;
2881
2882         if (dev->nErasedBlocks < 1) {
2883                 /* Hoosterman we've got a problem.
2884                  * Can't get space to gc
2885                  */
2886                 T(YAFFS_TRACE_ERROR,
2887                   (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2888
2889                 return -1;
2890         }
2891
2892         /* Find an empty block. */
2893
2894         for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2895                 dev->allocationBlockFinder++;
2896                 if (dev->allocationBlockFinder < dev->internalStartBlock
2897                     || dev->allocationBlockFinder > dev->internalEndBlock) {
2898                         dev->allocationBlockFinder = dev->internalStartBlock;
2899                 }
2900
2901                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2902
2903                 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2904                         bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2905                         dev->sequenceNumber++;
2906                         bi->sequenceNumber = dev->sequenceNumber;
2907                         dev->nErasedBlocks--;
2908                         T(YAFFS_TRACE_ALLOCATE,
2909                           (TSTR("Allocated block %d, seq  %d, %d left" TENDSTR),
2910                            dev->allocationBlockFinder, dev->sequenceNumber,
2911                            dev->nErasedBlocks));
2912                         return dev->allocationBlockFinder;
2913                 }
2914         }
2915
2916         T(YAFFS_TRACE_ALWAYS,
2917           (TSTR
2918            ("yaffs tragedy: no more erased blocks, but there should have been %d"
2919             TENDSTR), dev->nErasedBlocks));
2920
2921         return -1;
2922 }
2923
2924
2925
2926 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2927 {
2928         if (!dev->nCheckpointBlocksRequired &&
2929            dev->isYaffs2) {
2930                 /* Not a valid value so recalculate */
2931                 int nBytes = 0;
2932                 int nBlocks;
2933                 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2934                 int tnodeSize = yaffs_CalcTnodeSize(dev);
2935
2936                 nBytes += sizeof(yaffs_CheckpointValidity);
2937                 nBytes += sizeof(yaffs_CheckpointDevice);
2938                 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2939                 nBytes += devBlocks * dev->chunkBitmapStride;
2940                 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2941                 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2942                 nBytes += sizeof(yaffs_CheckpointValidity);
2943                 nBytes += sizeof(__u32); /* checksum*/
2944
2945                 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2946
2947                 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2948
2949                 dev->nCheckpointBlocksRequired = nBlocks;
2950         }
2951
2952         return dev->nCheckpointBlocksRequired;
2953 }
2954
2955 /*
2956  * Check if there's space to allocate...
2957  * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2958  */
2959 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev)
2960 {
2961         int reservedChunks;
2962         int reservedBlocks = dev->nReservedBlocks;
2963         int checkpointBlocks;
2964
2965         if (dev->isYaffs2) {
2966                 checkpointBlocks =  yaffs_CalcCheckpointBlocksRequired(dev) -
2967                                     dev->blocksInCheckpoint;
2968                 if (checkpointBlocks < 0)
2969                         checkpointBlocks = 0;
2970         } else {
2971                 checkpointBlocks = 0;
2972         }
2973
2974         reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2975
2976         return (dev->nFreeChunks > reservedChunks);
2977 }
2978
2979 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
2980                 yaffs_BlockInfo **blockUsedPtr)
2981 {
2982         int retVal;
2983         yaffs_BlockInfo *bi;
2984
2985         if (dev->allocationBlock < 0) {
2986                 /* Get next block to allocate off */
2987                 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2988                 dev->allocationPage = 0;
2989         }
2990
2991         if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2992                 /* Not enough space to allocate unless we're allowed to use the reserve. */
2993                 return -1;
2994         }
2995
2996         if (dev->nErasedBlocks < dev->nReservedBlocks
2997                         && dev->allocationPage == 0) {
2998                 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2999         }
3000
3001         /* Next page please.... */
3002         if (dev->allocationBlock >= 0) {
3003                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3004
3005                 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
3006                         dev->allocationPage;
3007                 bi->pagesInUse++;
3008                 yaffs_SetChunkBit(dev, dev->allocationBlock,
3009                                 dev->allocationPage);
3010
3011                 dev->allocationPage++;
3012
3013                 dev->nFreeChunks--;
3014
3015                 /* If the block is full set the state to full */
3016                 if (dev->allocationPage >= dev->nChunksPerBlock) {
3017                         bi->blockState = YAFFS_BLOCK_STATE_FULL;
3018                         dev->allocationBlock = -1;
3019                 }
3020
3021                 if (blockUsedPtr)
3022                         *blockUsedPtr = bi;
3023
3024                 return retVal;
3025         }
3026
3027         T(YAFFS_TRACE_ERROR,
3028                         (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
3029
3030         return -1;
3031 }
3032
3033 static int yaffs_GetErasedChunks(yaffs_Device *dev)
3034 {
3035         int n;
3036
3037         n = dev->nErasedBlocks * dev->nChunksPerBlock;
3038
3039         if (dev->allocationBlock > 0)
3040                 n += (dev->nChunksPerBlock - dev->allocationPage);
3041
3042         return n;
3043
3044 }
3045
3046 /*
3047  * yaffs_SkipRestOfBlock() skips over the rest of the allocation block
3048  * if we don't want to write to it.
3049  */
3050 static void yaffs_SkipRestOfBlock(yaffs_Device *dev)
3051 {
3052         if(dev->allocationBlock > 0){
3053                 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3054                 if(bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING){
3055                         bi->blockState = YAFFS_BLOCK_STATE_FULL;
3056                         dev->allocationBlock = -1;
3057                 }
3058         }
3059 }
3060
3061
3062 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
3063                 int wholeBlock)
3064 {
3065         int oldChunk;
3066         int newChunk;
3067         int markNAND;
3068         int retVal = YAFFS_OK;
3069         int cleanups = 0;
3070         int i;
3071         int isCheckpointBlock;
3072         int matchingChunk;
3073         int maxCopies;
3074
3075         int chunksBefore = yaffs_GetErasedChunks(dev);
3076         int chunksAfter;
3077
3078         yaffs_ExtendedTags tags;
3079
3080         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3081
3082         yaffs_Object *object;
3083
3084         isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3085
3086
3087         T(YAFFS_TRACE_TRACING,
3088                         (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3089                          block,
3090                          bi->pagesInUse,
3091                          bi->hasShrinkHeader,
3092                          wholeBlock));
3093
3094         /*yaffs_VerifyFreeChunks(dev); */
3095
3096         if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
3097                 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3098         
3099         bi->hasShrinkHeader = 0;        /* clear the flag so that the block can erase */
3100
3101         /* Take off the number of soft deleted entries because
3102          * they're going to get really deleted during GC.
3103          */
3104         if(dev->gcChunk == 0) /* first time through for this block */
3105                 dev->nFreeChunks -= bi->softDeletions;
3106
3107         dev->isDoingGC = 1;
3108
3109         if (isCheckpointBlock ||
3110                         !yaffs_StillSomeChunkBits(dev, block)) {
3111                 T(YAFFS_TRACE_TRACING,
3112                                 (TSTR
3113                                  ("Collecting block %d that has no chunks in use" TENDSTR),
3114                                  block));
3115                 yaffs_BlockBecameDirty(dev, block);
3116         } else {
3117
3118                 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3119
3120                 yaffs_VerifyBlock(dev, bi, block);
3121
3122                 maxCopies = (wholeBlock) ? dev->nChunksPerBlock : 10;
3123                 oldChunk = block * dev->nChunksPerBlock + dev->gcChunk;
3124
3125                 for (/* init already done */;
3126                      retVal == YAFFS_OK &&
3127                      dev->gcChunk < dev->nChunksPerBlock &&
3128                      (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
3129                      maxCopies > 0;
3130                      dev->gcChunk++, oldChunk++) {
3131                         if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3132
3133                                 /* This page is in use and might need to be copied off */
3134
3135                                 maxCopies--;
3136
3137                                 markNAND = 1;
3138
3139                                 yaffs_InitialiseTags(&tags);
3140
3141                                 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3142                                                                 buffer, &tags);
3143
3144                                 object =
3145                                     yaffs_FindObjectByNumber(dev,
3146                                                              tags.objectId);
3147
3148                                 T(YAFFS_TRACE_GC_DETAIL,
3149                                   (TSTR
3150                                    ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3151                                    dev->gcChunk, tags.objectId, tags.chunkId,
3152                                    tags.byteCount));
3153
3154                                 if (object && !yaffs_SkipVerification(dev)) {
3155                                         if (tags.chunkId == 0)
3156                                                 matchingChunk = object->hdrChunk;
3157                                         else if (object->softDeleted)
3158                                                 matchingChunk = oldChunk; /* Defeat the test */
3159                                         else
3160                                                 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
3161
3162                                         if (oldChunk != matchingChunk)
3163                                                 T(YAFFS_TRACE_ERROR,
3164                                                   (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3165                                                   oldChunk, matchingChunk, tags.objectId, tags.chunkId));
3166
3167                                 }
3168
3169                                 if (!object) {
3170                                         T(YAFFS_TRACE_ERROR,
3171                                           (TSTR
3172                                            ("page %d in gc has no object: %d %d %d "
3173                                             TENDSTR), oldChunk,
3174                                             tags.objectId, tags.chunkId, tags.byteCount));
3175                                 }
3176
3177                                 if (object &&
3178                                     object->deleted &&
3179                                     object->softDeleted &&
3180                                     tags.chunkId != 0) {
3181                                         /* Data chunk in a soft deleted file, throw it away
3182                                          * It's a soft deleted data chunk,
3183                                          * No need to copy this, just forget about it and
3184                                          * fix up the object.
3185                                          */
3186
3187                                         object->nDataChunks--;
3188
3189                                         if (object->nDataChunks <= 0) {
3190                                                 /* remeber to clean up the object */
3191                                                 dev->gcCleanupList[cleanups] =
3192                                                     tags.objectId;
3193                                                 cleanups++;
3194                                         }
3195                                         markNAND = 0;
3196                                 } else if (0) {
3197                                         /* Todo object && object->deleted && object->nDataChunks == 0 */
3198                                         /* Deleted object header with no data chunks.
3199                                          * Can be discarded and the file deleted.
3200                                          */
3201                                         object->hdrChunk = 0;
3202                                         yaffs_FreeTnode(object->myDev,
3203                                                         object->variant.
3204                                                         fileVariant.top);
3205                                         object->variant.fileVariant.top = NULL;
3206                                         yaffs_DoGenericObjectDeletion(object);
3207
3208                                 } else if (object) {
3209                                         /* It's either a data chunk in a live file or
3210                                          * an ObjectHeader, so we're interested in it.
3211                                          * NB Need to keep the ObjectHeaders of deleted files
3212                                          * until the whole file has been deleted off
3213                                          */
3214                                         tags.serialNumber++;
3215
3216                                         dev->nGCCopies++;
3217
3218                                         if (tags.chunkId == 0) {
3219                                                 /* It is an object Id,
3220                                                  * We need to nuke the shrinkheader flags first
3221                                                  * Also need to clean up shadowing.
3222                                                  * We no longer want the shrinkHeader flag since its work is done
3223                                                  * and if it is left in place it will mess up scanning.
3224                                                  */
3225
3226                                                 yaffs_ObjectHeader *oh;
3227                                                 oh = (yaffs_ObjectHeader *)buffer;
3228                                                 oh->isShrink = 0;
3229                                                 tags.extraIsShrinkHeader = 0;
3230                                                 oh->shadowsObject = 0;
3231                                                 oh->inbandShadowsObject = 0;
3232                                                 tags.extraShadows = 0;
3233
3234                                                 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
3235                                         }
3236
3237                                         newChunk =
3238                                             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3239
3240                                         if (newChunk < 0) {
3241                                                 retVal = YAFFS_FAIL;
3242                                         } else {
3243
3244                                                 /* Ok, now fix up the Tnodes etc. */
3245
3246                                                 if (tags.chunkId == 0) {
3247                                                         /* It's a header */
3248                                                         object->hdrChunk =  newChunk;
3249                                                         object->serial =   tags.serialNumber;
3250                                                 } else {
3251                                                         /* It's a data chunk */
3252                                                         int ok;
3253                                                         ok = yaffs_PutChunkIntoFile
3254                                                             (object,
3255                                                              tags.chunkId,
3256                                                              newChunk, 0);
3257                                                 }
3258                                         }
3259                                 }
3260
3261                                 if (retVal == YAFFS_OK)
3262                                         yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3263
3264                         }
3265                 }
3266
3267                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3268
3269
3270                 /* Do any required cleanups */
3271                 for (i = 0; i < cleanups; i++) {
3272                         /* Time to delete the file too */
3273                         object =
3274                             yaffs_FindObjectByNumber(dev,
3275                                                      dev->gcCleanupList[i]);
3276                         if (object) {
3277                                 yaffs_FreeTnode(dev,
3278                                                 object->variant.fileVariant.
3279                                                 top);
3280                                 object->variant.fileVariant.top = NULL;
3281                                 T(YAFFS_TRACE_GC,
3282                                   (TSTR
3283                                    ("yaffs: About to finally delete object %d"
3284                                     TENDSTR), object->objectId));
3285                                 yaffs_DoGenericObjectDeletion(object);
3286                                 object->myDev->nDeletedFiles--;
3287                         }
3288
3289                 }
3290
3291         }
3292
3293         yaffs_VerifyCollectedBlock(dev, bi, block);
3294
3295         chunksAfter = yaffs_GetErasedChunks(dev);
3296         if (chunksBefore >= chunksAfter) {
3297                 T(YAFFS_TRACE_GC,
3298                   (TSTR
3299                    ("gc did not increase free chunks before %d after %d"
3300                     TENDSTR), chunksBefore, chunksAfter));
3301         }
3302
3303         /* If the gc completed then clear the current gcBlock so that we find another. */
3304         if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING) {
3305                 dev->gcBlock = -1;
3306                 dev->gcChunk = 0;
3307         }
3308
3309         dev->isDoingGC = 0;
3310
3311         return retVal;
3312 }
3313
3314 /* New garbage collector
3315  * If we're very low on erased blocks then we do aggressive garbage collection
3316  * otherwise we do "leasurely" garbage collection.
3317  * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3318  * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3319  *
3320  * The idea is to help clear out space in a more spread-out manner.
3321  * Dunno if it really does anything useful.
3322  */
3323 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
3324 {
3325         int block;
3326         int aggressive;
3327         int gcOk = YAFFS_OK;
3328         int maxTries = 0;
3329
3330         int checkpointBlockAdjust;
3331
3332         if (dev->isDoingGC) {
3333                 /* Bail out so we don't get recursive gc */
3334                 return YAFFS_OK;
3335         }
3336
3337         /* This loop should pass the first time.
3338          * We'll only see looping here if the erase of the collected block fails.
3339          */
3340
3341         do {
3342                 maxTries++;
3343
3344                 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3345                 if (checkpointBlockAdjust < 0)
3346                         checkpointBlockAdjust = 0;
3347
3348                 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3349                         /* We need a block soon...*/
3350                         aggressive = 1;
3351                 } else {
3352                         /* We're in no hurry */
3353                         aggressive = 0;
3354                 }
3355
3356                 if (dev->gcBlock <= 0) {
3357                         dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3358                         dev->gcChunk = 0;
3359                 }
3360
3361                 block = dev->gcBlock;
3362
3363                 if (block > 0) {
3364                         dev->garbageCollections++;
3365                         if (!aggressive)
3366                                 dev->passiveGarbageCollections++;
3367
3368                         T(YAFFS_TRACE_GC,
3369                           (TSTR
3370                            ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3371                            dev->nErasedBlocks, aggressive));
3372
3373                         gcOk = yaffs_GarbageCollectBlock(dev, block, aggressive);
3374                 }
3375
3376                 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3377                         T(YAFFS_TRACE_GC,
3378                           (TSTR
3379                            ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3380                             TENDSTR), dev->nErasedBlocks, maxTries, block));
3381                 }
3382         } while ((dev->nErasedBlocks < dev->nReservedBlocks) &&
3383                  (block > 0) &&
3384                  (maxTries < 2));
3385
3386         return aggressive ? gcOk : YAFFS_OK;
3387 }
3388
3389 /*-------------------------  TAGS --------------------------------*/
3390
3391 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
3392                            int chunkInObject)
3393 {
3394         return (tags->chunkId == chunkInObject &&
3395                 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3396
3397 }
3398
3399
3400 /*-------------------- Data file manipulation -----------------*/
3401
3402 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
3403                                  yaffs_ExtendedTags *tags)
3404 {
3405         /*Get the Tnode, then get the level 0 offset chunk offset */
3406         yaffs_Tnode *tn;
3407         int theChunk = -1;
3408         yaffs_ExtendedTags localTags;
3409         int retVal = -1;
3410
3411         yaffs_Device *dev = in->myDev;
3412
3413         if (!tags) {
3414                 /* Passed a NULL, so use our own tags space */
3415                 tags = &localTags;
3416         }
3417
3418         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3419
3420         if (tn) {
3421                 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3422
3423                 retVal =
3424                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3425                                            chunkInInode);
3426         }
3427         return retVal;
3428 }
3429
3430 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
3431                                           yaffs_ExtendedTags *tags)
3432 {
3433         /* Get the Tnode, then get the level 0 offset chunk offset */
3434         yaffs_Tnode *tn;
3435         int theChunk = -1;
3436         yaffs_ExtendedTags localTags;
3437
3438         yaffs_Device *dev = in->myDev;
3439         int retVal = -1;
3440
3441         if (!tags) {
3442                 /* Passed a NULL, so use our own tags space */
3443                 tags = &localTags;
3444         }
3445
3446         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3447
3448         if (tn) {
3449
3450                 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3451
3452                 retVal =
3453                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3454                                            chunkInInode);
3455
3456                 /* Delete the entry in the filestructure (if found) */
3457                 if (retVal != -1)
3458                         yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, 0);
3459         }
3460
3461         return retVal;
3462 }
3463
3464 #ifdef YAFFS_PARANOID
3465
3466 static int yaffs_CheckFileSanity(yaffs_Object *in)
3467 {
3468         int chunk;
3469         int nChunks;
3470         int fSize;
3471         int failed = 0;
3472         int objId;
3473         yaffs_Tnode *tn;
3474         yaffs_Tags localTags;
3475         yaffs_Tags *tags = &localTags;
3476         int theChunk;
3477         int chunkDeleted;
3478
3479         if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3480                 return YAFFS_FAIL;
3481
3482         objId = in->objectId;
3483         fSize = in->variant.fileVariant.fileSize;
3484         nChunks =
3485             (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3486
3487         for (chunk = 1; chunk <= nChunks; chunk++) {
3488                 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3489                                            chunk);
3490
3491                 if (tn) {
3492
3493                         theChunk = yaffs_GetChunkGroupBase(dev, tn, chunk);
3494
3495                         if (yaffs_CheckChunkBits
3496                             (dev, theChunk / dev->nChunksPerBlock,
3497                              theChunk % dev->nChunksPerBlock)) {
3498
3499                                 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3500                                                             tags,
3501                                                             &chunkDeleted);
3502                                 if (yaffs_TagsMatch
3503                                     (tags, in->objectId, chunk, chunkDeleted)) {
3504                                         /* found it; */
3505
3506                                 }
3507                         } else {
3508
3509                                 failed = 1;
3510                         }
3511
3512                 } else {
3513                         /* T(("No level 0 found for %d\n", chunk)); */
3514                 }
3515         }
3516
3517         return failed ? YAFFS_FAIL : YAFFS_OK;
3518 }
3519
3520 #endif
3521
3522 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
3523                                   int chunkInNAND, int inScan)
3524 {
3525         /* NB inScan is zero unless scanning.
3526          * For forward scanning, inScan is > 0;
3527          * for backward scanning inScan is < 0
3528          *
3529          * chunkInNAND = 0 is a dummy insert to make sure the tnodes are there.
3530          */
3531
3532         yaffs_Tnode *tn;
3533         yaffs_Device *dev = in->myDev;
3534         int existingChunk;
3535         yaffs_ExtendedTags existingTags;
3536         yaffs_ExtendedTags newTags;
3537         unsigned existingSerial, newSerial;
3538
3539         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3540                 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3541                  * If it is not during Scanning then something went wrong!
3542                  */
3543                 if (!inScan) {
3544                         T(YAFFS_TRACE_ERROR,
3545                           (TSTR
3546                            ("yaffs tragedy:attempt to put data chunk into a non-file"
3547                             TENDSTR)));
3548                         YBUG();
3549                 }
3550
3551                 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3552                 return YAFFS_OK;
3553         }
3554
3555         tn = yaffs_AddOrFindLevel0Tnode(dev,
3556                                         &in->variant.fileVariant,
3557                                         chunkInInode,
3558                                         NULL);
3559         if (!tn)
3560                 return YAFFS_FAIL;
3561         
3562         if(!chunkInNAND)
3563                 /* Dummy insert, bail now */
3564                 return YAFFS_OK;
3565
3566         existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3567
3568         if (inScan != 0) {
3569                 /* If we're scanning then we need to test for duplicates
3570                  * NB This does not need to be efficient since it should only ever
3571                  * happen when the power fails during a write, then only one
3572                  * chunk should ever be affected.
3573                  *
3574                  * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3575                  * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3576                  */
3577
3578                 if (existingChunk > 0) {
3579                         /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3580                          *    thus we have to do a FindChunkInFile to get the real chunk id.
3581                          *
3582                          * We have a duplicate now we need to decide which one to use:
3583                          *
3584                          * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3585                          * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3586                          * YAFFS1: Get both sets of tags and compare serial numbers.
3587                          */
3588
3589                         if (inScan > 0) {
3590                                 /* Only do this for forward scanning */
3591                                 yaffs_ReadChunkWithTagsFromNAND(dev,
3592                                                                 chunkInNAND,
3593                                                                 NULL, &newTags);
3594
3595                                 /* Do a proper find */
3596                                 existingChunk =
3597                                     yaffs_FindChunkInFile(in, chunkInInode,
3598                                                           &existingTags);
3599                         }
3600
3601                         if (existingChunk <= 0) {
3602                                 /*Hoosterman - how did this happen? */
3603
3604                                 T(YAFFS_TRACE_ERROR,
3605                                   (TSTR
3606                                    ("yaffs tragedy: existing chunk < 0 in scan"
3607                                     TENDSTR)));
3608
3609                         }
3610
3611                         /* NB The deleted flags should be false, otherwise the chunks will
3612                          * not be loaded during a scan
3613                          */
3614
3615                         if (inScan > 0) {
3616                                 newSerial = newTags.serialNumber;
3617                                 existingSerial = existingTags.serialNumber;
3618                         }
3619
3620                         if ((inScan > 0) &&
3621                             (in->myDev->isYaffs2 ||
3622                              existingChunk <= 0 ||
3623                              ((existingSerial + 1) & 3) == newSerial)) {
3624                                 /* Forward scanning.
3625                                  * Use new
3626                                  * Delete the old one and drop through to update the tnode
3627                                  */
3628                                 yaffs_DeleteChunk(dev, existingChunk, 1,
3629                                                   __LINE__);
3630                         } else {
3631                                 /* Backward scanning or we want to use the existing one
3632                                  * Use existing.
3633                                  * Delete the new one and return early so that the tnode isn't changed
3634                                  */
3635                                 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3636                                                   __LINE__);
3637                                 return YAFFS_OK;
3638                         }
3639                 }
3640
3641         }
3642
3643         if (existingChunk == 0)
3644                 in->nDataChunks++;
3645
3646         yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
3647
3648         return YAFFS_OK;
3649 }
3650
3651 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
3652                                         __u8 *buffer)
3653 {
3654         int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3655
3656         if (chunkInNAND >= 0)
3657                 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3658                                                 buffer, NULL);
3659         else {
3660                 T(YAFFS_TRACE_NANDACCESS,
3661                   (TSTR("Chunk %d not found zero instead" TENDSTR),
3662                    chunkInNAND));
3663                 /* get sane (zero) data if you read a hole */
3664                 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3665                 return 0;
3666         }
3667
3668 }
3669
3670 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
3671 {
3672         int block;
3673         int page;
3674         yaffs_ExtendedTags tags;
3675         yaffs_BlockInfo *bi;
3676
3677         if (chunkId <= 0)
3678                 return;
3679
3680         dev->nDeletions++;
3681         block = chunkId / dev->nChunksPerBlock;
3682         page = chunkId % dev->nChunksPerBlock;
3683
3684
3685         if (!yaffs_CheckChunkBit(dev, block, page))
3686                 T(YAFFS_TRACE_VERIFY,
3687                         (TSTR("Deleting invalid chunk %d"TENDSTR),
3688                          chunkId));
3689
3690         bi = yaffs_GetBlockInfo(dev, block);
3691
3692         T(YAFFS_TRACE_DELETION,
3693           (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3694
3695         if (markNAND &&
3696             bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3697
3698                 yaffs_InitialiseTags(&tags);
3699
3700                 tags.chunkDeleted = 1;
3701
3702                 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3703                 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3704         } else {
3705                 dev->nUnmarkedDeletions++;
3706         }
3707
3708         /* Pull out of the management area.
3709          * If the whole block became dirty, this will kick off an erasure.
3710          */
3711         if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3712             bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3713             bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3714             bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3715                 dev->nFreeChunks++;
3716
3717                 yaffs_ClearChunkBit(dev, block, page);
3718
3719                 bi->pagesInUse--;
3720
3721                 if (bi->pagesInUse == 0 &&
3722                     !bi->hasShrinkHeader &&
3723                     bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3724                     bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3725                         yaffs_BlockBecameDirty(dev, block);
3726                 }
3727
3728         }
3729
3730 }
3731
3732 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
3733                                         const __u8 *buffer, int nBytes,
3734                                         int useReserve)
3735 {
3736         /* Find old chunk Need to do this to get serial number
3737          * Write new one and patch into tree.
3738          * Invalidate old tags.
3739          */
3740
3741         int prevChunkId;
3742         yaffs_ExtendedTags prevTags;
3743
3744         int newChunkId;
3745         yaffs_ExtendedTags newTags;
3746
3747         yaffs_Device *dev = in->myDev;
3748
3749         yaffs_CheckGarbageCollection(dev);
3750
3751         /* Get the previous chunk at this location in the file if it exists.
3752          * If it does not exist then put a zero into the tree. This creates
3753          * the tnode now, rather than later when it is harder to clean up.
3754          */
3755         prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3756         if(prevChunkId <= 0 &&
3757                 !yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0)){
3758         }
3759
3760         /* Set up new tags */
3761         yaffs_InitialiseTags(&newTags);
3762
3763         newTags.chunkId = chunkInInode;
3764         newTags.objectId = in->objectId;
3765         newTags.serialNumber =
3766             (prevChunkId > 0) ? prevTags.serialNumber + 1 : 1;
3767         newTags.byteCount = nBytes;
3768
3769         if (nBytes < 1 || nBytes > dev->totalBytesPerChunk) {
3770                 T(YAFFS_TRACE_ERROR,
3771                 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3772                 YBUG();
3773         }
3774         
3775         /*
3776          * If there isn't already a chunk there then do a dummy
3777          * insert to make sue we have the desired tnode structure.
3778          */
3779         if(prevChunkId < 1 &&
3780                 yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0) != YAFFS_OK)
3781                 return -1;
3782                 
3783         newChunkId =
3784             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3785                                               useReserve);
3786
3787         if (newChunkId > 0) {
3788                 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3789
3790                 if (prevChunkId > 0)
3791                         yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3792
3793                 yaffs_CheckFileSanity(in);
3794         }
3795         return newChunkId;
3796
3797 }
3798
3799 /* UpdateObjectHeader updates the header on NAND for an object.
3800  * If name is not NULL, then that new name is used.
3801  */
3802 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
3803                              int isShrink, int shadows)
3804 {
3805
3806         yaffs_BlockInfo *bi;
3807
3808         yaffs_Device *dev = in->myDev;
3809
3810         int prevChunkId;
3811         int retVal = 0;
3812         int result = 0;
3813
3814         int newChunkId;
3815         yaffs_ExtendedTags newTags;
3816         yaffs_ExtendedTags oldTags;
3817         YCHAR *alias = NULL;
3818
3819         __u8 *buffer = NULL;
3820         YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3821
3822         yaffs_ObjectHeader *oh = NULL;
3823
3824         yaffs_strcpy(oldName, _Y("silly old name"));
3825
3826
3827         if (!in->fake ||
3828                 in == dev->rootDir || /* The rootDir should also be saved */
3829                 force) {
3830
3831                 yaffs_CheckGarbageCollection(dev);
3832                 yaffs_CheckObjectDetailsLoaded(in);
3833
3834                 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3835                 oh = (yaffs_ObjectHeader *) buffer;
3836
3837                 prevChunkId = in->hdrChunk;
3838
3839                 if (prevChunkId > 0) {
3840                         result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3841                                                         buffer, &oldTags);
3842
3843                         yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
3844
3845                         memcpy(oldName, oh->name, sizeof(oh->name));
3846                 }
3847
3848                 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3849
3850                 oh->type = in->variantType;
3851                 oh->yst_mode = in->yst_mode;
3852                 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3853
3854 #ifdef CONFIG_YAFFS_WINCE
3855                 oh->win_atime[0] = in->win_atime[0];
3856                 oh->win_ctime[0] = in->win_ctime[0];
3857                 oh->win_mtime[0] = in->win_mtime[0];
3858                 oh->win_atime[1] = in->win_atime[1];
3859                 oh->win_ctime[1] = in->win_ctime[1];
3860                 oh->win_mtime[1] = in->win_mtime[1];
3861 #else
3862                 oh->yst_uid = in->yst_uid;
3863                 oh->yst_gid = in->yst_gid;
3864                 oh->yst_atime = in->yst_atime;
3865                 oh->yst_mtime = in->yst_mtime;
3866                 oh->yst_ctime = in->yst_ctime;
3867                 oh->yst_rdev = in->yst_rdev;
3868 #endif
3869                 if (in->parent)
3870                         oh->parentObjectId = in->parent->objectId;
3871                 else
3872                         oh->parentObjectId = 0;
3873
3874                 if (name && *name) {
3875                         memset(oh->name, 0, sizeof(oh->name));
3876                         yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3877                 } else if (prevChunkId > 0)
3878                         memcpy(oh->name, oldName, sizeof(oh->name));
3879                 else
3880                         memset(oh->name, 0, sizeof(oh->name));
3881
3882                 oh->isShrink = isShrink;
3883
3884                 switch (in->variantType) {
3885                 case YAFFS_OBJECT_TYPE_UNKNOWN:
3886                         /* Should not happen */
3887                         break;
3888                 case YAFFS_OBJECT_TYPE_FILE:
3889                         oh->fileSize =
3890                             (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3891                              || oh->parentObjectId ==
3892                              YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3893                             fileVariant.fileSize;
3894                         break;
3895                 case YAFFS_OBJECT_TYPE_HARDLINK: