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