fd3d636d8f48e6f432efe2ffb43a8f92234286fa
[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.113 2010-03-05 02:26:27 charles Exp $";
16
17 #include "yportenv.h"
18 #include "yaffs_trace.h"
19
20 #include "yaffsinterface.h"
21 #include "yaffs_guts.h"
22 #include "yaffs_tagsvalidity.h"
23 #include "yaffs_getblockinfo.h"
24
25 #include "yaffs_tagscompat.h"
26 #ifndef CONFIG_YAFFS_USE_OWN_SORT
27 #include "yaffs_qsort.h"
28 #endif
29 #include "yaffs_nand.h"
30
31 #include "yaffs_checkptrw.h"
32
33 #include "yaffs_nand.h"
34 #include "yaffs_packedtags2.h"
35
36
37 #define YAFFS_PASSIVE_GC_CHUNKS 2
38
39 #include "yaffs_ecc.h"
40
41
42 /* Robustification (if it ever comes about...) */
43 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND);
44 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
45                 int erasedOk);
46 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
47                                 const __u8 *data,
48                                 const yaffs_ExtendedTags *tags);
49 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
50                                 const yaffs_ExtendedTags *tags);
51
52 /* Other local prototypes */
53 static void yaffs_UpdateParent(yaffs_Object *obj);
54 static int yaffs_UnlinkObject(yaffs_Object *obj);
55 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
56
57 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
58
59 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev,
60                                         const __u8 *buffer,
61                                         yaffs_ExtendedTags *tags,
62                                         int useReserve);
63 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
64                                 int chunkInNAND, int inScan);
65
66 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
67                                         yaffs_ObjectType type);
68 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
69                                 yaffs_Object *obj);
70 static int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name,
71                                 int force, int isShrink, int shadows);
72 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
73 static int yaffs_CheckStructures(void);
74 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
75                         int chunkOffset, int *limit);
76 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
77
78 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev, int blockNo);
79
80
81 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
82                                 int chunkInNAND);
83
84 static int yaffs_UnlinkWorker(yaffs_Object *obj);
85
86 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
87                         int chunkInObject);
88
89 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
90                                 yaffs_BlockInfo **blockUsedPtr);
91
92 static void yaffs_VerifyFreeChunks(yaffs_Device *dev);
93
94 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
95
96 static void yaffs_VerifyDirectory(yaffs_Object *directory);
97 #ifdef YAFFS_PARANOID
98 static int yaffs_CheckFileSanity(yaffs_Object *in);
99 #else
100 #define yaffs_CheckFileSanity(in)
101 #endif
102
103 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
104 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
105
106 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
107
108 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
109                                 yaffs_ExtendedTags *tags);
110
111 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
112                 unsigned pos);
113 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
114                                         yaffs_FileStructure *fStruct,
115                                         __u32 chunkId);
116
117 static void yaffs_SkipRestOfBlock(yaffs_Device *dev);
118 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
119                                         int chunkInNAND,
120                                         const __u8 *data,
121                                         yaffs_ExtendedTags *tags);
122
123 /* Function to calculate chunk and offset */
124
125 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut,
126                 __u32 *offsetOut)
127 {
128         int chunk;
129         __u32 offset;
130
131         chunk  = (__u32)(addr >> dev->chunkShift);
132
133         if (dev->chunkDiv == 1) {
134                 /* easy power of 2 case */
135                 offset = (__u32)(addr & dev->chunkMask);
136         } else {
137                 /* Non power-of-2 case */
138
139                 loff_t chunkBase;
140
141                 chunk /= dev->chunkDiv;
142
143                 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
144                 offset = (__u32)(addr - chunkBase);
145         }
146
147         *chunkOut = chunk;
148         *offsetOut = offset;
149 }
150
151 /* Function to return the number of shifts for a power of 2 greater than or
152  * equal to the given number
153  * Note we don't try to cater for all possible numbers and this does not have to
154  * be hellishly efficient.
155  */
156
157 static __u32 ShiftsGE(__u32 x)
158 {
159         int extraBits;
160         int nShifts;
161
162         nShifts = extraBits = 0;
163
164         while (x > 1) {
165                 if (x & 1)
166                         extraBits++;
167                 x >>= 1;
168                 nShifts++;
169         }
170
171         if (extraBits)
172                 nShifts++;
173
174         return nShifts;
175 }
176
177 /* Function to return the number of shifts to get a 1 in bit 0
178  */
179
180 static __u32 Shifts(__u32 x)
181 {
182         int nShifts;
183
184         nShifts =  0;
185
186         if (!x)
187                 return 0;
188
189         while (!(x&1)) {
190                 x >>= 1;
191                 nShifts++;
192         }
193
194         return nShifts;
195 }
196
197
198
199 /*
200  * Temporary buffer manipulations.
201  */
202
203 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
204 {
205         int i;
206         __u8 *buf = (__u8 *)1;
207
208         memset(dev->tempBuffer, 0, sizeof(dev->tempBuffer));
209
210         for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
211                 dev->tempBuffer[i].line = 0;    /* not in use */
212                 dev->tempBuffer[i].buffer = buf =
213                     YMALLOC_DMA(dev->param.totalBytesPerChunk);
214         }
215
216         return buf ? YAFFS_OK : YAFFS_FAIL;
217 }
218
219 __u8 *yaffs_GetTempBuffer(yaffs_Device *dev, int lineNo)
220 {
221         int i, j;
222
223         dev->tempInUse++;
224         if (dev->tempInUse > dev->maxTemp)
225                 dev->maxTemp = dev->tempInUse;
226
227         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
228                 if (dev->tempBuffer[i].line == 0) {
229                         dev->tempBuffer[i].line = lineNo;
230                         if ((i + 1) > dev->maxTemp) {
231                                 dev->maxTemp = i + 1;
232                                 for (j = 0; j <= i; j++)
233                                         dev->tempBuffer[j].maxLine =
234                                             dev->tempBuffer[j].line;
235                         }
236
237                         return dev->tempBuffer[i].buffer;
238                 }
239         }
240
241         T(YAFFS_TRACE_BUFFERS,
242           (TSTR("Out of temp buffers at line %d, other held by lines:"),
243            lineNo));
244         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
245                 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
246
247         T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
248
249         /*
250          * If we got here then we have to allocate an unmanaged one
251          * This is not good.
252          */
253
254         dev->unmanagedTempAllocations++;
255         return YMALLOC(dev->nDataBytesPerChunk);
256
257 }
258
259 void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer,
260                                     int lineNo)
261 {
262         int i;
263
264         dev->tempInUse--;
265
266         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
267                 if (dev->tempBuffer[i].buffer == buffer) {
268                         dev->tempBuffer[i].line = 0;
269                         return;
270                 }
271         }
272
273         if (buffer) {
274                 /* assume it is an unmanaged one. */
275                 T(YAFFS_TRACE_BUFFERS,
276                   (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
277                    lineNo));
278                 YFREE(buffer);
279                 dev->unmanagedTempDeallocations++;
280         }
281
282 }
283
284 /*
285  * Determine if we have a managed buffer.
286  */
287 int yaffs_IsManagedTempBuffer(yaffs_Device *dev, const __u8 *buffer)
288 {
289         int i;
290
291         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
292                 if (dev->tempBuffer[i].buffer == buffer)
293                         return 1;
294         }
295
296         for (i = 0; i < dev->param.nShortOpCaches; i++) {
297                 if (dev->srCache[i].data == buffer)
298                         return 1;
299         }
300
301         if (buffer == dev->checkpointBuffer)
302                 return 1;
303
304         T(YAFFS_TRACE_ALWAYS,
305                 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
306         return 0;
307 }
308
309
310
311 /*
312  * Chunk bitmap manipulations
313  */
314
315 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
316 {
317         if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
318                 T(YAFFS_TRACE_ERROR,
319                         (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
320                         blk));
321                 YBUG();
322         }
323         return dev->chunkBits +
324                 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
325 }
326
327 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
328 {
329         if (blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
330                         chunk < 0 || chunk >= dev->param.nChunksPerBlock) {
331                 T(YAFFS_TRACE_ERROR,
332                 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),
333                         blk, chunk));
334                 YBUG();
335         }
336 }
337
338 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device *dev, int blk)
339 {
340         __u8 *blkBits = yaffs_BlockBits(dev, blk);
341
342         memset(blkBits, 0, dev->chunkBitmapStride);
343 }
344
345 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device *dev, int blk, int chunk)
346 {
347         __u8 *blkBits = yaffs_BlockBits(dev, blk);
348
349         yaffs_VerifyChunkBitId(dev, blk, chunk);
350
351         blkBits[chunk / 8] &= ~(1 << (chunk & 7));
352 }
353
354 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device *dev, int blk, int chunk)
355 {
356         __u8 *blkBits = yaffs_BlockBits(dev, blk);
357
358         yaffs_VerifyChunkBitId(dev, blk, chunk);
359
360         blkBits[chunk / 8] |= (1 << (chunk & 7));
361 }
362
363 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device *dev, int blk, int chunk)
364 {
365         __u8 *blkBits = yaffs_BlockBits(dev, blk);
366         yaffs_VerifyChunkBitId(dev, blk, chunk);
367
368         return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
369 }
370
371 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device *dev, int blk)
372 {
373         __u8 *blkBits = yaffs_BlockBits(dev, blk);
374         int i;
375         for (i = 0; i < dev->chunkBitmapStride; i++) {
376                 if (*blkBits)
377                         return 1;
378                 blkBits++;
379         }
380         return 0;
381 }
382
383 static int yaffs_CountChunkBits(yaffs_Device *dev, int blk)
384 {
385         __u8 *blkBits = yaffs_BlockBits(dev, blk);
386         int i;
387         int n = 0;
388         for (i = 0; i < dev->chunkBitmapStride; i++) {
389                 __u8 x = *blkBits;
390                 while (x) {
391                         if (x & 1)
392                                 n++;
393                         x >>= 1;
394                 }
395
396                 blkBits++;
397         }
398         return n;
399 }
400
401 /*
402  * Verification code
403  */
404
405 static int yaffs_SkipVerification(yaffs_Device *dev)
406 {
407         dev=dev;
408         return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
409 }
410
411 static int yaffs_SkipFullVerification(yaffs_Device *dev)
412 {
413         dev=dev;
414         return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
415 }
416
417 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
418 {
419         dev=dev;
420         return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
421 }
422
423 static const char *blockStateName[] = {
424 "Unknown",
425 "Needs scanning",
426 "Scanning",
427 "Empty",
428 "Allocating",
429 "Full",
430 "Dirty",
431 "Checkpoint",
432 "Collecting",
433 "Dead"
434 };
435
436 static void yaffs_VerifyBlock(yaffs_Device *dev, yaffs_BlockInfo *bi, int n)
437 {
438         int actuallyUsed;
439         int inUse;
440
441         if (yaffs_SkipVerification(dev))
442                 return;
443
444         /* Report illegal runtime states */
445         if (bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
446                 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has undefined state %d"TENDSTR), n, bi->blockState));
447
448         switch (bi->blockState) {
449         case YAFFS_BLOCK_STATE_UNKNOWN:
450         case YAFFS_BLOCK_STATE_SCANNING:
451         case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
452                 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has bad run-state %s"TENDSTR),
453                 n, blockStateName[bi->blockState]));
454         }
455
456         /* Check pages in use and soft deletions are legal */
457
458         actuallyUsed = bi->pagesInUse - bi->softDeletions;
459
460         if (bi->pagesInUse < 0 || bi->pagesInUse > dev->param.nChunksPerBlock ||
461            bi->softDeletions < 0 || bi->softDeletions > dev->param.nChunksPerBlock ||
462            actuallyUsed < 0 || actuallyUsed > dev->param.nChunksPerBlock)
463                 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
464                 n, bi->pagesInUse, bi->softDeletions));
465
466
467         /* Check chunk bitmap legal */
468         inUse = yaffs_CountChunkBits(dev, n);
469         if (inUse != bi->pagesInUse)
470                 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
471                         n, bi->pagesInUse, inUse));
472
473         /* Check that the sequence number is valid.
474          * Ten million is legal, but is very unlikely
475          */
476         if (dev->param.isYaffs2 &&
477            (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
478            (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000))
479                 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has suspect sequence number of %d"TENDSTR),
480                 n, bi->sequenceNumber));
481 }
482
483 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev, yaffs_BlockInfo *bi,
484                 int n)
485 {
486         yaffs_VerifyBlock(dev, bi, n);
487
488         /* After collection the block should be in the erased state */
489         /* This will need to change if we do partial gc */
490
491         if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
492                         bi->blockState != YAFFS_BLOCK_STATE_EMPTY) {
493                 T(YAFFS_TRACE_ERROR, (TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
494                         n, bi->blockState));
495         }
496 }
497
498 static void yaffs_VerifyBlocks(yaffs_Device *dev)
499 {
500         int i;
501         int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
502         int nIllegalBlockStates = 0;
503
504         if (yaffs_SkipVerification(dev))
505                 return;
506
507         memset(nBlocksPerState, 0, sizeof(nBlocksPerState));
508
509         for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
510                 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, i);
511                 yaffs_VerifyBlock(dev, bi, i);
512
513                 if (bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
514                         nBlocksPerState[bi->blockState]++;
515                 else
516                         nIllegalBlockStates++;
517         }
518
519         T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
520         T(YAFFS_TRACE_VERIFY, (TSTR("Block summary"TENDSTR)));
521
522         T(YAFFS_TRACE_VERIFY, (TSTR("%d blocks have illegal states"TENDSTR), nIllegalBlockStates));
523         if (nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
524                 T(YAFFS_TRACE_VERIFY, (TSTR("Too many allocating blocks"TENDSTR)));
525
526         for (i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
527                 T(YAFFS_TRACE_VERIFY,
528                   (TSTR("%s %d blocks"TENDSTR),
529                   blockStateName[i], nBlocksPerState[i]));
530
531         if (dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
532                 T(YAFFS_TRACE_VERIFY,
533                  (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
534                  dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
535
536         if (dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
537                 T(YAFFS_TRACE_VERIFY,
538                  (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
539                  dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
540
541         if (nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
542                 T(YAFFS_TRACE_VERIFY,
543                  (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
544                  nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
545
546         T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
547
548 }
549
550 /*
551  * Verify the object header. oh must be valid, but obj and tags may be NULL in which
552  * case those tests will not be performed.
553  */
554 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
555 {
556         if (obj && yaffs_SkipVerification(obj->myDev))
557                 return;
558
559         if (!(tags && obj && oh)) {
560                 T(YAFFS_TRACE_VERIFY,
561                                 (TSTR("Verifying object header tags %p obj %p oh %p"TENDSTR),
562                                 tags, obj, oh));
563                 return;
564         }
565
566         if (oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
567                         oh->type > YAFFS_OBJECT_TYPE_MAX)
568                 T(YAFFS_TRACE_VERIFY,
569                         (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
570                         tags->objectId, oh->type));
571
572         if (tags->objectId != obj->objectId)
573                 T(YAFFS_TRACE_VERIFY,
574                         (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
575                         tags->objectId, obj->objectId));
576
577
578         /*
579          * Check that the object's parent ids match if parentCheck requested.
580          *
581          * Tests do not apply to the root object.
582          */
583
584         if (parentCheck && tags->objectId > 1 && !obj->parent)
585                 T(YAFFS_TRACE_VERIFY,
586                         (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
587                         tags->objectId, oh->parentObjectId));
588
589         if (parentCheck && obj->parent &&
590                         oh->parentObjectId != obj->parent->objectId &&
591                         (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
592                         obj->parent->objectId != YAFFS_OBJECTID_DELETED))
593                 T(YAFFS_TRACE_VERIFY,
594                         (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
595                         tags->objectId, oh->parentObjectId, obj->parent->objectId));
596
597         if (tags->objectId > 1 && oh->name[0] == 0) /* Null name */
598                 T(YAFFS_TRACE_VERIFY,
599                         (TSTR("Obj %d header name is NULL"TENDSTR),
600                         obj->objectId));
601
602         if (tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
603                 T(YAFFS_TRACE_VERIFY,
604                         (TSTR("Obj %d header name is 0xFF"TENDSTR),
605                         obj->objectId));
606 }
607
608
609
610 static int yaffs_VerifyTnodeWorker(yaffs_Object *obj, yaffs_Tnode *tn,
611                                         __u32 level, int chunkOffset)
612 {
613         int i;
614         yaffs_Device *dev = obj->myDev;
615         int ok = 1;
616
617         if (tn) {
618                 if (level > 0) {
619
620                         for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
621                                 if (tn->internal[i]) {
622                                         ok = yaffs_VerifyTnodeWorker(obj,
623                                                         tn->internal[i],
624                                                         level - 1,
625                                                         (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
626                                 }
627                         }
628                 } else if (level == 0) {
629                         yaffs_ExtendedTags tags;
630                         __u32 objectId = obj->objectId;
631
632                         chunkOffset <<=  YAFFS_TNODES_LEVEL0_BITS;
633
634                         for (i = 0; i < YAFFS_NTNODES_LEVEL0; i++) {
635                                 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
636
637                                 if (theChunk > 0) {
638                                         /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
639                                         yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
640                                         if (tags.objectId != objectId || tags.chunkId != chunkOffset) {
641                                                 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
642                                                         objectId, chunkOffset, theChunk,
643                                                         tags.objectId, tags.chunkId));
644                                         }
645                                 }
646                                 chunkOffset++;
647                         }
648                 }
649         }
650
651         return ok;
652
653 }
654
655
656 static void yaffs_VerifyFile(yaffs_Object *obj)
657 {
658         int requiredTallness;
659         int actualTallness;
660         __u32 lastChunk;
661         __u32 x;
662         __u32 i;
663         yaffs_Device *dev;
664         yaffs_ExtendedTags tags;
665         yaffs_Tnode *tn;
666         __u32 objectId;
667
668         if (!obj)
669                 return;
670
671         if (yaffs_SkipVerification(obj->myDev))
672                 return;
673
674         dev = obj->myDev;
675         objectId = obj->objectId;
676
677         /* Check file size is consistent with tnode depth */
678         lastChunk =  obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
679         x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
680         requiredTallness = 0;
681         while (x > 0) {
682                 x >>= YAFFS_TNODES_INTERNAL_BITS;
683                 requiredTallness++;
684         }
685
686         actualTallness = obj->variant.fileVariant.topLevel;
687
688         /* Check that the chunks in the tnode tree are all correct.
689          * We do this by scanning through the tnode tree and
690          * checking the tags for every chunk match.
691          */
692
693         if (yaffs_SkipNANDVerification(dev))
694                 return;
695
696         for (i = 1; i <= lastChunk; i++) {
697                 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant, i);
698
699                 if (tn) {
700                         __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
701                         if (theChunk > 0) {
702                                 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
703                                 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
704                                 if (tags.objectId != objectId || tags.chunkId != i) {
705                                         T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
706                                                 objectId, i, theChunk,
707                                                 tags.objectId, tags.chunkId));
708                                 }
709                         }
710                 }
711         }
712 }
713
714
715 static void yaffs_VerifyHardLink(yaffs_Object *obj)
716 {
717         if (obj && yaffs_SkipVerification(obj->myDev))
718                 return;
719
720         /* Verify sane equivalent object */
721 }
722
723 static void yaffs_VerifySymlink(yaffs_Object *obj)
724 {
725         if (obj && yaffs_SkipVerification(obj->myDev))
726                 return;
727
728         /* Verify symlink string */
729 }
730
731 static void yaffs_VerifySpecial(yaffs_Object *obj)
732 {
733         if (obj && yaffs_SkipVerification(obj->myDev))
734                 return;
735 }
736
737 static void yaffs_VerifyObject(yaffs_Object *obj)
738 {
739         yaffs_Device *dev;
740
741         __u32 chunkMin;
742         __u32 chunkMax;
743
744         __u32 chunkIdOk;
745         __u32 chunkInRange;
746         __u32 chunkShouldNotBeDeleted;
747         __u32 chunkValid;
748
749         if (!obj)
750                 return;
751
752         if (obj->beingCreated)
753                 return;
754
755         dev = obj->myDev;
756
757         if (yaffs_SkipVerification(dev))
758                 return;
759
760         /* Check sane object header chunk */
761
762         chunkMin = dev->internalStartBlock * dev->param.nChunksPerBlock;
763         chunkMax = (dev->internalEndBlock+1) * dev->param.nChunksPerBlock - 1;
764
765         chunkInRange = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
766         chunkIdOk = chunkInRange || (obj->hdrChunk == 0);
767         chunkValid = chunkInRange &&
768                         yaffs_CheckChunkBit(dev,
769                                         obj->hdrChunk / dev->param.nChunksPerBlock,
770                                         obj->hdrChunk % dev->param.nChunksPerBlock);
771         chunkShouldNotBeDeleted = chunkInRange && !chunkValid;
772
773         if (!obj->fake &&
774                         (!chunkIdOk || chunkShouldNotBeDeleted)) {
775                 T(YAFFS_TRACE_VERIFY,
776                         (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
777                         obj->objectId, obj->hdrChunk,
778                         chunkIdOk ? "" : ",out of range",
779                         chunkShouldNotBeDeleted ? ",marked as deleted" : ""));
780         }
781
782         if (chunkValid && !yaffs_SkipNANDVerification(dev)) {
783                 yaffs_ExtendedTags tags;
784                 yaffs_ObjectHeader *oh;
785                 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
786
787                 oh = (yaffs_ObjectHeader *)buffer;
788
789                 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk, buffer,
790                                 &tags);
791
792                 yaffs_VerifyObjectHeader(obj, oh, &tags, 1);
793
794                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
795         }
796
797         /* Verify it has a parent */
798         if (obj && !obj->fake &&
799                         (!obj->parent || obj->parent->myDev != dev)) {
800                 T(YAFFS_TRACE_VERIFY,
801                         (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
802                         obj->objectId, obj->parent));
803         }
804
805         /* Verify parent is a directory */
806         if (obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
807                 T(YAFFS_TRACE_VERIFY,
808                         (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
809                         obj->objectId, obj->parent->variantType));
810         }
811
812         switch (obj->variantType) {
813         case YAFFS_OBJECT_TYPE_FILE:
814                 yaffs_VerifyFile(obj);
815                 break;
816         case YAFFS_OBJECT_TYPE_SYMLINK:
817                 yaffs_VerifySymlink(obj);
818                 break;
819         case YAFFS_OBJECT_TYPE_DIRECTORY:
820                 yaffs_VerifyDirectory(obj);
821                 break;
822         case YAFFS_OBJECT_TYPE_HARDLINK:
823                 yaffs_VerifyHardLink(obj);
824                 break;
825         case YAFFS_OBJECT_TYPE_SPECIAL:
826                 yaffs_VerifySpecial(obj);
827                 break;
828         case YAFFS_OBJECT_TYPE_UNKNOWN:
829         default:
830                 T(YAFFS_TRACE_VERIFY,
831                 (TSTR("Obj %d has illegaltype %d"TENDSTR),
832                 obj->objectId, obj->variantType));
833                 break;
834         }
835 }
836
837 static void yaffs_VerifyObjects(yaffs_Device *dev)
838 {
839         yaffs_Object *obj;
840         int i;
841         struct ylist_head *lh;
842
843         if (yaffs_SkipVerification(dev))
844                 return;
845
846         /* Iterate through the objects in each hash entry */
847
848         for (i = 0; i <  YAFFS_NOBJECT_BUCKETS; i++) {
849                 ylist_for_each(lh, &dev->objectBucket[i].list) {
850                         if (lh) {
851                                 obj = ylist_entry(lh, yaffs_Object, hashLink);
852                                 yaffs_VerifyObject(obj);
853                         }
854                 }
855         }
856 }
857
858
859 /*
860  *  Simple hash function. Needs to have a reasonable spread
861  */
862
863 static Y_INLINE int yaffs_HashFunction(int n)
864 {
865         n = abs(n);
866         return n % YAFFS_NOBJECT_BUCKETS;
867 }
868
869 /*
870  * Access functions to useful fake objects.
871  * Note that root might have a presence in NAND if permissions are set.
872  */
873
874 yaffs_Object *yaffs_Root(yaffs_Device *dev)
875 {
876         return dev->rootDir;
877 }
878
879 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
880 {
881         return dev->lostNFoundDir;
882 }
883
884
885 /*
886  *  Erased NAND checking functions
887  */
888
889 int yaffs_CheckFF(__u8 *buffer, int nBytes)
890 {
891         /* Horrible, slow implementation */
892         while (nBytes--) {
893                 if (*buffer != 0xFF)
894                         return 0;
895                 buffer++;
896         }
897         return 1;
898 }
899
900 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
901                                 int chunkInNAND)
902 {
903         int retval = YAFFS_OK;
904         __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
905         yaffs_ExtendedTags tags;
906         int result;
907
908         result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
909
910         if (tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
911                 retval = YAFFS_FAIL;
912
913         if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
914                 T(YAFFS_TRACE_NANDACCESS,
915                   (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
916                 retval = YAFFS_FAIL;
917         }
918
919         yaffs_ReleaseTempBuffer(dev, data, __LINE__);
920
921         return retval;
922
923 }
924
925
926 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
927                                         int chunkInNAND,
928                                         const __u8 *data,
929                                         yaffs_ExtendedTags *tags)
930 {
931         int retval = YAFFS_OK;
932         yaffs_ExtendedTags tempTags;
933         __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
934         int result;
935         
936         result = yaffs_ReadChunkWithTagsFromNAND(dev,chunkInNAND,buffer,&tempTags);
937         if(memcmp(buffer,data,dev->nDataBytesPerChunk) ||
938                 tempTags.objectId != tags->objectId ||
939                 tempTags.chunkId  != tags->chunkId ||
940                 tempTags.byteCount != tags->byteCount)
941                 retval = YAFFS_FAIL;
942
943         yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
944
945         return retval;
946 }
947
948 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
949                                         const __u8 *data,
950                                         yaffs_ExtendedTags *tags,
951                                         int useReserve)
952 {
953         int attempts = 0;
954         int writeOk = 0;
955         int chunk;
956
957         yaffs_InvalidateCheckpoint(dev);
958
959         do {
960                 yaffs_BlockInfo *bi = 0;
961                 int erasedOk = 0;
962
963                 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
964                 if (chunk < 0) {
965                         /* no space */
966                         break;
967                 }
968
969                 /* First check this chunk is erased, if it needs
970                  * checking.  The checking policy (unless forced
971                  * always on) is as follows:
972                  *
973                  * Check the first page we try to write in a block.
974                  * If the check passes then we don't need to check any
975                  * more.        If the check fails, we check again...
976                  * If the block has been erased, we don't need to check.
977                  *
978                  * However, if the block has been prioritised for gc,
979                  * then we think there might be something odd about
980                  * this block and stop using it.
981                  *
982                  * Rationale: We should only ever see chunks that have
983                  * not been erased if there was a partially written
984                  * chunk due to power loss.  This checking policy should
985                  * catch that case with very few checks and thus save a
986                  * lot of checks that are most likely not needed.
987                  *
988                  * Mods to the above
989                  * If an erase check fails or the write fails we skip the 
990                  * rest of the block.
991                  */
992
993                 /* let's give it a try */
994                 attempts++;
995
996 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
997                 bi->skipErasedCheck = 0;
998 #endif
999                 if (!bi->skipErasedCheck) {
1000                         erasedOk = yaffs_CheckChunkErased(dev, chunk);
1001                         if (erasedOk != YAFFS_OK) {
1002                                 T(YAFFS_TRACE_ERROR,
1003                                 (TSTR("**>> yaffs chunk %d was not erased"
1004                                 TENDSTR), chunk));
1005
1006                                 /* If not erased, delete this one,
1007                                  * skip rest of block and
1008                                  * try another chunk */
1009                                  yaffs_DeleteChunk(dev,chunk,1,__LINE__);
1010                                  yaffs_SkipRestOfBlock(dev);
1011                                 continue;
1012                         }
1013                 }
1014
1015                 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
1016                                 data, tags);
1017
1018                 if(!bi->skipErasedCheck)
1019                         writeOk = yaffs_VerifyChunkWritten(dev, chunk, data, tags);
1020
1021                 if (writeOk != YAFFS_OK) {
1022                         /* Clean up aborted write, skip to next block and
1023                          * try another chunk */
1024                         yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
1025                         continue;
1026                 }
1027
1028                 bi->skipErasedCheck = 1;
1029
1030                 /* Copy the data into the robustification buffer */
1031                 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
1032
1033         } while (writeOk != YAFFS_OK &&
1034                 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
1035
1036         if (!writeOk)
1037                 chunk = -1;
1038
1039         if (attempts > 1) {
1040                 T(YAFFS_TRACE_ERROR,
1041                         (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1042                         attempts));
1043
1044                 dev->nRetriedWrites += (attempts - 1);
1045         }
1046
1047         return chunk;
1048 }
1049
1050 /*
1051  * Block retiring for handling a broken block.
1052  */
1053
1054 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND)
1055 {
1056         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1057
1058         yaffs_InvalidateCheckpoint(dev);
1059
1060         if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
1061                 if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
1062                         T(YAFFS_TRACE_ALWAYS, (TSTR(
1063                                 "yaffs: Failed to mark bad and erase block %d"
1064                                 TENDSTR), blockInNAND));
1065                 } else {
1066                         yaffs_ExtendedTags tags;
1067                         int chunkId = blockInNAND * dev->param.nChunksPerBlock;
1068
1069                         __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
1070
1071                         memset(buffer, 0xff, dev->nDataBytesPerChunk);
1072                         yaffs_InitialiseTags(&tags);
1073                         tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
1074                         if (dev->param.writeChunkWithTagsToNAND(dev, chunkId -
1075                                 dev->chunkOffset, buffer, &tags) != YAFFS_OK)
1076                                 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
1077                                         TCONT("write bad block marker to block %d")
1078                                         TENDSTR), blockInNAND));
1079
1080                         yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
1081                 }
1082         }
1083
1084         bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1085         bi->gcPrioritise = 0;
1086         bi->needsRetiring = 0;
1087
1088         dev->nRetiredBlocks++;
1089 }
1090
1091 /*
1092  * Functions for robustisizing TODO
1093  *
1094  */
1095
1096 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
1097                                 const __u8 *data,
1098                                 const yaffs_ExtendedTags *tags)
1099 {
1100         dev=dev;
1101         chunkInNAND=chunkInNAND;
1102         data=data;
1103         tags=tags;
1104 }
1105
1106 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
1107                                 const yaffs_ExtendedTags *tags)
1108 {
1109         dev=dev;
1110         chunkInNAND=chunkInNAND;
1111         tags=tags;
1112 }
1113
1114 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1115 {
1116         if (!bi->gcPrioritise) {
1117                 bi->gcPrioritise = 1;
1118                 dev->hasPendingPrioritisedGCs = 1;
1119                 bi->chunkErrorStrikes++;
1120
1121                 if (bi->chunkErrorStrikes > 3) {
1122                         bi->needsRetiring = 1; /* Too many stikes, so retire this */
1123                         T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1124
1125                 }
1126         }
1127 }
1128
1129 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
1130                 int erasedOk)
1131 {
1132         int blockInNAND = chunkInNAND / dev->param.nChunksPerBlock;
1133         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1134
1135         yaffs_HandleChunkError(dev, bi);
1136
1137         if (erasedOk) {
1138                 /* Was an actual write failure, so mark the block for retirement  */
1139                 bi->needsRetiring = 1;
1140                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1141                   (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1142         }
1143
1144         /* Delete the chunk */
1145         yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1146         yaffs_SkipRestOfBlock(dev);
1147 }
1148
1149
1150 /*---------------- Name handling functions ------------*/
1151
1152 static __u16 yaffs_CalcNameSum(const YCHAR *name)
1153 {
1154         __u16 sum = 0;
1155         __u16 i = 1;
1156
1157         const YUCHAR *bname = (const YUCHAR *) name;
1158         if (bname) {
1159                 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1160
1161 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1162                         sum += yaffs_toupper(*bname) * i;
1163 #else
1164                         sum += (*bname) * i;
1165 #endif
1166                         i++;
1167                         bname++;
1168                 }
1169         }
1170         return sum;
1171 }
1172
1173 static void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
1174 {
1175 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1176         memset(obj->shortName, 0, sizeof(YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1177         if (name && yaffs_strnlen(name,YAFFS_SHORT_NAME_LENGTH+1) <= YAFFS_SHORT_NAME_LENGTH)
1178                 yaffs_strcpy(obj->shortName, name);
1179         else
1180                 obj->shortName[0] = _Y('\0');
1181 #endif
1182         obj->sum = yaffs_CalcNameSum(name);
1183 }
1184
1185 /*-------------------- TNODES -------------------
1186
1187  * List of spare tnodes
1188  * The list is hooked together using the first pointer
1189  * in the tnode.
1190  */
1191
1192 /* yaffs_CreateTnodes creates a bunch more tnodes and
1193  * adds them to the tnode free list.
1194  * Don't use this function directly
1195  */
1196 static Y_INLINE int yaffs_CalcTnodeSize(yaffs_Device *dev)
1197 {
1198         int tnodeSize;
1199         /* Calculate the tnode size in bytes for variable width tnode support.
1200          * Must be a multiple of 32-bits  */
1201         tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1202
1203         if (tnodeSize < sizeof(yaffs_Tnode))
1204                 tnodeSize = sizeof(yaffs_Tnode);
1205         return tnodeSize;
1206 }
1207
1208 static int yaffs_CreateTnodes(yaffs_Device *dev, int nTnodes)
1209 {
1210         int i;
1211         int tnodeSize = yaffs_CalcTnodeSize(dev);
1212         yaffs_Tnode *newTnodes;
1213         __u8 *mem;
1214         yaffs_Tnode *curr;
1215         yaffs_Tnode *next;
1216         yaffs_TnodeList *tnl;
1217
1218         if (nTnodes < 1)
1219                 return YAFFS_OK;
1220
1221
1222         /* make these things */
1223
1224         newTnodes = YMALLOC(nTnodes * tnodeSize);
1225         mem = (__u8 *)newTnodes;
1226
1227         if (!newTnodes) {
1228                 T(YAFFS_TRACE_ERROR,
1229                         (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1230                 return YAFFS_FAIL;
1231         }
1232
1233         /* Hook them into the free list */
1234 #if 0
1235         for (i = 0; i < nTnodes - 1; i++) {
1236                 newTnodes[i].internal[0] = &newTnodes[i + 1];
1237 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1238                 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1239 #endif
1240         }
1241
1242         newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1243 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1244         newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1245 #endif
1246         dev->freeTnodes = newTnodes;
1247 #else
1248         /* New hookup for wide tnodes */
1249         for (i = 0; i < nTnodes - 1; i++) {
1250                 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1251                 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1252                 curr->internal[0] = next;
1253         }
1254
1255         curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1256         curr->internal[0] = dev->freeTnodes;
1257         dev->freeTnodes = (yaffs_Tnode *)mem;
1258
1259 #endif
1260
1261
1262         dev->nFreeTnodes += nTnodes;
1263         dev->nTnodesCreated += nTnodes;
1264
1265         /* Now add this bunch of tnodes to a list for freeing up.
1266          * NB If we can't add this to the management list it isn't fatal
1267          * but it just means we can't free this bunch of tnodes later.
1268          */
1269
1270         tnl = YMALLOC(sizeof(yaffs_TnodeList));
1271         if (!tnl) {
1272                 T(YAFFS_TRACE_ERROR,
1273                   (TSTR
1274                    ("yaffs: Could not add tnodes to management list" TENDSTR)));
1275                    return YAFFS_FAIL;
1276         } else {
1277                 tnl->tnodes = newTnodes;
1278                 tnl->next = dev->allocatedTnodeList;
1279                 dev->allocatedTnodeList = tnl;
1280         }
1281
1282         T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1283
1284         return YAFFS_OK;
1285 }
1286
1287 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1288
1289 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device *dev)
1290 {
1291         yaffs_Tnode *tn = NULL;
1292
1293 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1294         tn = YMALLOC(yaffs_CalcTnodeSize(dev));
1295         if(tn)
1296                 dev->nTnodesCreated++;
1297 #else
1298         /* If there are none left make more */
1299         if (!dev->freeTnodes)
1300                 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1301
1302         if (dev->freeTnodes) {
1303                 tn = dev->freeTnodes;
1304 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1305                 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1306                         /* Hoosterman, this thing looks like it isn't in the list */
1307                         T(YAFFS_TRACE_ALWAYS,
1308                           (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1309                 }
1310 #endif
1311                 dev->freeTnodes = dev->freeTnodes->internal[0];
1312                 dev->nFreeTnodes--;
1313         }
1314 #endif
1315         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1316
1317         return tn;
1318 }
1319
1320 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
1321 {
1322         yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1323         int tnodeSize = yaffs_CalcTnodeSize(dev);
1324
1325         if (tn)
1326                 memset(tn, 0, tnodeSize);
1327
1328         return tn;
1329 }
1330
1331 /* FreeTnode frees up a tnode and puts it back on the free list */
1332 static void yaffs_FreeTnode(yaffs_Device *dev, yaffs_Tnode *tn)
1333 {
1334         if (tn) {
1335 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1336                 YFREE(tn);
1337                 dev->nTnodesCreated--;
1338 #else
1339 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1340                 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1341                         /* Hoosterman, this thing looks like it is already in the list */
1342                         T(YAFFS_TRACE_ALWAYS,
1343                           (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1344                 }
1345                 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1346 #endif
1347                 tn->internal[0] = dev->freeTnodes;
1348                 dev->freeTnodes = tn;
1349                 dev->nFreeTnodes++;
1350 #endif
1351         }
1352         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1353 }
1354
1355 static void yaffs_DeinitialiseTnodes(yaffs_Device *dev)
1356 {
1357         /* Free the list of allocated tnodes */
1358         yaffs_TnodeList *tmp;
1359
1360         while (dev->allocatedTnodeList) {
1361                 tmp = dev->allocatedTnodeList->next;
1362
1363                 YFREE(dev->allocatedTnodeList->tnodes);
1364                 YFREE(dev->allocatedTnodeList);
1365                 dev->allocatedTnodeList = tmp;
1366
1367         }
1368
1369         dev->freeTnodes = NULL;
1370         dev->nFreeTnodes = 0;
1371         dev->nTnodesCreated = 0;
1372 }
1373
1374 static void yaffs_InitialiseTnodes(yaffs_Device *dev)
1375 {
1376         dev->allocatedTnodeList = NULL;
1377         dev->freeTnodes = NULL;
1378         dev->nFreeTnodes = 0;
1379         dev->nTnodesCreated = 0;
1380 }
1381
1382
1383 void yaffs_LoadLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
1384                 unsigned val)
1385 {
1386         __u32 *map = (__u32 *)tn;
1387         __u32 bitInMap;
1388         __u32 bitInWord;
1389         __u32 wordInMap;
1390         __u32 mask;
1391
1392         pos &= YAFFS_TNODES_LEVEL0_MASK;
1393         val >>= dev->chunkGroupBits;
1394
1395         bitInMap = pos * dev->tnodeWidth;
1396         wordInMap = bitInMap / 32;
1397         bitInWord = bitInMap & (32 - 1);
1398
1399         mask = dev->tnodeMask << bitInWord;
1400
1401         map[wordInMap] &= ~mask;
1402         map[wordInMap] |= (mask & (val << bitInWord));
1403
1404         if (dev->tnodeWidth > (32 - bitInWord)) {
1405                 bitInWord = (32 - bitInWord);
1406                 wordInMap++;;
1407                 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1408                 map[wordInMap] &= ~mask;
1409                 map[wordInMap] |= (mask & (val >> bitInWord));
1410         }
1411 }
1412
1413 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
1414                 unsigned pos)
1415 {
1416         __u32 *map = (__u32 *)tn;
1417         __u32 bitInMap;
1418         __u32 bitInWord;
1419         __u32 wordInMap;
1420         __u32 val;
1421
1422         pos &= YAFFS_TNODES_LEVEL0_MASK;
1423
1424         bitInMap = pos * dev->tnodeWidth;
1425         wordInMap = bitInMap / 32;
1426         bitInWord = bitInMap & (32 - 1);
1427
1428         val = map[wordInMap] >> bitInWord;
1429
1430         if      (dev->tnodeWidth > (32 - bitInWord)) {
1431                 bitInWord = (32 - bitInWord);
1432                 wordInMap++;;
1433                 val |= (map[wordInMap] << bitInWord);
1434         }
1435
1436         val &= dev->tnodeMask;
1437         val <<= dev->chunkGroupBits;
1438
1439         return val;
1440 }
1441
1442 /* ------------------- End of individual tnode manipulation -----------------*/
1443
1444 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1445  * The look up tree is represented by the top tnode and the number of topLevel
1446  * in the tree. 0 means only the level 0 tnode is in the tree.
1447  */
1448
1449 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1450 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
1451                                         yaffs_FileStructure *fStruct,
1452                                         __u32 chunkId)
1453 {
1454         yaffs_Tnode *tn = fStruct->top;
1455         __u32 i;
1456         int requiredTallness;
1457         int level = fStruct->topLevel;
1458
1459         dev=dev;
1460
1461         /* Check sane level and chunk Id */
1462         if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
1463                 return NULL;
1464
1465         if (chunkId > YAFFS_MAX_CHUNK_ID)
1466                 return NULL;
1467
1468         /* First check we're tall enough (ie enough topLevel) */
1469
1470         i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1471         requiredTallness = 0;
1472         while (i) {
1473                 i >>= YAFFS_TNODES_INTERNAL_BITS;
1474                 requiredTallness++;
1475         }
1476
1477         if (requiredTallness > fStruct->topLevel)
1478                 return NULL; /* Not tall enough, so we can't find it */
1479
1480         /* Traverse down to level 0 */
1481         while (level > 0 && tn) {
1482                 tn = tn->internal[(chunkId >>
1483                         (YAFFS_TNODES_LEVEL0_BITS +
1484                                 (level - 1) *
1485                                 YAFFS_TNODES_INTERNAL_BITS)) &
1486                         YAFFS_TNODES_INTERNAL_MASK];
1487                 level--;
1488         }
1489
1490         return tn;
1491 }
1492
1493 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1494  * This happens in two steps:
1495  *  1. If the tree isn't tall enough, then make it taller.
1496  *  2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1497  *
1498  * Used when modifying the tree.
1499  *
1500  *  If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1501  *  be plugged into the ttree.
1502  */
1503
1504 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
1505                                         yaffs_FileStructure *fStruct,
1506                                         __u32 chunkId,
1507                                         yaffs_Tnode *passedTn)
1508 {
1509         int requiredTallness;
1510         int i;
1511         int l;
1512         yaffs_Tnode *tn;
1513
1514         __u32 x;
1515
1516
1517         /* Check sane level and page Id */
1518         if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
1519                 return NULL;
1520
1521         if (chunkId > YAFFS_MAX_CHUNK_ID)
1522                 return NULL;
1523
1524         /* First check we're tall enough (ie enough topLevel) */
1525
1526         x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1527         requiredTallness = 0;
1528         while (x) {
1529                 x >>= YAFFS_TNODES_INTERNAL_BITS;
1530                 requiredTallness++;
1531         }
1532
1533
1534         if (requiredTallness > fStruct->topLevel) {
1535                 /* Not tall enough, gotta make the tree taller */
1536                 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1537
1538                         tn = yaffs_GetTnode(dev);
1539
1540                         if (tn) {
1541                                 tn->internal[0] = fStruct->top;
1542                                 fStruct->top = tn;
1543                                 fStruct->topLevel++;
1544                         } else {
1545                                 T(YAFFS_TRACE_ERROR,
1546                                         (TSTR("yaffs: no more tnodes" TENDSTR)));
1547                                 return NULL;
1548                         }
1549                 }
1550         }
1551
1552         /* Traverse down to level 0, adding anything we need */
1553
1554         l = fStruct->topLevel;
1555         tn = fStruct->top;
1556
1557         if (l > 0) {
1558                 while (l > 0 && tn) {
1559                         x = (chunkId >>
1560                              (YAFFS_TNODES_LEVEL0_BITS +
1561                               (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1562                             YAFFS_TNODES_INTERNAL_MASK;
1563
1564
1565                         if ((l > 1) && !tn->internal[x]) {
1566                                 /* Add missing non-level-zero tnode */
1567                                 tn->internal[x] = yaffs_GetTnode(dev);
1568                                 if(!tn->internal[x])
1569                                         return NULL;
1570                         } else if (l == 1) {
1571                                 /* Looking from level 1 at level 0 */
1572                                 if (passedTn) {
1573                                         /* If we already have one, then release it.*/
1574                                         if (tn->internal[x])
1575                                                 yaffs_FreeTnode(dev, tn->internal[x]);
1576                                         tn->internal[x] = passedTn;
1577
1578                                 } else if (!tn->internal[x]) {
1579                                         /* Don't have one, none passed in */
1580                                         tn->internal[x] = yaffs_GetTnode(dev);
1581                                         if(!tn->internal[x])
1582                                                 return NULL;
1583                                 }
1584                         }
1585
1586                         tn = tn->internal[x];
1587                         l--;
1588                 }
1589         } else {
1590                 /* top is level 0 */
1591                 if (passedTn) {
1592                         memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1593                         yaffs_FreeTnode(dev, passedTn);
1594                 }
1595         }
1596
1597         return tn;
1598 }
1599
1600 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
1601                                 yaffs_ExtendedTags *tags, int objectId,
1602                                 int chunkInInode)
1603 {
1604         int j;
1605
1606         for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1607                 if (yaffs_CheckChunkBit(dev, theChunk / dev->param.nChunksPerBlock,
1608                                 theChunk % dev->param.nChunksPerBlock)) {
1609                         
1610                         if(dev->chunkGroupSize == 1)
1611                                 return theChunk;
1612                         else {
1613                                 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1614                                                                 tags);
1615                                 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1616                                         /* found it; */
1617                                         return theChunk;
1618                                 }
1619                         }
1620                 }
1621                 theChunk++;
1622         }
1623         return -1;
1624 }
1625
1626
1627 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1628  * chunks and tnodes in the file
1629  * Returns 1 if the tree was deleted.
1630  * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1631  */
1632
1633 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
1634                               int chunkOffset, int *limit)
1635 {
1636         int i;
1637         int chunkInInode;
1638         int theChunk;
1639         yaffs_ExtendedTags tags;
1640         int foundChunk;
1641         yaffs_Device *dev = in->myDev;
1642
1643         int allDone = 1;
1644
1645         if (tn) {
1646                 if (level > 0) {
1647                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1648                              i--) {
1649                                 if (tn->internal[i]) {
1650                                         if (limit && (*limit) < 0) {
1651                                                 allDone = 0;
1652                                         } else {
1653                                                 allDone =
1654                                                         yaffs_DeleteWorker(in,
1655                                                                 tn->
1656                                                                 internal
1657                                                                 [i],
1658                                                                 level -
1659                                                                 1,
1660                                                                 (chunkOffset
1661                                                                         <<
1662                                                                         YAFFS_TNODES_INTERNAL_BITS)
1663                                                                 + i,
1664                                                                 limit);
1665                                         }
1666                                         if (allDone) {
1667                                                 yaffs_FreeTnode(dev,
1668                                                                 tn->
1669                                                                 internal[i]);
1670                                                 tn->internal[i] = NULL;
1671                                         }
1672                                 }
1673                         }
1674                         return (allDone) ? 1 : 0;
1675                 } else if (level == 0) {
1676                         int hitLimit = 0;
1677
1678                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1679                                         i--) {
1680                                 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1681                                 if (theChunk) {
1682
1683                                         chunkInInode = (chunkOffset <<
1684                                                 YAFFS_TNODES_LEVEL0_BITS) + i;
1685
1686                                         foundChunk =
1687                                                 yaffs_FindChunkInGroup(dev,
1688                                                                 theChunk,
1689                                                                 &tags,
1690                                                                 in->objectId,
1691                                                                 chunkInInode);
1692
1693                                         if (foundChunk > 0) {
1694                                                 yaffs_DeleteChunk(dev,
1695                                                                   foundChunk, 1,
1696                                                                   __LINE__);
1697                                                 in->nDataChunks--;
1698                                                 if (limit) {
1699                                                         *limit = *limit - 1;
1700                                                         if (*limit <= 0)
1701                                                                 hitLimit = 1;
1702                                                 }
1703
1704                                         }
1705
1706                                         yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1707                                 }
1708
1709                         }
1710                         return (i < 0) ? 1 : 0;
1711
1712                 }
1713
1714         }
1715
1716         return 1;
1717
1718 }
1719
1720 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1721 {
1722         yaffs_BlockInfo *theBlock;
1723
1724         T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1725
1726         theBlock = yaffs_GetBlockInfo(dev, chunk / dev->param.nChunksPerBlock);
1727         if (theBlock) {
1728                 theBlock->softDeletions++;
1729                 dev->nFreeChunks++;
1730         }
1731 }
1732
1733 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1734  * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1735  * of the tnode.
1736  * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1737  */
1738
1739 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1740                                   __u32 level, int chunkOffset)
1741 {
1742         int i;
1743         int theChunk;
1744         int allDone = 1;
1745         yaffs_Device *dev = in->myDev;
1746
1747         if (tn) {
1748                 if (level > 0) {
1749
1750                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1751                              i--) {
1752                                 if (tn->internal[i]) {
1753                                         allDone =
1754                                             yaffs_SoftDeleteWorker(in,
1755                                                                    tn->
1756                                                                    internal[i],
1757                                                                    level - 1,
1758                                                                    (chunkOffset
1759                                                                     <<
1760                                                                     YAFFS_TNODES_INTERNAL_BITS)
1761                                                                    + i);
1762                                         if (allDone) {
1763                                                 yaffs_FreeTnode(dev,
1764                                                                 tn->
1765                                                                 internal[i]);
1766                                                 tn->internal[i] = NULL;
1767                                         } else {
1768                                                 /* Hoosterman... how could this happen? */
1769                                         }
1770                                 }
1771                         }
1772                         return (allDone) ? 1 : 0;
1773                 } else if (level == 0) {
1774
1775                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1776                                 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1777                                 if (theChunk) {
1778                                         /* Note this does not find the real chunk, only the chunk group.
1779                                          * We make an assumption that a chunk group is not larger than
1780                                          * a block.
1781                                          */
1782                                         yaffs_SoftDeleteChunk(dev, theChunk);
1783                                         yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1784                                 }
1785
1786                         }
1787                         return 1;
1788
1789                 }
1790
1791         }
1792
1793         return 1;
1794
1795 }
1796
1797 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1798 {
1799         if (obj->deleted &&
1800             obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1801                 if (obj->nDataChunks <= 0) {
1802                         /* Empty file with no duplicate object headers, just delete it immediately */
1803                         yaffs_FreeTnode(obj->myDev,
1804                                         obj->variant.fileVariant.top);
1805                         obj->variant.fileVariant.top = NULL;
1806                         T(YAFFS_TRACE_TRACING,
1807                           (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1808                            obj->objectId));
1809                         yaffs_DoGenericObjectDeletion(obj);
1810                 } else {
1811                         yaffs_SoftDeleteWorker(obj,
1812                                                obj->variant.fileVariant.top,
1813                                                obj->variant.fileVariant.
1814                                                topLevel, 0);
1815                         obj->softDeleted = 1;
1816                 }
1817         }
1818 }
1819
1820 /* Pruning removes any part of the file structure tree that is beyond the
1821  * bounds of the file (ie that does not point to chunks).
1822  *
1823  * A file should only get pruned when its size is reduced.
1824  *
1825  * Before pruning, the chunks must be pulled from the tree and the
1826  * level 0 tnode entries must be zeroed out.
1827  * Could also use this for file deletion, but that's probably better handled
1828  * by a special case.
1829  *
1830  * This function is recursive. For levels > 0 the function is called again on
1831  * any sub-tree. For level == 0 we just check if the sub-tree has data.
1832  * If there is no data in a subtree then it is pruned.
1833  */
1834
1835 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1836                                 __u32 level, int del0)
1837 {
1838         int i;
1839         int hasData;
1840
1841         if (tn) {
1842                 hasData = 0;
1843
1844                 if(level > 0){
1845                         for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1846                                 if (tn->internal[i]) {
1847                                         tn->internal[i] =
1848                                                 yaffs_PruneWorker(dev, tn->internal[i],
1849                                                         level - 1,
1850                                                         (i == 0) ? del0 : 1);
1851                                 }
1852
1853                                 if (tn->internal[i])
1854                                         hasData++;
1855                         }
1856                 } else {
1857                         int tnodeSize_u32 = yaffs_CalcTnodeSize(dev)/sizeof(__u32);
1858                         __u32 *map = (__u32 *)tn;
1859
1860                         for(i = 0; !hasData && i < tnodeSize_u32; i++){
1861                                 if(map[i])
1862                                         hasData++;
1863                         }
1864                 }
1865
1866                 if (hasData == 0 && del0) {
1867                         /* Free and return NULL */
1868
1869                         yaffs_FreeTnode(dev, tn);
1870                         tn = NULL;
1871                 }
1872
1873         }
1874
1875         return tn;
1876
1877 }
1878
1879 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1880                                 yaffs_FileStructure *fStruct)
1881 {
1882         int i;
1883         int hasData;
1884         int done = 0;
1885         yaffs_Tnode *tn;
1886
1887         if (fStruct->topLevel > 0) {
1888                 fStruct->top =
1889                     yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1890
1891                 /* Now we have a tree with all the non-zero branches NULL but the height
1892                  * is the same as it was.
1893                  * Let's see if we can trim internal tnodes to shorten the tree.
1894                  * We can do this if only the 0th element in the tnode is in use
1895                  * (ie all the non-zero are NULL)
1896                  */
1897
1898                 while (fStruct->topLevel && !done) {
1899                         tn = fStruct->top;
1900
1901                         hasData = 0;
1902                         for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1903                                 if (tn->internal[i])
1904                                         hasData++;
1905                         }
1906
1907                         if (!hasData) {
1908                                 fStruct->top = tn->internal[0];
1909                                 fStruct->topLevel--;
1910                                 yaffs_FreeTnode(dev, tn);
1911                         } else {
1912                                 done = 1;
1913                         }
1914                 }
1915         }
1916
1917         return YAFFS_OK;
1918 }
1919
1920 /*-------------------- End of File Structure functions.-------------------*/
1921
1922 /* yaffs_CreateFreeObjects creates a bunch more objects and
1923  * adds them to the object free list.
1924  */
1925 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1926 {
1927         int i;
1928         yaffs_Object *newObjects;
1929         yaffs_ObjectList *list;
1930
1931         if (nObjects < 1)
1932                 return YAFFS_OK;
1933
1934         /* make these things */
1935         newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1936         list = YMALLOC(sizeof(yaffs_ObjectList));
1937
1938         if (!newObjects || !list) {
1939                 if (newObjects){
1940                         YFREE(newObjects);
1941                         newObjects = NULL;
1942                 }
1943                 if (list){
1944                         YFREE(list);
1945                         list = NULL;
1946                 }
1947                 T(YAFFS_TRACE_ALLOCATE,
1948                   (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1949                 return YAFFS_FAIL;
1950         }
1951
1952         /* Hook them into the free list */
1953         for (i = 0; i < nObjects - 1; i++) {
1954                 newObjects[i].siblings.next =
1955                                 (struct ylist_head *)(&newObjects[i + 1]);
1956         }
1957
1958         newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1959         dev->freeObjects = newObjects;
1960         dev->nFreeObjects += nObjects;
1961         dev->nObjectsCreated += nObjects;
1962
1963         /* Now add this bunch of Objects to a list for freeing up. */
1964
1965         list->objects = newObjects;
1966         list->next = dev->allocatedObjectList;
1967         dev->allocatedObjectList = list;
1968
1969         return YAFFS_OK;
1970 }
1971
1972
1973 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1974 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1975 {
1976         yaffs_Object *tn = NULL;
1977
1978 #ifdef CONFIG_YAFFS_VALGRIND_TEST
1979         tn = YMALLOC(sizeof(yaffs_Object));
1980         if(tn)
1981                 dev->nObjectsCreated++;
1982 #else
1983         /* If there are none left make more */
1984         if (!dev->freeObjects)
1985                 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1986
1987         if (dev->freeObjects) {
1988                 tn = dev->freeObjects;
1989                 dev->freeObjects =
1990                         (yaffs_Object *) (dev->freeObjects->siblings.next);
1991                 dev->nFreeObjects--;
1992         }
1993 #endif
1994         if (tn) {
1995                 /* Now sweeten it up... */
1996
1997                 memset(tn, 0, sizeof(yaffs_Object));
1998                 tn->beingCreated = 1;
1999
2000                 tn->myDev = dev;
2001                 tn->hdrChunk = 0;
2002                 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
2003                 YINIT_LIST_HEAD(&(tn->hardLinks));
2004                 YINIT_LIST_HEAD(&(tn->hashLink));
2005                 YINIT_LIST_HEAD(&tn->siblings);
2006
2007
2008                 /* Now make the directory sane */
2009                 if (dev->rootDir) {
2010                         tn->parent = dev->rootDir;
2011                         ylist_add(&(tn->siblings), &dev->rootDir->variant.directoryVariant.children);
2012                 }
2013
2014                 /* Add it to the lost and found directory.
2015                  * NB Can't put root or lostNFound in lostNFound so
2016                  * check if lostNFound exists first
2017                  */
2018                 if (dev->lostNFoundDir)
2019                         yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
2020
2021                 tn->beingCreated = 0;
2022         }
2023
2024         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2025
2026         return tn;
2027 }
2028
2029 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
2030                                                __u32 mode)
2031 {
2032
2033         yaffs_Object *obj =
2034             yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
2035         if (obj) {
2036                 obj->fake = 1;          /* it is fake so it might have no NAND presence... */
2037                 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
2038                 obj->unlinkAllowed = 0; /* ... or unlink it */
2039                 obj->deleted = 0;
2040                 obj->unlinked = 0;
2041                 obj->yst_mode = mode;
2042                 obj->myDev = dev;
2043                 obj->hdrChunk = 0;      /* Not a valid chunk. */
2044         }
2045
2046         return obj;
2047
2048 }
2049
2050 static void yaffs_UnhashObject(yaffs_Object *tn)
2051 {
2052         int bucket;
2053         yaffs_Device *dev = tn->myDev;
2054
2055         /* If it is still linked into the bucket list, free from the list */
2056         if (!ylist_empty(&tn->hashLink)) {
2057                 ylist_del_init(&tn->hashLink);
2058                 bucket = yaffs_HashFunction(tn->objectId);
2059                 dev->objectBucket[bucket].count--;
2060         }
2061 }
2062
2063 /*  FreeObject frees up a Object and puts it back on the free list */
2064 static void yaffs_FreeObject(yaffs_Object *tn)
2065 {
2066         yaffs_Device *dev = tn->myDev;
2067
2068         T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), tn, tn->myInode));
2069
2070         if (!tn)
2071                 YBUG();
2072         if (tn->parent)
2073                 YBUG();
2074         if (!ylist_empty(&tn->siblings))
2075                 YBUG();
2076
2077
2078         if (tn->myInode) {
2079                 /* We're still hooked up to a cached inode.
2080                  * Don't delete now, but mark for later deletion
2081                  */
2082                 tn->deferedFree = 1;
2083                 return;
2084         }
2085
2086         yaffs_UnhashObject(tn);
2087
2088 #ifdef CONFIG_YAFFS_VALGRIND_TEST
2089         YFREE(tn);
2090         dev->nObjectsCreated--;
2091         tn = NULL;
2092 #else
2093         /* Link into the free list. */
2094         tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2095         dev->freeObjects = tn;
2096         dev->nFreeObjects++;
2097 #endif
2098         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2099 }
2100
2101
2102 void yaffs_HandleDeferedFree(yaffs_Object *obj)
2103 {
2104         if (obj->deferedFree)
2105                 yaffs_FreeObject(obj);
2106 }
2107
2108
2109 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
2110 {
2111         /* Free the list of allocated Objects */
2112
2113         yaffs_ObjectList *tmp;
2114
2115         while (dev->allocatedObjectList) {
2116                 tmp = dev->allocatedObjectList->next;
2117                 YFREE(dev->allocatedObjectList->objects);
2118                 YFREE(dev->allocatedObjectList);
2119
2120                 dev->allocatedObjectList = tmp;
2121         }
2122
2123         dev->freeObjects = NULL;
2124         dev->nFreeObjects = 0;
2125         dev->nObjectsCreated = 0;
2126 }
2127
2128 static void yaffs_InitialiseObjects(yaffs_Device *dev)
2129 {
2130         int i;
2131
2132         dev->allocatedObjectList = NULL;
2133         dev->freeObjects = NULL;
2134         dev->nFreeObjects = 0;
2135
2136         for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2137                 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2138                 dev->objectBucket[i].count = 0;
2139         }
2140 }
2141
2142 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
2143 {
2144         int i;
2145         int l = 999;
2146         int lowest = 999999;
2147
2148
2149         /* Search for the shortest list or one that
2150          * isn't too long.
2151          */
2152
2153         for (i = 0; i < 10 && lowest > 4; i++) {
2154                 dev->bucketFinder++;
2155                 dev->bucketFinder %= YAFFS_NOBJECT_BUCKETS;
2156                 if (dev->objectBucket[dev->bucketFinder].count < lowest) {
2157                         lowest = dev->objectBucket[dev->bucketFinder].count;
2158                         l = dev->bucketFinder;
2159                 }
2160
2161         }
2162
2163         return l;
2164 }
2165
2166 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
2167 {
2168         int bucket = yaffs_FindNiceObjectBucket(dev);
2169
2170         /* Now find an object value that has not already been taken
2171          * by scanning the list.
2172          */
2173
2174         int found = 0;
2175         struct ylist_head *i;
2176
2177         __u32 n = (__u32) bucket;
2178
2179         /* yaffs_CheckObjectHashSanity();  */
2180
2181         while (!found) {
2182                 found = 1;
2183                 n += YAFFS_NOBJECT_BUCKETS;
2184                 if (1 || dev->objectBucket[bucket].count > 0) {
2185                         ylist_for_each(i, &dev->objectBucket[bucket].list) {
2186                                 /* If there is already one in the list */
2187                                 if (i && ylist_entry(i, yaffs_Object,
2188                                                 hashLink)->objectId == n) {
2189                                         found = 0;
2190                                 }
2191                         }
2192                 }
2193         }
2194
2195         return n;
2196 }
2197
2198 static void yaffs_HashObject(yaffs_Object *in)
2199 {
2200         int bucket = yaffs_HashFunction(in->objectId);
2201         yaffs_Device *dev = in->myDev;
2202
2203         ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2204         dev->objectBucket[bucket].count++;
2205 }
2206
2207 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
2208 {
2209         int bucket = yaffs_HashFunction(number);
2210         struct ylist_head *i;
2211         yaffs_Object *in;
2212
2213         ylist_for_each(i, &dev->objectBucket[bucket].list) {
2214                 /* Look if it is in the list */
2215                 if (i) {
2216                         in = ylist_entry(i, yaffs_Object, hashLink);
2217                         if (in->objectId == number) {
2218
2219                                 /* Don't tell the VFS about this one if it is defered free */
2220                                 if (in->deferedFree)
2221                                         return NULL;
2222
2223                                 return in;
2224                         }
2225                 }
2226         }
2227
2228         return NULL;
2229 }
2230
2231 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
2232                                     yaffs_ObjectType type)
2233 {
2234         yaffs_Object *theObject=NULL;
2235         yaffs_Tnode *tn = NULL;
2236
2237         if (number < 0)
2238                 number = yaffs_CreateNewObjectNumber(dev);
2239
2240         if (type == YAFFS_OBJECT_TYPE_FILE) {
2241                 tn = yaffs_GetTnode(dev);
2242                 if (!tn)
2243                         return NULL;
2244         }
2245
2246         theObject = yaffs_AllocateEmptyObject(dev);
2247         if (!theObject){
2248                 if(tn)
2249                         yaffs_FreeTnode(dev,tn);
2250                 return NULL;
2251         }
2252
2253
2254         if (theObject) {
2255                 theObject->fake = 0;
2256                 theObject->renameAllowed = 1;
2257                 theObject->unlinkAllowed = 1;
2258                 theObject->objectId = number;
2259                 yaffs_HashObject(theObject);
2260                 theObject->variantType = type;
2261 #ifdef CONFIG_YAFFS_WINCE
2262                 yfsd_WinFileTimeNow(theObject->win_atime);
2263                 theObject->win_ctime[0] = theObject->win_mtime[0] =
2264                     theObject->win_atime[0];
2265                 theObject->win_ctime[1] = theObject->win_mtime[1] =
2266                     theObject->win_atime[1];
2267
2268 #else
2269
2270                 theObject->yst_atime = theObject->yst_mtime =
2271                     theObject->yst_ctime = Y_CURRENT_TIME;
2272 #endif
2273                 switch (type) {
2274                 case YAFFS_OBJECT_TYPE_FILE:
2275                         theObject->variant.fileVariant.fileSize = 0;
2276                         theObject->variant.fileVariant.scannedFileSize = 0;
2277                         theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2278                         theObject->variant.fileVariant.topLevel = 0;
2279                         theObject->variant.fileVariant.top = tn;
2280                         break;
2281                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2282                         YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2283                                         children);
2284                         break;
2285                 case YAFFS_OBJECT_TYPE_SYMLINK:
2286                 case YAFFS_OBJECT_TYPE_HARDLINK:
2287                 case YAFFS_OBJECT_TYPE_SPECIAL:
2288                         /* No action required */
2289                         break;
2290                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2291                         /* todo this should not happen */
2292                         break;
2293                 }
2294         }
2295
2296         return theObject;
2297 }
2298
2299 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
2300                                                       int number,
2301                                                       yaffs_ObjectType type)
2302 {
2303         yaffs_Object *theObject = NULL;
2304
2305         if (number > 0)
2306                 theObject = yaffs_FindObjectByNumber(dev, number);
2307
2308         if (!theObject)
2309                 theObject = yaffs_CreateNewObject(dev, number, type);
2310
2311         return theObject;
2312
2313 }
2314
2315
2316 static YCHAR *yaffs_CloneString(const YCHAR *str)
2317 {
2318         YCHAR *newStr = NULL;
2319         int len;
2320
2321         if (!str)
2322                 str = _Y("");
2323
2324         len = yaffs_strnlen(str,YAFFS_MAX_ALIAS_LENGTH);
2325         newStr = YMALLOC((len + 1) * sizeof(YCHAR));
2326         if (newStr){
2327                 yaffs_strncpy(newStr, str,len);
2328                 newStr[len] = 0;
2329         }
2330         return newStr;
2331
2332 }
2333
2334 /*
2335  * Mknod (create) a new object.
2336  * equivalentObject only has meaning for a hard link;
2337  * aliasString only has meaning for a symlink.
2338  * rdev only has meaning for devices (a subset of special objects)
2339  */
2340
2341 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2342                                        yaffs_Object *parent,
2343                                        const YCHAR *name,
2344                                        __u32 mode,
2345                                        __u32 uid,
2346                                        __u32 gid,
2347                                        yaffs_Object *equivalentObject,
2348                                        const YCHAR *aliasString, __u32 rdev)
2349 {
2350         yaffs_Object *in;
2351         YCHAR *str = NULL;
2352
2353         yaffs_Device *dev = parent->myDev;
2354
2355         /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2356         if (yaffs_FindObjectByName(parent, name))
2357                 return NULL;
2358
2359         if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2360                 str = yaffs_CloneString(aliasString);
2361                 if (!str)
2362                         return NULL;
2363         }
2364
2365         in = yaffs_CreateNewObject(dev, -1, type);
2366
2367         if (!in){
2368                 if(str)
2369                         YFREE(str);
2370                 return NULL;
2371         }
2372
2373
2374
2375
2376
2377         if (in) {
2378                 in->hdrChunk = 0;
2379                 in->valid = 1;
2380                 in->variantType = type;
2381
2382                 in->yst_mode = mode;
2383
2384 #ifdef CONFIG_YAFFS_WINCE
2385                 yfsd_WinFileTimeNow(in->win_atime);
2386                 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2387                 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2388
2389 #else
2390                 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2391
2392                 in->yst_rdev = rdev;
2393                 in->yst_uid = uid;
2394                 in->yst_gid = gid;
2395 #endif
2396                 in->nDataChunks = 0;
2397
2398                 yaffs_SetObjectName(in, name);
2399                 in->dirty = 1;
2400
2401                 yaffs_AddObjectToDirectory(parent, in);
2402
2403                 in->myDev = parent->myDev;
2404
2405                 switch (type) {
2406                 case YAFFS_OBJECT_TYPE_SYMLINK:
2407                         in->variant.symLinkVariant.alias = str;
2408                         break;
2409                 case YAFFS_OBJECT_TYPE_HARDLINK:
2410                         in->variant.hardLinkVariant.equivalentObject =
2411                                 equivalentObject;
2412                         in->variant.hardLinkVariant.equivalentObjectId =
2413                                 equivalentObject->objectId;
2414                         ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2415                         break;
2416                 case YAFFS_OBJECT_TYPE_FILE:
2417                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2418                 case YAFFS_OBJECT_TYPE_SPECIAL:
2419                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2420                         /* do nothing */
2421                         break;
2422                 }
2423
2424                 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2425                         /* Could not create the object header, fail the creation */
2426                         yaffs_DeleteObject(in);
2427                         in = NULL;
2428                 }
2429
2430                 yaffs_UpdateParent(parent);
2431         }
2432
2433         return in;
2434 }
2435
2436 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
2437                         __u32 mode, __u32 uid, __u32 gid)
2438 {
2439         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2440                                 uid, gid, NULL, NULL, 0);
2441 }
2442
2443 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
2444                                 __u32 mode, __u32 uid, __u32 gid)
2445 {
2446         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2447                                  mode, uid, gid, NULL, NULL, 0);
2448 }
2449
2450 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
2451                                 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2452 {
2453         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2454                                  uid, gid, NULL, NULL, rdev);
2455 }
2456
2457 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
2458                                 __u32 mode, __u32 uid, __u32 gid,
2459                                 const YCHAR *alias)
2460 {
2461         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2462                                 uid, gid, NULL, alias, 0);
2463 }
2464
2465 /* yaffs_Link returns the object id of the equivalent object.*/
2466 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
2467                         yaffs_Object *equivalentObject)
2468 {
2469         /* Get the real object in case we were fed a hard link as an equivalent object */
2470         equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2471
2472         if (yaffs_MknodObject
2473             (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2474              equivalentObject, NULL, 0)) {
2475                 return equivalentObject;
2476         } else {
2477                 return NULL;
2478         }
2479
2480 }
2481
2482 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
2483                                 const YCHAR *newName, int force, int shadows)
2484 {
2485         int unlinkOp;
2486         int deleteOp;
2487
2488         yaffs_Object *existingTarget;
2489
2490         if (newDir == NULL)
2491                 newDir = obj->parent;   /* use the old directory */
2492
2493         if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2494                 T(YAFFS_TRACE_ALWAYS,
2495                   (TSTR
2496                    ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2497                     TENDSTR)));
2498                 YBUG();
2499         }
2500
2501         /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2502         if (obj->myDev->param.isYaffs2)
2503                 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2504         else
2505                 unlinkOp = (newDir == obj->myDev->unlinkedDir
2506                             && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2507
2508         deleteOp = (newDir == obj->myDev->deletedDir);
2509
2510         existingTarget = yaffs_FindObjectByName(newDir, newName);
2511
2512         /* If the object is a file going into the unlinked directory,
2513          *   then it is OK to just stuff it in since duplicate names are allowed.
2514          *   else only proceed if the new name does not exist and if we're putting
2515          *   it into a directory.
2516          */
2517         if ((unlinkOp ||
2518              deleteOp ||
2519              force ||
2520              (shadows > 0) ||
2521              !existingTarget) &&
2522             newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2523                 yaffs_SetObjectName(obj, newName);
2524                 obj->dirty = 1;
2525
2526                 yaffs_AddObjectToDirectory(newDir, obj);
2527
2528                 if (unlinkOp)
2529                         obj->unlinked = 1;
2530
2531                 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2532                 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows) >= 0)
2533                         return YAFFS_OK;
2534         }
2535
2536         return YAFFS_FAIL;
2537 }
2538
2539 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
2540                 yaffs_Object *newDir, const YCHAR *newName)
2541 {
2542         yaffs_Object *obj = NULL;
2543         yaffs_Object *existingTarget = NULL;
2544         int force = 0;
2545         int result;
2546         yaffs_Device *dev;
2547
2548
2549         if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2550                 YBUG();
2551         if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2552                 YBUG();
2553
2554         dev = oldDir->myDev;
2555
2556 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2557         /* Special case for case insemsitive systems (eg. WinCE).
2558          * While look-up is case insensitive, the name isn't.
2559          * Therefore we might want to change x.txt to X.txt
2560         */
2561         if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
2562                 force = 1;
2563 #endif
2564
2565         if(yaffs_strnlen(newName,YAFFS_MAX_NAME_LENGTH+1) > YAFFS_MAX_NAME_LENGTH)
2566                 /* ENAMETOOLONG */
2567                 return YAFFS_FAIL;
2568
2569         obj = yaffs_FindObjectByName(oldDir, oldName);
2570
2571         if (obj && obj->renameAllowed) {
2572
2573                 /* Now do the handling for an existing target, if there is one */
2574
2575                 existingTarget = yaffs_FindObjectByName(newDir, newName);
2576                 if (existingTarget &&
2577                         existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2578                         !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2579                         /* There is a target that is a non-empty directory, so we fail */
2580                         return YAFFS_FAIL;      /* EEXIST or ENOTEMPTY */
2581                 } else if (existingTarget && existingTarget != obj) {
2582                         /* Nuke the target first, using shadowing,
2583                          * but only if it isn't the same object.
2584                          *
2585                          * Note we must disable gc otherwise it can mess up the shadowing.
2586                          *
2587                          */
2588                         dev->isDoingGC=1;
2589                         yaffs_ChangeObjectName(obj, newDir, newName, force,
2590                                                 existingTarget->objectId);
2591                         existingTarget->isShadowed = 1;
2592                         yaffs_UnlinkObject(existingTarget);
2593                         dev->isDoingGC=0;
2594                 }
2595
2596                 result = yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2597
2598                 yaffs_UpdateParent(oldDir);
2599                 if(newDir != oldDir)
2600                         yaffs_UpdateParent(newDir);
2601                 
2602                 return result;
2603         }
2604         return YAFFS_FAIL;
2605 }
2606
2607 /*------------------------- Block Management and Page Allocation ----------------*/
2608
2609 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
2610 {
2611         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2612
2613         dev->blockInfo = NULL;
2614         dev->chunkBits = NULL;
2615
2616         dev->allocationBlock = -1;      /* force it to get a new one */
2617
2618         /* If the first allocation strategy fails, thry the alternate one */
2619         dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2620         if (!dev->blockInfo) {
2621                 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2622                 dev->blockInfoAlt = 1;
2623         } else
2624                 dev->blockInfoAlt = 0;
2625
2626         if (dev->blockInfo) {
2627                 /* Set up dynamic blockinfo stuff. */
2628                 dev->chunkBitmapStride = (dev->param.nChunksPerBlock + 7) / 8; /* round up bytes */
2629                 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2630                 if (!dev->chunkBits) {
2631                         dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2632                         dev->chunkBitsAlt = 1;
2633                 } else
2634                         dev->chunkBitsAlt = 0;
2635         }
2636
2637         if (dev->blockInfo && dev->chunkBits) {
2638                 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2639                 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2640                 return YAFFS_OK;
2641         }
2642
2643         return YAFFS_FAIL;
2644 }
2645
2646 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2647 {
2648         if (dev->blockInfoAlt && dev->blockInfo)
2649                 YFREE_ALT(dev->blockInfo);
2650         else if (dev->blockInfo)
2651                 YFREE(dev->blockInfo);
2652
2653         dev->blockInfoAlt = 0;
2654
2655         dev->blockInfo = NULL;
2656
2657         if (dev->chunkBitsAlt && dev->chunkBits)
2658                 YFREE_ALT(dev->chunkBits);
2659         else if (dev->chunkBits)
2660                 YFREE(dev->chunkBits);
2661         dev->chunkBitsAlt = 0;
2662         dev->chunkBits = NULL;
2663 }
2664
2665 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
2666                                         yaffs_BlockInfo *bi)
2667 {
2668         int i;
2669         __u32 seq;
2670         yaffs_BlockInfo *b;
2671
2672         if (!dev->param.isYaffs2)
2673                 return 1;       /* disqualification only applies to yaffs2. */
2674
2675         if (!bi->hasShrinkHeader)
2676                 return 1;       /* can gc */
2677
2678         /* Find the oldest dirty sequence number if we don't know it and save it
2679          * so we don't have to keep recomputing it.
2680          */
2681         if (!dev->oldestDirtySequence) {
2682                 seq = dev->sequenceNumber;
2683
2684                 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2685                                 i++) {
2686                         b = yaffs_GetBlockInfo(dev, i);
2687                         if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2688                             (b->pagesInUse - b->softDeletions) <
2689                             dev->param.nChunksPerBlock && b->sequenceNumber < seq) {
2690                                 seq = b->sequenceNumber;
2691                         }
2692                 }
2693                 dev->oldestDirtySequence = seq;
2694         }
2695
2696         /* Can't do gc of this block if there are any blocks older than this one that have
2697          * discarded pages.
2698          */
2699         return (bi->sequenceNumber <= dev->oldestDirtySequence);
2700 }
2701
2702 /*
2703  * yaffs_FindRefreshBlock()
2704  * periodically finds the oldest full block by sequence number for refreshing.
2705  * Only for yaffs2.
2706  */
2707 static __u32 yaffs_FindRefreshBlock(yaffs_Device *dev)
2708 {
2709         __u32 b ;
2710
2711         __u32 oldest = 0;
2712         __u32 oldestSequence = 0;
2713
2714         yaffs_BlockInfo *bi;
2715
2716         /*
2717          * If refresh period < 10 then refreshing is disabled.
2718          */
2719         if(dev->param.refreshPeriod < 10 ||
2720                 !dev->param.isYaffs2)
2721                 return oldest;
2722
2723         /*
2724          * Fix broken values.
2725          */
2726         if(dev->refreshSkip > dev->param.refreshPeriod)
2727                 dev->refreshSkip = dev->param.refreshPeriod;
2728
2729         if(dev->refreshSkip > 0){
2730                 dev->refreshSkip--;
2731                 return oldest;
2732         }
2733
2734         /*
2735          * Refresh skip is now zero.
2736          * We'll do a refresh this time around....
2737          * Update the refresh skip and find the oldest block.
2738          */
2739         dev->refreshSkip = dev->param.refreshPeriod;
2740         dev->refreshCount++;
2741
2742         for (b = dev->internalStartBlock; b <=dev->internalEndBlock; b++){
2743
2744                 bi = yaffs_GetBlockInfo(dev, b);
2745                 
2746
2747                 if (bi->blockState == YAFFS_BLOCK_STATE_FULL){
2748
2749                         if(oldest < 1 ||
2750                                 bi->sequenceNumber < oldestSequence){
2751                                 oldest = b;
2752                                 oldestSequence = bi->sequenceNumber;
2753                         }
2754                 }
2755         }
2756
2757         if (oldest > 0) {
2758                 T(YAFFS_TRACE_GC,
2759                   (TSTR("GC refresh count %d selected block %d with sequenceNumber %d" TENDSTR),
2760                    dev->refreshCount, oldest, oldestSequence));
2761         }
2762
2763         return oldest;
2764 }
2765
2766 /*
2767  * FindDiretiestBlock is used to select the dirtiest block (or close enough)
2768  * for garbage collection.
2769  */
2770
2771 static int yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
2772                                         int aggressive)
2773 {
2774         int b = dev->currentDirtyChecker;
2775
2776         int i;
2777         int iterations;
2778         int dirtiest = -1;
2779         int pagesInUse = 0;
2780         int prioritised = 0;
2781         yaffs_BlockInfo *bi;
2782         int pendingPrioritisedExist = 0;
2783
2784         /* First let's see if we need to grab a prioritised block */
2785         if (dev->hasPendingPrioritisedGCs) {
2786                 for (i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++) {
2787
2788                         bi = yaffs_GetBlockInfo(dev, i);
2789                         /* yaffs_VerifyBlock(dev,bi,i); */
2790
2791                         if (bi->gcPrioritise) {
2792                                 pendingPrioritisedExist = 1;
2793                                 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2794                                    yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2795                                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
2796                                         dirtiest = i;
2797                                         prioritised = 1;
2798                                         aggressive = 1; /* Fool the non-aggressive skip logiv below */
2799                                 }
2800                         }
2801                 }
2802
2803                 if (!pendingPrioritisedExist) /* None found, so we can clear this */
2804                         dev->hasPendingPrioritisedGCs = 0;
2805         }
2806
2807         /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2808          * search harder.
2809          * else (we're doing a leasurely gc), then we only bother to do this if the
2810          * block has only a few pages in use.
2811          */
2812
2813         dev->nonAggressiveSkip--;
2814
2815         if (!aggressive && (dev->nonAggressiveSkip > 0))
2816                 return -1;
2817
2818         if (!prioritised)
2819                 pagesInUse =
2820                         (aggressive) ? dev->param.nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2821
2822         if (aggressive)
2823                 iterations =
2824                     dev->internalEndBlock - dev->internalStartBlock + 1;
2825         else {
2826                 iterations =
2827                     dev->internalEndBlock - dev->internalStartBlock + 1;
2828                 iterations = iterations / 16;
2829                 if (iterations > 200)
2830                         iterations = 200;
2831         }
2832
2833         for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2834                 b++;
2835                 if (b < dev->internalStartBlock || b > dev->internalEndBlock)
2836                         b = dev->internalStartBlock;
2837
2838                 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2839                         T(YAFFS_TRACE_ERROR,
2840                           (TSTR("**>> Block %d is not valid" TENDSTR), b));
2841                         YBUG();
2842                 }
2843
2844                 bi = yaffs_GetBlockInfo(dev, b);
2845
2846                 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2847                         (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2848                                 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2849                         dirtiest = b;
2850                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
2851                 }
2852         }
2853
2854         dev->currentDirtyChecker = b;
2855
2856         if (dirtiest > 0) {
2857                 T(YAFFS_TRACE_GC,
2858                   (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2859                    dev->param.nChunksPerBlock - pagesInUse, prioritised));
2860         }
2861
2862         dev->oldestDirtySequence = 0;
2863
2864         if (dirtiest > 0)
2865                 dev->nonAggressiveSkip = 4;
2866
2867         return dirtiest;
2868 }
2869
2870 static void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
2871 {
2872         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2873
2874         int erasedOk = 0;
2875
2876         /* If the block is still healthy erase it and mark as clean.
2877          * If the block has had a data failure, then retire it.
2878          */
2879
2880         T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2881                 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2882                 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2883
2884         bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2885
2886         if (!bi->needsRetiring) {
2887                 yaffs_InvalidateCheckpoint(dev);
2888                 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2889                 if (!erasedOk) {
2890                         dev->nErasureFailures++;
2891                         T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2892                           (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2893                 }
2894         }
2895
2896         if (erasedOk &&
2897             ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2898                 int i;
2899                 for (i = 0; i < dev->param.nChunksPerBlock; i++) {
2900                         if (!yaffs_CheckChunkErased
2901                             (dev, blockNo * dev->param.nChunksPerBlock + i)) {
2902                                 T(YAFFS_TRACE_ERROR,
2903                                   (TSTR
2904                                    (">>Block %d erasure supposedly OK, but chunk %d not erased"
2905                                     TENDSTR), blockNo, i));
2906                         }
2907                 }
2908         }
2909
2910         if (erasedOk) {
2911                 /* Clean it up... */
2912                 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2913                 bi->sequenceNumber = 0;
2914                 dev->nErasedBlocks++;
2915                 bi->pagesInUse = 0;
2916                 bi->softDeletions = 0;
2917                 bi->hasShrinkHeader = 0;
2918                 bi->skipErasedCheck = 1;  /* This is clean, so no need to check */
2919                 bi->gcPrioritise = 0;
2920                 yaffs_ClearChunkBits(dev, blockNo);
2921
2922                 T(YAFFS_TRACE_ERASE,
2923                   (TSTR("Erased block %d" TENDSTR), blockNo));
2924         } else {
2925                 dev->nFreeChunks -= dev->param.nChunksPerBlock; /* We lost a block of free space */
2926
2927                 yaffs_RetireBlock(dev, blockNo);
2928                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2929                   (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2930         }
2931 }
2932
2933 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2934 {
2935         int i;
2936
2937         yaffs_BlockInfo *bi;
2938
2939         if (dev->nErasedBlocks < 1) {
2940                 /* Hoosterman we've got a problem.
2941                  * Can't get space to gc
2942                  */
2943                 T(YAFFS_TRACE_ERROR,
2944                   (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2945
2946                 return -1;
2947         }
2948
2949         /* Find an empty block. */
2950
2951         for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2952                 dev->allocationBlockFinder++;
2953                 if (dev->allocationBlockFinder < dev->internalStartBlock
2954                     || dev->allocationBlockFinder > dev->internalEndBlock) {
2955                         dev->allocationBlockFinder = dev->internalStartBlock;
2956                 }
2957
2958                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2959
2960                 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2961                         bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2962                         dev->sequenceNumber++;
2963                         bi->sequenceNumber = dev->sequenceNumber;
2964                         dev->nErasedBlocks--;
2965                         T(YAFFS_TRACE_ALLOCATE,
2966                           (TSTR("Allocated block %d, seq  %d, %d left" TENDSTR),
2967                            dev->allocationBlockFinder, dev->sequenceNumber,
2968                            dev->nErasedBlocks));
2969                         return dev->allocationBlockFinder;
2970                 }
2971         }
2972
2973         T(YAFFS_TRACE_ALWAYS,
2974           (TSTR
2975            ("yaffs tragedy: no more erased blocks, but there should have been %d"
2976             TENDSTR), dev->nErasedBlocks));
2977
2978         return -1;
2979 }
2980
2981
2982
2983 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2984 {
2985         if (!dev->nCheckpointBlocksRequired &&
2986            dev->param.isYaffs2) {
2987                 /* Not a valid value so recalculate */
2988                 int nBytes = 0;
2989                 int nBlocks;
2990                 int devBlocks = (dev->param.endBlock - dev->param.startBlock + 1);
2991                 int tnodeSize = yaffs_CalcTnodeSize(dev);
2992
2993                 nBytes += sizeof(yaffs_CheckpointValidity);
2994                 nBytes += sizeof(yaffs_CheckpointDevice);
2995                 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2996                 nBytes += devBlocks * dev->chunkBitmapStride;
2997                 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2998                 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2999                 nBytes += sizeof(yaffs_CheckpointValidity);
3000                 nBytes += sizeof(__u32); /* checksum*/
3001
3002                 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
3003
3004                 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->param.nChunksPerBlock)) + 3;
3005
3006                 dev->nCheckpointBlocksRequired = nBlocks;
3007         }
3008
3009         return dev->nCheckpointBlocksRequired;
3010 }
3011
3012 /*
3013  * Check if there's space to allocate...
3014  * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
3015  */
3016 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev)
3017 {
3018         int reservedChunks;
3019         int reservedBlocks = dev->param.nReservedBlocks;
3020         int checkpointBlocks;
3021
3022         if (dev->param.isYaffs2) {
3023                 checkpointBlocks =  yaffs_CalcCheckpointBlocksRequired(dev) -
3024                                     dev->blocksInCheckpoint;
3025                 if (checkpointBlocks < 0)
3026                         checkpointBlocks = 0;
3027         } else {
3028                 checkpointBlocks = 0;
3029         }
3030
3031         reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->param.nChunksPerBlock);
3032
3033         return (dev->nFreeChunks > reservedChunks);
3034 }
3035
3036 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
3037                 yaffs_BlockInfo **blockUsedPtr)
3038 {
3039         int retVal;
3040         yaffs_BlockInfo *bi;
3041
3042         if (dev->allocationBlock < 0) {
3043                 /* Get next block to allocate off */
3044                 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
3045                 dev->allocationPage = 0;
3046         }
3047
3048         if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
3049                 /* Not enough space to allocate unless we're allowed to use the reserve. */
3050                 return -1;
3051         }
3052
3053         if (dev->nErasedBlocks < dev->param.nReservedBlocks
3054                         && dev->allocationPage == 0) {
3055                 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
3056         }
3057
3058         /* Next page please.... */
3059         if (dev->allocationBlock >= 0) {
3060                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3061
3062                 retVal = (dev->allocationBlock * dev->param.nChunksPerBlock) +
3063                         dev->allocationPage;
3064                 bi->pagesInUse++;
3065                 yaffs_SetChunkBit(dev, dev->allocationBlock,
3066                                 dev->allocationPage);
3067
3068                 dev->allocationPage++;
3069
3070                 dev->nFreeChunks--;
3071
3072                 /* If the block is full set the state to full */
3073                 if (dev->allocationPage >= dev->param.nChunksPerBlock) {
3074                         bi->blockState = YAFFS_BLOCK_STATE_FULL;
3075                         dev->allocationBlock = -1;
3076                 }
3077
3078                 if (blockUsedPtr)
3079                         *blockUsedPtr = bi;
3080
3081                 return retVal;
3082         }
3083
3084         T(YAFFS_TRACE_ERROR,
3085                         (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
3086
3087         return -1;
3088 }
3089
3090 static int yaffs_GetErasedChunks(yaffs_Device *dev)
3091 {
3092         int n;
3093
3094         n = dev->nErasedBlocks * dev->param.nChunksPerBlock;
3095
3096         if (dev->allocationBlock > 0)
3097                 n += (dev->param.nChunksPerBlock - dev->allocationPage);
3098
3099         return n;
3100
3101 }
3102
3103 /*
3104  * yaffs_SkipRestOfBlock() skips over the rest of the allocation block
3105  * if we don't want to write to it.
3106  */
3107 static void yaffs_SkipRestOfBlock(yaffs_Device *dev)
3108 {
3109         if(dev->allocationBlock > 0){
3110                 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3111                 if(bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING){
3112                         bi->blockState = YAFFS_BLOCK_STATE_FULL;
3113                         dev->allocationBlock = -1;
3114                 }
3115         }
3116 }
3117
3118
3119 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
3120                 int wholeBlock)
3121 {
3122         int oldChunk;
3123         int newChunk;
3124         int markNAND;
3125         int retVal = YAFFS_OK;
3126         int cleanups = 0;
3127         int i;
3128         int isCheckpointBlock;
3129         int matchingChunk;
3130         int maxCopies;
3131
3132         int chunksBefore = yaffs_GetErasedChunks(dev);
3133         int chunksAfter;
3134
3135         yaffs_ExtendedTags tags;
3136
3137         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3138
3139         yaffs_Object *object;
3140
3141         isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3142
3143
3144         T(YAFFS_TRACE_TRACING,
3145                         (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3146                          block,
3147                          bi->pagesInUse,
3148                          bi->hasShrinkHeader,
3149                          wholeBlock));
3150
3151         /*yaffs_VerifyFreeChunks(dev); */
3152
3153         if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
3154                 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3155         
3156         bi->hasShrinkHeader = 0;        /* clear the flag so that the block can erase */
3157
3158         /* Take off the number of soft deleted entries because
3159          * they're going to get really deleted during GC.
3160          */
3161         if(dev->gcChunk == 0) /* first time through for this block */
3162                 dev->nFreeChunks -= bi->softDeletions;
3163
3164         dev->isDoingGC = 1;
3165
3166         if (isCheckpointBlock ||
3167                         !yaffs_StillSomeChunkBits(dev, block)) {
3168                 T(YAFFS_TRACE_TRACING,
3169                                 (TSTR
3170                                  ("Collecting block %d that has no chunks in use" TENDSTR),
3171                                  block));
3172                 yaffs_BlockBecameDirty(dev, block);
3173         } else {
3174
3175                 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3176
3177                 yaffs_VerifyBlock(dev, bi, block);
3178
3179                 maxCopies = (wholeBlock) ? dev->param.nChunksPerBlock : 10;
3180                 oldChunk = block * dev->param.nChunksPerBlock + dev->gcChunk;
3181
3182                 for (/* init already done */;
3183                      retVal == YAFFS_OK &&
3184                      dev->gcChunk < dev->param.nChunksPerBlock &&
3185                      (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
3186                      maxCopies > 0;
3187                      dev->gcChunk++, oldChunk++) {
3188                         if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3189
3190                                 /* This page is in use and might need to be copied off */
3191
3192                                 maxCopies--;
3193
3194                                 markNAND = 1;
3195
3196                                 yaffs_InitialiseTags(&tags);
3197
3198                                 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3199                                                                 buffer, &tags);
3200
3201                                 object =
3202                                     yaffs_FindObjectByNumber(dev,
3203                                                              tags.objectId);
3204
3205                                 T(YAFFS_TRACE_GC_DETAIL,
3206                                   (TSTR
3207                                    ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3208                                    dev->gcChunk, tags.objectId, tags.chunkId,
3209                                    tags.byteCount));
3210
3211                                 if (object && !yaffs_SkipVerification(dev)) {
3212                                         if (tags.chunkId == 0)
3213                                                 matchingChunk = object->hdrChunk;
3214                                         else if (object->softDeleted)
3215                                                 matchingChunk = oldChunk; /* Defeat the test */
3216                                         else
3217                                                 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
3218
3219                                         if (oldChunk != matchingChunk)
3220                                                 T(YAFFS_TRACE_ERROR,
3221                                                   (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3222                                                   oldChunk, matchingChunk, tags.objectId, tags.chunkId));
3223
3224                                 }
3225
3226                                 if (!object) {
3227                                         T(YAFFS_TRACE_ERROR,
3228                                           (TSTR
3229                                            ("page %d in gc has no object: %d %d %d "
3230                                             TENDSTR), oldChunk,
3231                                             tags.objectId, tags.chunkId, tags.byteCount));
3232                                 }
3233
3234                                 if (object &&
3235                                     object->deleted &&
3236                                     object->softDeleted &&
3237                                     tags.chunkId != 0) {
3238                                         /* Data chunk in a soft deleted file, throw it away
3239                                          * It's a soft deleted data chunk,
3240                                          * No need to copy this, just forget about it and
3241                                          * fix up the object.
3242                                          */
3243
3244                                         object->nDataChunks--;
3245
3246                                         if (object->nDataChunks <= 0) {
3247                                                 /* remeber to clean up the object */
3248                                                 dev->gcCleanupList[cleanups] =
3249                                                     tags.objectId;
3250                                                 cleanups++;
3251                                         }
3252                                         markNAND = 0;
3253                                 } else if (0) {
3254                                         /* Todo object && object->deleted && object->nDataChunks == 0 */
3255                                         /* Deleted object header with no data chunks.
3256                                          * Can be discarded and the file deleted.
3257                                          */
3258                                         object->hdrChunk = 0;
3259                                         yaffs_FreeTnode(object->myDev,
3260                                                         object->variant.
3261                                                         fileVariant.top);
3262                                         object->variant.fileVariant.top = NULL;
3263                                         yaffs_DoGenericObjectDeletion(object);
3264
3265                                 } else if (object) {
3266                                         /* It's either a data chunk in a live file or
3267                                          * an ObjectHeader, so we're interested in it.
3268                                          * NB Need to keep the ObjectHeaders of deleted files
3269                                          * until the whole file has been deleted off
3270                                          */
3271                                         tags.serialNumber++;
3272
3273                                         dev->nGCCopies++;
3274
3275                                         if (tags.chunkId == 0) {
3276                                                 /* It is an object Id,
3277                                                  * We need to nuke the shrinkheader flags first
3278                                                  * Also need to clean up shadowing.
3279                                                  * We no longer want the shrinkHeader flag since its work is done
3280                                                  * and if it is left in place it will mess up scanning.
3281                                                  */
3282
3283                                                 yaffs_ObjectHeader *oh;
3284                                                 oh = (yaffs_ObjectHeader *)buffer;
3285                                                 oh->isShrink = 0;
3286                                                 tags.extraIsShrinkHeader = 0;
3287                                                 oh->shadowsObject = 0;
3288                                                 oh->inbandShadowsObject = 0;
3289                                                 if(object->variantType == YAFFS_OBJECT_TYPE_FILE)
3290                                                         oh->fileSize = object->variant.fileVariant.fileSize;
3291                                                 tags.extraShadows = 0;
3292
3293                                                 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
3294                                                 newChunk =
3295                                                     yaffs_WriteNewChunkWithTagsToNAND(dev,(__u8 *) oh, &tags, 1);
3296                                         } else
3297                                                 newChunk =
3298                                                     yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3299
3300                                         if (newChunk < 0) {
3301                                                 retVal = YAFFS_FAIL;
3302                                         } else {
3303
3304                                                 /* Ok, now fix up the Tnodes etc. */
3305
3306                                                 if (tags.chunkId == 0) {
3307                                                         /* It's a header */
3308                                                         object->hdrChunk =  newChunk;
3309                                                         object->serial =   tags.serialNumber;
3310                                                 } else {
3311                                                         /* It's a data chunk */
3312                                                         int ok;
3313                                                         ok = yaffs_PutChunkIntoFile
3314                                                             (object,
3315                                                              tags.chunkId,
3316                                                              newChunk, 0);
3317                                                 }
3318                                         }
3319                                 }
3320
3321                                 if (retVal == YAFFS_OK)
3322                                         yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3323
3324                         }
3325                 }
3326
3327                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3328
3329
3330                 /* Do any required cleanups */
3331                 for (i = 0; i < cleanups; i++) {
3332                         /* Time to delete the file too */
3333                         object =
3334                             yaffs_FindObjectByNumber(dev,
3335                                                      dev->gcCleanupList[i]);
3336                         if (object) {
3337                                 yaffs_FreeTnode(dev,
3338                                                 object->variant.fileVariant.
3339                                                 top);
3340                                 object->variant.fileVariant.top = NULL;
3341                                 T(YAFFS_TRACE_GC,
3342                                   (TSTR
3343                                    ("yaffs: About to finally delete object %d"
3344                                     TENDSTR), object->objectId));
3345                                 yaffs_DoGenericObjectDeletion(object);
3346                                 object->myDev->nDeletedFiles--;
3347                         }
3348
3349                 }
3350
3351         }
3352
3353         yaffs_VerifyCollectedBlock(dev, bi, block);
3354
3355
3356
3357         /* If the gc completed then clear the current gcBlock so that we find another. */
3358         if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING) {
3359                 chunksAfter = yaffs_GetErasedChunks(dev);
3360                 if (chunksBefore >= chunksAfter) {
3361                         T(YAFFS_TRACE_GC,
3362                           (TSTR
3363                            ("gc did not increase free chunks before %d after %d"
3364                             TENDSTR), chunksBefore, chunksAfter));
3365                 }
3366                 dev->gcBlock = -1;
3367                 dev->gcChunk = 0;
3368         }
3369
3370         dev->isDoingGC = 0;
3371
3372         return retVal;
3373 }
3374
3375 /* New garbage collector
3376  * If we're very low on erased blocks then we do aggressive garbage collection
3377  * otherwise we do "leasurely" garbage collection.
3378  * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3379  * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3380  *
3381  * The idea is to help clear out space in a more spread-out manner.
3382  * Dunno if it really does anything useful.
3383  */
3384 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
3385 {
3386         int block;
3387         int aggressive;
3388         int gcOk = YAFFS_OK;
3389         int maxTries = 0;
3390
3391         int checkpointBlockAdjust;
3392
3393         if (dev->isDoingGC) {
3394                 /* Bail out so we don't get recursive gc */
3395                 return YAFFS_OK;
3396         }
3397
3398         /* This loop should pass the first time.
3399          * We'll only see looping here if the erase of the collected block fails.
3400          */
3401
3402         do {
3403                 maxTries++;
3404
3405                 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3406                 if (checkpointBlockAdjust < 0)
3407                         checkpointBlockAdjust = 0;
3408
3409                 /* If we need a block soon then do aggressive gc.*/
3410                 if (dev->nErasedBlocks < (dev->param.nReservedBlocks + checkpointBlockAdjust + 2))
3411                         aggressive = 1;
3412                 else
3413                         aggressive = 0;
3414
3415                 /* If we don't already have a block being gc'd then see if we should start another */
3416
3417                 if (dev->gcBlock < 1 && !aggressive) {
3418                         dev->gcBlock = yaffs_FindRefreshBlock(dev);
3419                         dev->gcChunk = 0;
3420                 }
3421                 if (dev->gcBlock < 1) {
3422                         dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3423                         dev->gcChunk = 0;
3424                 }
3425
3426                 block = dev->gcBlock;
3427
3428                 if (block > 0) {
3429                         dev->garbageCollections++;
3430                         if (!aggressive)
3431                                 dev->passiveGarbageCollections++;
3432
3433                         T(YAFFS_TRACE_GC,
3434                           (TSTR
3435                            ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3436                            dev->nErasedBlocks, aggressive));
3437
3438                         gcOk = yaffs_GarbageCollectBlock(dev, block, aggressive);
3439                 }
3440
3441                 if (dev->nErasedBlocks < (dev->param.nReservedBlocks) && block > 0) {
3442                         T(YAFFS_TRACE_GC,
3443                           (TSTR
3444                            ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3445                             TENDSTR), dev->nErasedBlocks, maxTries, block));
3446                 }
3447         } while ((dev->nErasedBlocks < dev->param.nReservedBlocks) &&
3448                  (block > 0) &&
3449                  (maxTries < 2));
3450
3451         return aggressive ? gcOk : YAFFS_OK;
3452 }
3453
3454 /*-------------------------  TAGS --------------------------------*/
3455
3456 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
3457                            int chunkInObject)
3458 {
3459         return (tags->chunkId == chunkInObject &&
3460                 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3461
3462 }
3463
3464
3465 /*-------------------- Data file manipulation -----------------*/
3466
3467 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
3468                                  yaffs_ExtendedTags *tags)
3469 {
3470         /*Get the Tnode, then get the level 0 offset chunk offset */
3471         yaffs_Tnode *tn;
3472         int theChunk = -1;
3473         yaffs_ExtendedTags localTags;
3474         int retVal = -1;
3475
3476         yaffs_Device *dev = in->myDev;
3477
3478         if (!tags) {
3479                 /* Passed a NULL, so use our own tags space */
3480                 tags = &localTags;
3481         }
3482
3483         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3484
3485         if (tn) {
3486                 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3487
3488                 retVal =
3489                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3490                                            chunkInInode);
3491         }
3492         return retVal;
3493 }
3494
3495 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
3496                                           yaffs_ExtendedTags *tags)
3497 {
3498         /* Get the Tnode, then get the level 0 offset chunk offset */
3499         yaffs_Tnode *tn;
3500         int theChunk = -1;
3501         yaffs_ExtendedTags localTags;
3502
3503         yaffs_Device *dev = in->myDev;
3504         int retVal = -1;
3505
3506         if (!tags) {
3507                 /* Passed a NULL, so use our own tags space */
3508                 tags = &localTags;
3509         }
3510
3511         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3512
3513         if (tn) {
3514
3515                 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3516
3517                 retVal =
3518                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3519                                            chunkInInode);
3520
3521                 /* Delete the entry in the filestructure (if found) */
3522                 if (retVal != -1)
3523                         yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, 0);
3524         }
3525
3526         return retVal;
3527 }
3528
3529 #ifdef YAFFS_PARANOID
3530
3531 static int yaffs_CheckFileSanity(yaffs_Object *in)
3532 {
3533         int chunk;
3534         int nChunks;
3535         int fSize;
3536         int failed = 0;
3537         int objId;
3538         yaffs_Tnode *tn;
3539         yaffs_Tags localTags;
3540         yaffs_Tags *tags = &localTags;
3541         int theChunk;
3542         int chunkDeleted;
3543
3544         if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3545                 return YAFFS_FAIL;
3546
3547         objId = in->objectId;
3548         fSize = in->variant.fileVariant.fileSize;
3549         nChunks =
3550             (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3551
3552         for (chunk = 1; chunk <= nChunks; chunk++) {
3553                 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3554                                            chunk);
3555
3556                 if (tn) {
3557
3558                         theChunk = yaffs_GetChunkGroupBase(dev, tn, chunk);
3559
3560                         if (yaffs_CheckChunkBits
3561                             (dev, theChunk / dev->param.nChunksPerBlock,
3562                              theChunk % dev->param.nChunksPerBlock)) {
3563
3564                                 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3565                                                             tags,
3566                                                             &chunkDeleted);
3567                                 if (yaffs_TagsMatch
3568                                     (tags, in->objectId, chunk, chunkDeleted)) {
3569                                         /* found it; */
3570
3571                                 }
3572                         } else {
3573
3574                                 failed = 1;
3575                         }
3576
3577                 } else {
3578                         /* T(("No level 0 found for %d\n", chunk)); */
3579                 }
3580         }
3581
3582         return failed ? YAFFS_FAIL : YAFFS_OK;
3583 }
3584
3585 #endif
3586
3587 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
3588                                   int chunkInNAND, int inScan)
3589 {
3590         /* NB inScan is zero unless scanning.
3591          * For forward scanning, inScan is > 0;
3592          * for backward scanning inScan is < 0
3593          *
3594          * chunkInNAND = 0 is a dummy insert to make sure the tnodes are there.
3595          */
3596
3597         yaffs_Tnode *tn;
3598         yaffs_Device *dev = in->myDev;
3599         int existingChunk;
3600         yaffs_ExtendedTags existingTags;
3601         yaffs_ExtendedTags newTags;
3602         unsigned existingSerial, newSerial;
3603
3604         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3605                 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3606                  * If it is not during Scanning then something went wrong!
3607                  */
3608                 if (!inScan) {
3609                         T(YAFFS_TRACE_ERROR,
3610                           (TSTR
3611                            ("yaffs tragedy:attempt to put data chunk into a non-file"
3612                             TENDSTR)));
3613                         YBUG();
3614                 }
3615
3616                 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3617                 return YAFFS_OK;
3618         }
3619
3620         tn = yaffs_AddOrFindLevel0Tnode(dev,
3621                                         &in->variant.fileVariant,
3622                                         chunkInInode,
3623                                         NULL);
3624         if (!tn)
3625                 return YAFFS_FAIL;
3626         
3627         if(!chunkInNAND)
3628                 /* Dummy insert, bail now */
3629                 return YAFFS_OK;
3630
3631         existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3632
3633         if (inScan != 0) {
3634                 /* If we're scanning then we need to test for duplicates
3635                  * NB This does not need to be efficient since it should only ever
3636                  * happen when the power fails during a write, then only one
3637                  * chunk should ever be affected.
3638                  *
3639                  * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3640                  * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3641                  */
3642
3643                 if (existingChunk > 0) {
3644                         /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3645                          *    thus we have to do a FindChunkInFile to get the real chunk id.
3646                          *
3647                          * We have a duplicate now we need to decide which one to use:
3648                          *
3649                          * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3650                          * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3651                          * YAFFS1: Get both sets of tags and compare serial numbers.
3652                          */
3653
3654                         if (inScan > 0) {
3655                                 /* Only do this for forward scanning */
3656                                 yaffs_ReadChunkWithTagsFromNAND(dev,
3657                                                                 chunkInNAND,
3658                                                                 NULL, &newTags);
3659
3660                                 /* Do a proper find */
3661                                 existingChunk =
3662                                     yaffs_FindChunkInFile(in, chunkInInode,
3663                                                           &existingTags);
3664                         }
3665
3666                         if (existingChunk <= 0) {
3667                                 /*Hoosterman - how did this happen? */
3668
3669                                 T(YAFFS_TRACE_ERROR,
3670                                   (TSTR
3671                                    ("yaffs tragedy: existing chunk < 0 in scan"
3672                                     TENDSTR)));
3673
3674                         }
3675
3676                         /* NB The deleted flags should be false, otherwise the chunks will
3677                          * not be loaded during a scan
3678                          */
3679
3680                         if (inScan > 0) {
3681                                 newSerial = newTags.serialNumber;
3682                                 existingSerial = existingTags.serialNumber;
3683                         }
3684
3685                         if ((inScan > 0) &&
3686                             (in->myDev->param.isYaffs2 ||
3687                              existingChunk <= 0 ||
3688                              ((existingSerial + 1) & 3) == newSerial)) {
3689                                 /* Forward scanning.
3690                                  * Use new
3691                                  * Delete the old one and drop through to update the tnode
3692                                  */
3693                                 yaffs_DeleteChunk(dev, existingChunk, 1,
3694                                                   __LINE__);
3695                         } else {
3696                                 /* Backward scanning or we want to use the existing one
3697                                  * Use existing.
3698                                  * Delete the new one and return early so that the tnode isn't changed
3699                                  */
3700                                 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3701                                                   __LINE__);
3702                                 return YAFFS_OK;
3703                         }
3704                 }
3705
3706         }
3707
3708         if (existingChunk == 0)
3709                 in->nDataChunks++;
3710
3711         yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
3712
3713         return YAFFS_OK;
3714 }
3715
3716 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
3717                                         __u8 *buffer)
3718 {
3719         int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3720
3721         if (chunkInNAND >= 0)
3722                 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3723                                                 buffer, NULL);
3724         else {
3725                 T(YAFFS_TRACE_NANDACCESS,
3726                   (TSTR("Chunk %d not found zero instead" TENDSTR),
3727                    chunkInNAND));
3728                 /* get sane (zero) data if you read a hole */
3729                 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3730                 return 0;
3731         }
3732
3733 }
3734
3735 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
3736 {
3737         int block;
3738         int page;
3739         yaffs_ExtendedTags tags;
3740         yaffs_BlockInfo *bi;
3741
3742         if (chunkId <= 0)
3743                 return;
3744
3745         dev->nDeletions++;
3746         block = chunkId / dev->param.nChunksPerBlock;
3747         page = chunkId % dev->param.nChunksPerBlock;
3748
3749
3750         if (!yaffs_CheckChunkBit(dev, block, page))
3751                 T(YAFFS_TRACE_VERIFY,
3752                         (TSTR("Deleting invalid chunk %d"TENDSTR),
3753                          chunkId));
3754
3755         bi = yaffs_GetBlockInfo(dev, block);
3756
3757         T(YAFFS_TRACE_DELETION,
3758           (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3759
3760         if (markNAND &&
3761             bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->param.isYaffs2) {
3762
3763                 yaffs_InitialiseTags(&tags);
3764
3765                 tags.chunkDeleted = 1;
3766
3767                 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3768                 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3769         } else {
3770                 dev->nUnmarkedDeletions++;
3771         }
3772
3773         /* Pull out of the management area.
3774          * If the whole block became dirty, this will kick off an erasure.
3775          */
3776         if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3777             bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3778             bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3779             bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3780                 dev->nFreeChunks++;
3781
3782                 yaffs_ClearChunkBit(dev, block, page);
3783
3784                 bi->pagesInUse--;
3785
3786                 if (bi->pagesInUse == 0 &&
3787                     !bi->hasShrinkHeader &&
3788                     bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3789                     bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3790                         yaffs_BlockBecameDirty(dev, block);
3791                 }
3792
3793         }
3794
3795 }
3796
3797 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
3798                                         const __u8 *buffer, int nBytes,
3799                                         int useReserve)
3800 {
3801         /* Find old chunk Need to do this to get serial number
3802          * Write new one and patch into tree.
3803          * Invalidate old tags.
3804          */
3805
3806         int prevChunkId;
3807         yaffs_ExtendedTags prevTags;
3808
3809         int newChunkId;
3810         yaffs_ExtendedTags newTags;
3811
3812         yaffs_Device *dev = in->myDev;
3813
3814         yaffs_CheckGarbageCollection(dev);
3815
3816         /* Get the previous chunk at this location in the file if it exists.
3817          * If it does not exist then put a zero into the tree. This creates
3818          * the tnode now, rather than later when it is harder to clean up.
3819          */
3820         prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3821         if(prevChunkId < 1 &&
3822                 !yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0))
3823                 return 0;
3824
3825         /* Set up new tags */
3826         yaffs_InitialiseTags(&newTags);
3827
3828         newTags.chunkId = chunkInInode;
3829         newTags.objectId = in->objectId;
3830         newTags.serialNumber =
3831             (prevChunkId > 0) ? prevTags.serialNumber + 1 : 1;
3832         newTags.byteCount = nBytes;
3833
3834         if (nBytes < 1 || nBytes > dev->param.totalBytesPerChunk) {
3835                 T(YAFFS_TRACE_ERROR,
3836                 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3837                 YBUG();
3838         }
3839         
3840                 
3841         newChunkId =
3842             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3843                                               useReserve);
3844
3845         if (newChunkId > 0) {
3846                 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3847
3848                 if (prevChunkId > 0)
3849                         yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3850
3851                 yaffs_CheckFileSanity(in);
3852         }
3853         return newChunkId;
3854
3855 }
3856
3857 /* UpdateObjectHeader updates the header on NAND for an object.
3858  * If name is not NULL, then that new name is used.
3859  */
3860 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
3861                              int isShrink, int shadows)
3862 {
3863
3864         yaffs_BlockInfo *bi;
3865
3866         yaffs_Device *dev = in->myDev;
3867
3868         int prevChunkId;
3869         int retVal = 0;
3870         int result = 0;
3871
3872         int newChunkId;
3873         yaffs_ExtendedTags newTags;
3874         yaffs_ExtendedTags oldTags;
3875         YCHAR *alias = NULL;
3876
3877         __u8 *buffer = NULL;
3878         YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3879
3880         yaffs_ObjectHeader *oh = NULL;
3881
3882         yaffs_strcpy(oldName, _Y("silly old name"));
3883
3884
3885         if (!in->fake ||
3886                 in == dev->rootDir || /* The rootDir should also be saved */
3887                 force) {
3888
3889                 yaffs_CheckGarbageCollection(dev);
3890                 yaffs_CheckObjectDetailsLoaded(in);
3891
3892                 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3893                 oh = (yaffs_ObjectHeader *) buffer;
3894
3895                 prevChunkId = in->hdrChunk;
3896
3897                 if (prevChunkId > 0) {
3898                         result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3899                                                         buffer, &oldTags);
3900