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