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