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