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