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