9f6ba510e635aed3168a865923868b519bc51482
[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.97 2009-12-06 22:53:10 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 /* Function to calculate chunk and offset */
117
118 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut,
119                 __u32 *offsetOut)
120 {
121         int chunk;
122         __u32 offset;
123
124         chunk  = (__u32)(addr >> dev->chunkShift);
125
126         if (dev->chunkDiv == 1) {
127                 /* easy power of 2 case */
128                 offset = (__u32)(addr & dev->chunkMask);
129         } else {
130                 /* Non power-of-2 case */
131
132                 loff_t chunkBase;
133
134                 chunk /= dev->chunkDiv;
135
136                 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
137                 offset = (__u32)(addr - chunkBase);
138         }
139
140         *chunkOut = chunk;
141         *offsetOut = offset;
142 }
143
144 /* Function to return the number of shifts for a power of 2 greater than or
145  * equal to the given number
146  * Note we don't try to cater for all possible numbers and this does not have to
147  * be hellishly efficient.
148  */
149
150 static __u32 ShiftsGE(__u32 x)
151 {
152         int extraBits;
153         int nShifts;
154
155         nShifts = extraBits = 0;
156
157         while (x > 1) {
158                 if (x & 1)
159                         extraBits++;
160                 x >>= 1;
161                 nShifts++;
162         }
163
164         if (extraBits)
165                 nShifts++;
166
167         return nShifts;
168 }
169
170 /* Function to return the number of shifts to get a 1 in bit 0
171  */
172
173 static __u32 Shifts(__u32 x)
174 {
175         int nShifts;
176
177         nShifts =  0;
178
179         if (!x)
180                 return 0;
181
182         while (!(x&1)) {
183                 x >>= 1;
184                 nShifts++;
185         }
186
187         return nShifts;
188 }
189
190
191
192 /*
193  * Temporary buffer manipulations.
194  */
195
196 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
197 {
198         int i;
199         __u8 *buf = (__u8 *)1;
200
201         memset(dev->tempBuffer, 0, sizeof(dev->tempBuffer));
202
203         for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
204                 dev->tempBuffer[i].line = 0;    /* not in use */
205                 dev->tempBuffer[i].buffer = buf =
206                     YMALLOC_DMA(dev->totalBytesPerChunk);
207         }
208
209         return buf ? YAFFS_OK : YAFFS_FAIL;
210 }
211
212 __u8 *yaffs_GetTempBuffer(yaffs_Device *dev, int lineNo)
213 {
214         int i, j;
215
216         dev->tempInUse++;
217         if (dev->tempInUse > dev->maxTemp)
218                 dev->maxTemp = dev->tempInUse;
219
220         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
221                 if (dev->tempBuffer[i].line == 0) {
222                         dev->tempBuffer[i].line = lineNo;
223                         if ((i + 1) > dev->maxTemp) {
224                                 dev->maxTemp = i + 1;
225                                 for (j = 0; j <= i; j++)
226                                         dev->tempBuffer[j].maxLine =
227                                             dev->tempBuffer[j].line;
228                         }
229
230                         return dev->tempBuffer[i].buffer;
231                 }
232         }
233
234         T(YAFFS_TRACE_BUFFERS,
235           (TSTR("Out of temp buffers at line %d, other held by lines:"),
236            lineNo));
237         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
238                 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
239
240         T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
241
242         /*
243          * If we got here then we have to allocate an unmanaged one
244          * This is not good.
245          */
246
247         dev->unmanagedTempAllocations++;
248         return YMALLOC(dev->nDataBytesPerChunk);
249
250 }
251
252 void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer,
253                                     int lineNo)
254 {
255         int i;
256
257         dev->tempInUse--;
258
259         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
260                 if (dev->tempBuffer[i].buffer == buffer) {
261                         dev->tempBuffer[i].line = 0;
262                         return;
263                 }
264         }
265
266         if (buffer) {
267                 /* assume it is an unmanaged one. */
268                 T(YAFFS_TRACE_BUFFERS,
269                   (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
270                    lineNo));
271                 YFREE(buffer);
272                 dev->unmanagedTempDeallocations++;
273         }
274
275 }
276
277 /*
278  * Determine if we have a managed buffer.
279  */
280 int yaffs_IsManagedTempBuffer(yaffs_Device *dev, const __u8 *buffer)
281 {
282         int i;
283
284         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
285                 if (dev->tempBuffer[i].buffer == buffer)
286                         return 1;
287         }
288
289         for (i = 0; i < dev->nShortOpCaches; i++) {
290                 if (dev->srCache[i].data == buffer)
291                         return 1;
292         }
293
294         if (buffer == dev->checkpointBuffer)
295                 return 1;
296
297         T(YAFFS_TRACE_ALWAYS,
298                 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
299         return 0;
300 }
301
302
303
304 /*
305  * Chunk bitmap manipulations
306  */
307
308 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device *dev, int blk)
309 {
310         if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
311                 T(YAFFS_TRACE_ERROR,
312                         (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
313                         blk));
314                 YBUG();
315         }
316         return dev->chunkBits +
317                 (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
318 }
319
320 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
321 {
322         if (blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
323                         chunk < 0 || chunk >= dev->nChunksPerBlock) {
324                 T(YAFFS_TRACE_ERROR,
325                 (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),
326                         blk, chunk));
327                 YBUG();
328         }
329 }
330
331 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device *dev, int blk)
332 {
333         __u8 *blkBits = yaffs_BlockBits(dev, blk);
334
335         memset(blkBits, 0, dev->chunkBitmapStride);
336 }
337
338 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device *dev, int blk, int chunk)
339 {
340         __u8 *blkBits = yaffs_BlockBits(dev, blk);
341
342         yaffs_VerifyChunkBitId(dev, blk, chunk);
343
344         blkBits[chunk / 8] &= ~(1 << (chunk & 7));
345 }
346
347 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device *dev, int blk, int chunk)
348 {
349         __u8 *blkBits = yaffs_BlockBits(dev, blk);
350
351         yaffs_VerifyChunkBitId(dev, blk, chunk);
352
353         blkBits[chunk / 8] |= (1 << (chunk & 7));
354 }
355
356 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device *dev, int blk, int chunk)
357 {
358         __u8 *blkBits = yaffs_BlockBits(dev, blk);
359         yaffs_VerifyChunkBitId(dev, blk, chunk);
360
361         return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
362 }
363
364 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device *dev, int blk)
365 {
366         __u8 *blkBits = yaffs_BlockBits(dev, blk);
367         int i;
368         for (i = 0; i < dev->chunkBitmapStride; i++) {
369                 if (*blkBits)
370                         return 1;
371                 blkBits++;
372         }
373         return 0;
374 }
375
376 static int yaffs_CountChunkBits(yaffs_Device *dev, int blk)
377 {
378         __u8 *blkBits = yaffs_BlockBits(dev, blk);
379         int i;
380         int n = 0;
381         for (i = 0; i < dev->chunkBitmapStride; i++) {
382                 __u8 x = *blkBits;
383                 while (x) {
384                         if (x & 1)
385                                 n++;
386                         x >>= 1;
387                 }
388
389                 blkBits++;
390         }
391         return n;
392 }
393
394 /*
395  * Verification code
396  */
397
398 static int yaffs_SkipVerification(yaffs_Device *dev)
399 {
400         return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
401 }
402
403 static int yaffs_SkipFullVerification(yaffs_Device *dev)
404 {
405         return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
406 }
407
408 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
409 {
410         return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
411 }
412
413 static const char *blockStateName[] = {
414 "Unknown",
415 "Needs scanning",
416 "Scanning",
417 "Empty",
418 "Allocating",
419 "Full",
420 "Dirty",
421 "Checkpoint",
422 "Collecting",
423 "Dead"
424 };
425
426 static void yaffs_VerifyBlock(yaffs_Device *dev, yaffs_BlockInfo *bi, int n)
427 {
428         int actuallyUsed;
429         int inUse;
430
431         if (yaffs_SkipVerification(dev))
432                 return;
433
434         /* Report illegal runtime states */
435         if (bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
436                 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has undefined state %d"TENDSTR), n, bi->blockState));
437
438         switch (bi->blockState) {
439         case YAFFS_BLOCK_STATE_UNKNOWN:
440         case YAFFS_BLOCK_STATE_SCANNING:
441         case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
442                 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has bad run-state %s"TENDSTR),
443                 n, blockStateName[bi->blockState]));
444         }
445
446         /* Check pages in use and soft deletions are legal */
447
448         actuallyUsed = bi->pagesInUse - bi->softDeletions;
449
450         if (bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
451            bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
452            actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock)
453                 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
454                 n, bi->pagesInUse, bi->softDeletions));
455
456
457         /* Check chunk bitmap legal */
458         inUse = yaffs_CountChunkBits(dev, n);
459         if (inUse != bi->pagesInUse)
460                 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
461                         n, bi->pagesInUse, inUse));
462
463         /* Check that the sequence number is valid.
464          * Ten million is legal, but is very unlikely
465          */
466         if (dev->isYaffs2 &&
467            (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
468            (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000))
469                 T(YAFFS_TRACE_VERIFY, (TSTR("Block %d has suspect sequence number of %d"TENDSTR),
470                 n, bi->sequenceNumber));
471 }
472
473 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev, yaffs_BlockInfo *bi,
474                 int n)
475 {
476         yaffs_VerifyBlock(dev, bi, n);
477
478         /* After collection the block should be in the erased state */
479         /* This will need to change if we do partial gc */
480
481         if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING &&
482                         bi->blockState != YAFFS_BLOCK_STATE_EMPTY) {
483                 T(YAFFS_TRACE_ERROR, (TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
484                         n, bi->blockState));
485         }
486 }
487
488 static void yaffs_VerifyBlocks(yaffs_Device *dev)
489 {
490         int i;
491         int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
492         int nIllegalBlockStates = 0;
493
494         if (yaffs_SkipVerification(dev))
495                 return;
496
497         memset(nBlocksPerState, 0, sizeof(nBlocksPerState));
498
499         for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
500                 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, i);
501                 yaffs_VerifyBlock(dev, bi, i);
502
503                 if (bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
504                         nBlocksPerState[bi->blockState]++;
505                 else
506                         nIllegalBlockStates++;
507         }
508
509         T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
510         T(YAFFS_TRACE_VERIFY, (TSTR("Block summary"TENDSTR)));
511
512         T(YAFFS_TRACE_VERIFY, (TSTR("%d blocks have illegal states"TENDSTR), nIllegalBlockStates));
513         if (nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
514                 T(YAFFS_TRACE_VERIFY, (TSTR("Too many allocating blocks"TENDSTR)));
515
516         for (i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
517                 T(YAFFS_TRACE_VERIFY,
518                   (TSTR("%s %d blocks"TENDSTR),
519                   blockStateName[i], nBlocksPerState[i]));
520
521         if (dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
522                 T(YAFFS_TRACE_VERIFY,
523                  (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
524                  dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
525
526         if (dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
527                 T(YAFFS_TRACE_VERIFY,
528                  (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
529                  dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
530
531         if (nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
532                 T(YAFFS_TRACE_VERIFY,
533                  (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
534                  nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
535
536         T(YAFFS_TRACE_VERIFY, (TSTR(""TENDSTR)));
537
538 }
539
540 /*
541  * Verify the object header. oh must be valid, but obj and tags may be NULL in which
542  * case those tests will not be performed.
543  */
544 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
545 {
546         if (obj && yaffs_SkipVerification(obj->myDev))
547                 return;
548
549         if (!(tags && obj && oh)) {
550                 T(YAFFS_TRACE_VERIFY,
551                                 (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR),
552                                 (__u32)tags, (__u32)obj, (__u32)oh));
553                 return;
554         }
555
556         if (oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
557                         oh->type > YAFFS_OBJECT_TYPE_MAX)
558                 T(YAFFS_TRACE_VERIFY,
559                         (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
560                         tags->objectId, oh->type));
561
562         if (tags->objectId != obj->objectId)
563                 T(YAFFS_TRACE_VERIFY,
564                         (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
565                         tags->objectId, obj->objectId));
566
567
568         /*
569          * Check that the object's parent ids match if parentCheck requested.
570          *
571          * Tests do not apply to the root object.
572          */
573
574         if (parentCheck && tags->objectId > 1 && !obj->parent)
575                 T(YAFFS_TRACE_VERIFY,
576                         (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
577                         tags->objectId, oh->parentObjectId));
578
579         if (parentCheck && obj->parent &&
580                         oh->parentObjectId != obj->parent->objectId &&
581                         (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
582                         obj->parent->objectId != YAFFS_OBJECTID_DELETED))
583                 T(YAFFS_TRACE_VERIFY,
584                         (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
585                         tags->objectId, oh->parentObjectId, obj->parent->objectId));
586
587         if (tags->objectId > 1 && oh->name[0] == 0) /* Null name */
588                 T(YAFFS_TRACE_VERIFY,
589                         (TSTR("Obj %d header name is NULL"TENDSTR),
590                         obj->objectId));
591
592         if (tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
593                 T(YAFFS_TRACE_VERIFY,
594                         (TSTR("Obj %d header name is 0xFF"TENDSTR),
595                         obj->objectId));
596 }
597
598
599
600 static int yaffs_VerifyTnodeWorker(yaffs_Object *obj, yaffs_Tnode *tn,
601                                         __u32 level, int chunkOffset)
602 {
603         int i;
604         yaffs_Device *dev = obj->myDev;
605         int ok = 1;
606
607         if (tn) {
608                 if (level > 0) {
609
610                         for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
611                                 if (tn->internal[i]) {
612                                         ok = yaffs_VerifyTnodeWorker(obj,
613                                                         tn->internal[i],
614                                                         level - 1,
615                                                         (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
616                                 }
617                         }
618                 } else if (level == 0) {
619                         yaffs_ExtendedTags tags;
620                         __u32 objectId = obj->objectId;
621
622                         chunkOffset <<=  YAFFS_TNODES_LEVEL0_BITS;
623
624                         for (i = 0; i < YAFFS_NTNODES_LEVEL0; i++) {
625                                 __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
626
627                                 if (theChunk > 0) {
628                                         /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
629                                         yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
630                                         if (tags.objectId != objectId || tags.chunkId != chunkOffset) {
631                                                 T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
632                                                         objectId, chunkOffset, theChunk,
633                                                         tags.objectId, tags.chunkId));
634                                         }
635                                 }
636                                 chunkOffset++;
637                         }
638                 }
639         }
640
641         return ok;
642
643 }
644
645
646 static void yaffs_VerifyFile(yaffs_Object *obj)
647 {
648         int requiredTallness;
649         int actualTallness;
650         __u32 lastChunk;
651         __u32 x;
652         __u32 i;
653         yaffs_Device *dev;
654         yaffs_ExtendedTags tags;
655         yaffs_Tnode *tn;
656         __u32 objectId;
657
658         if (!obj)
659                 return;
660
661         if (yaffs_SkipVerification(obj->myDev))
662                 return;
663
664         dev = obj->myDev;
665         objectId = obj->objectId;
666
667         /* Check file size is consistent with tnode depth */
668         lastChunk =  obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
669         x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
670         requiredTallness = 0;
671         while (x > 0) {
672                 x >>= YAFFS_TNODES_INTERNAL_BITS;
673                 requiredTallness++;
674         }
675
676         actualTallness = obj->variant.fileVariant.topLevel;
677
678         if (requiredTallness > actualTallness)
679                 T(YAFFS_TRACE_VERIFY,
680                 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
681                  obj->objectId, actualTallness, requiredTallness));
682
683
684         /* Check that the chunks in the tnode tree are all correct.
685          * We do this by scanning through the tnode tree and
686          * checking the tags for every chunk match.
687          */
688
689         if (yaffs_SkipNANDVerification(dev))
690                 return;
691
692         for (i = 1; i <= lastChunk; i++) {
693                 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant, i);
694
695                 if (tn) {
696                         __u32 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
697                         if (theChunk > 0) {
698                                 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
699                                 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL, &tags);
700                                 if (tags.objectId != objectId || tags.chunkId != i) {
701                                         T(~0, (TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
702                                                 objectId, i, theChunk,
703                                                 tags.objectId, tags.chunkId));
704                                 }
705                         }
706                 }
707         }
708 }
709
710
711 static void yaffs_VerifyHardLink(yaffs_Object *obj)
712 {
713         if (obj && yaffs_SkipVerification(obj->myDev))
714                 return;
715
716         /* Verify sane equivalent object */
717 }
718
719 static void yaffs_VerifySymlink(yaffs_Object *obj)
720 {
721         if (obj && yaffs_SkipVerification(obj->myDev))
722                 return;
723
724         /* Verify symlink string */
725 }
726
727 static void yaffs_VerifySpecial(yaffs_Object *obj)
728 {
729         if (obj && yaffs_SkipVerification(obj->myDev))
730                 return;
731 }
732
733 static void yaffs_VerifyObject(yaffs_Object *obj)
734 {
735         yaffs_Device *dev;
736
737         __u32 chunkMin;
738         __u32 chunkMax;
739
740         __u32 chunkIdOk;
741         __u32 chunkInRange;
742         __u32 chunkShouldNotBeDeleted;
743         __u32 chunkValid;
744
745         if (!obj)
746                 return;
747
748         if (obj->beingCreated)
749                 return;
750
751         dev = obj->myDev;
752
753         if (yaffs_SkipVerification(dev))
754                 return;
755
756         /* Check sane object header chunk */
757
758         chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
759         chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
760
761         chunkInRange = (((unsigned)(obj->hdrChunk)) >= chunkMin && ((unsigned)(obj->hdrChunk)) <= chunkMax);
762         chunkIdOk = chunkInRange || (obj->hdrChunk == 0);
763         chunkValid = chunkInRange &&
764                         yaffs_CheckChunkBit(dev,
765                                         obj->hdrChunk / dev->nChunksPerBlock,
766                                         obj->hdrChunk % dev->nChunksPerBlock);
767         chunkShouldNotBeDeleted = chunkInRange && !chunkValid;
768
769         if (!obj->fake &&
770                         (!chunkIdOk || chunkShouldNotBeDeleted)) {
771                 T(YAFFS_TRACE_VERIFY,
772                         (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
773                         obj->objectId, obj->hdrChunk,
774                         chunkIdOk ? "" : ",out of range",
775                         chunkShouldNotBeDeleted ? ",marked as deleted" : ""));
776         }
777
778         if (chunkValid && !yaffs_SkipNANDVerification(dev)) {
779                 yaffs_ExtendedTags tags;
780                 yaffs_ObjectHeader *oh;
781                 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
782
783                 oh = (yaffs_ObjectHeader *)buffer;
784
785                 yaffs_ReadChunkWithTagsFromNAND(dev, obj->hdrChunk, buffer,
786                                 &tags);
787
788                 yaffs_VerifyObjectHeader(obj, oh, &tags, 1);
789
790                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
791         }
792
793         /* Verify it has a parent */
794         if (obj && !obj->fake &&
795                         (!obj->parent || obj->parent->myDev != dev)) {
796                 T(YAFFS_TRACE_VERIFY,
797                         (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
798                         obj->objectId, obj->parent));
799         }
800
801         /* Verify parent is a directory */
802         if (obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
803                 T(YAFFS_TRACE_VERIFY,
804                         (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
805                         obj->objectId, obj->parent->variantType));
806         }
807
808         switch (obj->variantType) {
809         case YAFFS_OBJECT_TYPE_FILE:
810                 yaffs_VerifyFile(obj);
811                 break;
812         case YAFFS_OBJECT_TYPE_SYMLINK:
813                 yaffs_VerifySymlink(obj);
814                 break;
815         case YAFFS_OBJECT_TYPE_DIRECTORY:
816                 yaffs_VerifyDirectory(obj);
817                 break;
818         case YAFFS_OBJECT_TYPE_HARDLINK:
819                 yaffs_VerifyHardLink(obj);
820                 break;
821         case YAFFS_OBJECT_TYPE_SPECIAL:
822                 yaffs_VerifySpecial(obj);
823                 break;
824         case YAFFS_OBJECT_TYPE_UNKNOWN:
825         default:
826                 T(YAFFS_TRACE_VERIFY,
827                 (TSTR("Obj %d has illegaltype %d"TENDSTR),
828                 obj->objectId, obj->variantType));
829                 break;
830         }
831 }
832
833 static void yaffs_VerifyObjects(yaffs_Device *dev)
834 {
835         yaffs_Object *obj;
836         int i;
837         struct ylist_head *lh;
838
839         if (yaffs_SkipVerification(dev))
840                 return;
841
842         /* Iterate through the objects in each hash entry */
843
844         for (i = 0; i <  YAFFS_NOBJECT_BUCKETS; i++) {
845                 ylist_for_each(lh, &dev->objectBucket[i].list) {
846                         if (lh) {
847                                 obj = ylist_entry(lh, yaffs_Object, hashLink);
848                                 yaffs_VerifyObject(obj);
849                         }
850                 }
851         }
852 }
853
854
855 /*
856  *  Simple hash function. Needs to have a reasonable spread
857  */
858
859 static Y_INLINE int yaffs_HashFunction(int n)
860 {
861         n = abs(n);
862         return n % YAFFS_NOBJECT_BUCKETS;
863 }
864
865 /*
866  * Access functions to useful fake objects.
867  * Note that root might have a presence in NAND if permissions are set.
868  */
869
870 yaffs_Object *yaffs_Root(yaffs_Device *dev)
871 {
872         return dev->rootDir;
873 }
874
875 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
876 {
877         return dev->lostNFoundDir;
878 }
879
880
881 /*
882  *  Erased NAND checking functions
883  */
884
885 int yaffs_CheckFF(__u8 *buffer, int nBytes)
886 {
887         /* Horrible, slow implementation */
888         while (nBytes--) {
889                 if (*buffer != 0xFF)
890                         return 0;
891                 buffer++;
892         }
893         return 1;
894 }
895
896 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
897                                 int chunkInNAND)
898 {
899         int retval = YAFFS_OK;
900         __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
901         yaffs_ExtendedTags tags;
902         int result;
903
904         result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
905
906         if (tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
907                 retval = YAFFS_FAIL;
908
909         if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
910                 T(YAFFS_TRACE_NANDACCESS,
911                   (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
912                 retval = YAFFS_FAIL;
913         }
914
915         yaffs_ReleaseTempBuffer(dev, data, __LINE__);
916
917         return retval;
918
919 }
920
921 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
922                                         const __u8 *data,
923                                         yaffs_ExtendedTags *tags,
924                                         int useReserve)
925 {
926         int attempts = 0;
927         int writeOk = 0;
928         int chunk;
929
930         yaffs_InvalidateCheckpoint(dev);
931
932         do {
933                 yaffs_BlockInfo *bi = 0;
934                 int erasedOk = 0;
935
936                 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
937                 if (chunk < 0) {
938                         /* no space */
939                         break;
940                 }
941
942                 /* First check this chunk is erased, if it needs
943                  * checking.  The checking policy (unless forced
944                  * always on) is as follows:
945                  *
946                  * Check the first page we try to write in a block.
947                  * If the check passes then we don't need to check any
948                  * more.        If the check fails, we check again...
949                  * If the block has been erased, we don't need to check.
950                  *
951                  * However, if the block has been prioritised for gc,
952                  * then we think there might be something odd about
953                  * this block and stop using it.
954                  *
955                  * Rationale: We should only ever see chunks that have
956                  * not been erased if there was a partially written
957                  * chunk due to power loss.  This checking policy should
958                  * catch that case with very few checks and thus save a
959                  * lot of checks that are most likely not needed.
960                  */
961                 if (bi->gcPrioritise) {
962                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
963                         /* try another chunk */
964                         continue;
965                 }
966
967                 /* let's give it a try */
968                 attempts++;
969
970 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
971                 bi->skipErasedCheck = 0;
972 #endif
973                 if (!bi->skipErasedCheck) {
974                         erasedOk = yaffs_CheckChunkErased(dev, chunk);
975                         if (erasedOk != YAFFS_OK) {
976                                 T(YAFFS_TRACE_ERROR,
977                                 (TSTR("**>> yaffs chunk %d was not erased"
978                                 TENDSTR), chunk));
979
980                                 /* try another chunk */
981                                 continue;
982                         }
983                         bi->skipErasedCheck = 1;
984                 }
985
986                 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
987                                 data, tags);
988                 if (writeOk != YAFFS_OK) {
989                         yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
990                         /* try another chunk */
991                         continue;
992                 }
993
994                 /* Copy the data into the robustification buffer */
995                 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
996
997         } while (writeOk != YAFFS_OK &&
998                 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
999
1000         if (!writeOk)
1001                 chunk = -1;
1002
1003         if (attempts > 1) {
1004                 T(YAFFS_TRACE_ERROR,
1005                         (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1006                         attempts));
1007
1008                 dev->nRetriedWrites += (attempts - 1);
1009         }
1010
1011         return chunk;
1012 }
1013
1014 /*
1015  * Block retiring for handling a broken block.
1016  */
1017
1018 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND)
1019 {
1020         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1021
1022         yaffs_InvalidateCheckpoint(dev);
1023
1024         if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
1025                 if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
1026                         T(YAFFS_TRACE_ALWAYS, (TSTR(
1027                                 "yaffs: Failed to mark bad and erase block %d"
1028                                 TENDSTR), blockInNAND));
1029                 } else {
1030                         yaffs_ExtendedTags tags;
1031                         int chunkId = blockInNAND * dev->nChunksPerBlock;
1032
1033                         __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
1034
1035                         memset(buffer, 0xff, dev->nDataBytesPerChunk);
1036                         yaffs_InitialiseTags(&tags);
1037                         tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
1038                         if (dev->writeChunkWithTagsToNAND(dev, chunkId -
1039                                 dev->chunkOffset, buffer, &tags) != YAFFS_OK)
1040                                 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
1041                                         TCONT("write bad block marker to block %d")
1042                                         TENDSTR), blockInNAND));
1043
1044                         yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
1045                 }
1046         }
1047
1048         bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1049         bi->gcPrioritise = 0;
1050         bi->needsRetiring = 0;
1051
1052         dev->nRetiredBlocks++;
1053 }
1054
1055 /*
1056  * Functions for robustisizing TODO
1057  *
1058  */
1059
1060 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
1061                                 const __u8 *data,
1062                                 const yaffs_ExtendedTags *tags)
1063 {
1064 }
1065
1066 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
1067                                 const yaffs_ExtendedTags *tags)
1068 {
1069 }
1070
1071 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1072 {
1073         if (!bi->gcPrioritise) {
1074                 bi->gcPrioritise = 1;
1075                 dev->hasPendingPrioritisedGCs = 1;
1076                 bi->chunkErrorStrikes++;
1077
1078                 if (bi->chunkErrorStrikes > 3) {
1079                         bi->needsRetiring = 1; /* Too many stikes, so retire this */
1080                         T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1081
1082                 }
1083         }
1084 }
1085
1086 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
1087                 int erasedOk)
1088 {
1089         int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1090         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1091
1092         yaffs_HandleChunkError(dev, bi);
1093
1094         if (erasedOk) {
1095                 /* Was an actual write failure, so mark the block for retirement  */
1096                 bi->needsRetiring = 1;
1097                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1098                   (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1099         }
1100
1101         /* Delete the chunk */
1102         yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1103 }
1104
1105
1106 /*---------------- Name handling functions ------------*/
1107
1108 static __u16 yaffs_CalcNameSum(const YCHAR *name)
1109 {
1110         __u16 sum = 0;
1111         __u16 i = 1;
1112
1113         const YUCHAR *bname = (const YUCHAR *) name;
1114         if (bname) {
1115                 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1116
1117 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1118                         sum += yaffs_toupper(*bname) * i;
1119 #else
1120                         sum += (*bname) * i;
1121 #endif
1122                         i++;
1123                         bname++;
1124                 }
1125         }
1126         return sum;
1127 }
1128
1129 static void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
1130 {
1131 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1132         memset(obj->shortName, 0, sizeof(YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
1133         if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH)
1134                 yaffs_strcpy(obj->shortName, name);
1135         else
1136                 obj->shortName[0] = _Y('\0');
1137 #endif
1138         obj->sum = yaffs_CalcNameSum(name);
1139 }
1140
1141 /*-------------------- TNODES -------------------
1142
1143  * List of spare tnodes
1144  * The list is hooked together using the first pointer
1145  * in the tnode.
1146  */
1147
1148 /* yaffs_CreateTnodes creates a bunch more tnodes and
1149  * adds them to the tnode free list.
1150  * Don't use this function directly
1151  */
1152
1153 static int yaffs_CreateTnodes(yaffs_Device *dev, int nTnodes)
1154 {
1155         int i;
1156         int tnodeSize;
1157         yaffs_Tnode *newTnodes;
1158         __u8 *mem;
1159         yaffs_Tnode *curr;
1160         yaffs_Tnode *next;
1161         yaffs_TnodeList *tnl;
1162
1163         if (nTnodes < 1)
1164                 return YAFFS_OK;
1165
1166         /* Calculate the tnode size in bytes for variable width tnode support.
1167          * Must be a multiple of 32-bits  */
1168         tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1169
1170         if (tnodeSize < sizeof(yaffs_Tnode))
1171                 tnodeSize = sizeof(yaffs_Tnode);
1172
1173         /* make these things */
1174
1175         newTnodes = YMALLOC(nTnodes * tnodeSize);
1176         mem = (__u8 *)newTnodes;
1177
1178         if (!newTnodes) {
1179                 T(YAFFS_TRACE_ERROR,
1180                         (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1181                 return YAFFS_FAIL;
1182         }
1183
1184         /* Hook them into the free list */
1185 #if 0
1186         for (i = 0; i < nTnodes - 1; i++) {
1187                 newTnodes[i].internal[0] = &newTnodes[i + 1];
1188 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1189                 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1190 #endif
1191         }
1192
1193         newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1194 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1195         newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1196 #endif
1197         dev->freeTnodes = newTnodes;
1198 #else
1199         /* New hookup for wide tnodes */
1200         for (i = 0; i < nTnodes - 1; i++) {
1201                 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1202                 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1203                 curr->internal[0] = next;
1204         }
1205
1206         curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1207         curr->internal[0] = dev->freeTnodes;
1208         dev->freeTnodes = (yaffs_Tnode *)mem;
1209
1210 #endif
1211
1212
1213         dev->nFreeTnodes += nTnodes;
1214         dev->nTnodesCreated += nTnodes;
1215
1216         /* Now add this bunch of tnodes to a list for freeing up.
1217          * NB If we can't add this to the management list it isn't fatal
1218          * but it just means we can't free this bunch of tnodes later.
1219          */
1220
1221         tnl = YMALLOC(sizeof(yaffs_TnodeList));
1222         if (!tnl) {
1223                 T(YAFFS_TRACE_ERROR,
1224                   (TSTR
1225                    ("yaffs: Could not add tnodes to management list" TENDSTR)));
1226                    return YAFFS_FAIL;
1227         } else {
1228                 tnl->tnodes = newTnodes;
1229                 tnl->next = dev->allocatedTnodeList;
1230                 dev->allocatedTnodeList = tnl;
1231         }
1232
1233         T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1234
1235         return YAFFS_OK;
1236 }
1237
1238 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1239
1240 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device *dev)
1241 {
1242         yaffs_Tnode *tn = NULL;
1243
1244         /* If there are none left make more */
1245         if (!dev->freeTnodes)
1246                 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1247
1248         if (dev->freeTnodes) {
1249                 tn = dev->freeTnodes;
1250 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1251                 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1252                         /* Hoosterman, this thing looks like it isn't in the list */
1253                         T(YAFFS_TRACE_ALWAYS,
1254                           (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1255                 }
1256 #endif
1257                 dev->freeTnodes = dev->freeTnodes->internal[0];
1258                 dev->nFreeTnodes--;
1259         }
1260
1261         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1262
1263         return tn;
1264 }
1265
1266 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
1267 {
1268         yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1269         int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1270
1271         if (tnodeSize < sizeof(yaffs_Tnode))
1272                 tnodeSize = sizeof(yaffs_Tnode);
1273
1274         if (tn)
1275                 memset(tn, 0, tnodeSize);
1276
1277         return tn;
1278 }
1279
1280 /* FreeTnode frees up a tnode and puts it back on the free list */
1281 static void yaffs_FreeTnode(yaffs_Device *dev, yaffs_Tnode *tn)
1282 {
1283         if (tn) {
1284 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1285                 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1286                         /* Hoosterman, this thing looks like it is already in the list */
1287                         T(YAFFS_TRACE_ALWAYS,
1288                           (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1289                 }
1290                 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1291 #endif
1292                 tn->internal[0] = dev->freeTnodes;
1293                 dev->freeTnodes = tn;
1294                 dev->nFreeTnodes++;
1295         }
1296         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1297 }
1298
1299 static void yaffs_DeinitialiseTnodes(yaffs_Device *dev)
1300 {
1301         /* Free the list of allocated tnodes */
1302         yaffs_TnodeList *tmp;
1303
1304         while (dev->allocatedTnodeList) {
1305                 tmp = dev->allocatedTnodeList->next;
1306
1307                 YFREE(dev->allocatedTnodeList->tnodes);
1308                 YFREE(dev->allocatedTnodeList);
1309                 dev->allocatedTnodeList = tmp;
1310
1311         }
1312
1313         dev->freeTnodes = NULL;
1314         dev->nFreeTnodes = 0;
1315 }
1316
1317 static void yaffs_InitialiseTnodes(yaffs_Device *dev)
1318 {
1319         dev->allocatedTnodeList = NULL;
1320         dev->freeTnodes = NULL;
1321         dev->nFreeTnodes = 0;
1322         dev->nTnodesCreated = 0;
1323 }
1324
1325
1326 void yaffs_LoadLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
1327                 unsigned val)
1328 {
1329         __u32 *map = (__u32 *)tn;
1330         __u32 bitInMap;
1331         __u32 bitInWord;
1332         __u32 wordInMap;
1333         __u32 mask;
1334
1335         pos &= YAFFS_TNODES_LEVEL0_MASK;
1336         val >>= dev->chunkGroupBits;
1337
1338         bitInMap = pos * dev->tnodeWidth;
1339         wordInMap = bitInMap / 32;
1340         bitInWord = bitInMap & (32 - 1);
1341
1342         mask = dev->tnodeMask << bitInWord;
1343
1344         map[wordInMap] &= ~mask;
1345         map[wordInMap] |= (mask & (val << bitInWord));
1346
1347         if (dev->tnodeWidth > (32 - bitInWord)) {
1348                 bitInWord = (32 - bitInWord);
1349                 wordInMap++;;
1350                 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1351                 map[wordInMap] &= ~mask;
1352                 map[wordInMap] |= (mask & (val >> bitInWord));
1353         }
1354 }
1355
1356 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
1357                 unsigned pos)
1358 {
1359         __u32 *map = (__u32 *)tn;
1360         __u32 bitInMap;
1361         __u32 bitInWord;
1362         __u32 wordInMap;
1363         __u32 val;
1364
1365         pos &= YAFFS_TNODES_LEVEL0_MASK;
1366
1367         bitInMap = pos * dev->tnodeWidth;
1368         wordInMap = bitInMap / 32;
1369         bitInWord = bitInMap & (32 - 1);
1370
1371         val = map[wordInMap] >> bitInWord;
1372
1373         if      (dev->tnodeWidth > (32 - bitInWord)) {
1374                 bitInWord = (32 - bitInWord);
1375                 wordInMap++;;
1376                 val |= (map[wordInMap] << bitInWord);
1377         }
1378
1379         val &= dev->tnodeMask;
1380         val <<= dev->chunkGroupBits;
1381
1382         return val;
1383 }
1384
1385 /* ------------------- End of individual tnode manipulation -----------------*/
1386
1387 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1388  * The look up tree is represented by the top tnode and the number of topLevel
1389  * in the tree. 0 means only the level 0 tnode is in the tree.
1390  */
1391
1392 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1393 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
1394                                         yaffs_FileStructure *fStruct,
1395                                         __u32 chunkId)
1396 {
1397         yaffs_Tnode *tn = fStruct->top;
1398         __u32 i;
1399         int requiredTallness;
1400         int level = fStruct->topLevel;
1401
1402         /* Check sane level and chunk Id */
1403         if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
1404                 return NULL;
1405
1406         if (chunkId > YAFFS_MAX_CHUNK_ID)
1407                 return NULL;
1408
1409         /* First check we're tall enough (ie enough topLevel) */
1410
1411         i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1412         requiredTallness = 0;
1413         while (i) {
1414                 i >>= YAFFS_TNODES_INTERNAL_BITS;
1415                 requiredTallness++;
1416         }
1417
1418         if (requiredTallness > fStruct->topLevel)
1419                 return NULL; /* Not tall enough, so we can't find it */
1420
1421         /* Traverse down to level 0 */
1422         while (level > 0 && tn) {
1423                 tn = tn->internal[(chunkId >>
1424                         (YAFFS_TNODES_LEVEL0_BITS +
1425                                 (level - 1) *
1426                                 YAFFS_TNODES_INTERNAL_BITS)) &
1427                         YAFFS_TNODES_INTERNAL_MASK];
1428                 level--;
1429         }
1430
1431         return tn;
1432 }
1433
1434 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1435  * This happens in two steps:
1436  *  1. If the tree isn't tall enough, then make it taller.
1437  *  2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1438  *
1439  * Used when modifying the tree.
1440  *
1441  *  If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1442  *  be plugged into the ttree.
1443  */
1444
1445 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
1446                                         yaffs_FileStructure *fStruct,
1447                                         __u32 chunkId,
1448                                         yaffs_Tnode *passedTn)
1449 {
1450         int requiredTallness;
1451         int i;
1452         int l;
1453         yaffs_Tnode *tn;
1454
1455         __u32 x;
1456
1457
1458         /* Check sane level and page Id */
1459         if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
1460                 return NULL;
1461
1462         if (chunkId > YAFFS_MAX_CHUNK_ID)
1463                 return NULL;
1464
1465         /* First check we're tall enough (ie enough topLevel) */
1466
1467         x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1468         requiredTallness = 0;
1469         while (x) {
1470                 x >>= YAFFS_TNODES_INTERNAL_BITS;
1471                 requiredTallness++;
1472         }
1473
1474
1475         if (requiredTallness > fStruct->topLevel) {
1476                 /* Not tall enough, gotta make the tree taller */
1477                 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1478
1479                         tn = yaffs_GetTnode(dev);
1480
1481                         if (tn) {
1482                                 tn->internal[0] = fStruct->top;
1483                                 fStruct->top = tn;
1484                                 fStruct->topLevel++;
1485                         } else {
1486                                 T(YAFFS_TRACE_ERROR,
1487                                         (TSTR("yaffs: no more tnodes" TENDSTR)));
1488                                 return NULL;
1489                         }
1490                 }
1491         }
1492
1493         /* Traverse down to level 0, adding anything we need */
1494
1495         l = fStruct->topLevel;
1496         tn = fStruct->top;
1497
1498         if (l > 0) {
1499                 while (l > 0 && tn) {
1500                         x = (chunkId >>
1501                              (YAFFS_TNODES_LEVEL0_BITS +
1502                               (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1503                             YAFFS_TNODES_INTERNAL_MASK;
1504
1505
1506                         if ((l > 1) && !tn->internal[x]) {
1507                                 /* Add missing non-level-zero tnode */
1508                                 tn->internal[x] = yaffs_GetTnode(dev);
1509                                 if(!tn->internal[x])
1510                                         return NULL;
1511
1512                         } else if (l == 1) {
1513                                 /* Looking from level 1 at level 0 */
1514                                 if (passedTn) {
1515                                         /* If we already have one, then release it.*/
1516                                         if (tn->internal[x])
1517                                                 yaffs_FreeTnode(dev, tn->internal[x]);
1518                                         tn->internal[x] = passedTn;
1519
1520                                 } else if (!tn->internal[x]) {
1521                                         /* Don't have one, none passed in */
1522                                         tn->internal[x] = yaffs_GetTnode(dev);
1523                                         if(!tn->internal[x])
1524                                                 return NULL;
1525                                 }
1526                         }
1527
1528                         tn = tn->internal[x];
1529                         l--;
1530                 }
1531         } else {
1532                 /* top is level 0 */
1533                 if (passedTn) {
1534                         memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1535                         yaffs_FreeTnode(dev, passedTn);
1536                 }
1537         }
1538
1539         return tn;
1540 }
1541
1542 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
1543                                 yaffs_ExtendedTags *tags, int objectId,
1544                                 int chunkInInode)
1545 {
1546         int j;
1547
1548         for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1549                 if (yaffs_CheckChunkBit(dev, theChunk / dev->nChunksPerBlock,
1550                                 theChunk % dev->nChunksPerBlock)) {
1551                         
1552                         if(dev->chunkGroupSize == 1)
1553                                 return theChunk;
1554                         else {
1555                                 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1556                                                                 tags);
1557                                 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1558                                         /* found it; */
1559                                         return theChunk;
1560                                 }
1561                         }
1562                 }
1563                 theChunk++;
1564         }
1565         return -1;
1566 }
1567
1568
1569 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1570  * chunks and tnodes in the file
1571  * Returns 1 if the tree was deleted.
1572  * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1573  */
1574
1575 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
1576                               int chunkOffset, int *limit)
1577 {
1578         int i;
1579         int chunkInInode;
1580         int theChunk;
1581         yaffs_ExtendedTags tags;
1582         int foundChunk;
1583         yaffs_Device *dev = in->myDev;
1584
1585         int allDone = 1;
1586
1587         if (tn) {
1588                 if (level > 0) {
1589                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1590                              i--) {
1591                                 if (tn->internal[i]) {
1592                                         if (limit && (*limit) < 0) {
1593                                                 allDone = 0;
1594                                         } else {
1595                                                 allDone =
1596                                                         yaffs_DeleteWorker(in,
1597                                                                 tn->
1598                                                                 internal
1599                                                                 [i],
1600                                                                 level -
1601                                                                 1,
1602                                                                 (chunkOffset
1603                                                                         <<
1604                                                                         YAFFS_TNODES_INTERNAL_BITS)
1605                                                                 + i,
1606                                                                 limit);
1607                                         }
1608                                         if (allDone) {
1609                                                 yaffs_FreeTnode(dev,
1610                                                                 tn->
1611                                                                 internal[i]);
1612                                                 tn->internal[i] = NULL;
1613                                         }
1614                                 }
1615                         }
1616                         return (allDone) ? 1 : 0;
1617                 } else if (level == 0) {
1618                         int hitLimit = 0;
1619
1620                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1621                                         i--) {
1622                                 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1623                                 if (theChunk) {
1624
1625                                         chunkInInode = (chunkOffset <<
1626                                                 YAFFS_TNODES_LEVEL0_BITS) + i;
1627
1628                                         foundChunk =
1629                                                 yaffs_FindChunkInGroup(dev,
1630                                                                 theChunk,
1631                                                                 &tags,
1632                                                                 in->objectId,
1633                                                                 chunkInInode);
1634
1635                                         if (foundChunk > 0) {
1636                                                 yaffs_DeleteChunk(dev,
1637                                                                   foundChunk, 1,
1638                                                                   __LINE__);
1639                                                 in->nDataChunks--;
1640                                                 if (limit) {
1641                                                         *limit = *limit - 1;
1642                                                         if (*limit <= 0)
1643                                                                 hitLimit = 1;
1644                                                 }
1645
1646                                         }
1647
1648                                         yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1649                                 }
1650
1651                         }
1652                         return (i < 0) ? 1 : 0;
1653
1654                 }
1655
1656         }
1657
1658         return 1;
1659
1660 }
1661
1662 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1663 {
1664         yaffs_BlockInfo *theBlock;
1665
1666         T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1667
1668         theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1669         if (theBlock) {
1670                 theBlock->softDeletions++;
1671                 dev->nFreeChunks++;
1672         }
1673 }
1674
1675 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1676  * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1677  * of the tnode.
1678  * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1679  */
1680
1681 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1682                                   __u32 level, int chunkOffset)
1683 {
1684         int i;
1685         int theChunk;
1686         int allDone = 1;
1687         yaffs_Device *dev = in->myDev;
1688
1689         if (tn) {
1690                 if (level > 0) {
1691
1692                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1693                              i--) {
1694                                 if (tn->internal[i]) {
1695                                         allDone =
1696                                             yaffs_SoftDeleteWorker(in,
1697                                                                    tn->
1698                                                                    internal[i],
1699                                                                    level - 1,
1700                                                                    (chunkOffset
1701                                                                     <<
1702                                                                     YAFFS_TNODES_INTERNAL_BITS)
1703                                                                    + i);
1704                                         if (allDone) {
1705                                                 yaffs_FreeTnode(dev,
1706                                                                 tn->
1707                                                                 internal[i]);
1708                                                 tn->internal[i] = NULL;
1709                                         } else {
1710                                                 /* Hoosterman... how could this happen? */
1711                                         }
1712                                 }
1713                         }
1714                         return (allDone) ? 1 : 0;
1715                 } else if (level == 0) {
1716
1717                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1718                                 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1719                                 if (theChunk) {
1720                                         /* Note this does not find the real chunk, only the chunk group.
1721                                          * We make an assumption that a chunk group is not larger than
1722                                          * a block.
1723                                          */
1724                                         yaffs_SoftDeleteChunk(dev, theChunk);
1725                                         yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1726                                 }
1727
1728                         }
1729                         return 1;
1730
1731                 }
1732
1733         }
1734
1735         return 1;
1736
1737 }
1738
1739 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1740 {
1741         if (obj->deleted &&
1742             obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1743                 if (obj->nDataChunks <= 0) {
1744                         /* Empty file with no duplicate object headers, just delete it immediately */
1745                         yaffs_FreeTnode(obj->myDev,
1746                                         obj->variant.fileVariant.top);
1747                         obj->variant.fileVariant.top = NULL;
1748                         T(YAFFS_TRACE_TRACING,
1749                           (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1750                            obj->objectId));
1751                         yaffs_DoGenericObjectDeletion(obj);
1752                 } else {
1753                         yaffs_SoftDeleteWorker(obj,
1754                                                obj->variant.fileVariant.top,
1755                                                obj->variant.fileVariant.
1756                                                topLevel, 0);
1757                         obj->softDeleted = 1;
1758                 }
1759         }
1760 }
1761
1762 /* Pruning removes any part of the file structure tree that is beyond the
1763  * bounds of the file (ie that does not point to chunks).
1764  *
1765  * A file should only get pruned when its size is reduced.
1766  *
1767  * Before pruning, the chunks must be pulled from the tree and the
1768  * level 0 tnode entries must be zeroed out.
1769  * Could also use this for file deletion, but that's probably better handled
1770  * by a special case.
1771  */
1772
1773 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1774                                 __u32 level, int del0)
1775 {
1776         int i;
1777         int hasData;
1778
1779         if (tn) {
1780                 hasData = 0;
1781
1782                 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1783                         if (tn->internal[i] && level > 0) {
1784                                 tn->internal[i] =
1785                                     yaffs_PruneWorker(dev, tn->internal[i],
1786                                                       level - 1,
1787                                                       (i == 0) ? del0 : 1);
1788                         }
1789
1790                         if (tn->internal[i])
1791                                 hasData++;
1792                 }
1793
1794                 if (hasData == 0 && del0) {
1795                         /* Free and return NULL */
1796
1797                         yaffs_FreeTnode(dev, tn);
1798                         tn = NULL;
1799                 }
1800
1801         }
1802
1803         return tn;
1804
1805 }
1806
1807 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1808                                 yaffs_FileStructure *fStruct)
1809 {
1810         int i;
1811         int hasData;
1812         int done = 0;
1813         yaffs_Tnode *tn;
1814
1815         if (fStruct->topLevel > 0) {
1816                 fStruct->top =
1817                     yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1818
1819                 /* Now we have a tree with all the non-zero branches NULL but the height
1820                  * is the same as it was.
1821                  * Let's see if we can trim internal tnodes to shorten the tree.
1822                  * We can do this if only the 0th element in the tnode is in use
1823                  * (ie all the non-zero are NULL)
1824                  */
1825
1826                 while (fStruct->topLevel && !done) {
1827                         tn = fStruct->top;
1828
1829                         hasData = 0;
1830                         for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1831                                 if (tn->internal[i])
1832                                         hasData++;
1833                         }
1834
1835                         if (!hasData) {
1836                                 fStruct->top = tn->internal[0];
1837                                 fStruct->topLevel--;
1838                                 yaffs_FreeTnode(dev, tn);
1839                         } else {
1840                                 done = 1;
1841                         }
1842                 }
1843         }
1844
1845         return YAFFS_OK;
1846 }
1847
1848 /*-------------------- End of File Structure functions.-------------------*/
1849
1850 /* yaffs_CreateFreeObjects creates a bunch more objects and
1851  * adds them to the object free list.
1852  */
1853 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1854 {
1855         int i;
1856         yaffs_Object *newObjects;
1857         yaffs_ObjectList *list;
1858
1859         if (nObjects < 1)
1860                 return YAFFS_OK;
1861
1862         /* make these things */
1863         newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1864         list = YMALLOC(sizeof(yaffs_ObjectList));
1865
1866         if (!newObjects || !list) {
1867                 if (newObjects){
1868                         YFREE(newObjects);
1869                         newObjects = NULL;
1870                 }
1871                 if (list){
1872                         YFREE(list);
1873                         list = NULL;
1874                 }
1875                 T(YAFFS_TRACE_ALLOCATE,
1876                   (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1877                 return YAFFS_FAIL;
1878         }
1879
1880         /* Hook them into the free list */
1881         for (i = 0; i < nObjects - 1; i++) {
1882                 newObjects[i].siblings.next =
1883                                 (struct ylist_head *)(&newObjects[i + 1]);
1884         }
1885
1886         newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1887         dev->freeObjects = newObjects;
1888         dev->nFreeObjects += nObjects;
1889         dev->nObjectsCreated += nObjects;
1890
1891         /* Now add this bunch of Objects to a list for freeing up. */
1892
1893         list->objects = newObjects;
1894         list->next = dev->allocatedObjectList;
1895         dev->allocatedObjectList = list;
1896
1897         return YAFFS_OK;
1898 }
1899
1900
1901 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1902 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1903 {
1904         yaffs_Object *tn = NULL;
1905
1906 #ifdef VALGRIND_TEST
1907         tn = YMALLOC(sizeof(yaffs_Object));
1908 #else
1909         /* If there are none left make more */
1910         if (!dev->freeObjects)
1911                 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1912
1913         if (dev->freeObjects) {
1914                 tn = dev->freeObjects;
1915                 dev->freeObjects =
1916                         (yaffs_Object *) (dev->freeObjects->siblings.next);
1917                 dev->nFreeObjects--;
1918         }
1919 #endif
1920         if (tn) {
1921                 /* Now sweeten it up... */
1922
1923                 memset(tn, 0, sizeof(yaffs_Object));
1924                 tn->beingCreated = 1;
1925
1926                 tn->myDev = dev;
1927                 tn->hdrChunk = 0;
1928                 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1929                 YINIT_LIST_HEAD(&(tn->hardLinks));
1930                 YINIT_LIST_HEAD(&(tn->hashLink));
1931                 YINIT_LIST_HEAD(&tn->siblings);
1932
1933
1934                 /* Now make the directory sane */
1935                 if (dev->rootDir) {
1936                         tn->parent = dev->rootDir;
1937                         ylist_add(&(tn->siblings), &dev->rootDir->variant.directoryVariant.children);
1938                 }
1939
1940                 /* Add it to the lost and found directory.
1941                  * NB Can't put root or lostNFound in lostNFound so
1942                  * check if lostNFound exists first
1943                  */
1944                 if (dev->lostNFoundDir)
1945                         yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1946
1947                 tn->beingCreated = 0;
1948         }
1949
1950         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1951
1952         return tn;
1953 }
1954
1955 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
1956                                                __u32 mode)
1957 {
1958
1959         yaffs_Object *obj =
1960             yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1961         if (obj) {
1962                 obj->fake = 1;          /* it is fake so it might have no NAND presence... */
1963                 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1964                 obj->unlinkAllowed = 0; /* ... or unlink it */
1965                 obj->deleted = 0;
1966                 obj->unlinked = 0;
1967                 obj->yst_mode = mode;
1968                 obj->myDev = dev;
1969                 obj->hdrChunk = 0;      /* Not a valid chunk. */
1970         }
1971
1972         return obj;
1973
1974 }
1975
1976 static void yaffs_UnhashObject(yaffs_Object *tn)
1977 {
1978         int bucket;
1979         yaffs_Device *dev = tn->myDev;
1980
1981         /* If it is still linked into the bucket list, free from the list */
1982         if (!ylist_empty(&tn->hashLink)) {
1983                 ylist_del_init(&tn->hashLink);
1984                 bucket = yaffs_HashFunction(tn->objectId);
1985                 dev->objectBucket[bucket].count--;
1986         }
1987 }
1988
1989 /*  FreeObject frees up a Object and puts it back on the free list */
1990 static void yaffs_FreeObject(yaffs_Object *tn)
1991 {
1992         yaffs_Device *dev = tn->myDev;
1993
1994 #ifdef __KERNEL__
1995         T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), tn, tn->myInode));
1996 #endif
1997
1998         if (tn->parent)
1999                 YBUG();
2000         if (!ylist_empty(&tn->siblings))
2001                 YBUG();
2002
2003
2004 #ifdef __KERNEL__
2005         if (tn->myInode) {
2006                 /* We're still hooked up to a cached inode.
2007                  * Don't delete now, but mark for later deletion
2008                  */
2009                 tn->deferedFree = 1;
2010                 return;
2011         }
2012 #endif
2013
2014         yaffs_UnhashObject(tn);
2015
2016 #ifdef VALGRIND_TEST
2017         YFREE(tn);
2018         tn = NULL;
2019 #else
2020         /* Link into the free list. */
2021         tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2022         dev->freeObjects = tn;
2023         dev->nFreeObjects++;
2024 #endif
2025         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2026 }
2027
2028 #ifdef __KERNEL__
2029
2030 void yaffs_HandleDeferedFree(yaffs_Object *obj)
2031 {
2032         if (obj->deferedFree)
2033                 yaffs_FreeObject(obj);
2034 }
2035
2036 #endif
2037
2038 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
2039 {
2040         /* Free the list of allocated Objects */
2041
2042         yaffs_ObjectList *tmp;
2043
2044         while (dev->allocatedObjectList) {
2045                 tmp = dev->allocatedObjectList->next;
2046                 YFREE(dev->allocatedObjectList->objects);
2047                 YFREE(dev->allocatedObjectList);
2048
2049                 dev->allocatedObjectList = tmp;
2050         }
2051
2052         dev->freeObjects = NULL;
2053         dev->nFreeObjects = 0;
2054 }
2055
2056 static void yaffs_InitialiseObjects(yaffs_Device *dev)
2057 {
2058         int i;
2059
2060         dev->allocatedObjectList = NULL;
2061         dev->freeObjects = NULL;
2062         dev->nFreeObjects = 0;
2063
2064         for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2065                 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2066                 dev->objectBucket[i].count = 0;
2067         }
2068 }
2069
2070 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
2071 {
2072         static int x;
2073         int i;
2074         int l = 999;
2075         int lowest = 999999;
2076
2077         /* First let's see if we can find one that's empty. */
2078
2079         for (i = 0; i < 10 && lowest > 0; i++) {
2080                 x++;
2081                 x %= YAFFS_NOBJECT_BUCKETS;
2082                 if (dev->objectBucket[x].count < lowest) {
2083                         lowest = dev->objectBucket[x].count;
2084                         l = x;
2085                 }
2086
2087         }
2088
2089         /* If we didn't find an empty list, then try
2090          * looking a bit further for a short one
2091          */
2092
2093         for (i = 0; i < 10 && lowest > 3; i++) {
2094                 x++;
2095                 x %= YAFFS_NOBJECT_BUCKETS;
2096                 if (dev->objectBucket[x].count < lowest) {
2097                         lowest = dev->objectBucket[x].count;
2098                         l = x;
2099                 }
2100
2101         }
2102
2103         return l;
2104 }
2105
2106 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
2107 {
2108         int bucket = yaffs_FindNiceObjectBucket(dev);
2109
2110         /* Now find an object value that has not already been taken
2111          * by scanning the list.
2112          */
2113
2114         int found = 0;
2115         struct ylist_head *i;
2116
2117         __u32 n = (__u32) bucket;
2118
2119         /* yaffs_CheckObjectHashSanity();  */
2120
2121         while (!found) {
2122                 found = 1;
2123                 n += YAFFS_NOBJECT_BUCKETS;
2124                 if (1 || dev->objectBucket[bucket].count > 0) {
2125                         ylist_for_each(i, &dev->objectBucket[bucket].list) {
2126                                 /* If there is already one in the list */
2127                                 if (i && ylist_entry(i, yaffs_Object,
2128                                                 hashLink)->objectId == n) {
2129                                         found = 0;
2130                                 }
2131                         }
2132                 }
2133         }
2134
2135         return n;
2136 }
2137
2138 static void yaffs_HashObject(yaffs_Object *in)
2139 {
2140         int bucket = yaffs_HashFunction(in->objectId);
2141         yaffs_Device *dev = in->myDev;
2142
2143         ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2144         dev->objectBucket[bucket].count++;
2145 }
2146
2147 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
2148 {
2149         int bucket = yaffs_HashFunction(number);
2150         struct ylist_head *i;
2151         yaffs_Object *in;
2152
2153         ylist_for_each(i, &dev->objectBucket[bucket].list) {
2154                 /* Look if it is in the list */
2155                 if (i) {
2156                         in = ylist_entry(i, yaffs_Object, hashLink);
2157                         if (in->objectId == number) {
2158 #ifdef __KERNEL__
2159                                 /* Don't tell the VFS about this one if it is defered free */
2160                                 if (in->deferedFree)
2161                                         return NULL;
2162 #endif
2163
2164                                 return in;
2165                         }
2166                 }
2167         }
2168
2169         return NULL;
2170 }
2171
2172 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
2173                                     yaffs_ObjectType type)
2174 {
2175         yaffs_Object *theObject;
2176         yaffs_Tnode *tn = NULL;
2177
2178         if (number < 0)
2179                 number = yaffs_CreateNewObjectNumber(dev);
2180
2181         if (type == YAFFS_OBJECT_TYPE_FILE) {
2182                 tn = yaffs_GetTnode(dev);
2183                 if (!tn)
2184                         return NULL;
2185         }
2186
2187         theObject = yaffs_AllocateEmptyObject(dev);
2188         if (!theObject){
2189                 if(tn)
2190                         yaffs_FreeTnode(dev,tn);
2191                 return NULL;
2192         }
2193
2194
2195         if (theObject) {
2196                 theObject->fake = 0;
2197                 theObject->renameAllowed = 1;
2198                 theObject->unlinkAllowed = 1;
2199                 theObject->objectId = number;
2200                 yaffs_HashObject(theObject);
2201                 theObject->variantType = type;
2202 #ifdef CONFIG_YAFFS_WINCE
2203                 yfsd_WinFileTimeNow(theObject->win_atime);
2204                 theObject->win_ctime[0] = theObject->win_mtime[0] =
2205                     theObject->win_atime[0];
2206                 theObject->win_ctime[1] = theObject->win_mtime[1] =
2207                     theObject->win_atime[1];
2208
2209 #else
2210
2211                 theObject->yst_atime = theObject->yst_mtime =
2212                     theObject->yst_ctime = Y_CURRENT_TIME;
2213 #endif
2214                 switch (type) {
2215                 case YAFFS_OBJECT_TYPE_FILE:
2216                         theObject->variant.fileVariant.fileSize = 0;
2217                         theObject->variant.fileVariant.scannedFileSize = 0;
2218                         theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2219                         theObject->variant.fileVariant.topLevel = 0;
2220                         theObject->variant.fileVariant.top = tn;
2221                         break;
2222                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2223                         YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2224                                         children);
2225                         break;
2226                 case YAFFS_OBJECT_TYPE_SYMLINK:
2227                 case YAFFS_OBJECT_TYPE_HARDLINK:
2228                 case YAFFS_OBJECT_TYPE_SPECIAL:
2229                         /* No action required */
2230                         break;
2231                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2232                         /* todo this should not happen */
2233                         break;
2234                 }
2235         }
2236
2237         return theObject;
2238 }
2239
2240 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
2241                                                       int number,
2242                                                       yaffs_ObjectType type)
2243 {
2244         yaffs_Object *theObject = NULL;
2245
2246         if (number > 0)
2247                 theObject = yaffs_FindObjectByNumber(dev, number);
2248
2249         if (!theObject)
2250                 theObject = yaffs_CreateNewObject(dev, number, type);
2251
2252         return theObject;
2253
2254 }
2255
2256
2257 static YCHAR *yaffs_CloneString(const YCHAR *str)
2258 {
2259         YCHAR *newStr = NULL;
2260
2261         if (!str)
2262                 str = _Y("");
2263
2264         newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2265         if (newStr)
2266                 yaffs_strcpy(newStr, str);
2267
2268         return newStr;
2269
2270 }
2271
2272 /*
2273  * Mknod (create) a new object.
2274  * equivalentObject only has meaning for a hard link;
2275  * aliasString only has meaning for a symlink.
2276  * rdev only has meaning for devices (a subset of special objects)
2277  */
2278
2279 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2280                                        yaffs_Object *parent,
2281                                        const YCHAR *name,
2282                                        __u32 mode,
2283                                        __u32 uid,
2284                                        __u32 gid,
2285                                        yaffs_Object *equivalentObject,
2286                                        const YCHAR *aliasString, __u32 rdev)
2287 {
2288         yaffs_Object *in;
2289         YCHAR *str = NULL;
2290
2291         yaffs_Device *dev = parent->myDev;
2292
2293         /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2294         if (yaffs_FindObjectByName(parent, name))
2295                 return NULL;
2296
2297         if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2298                 str = yaffs_CloneString(aliasString);
2299                 if (!str)
2300                         return NULL;
2301         }
2302
2303         in = yaffs_CreateNewObject(dev, -1, type);
2304
2305         if (!in){
2306                 if(str)
2307                         YFREE(str);
2308                 return NULL;
2309         }
2310
2311
2312
2313
2314         if (in) {
2315                 in->hdrChunk = 0;
2316                 in->valid = 1;
2317                 in->variantType = type;
2318
2319                 in->yst_mode = mode;
2320
2321 #ifdef CONFIG_YAFFS_WINCE
2322                 yfsd_WinFileTimeNow(in->win_atime);
2323                 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2324                 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2325
2326 #else
2327                 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2328
2329                 in->yst_rdev = rdev;
2330                 in->yst_uid = uid;
2331                 in->yst_gid = gid;
2332 #endif
2333                 in->nDataChunks = 0;
2334
2335                 yaffs_SetObjectName(in, name);
2336                 in->dirty = 1;
2337
2338                 yaffs_AddObjectToDirectory(parent, in);
2339
2340                 in->myDev = parent->myDev;
2341
2342                 switch (type) {
2343                 case YAFFS_OBJECT_TYPE_SYMLINK:
2344                         in->variant.symLinkVariant.alias = str;
2345                         break;
2346                 case YAFFS_OBJECT_TYPE_HARDLINK:
2347                         in->variant.hardLinkVariant.equivalentObject =
2348                                 equivalentObject;
2349                         in->variant.hardLinkVariant.equivalentObjectId =
2350                                 equivalentObject->objectId;
2351                         ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2352                         break;
2353                 case YAFFS_OBJECT_TYPE_FILE:
2354                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2355                 case YAFFS_OBJECT_TYPE_SPECIAL:
2356                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2357                         /* do nothing */
2358                         break;
2359                 }
2360
2361                 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2362                         /* Could not create the object header, fail the creation */
2363                         yaffs_DeleteObject(in);
2364                         in = NULL;
2365                 }
2366
2367                 yaffs_UpdateParent(parent);
2368         }
2369
2370         return in;
2371 }
2372
2373 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
2374                         __u32 mode, __u32 uid, __u32 gid)
2375 {
2376         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2377                                 uid, gid, NULL, NULL, 0);
2378 }
2379
2380 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
2381                                 __u32 mode, __u32 uid, __u32 gid)
2382 {
2383         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2384                                  mode, uid, gid, NULL, NULL, 0);
2385 }
2386
2387 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
2388                                 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2389 {
2390         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2391                                  uid, gid, NULL, NULL, rdev);
2392 }
2393
2394 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
2395                                 __u32 mode, __u32 uid, __u32 gid,
2396                                 const YCHAR *alias)
2397 {
2398         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2399                                 uid, gid, NULL, alias, 0);
2400 }
2401
2402 /* yaffs_Link returns the object id of the equivalent object.*/
2403 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
2404                         yaffs_Object *equivalentObject)
2405 {
2406         /* Get the real object in case we were fed a hard link as an equivalent object */
2407         equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2408
2409         if (yaffs_MknodObject
2410             (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2411              equivalentObject, NULL, 0)) {
2412                 return equivalentObject;
2413         } else {
2414                 return NULL;
2415         }
2416
2417 }
2418
2419 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
2420                                 const YCHAR *newName, int force, int shadows)
2421 {
2422         int unlinkOp;
2423         int deleteOp;
2424
2425         yaffs_Object *existingTarget;
2426
2427         if (newDir == NULL)
2428                 newDir = obj->parent;   /* use the old directory */
2429
2430         if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2431                 T(YAFFS_TRACE_ALWAYS,
2432                   (TSTR
2433                    ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2434                     TENDSTR)));
2435                 YBUG();
2436         }
2437
2438         /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2439         if (obj->myDev->isYaffs2)
2440                 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2441         else
2442                 unlinkOp = (newDir == obj->myDev->unlinkedDir
2443                             && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2444
2445         deleteOp = (newDir == obj->myDev->deletedDir);
2446
2447         existingTarget = yaffs_FindObjectByName(newDir, newName);
2448
2449         /* If the object is a file going into the unlinked directory,
2450          *   then it is OK to just stuff it in since duplicate names are allowed.
2451          *   else only proceed if the new name does not exist and if we're putting
2452          *   it into a directory.
2453          */
2454         if ((unlinkOp ||
2455              deleteOp ||
2456              force ||
2457              (shadows > 0) ||
2458              !existingTarget) &&
2459             newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2460                 yaffs_SetObjectName(obj, newName);
2461                 obj->dirty = 1;
2462
2463                 yaffs_AddObjectToDirectory(newDir, obj);
2464
2465                 if (unlinkOp)
2466                         obj->unlinked = 1;
2467
2468                 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2469                 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows) >= 0)
2470                         return YAFFS_OK;
2471         }
2472
2473         return YAFFS_FAIL;
2474 }
2475
2476 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
2477                 yaffs_Object *newDir, const YCHAR *newName)
2478 {
2479         yaffs_Object *obj = NULL;
2480         yaffs_Object *existingTarget = NULL;
2481         int force = 0;
2482         int result;
2483         yaffs_Device *dev;
2484
2485
2486         if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2487                 YBUG();
2488         if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2489                 YBUG();
2490
2491         dev = oldDir->myDev;
2492
2493 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2494         /* Special case for case insemsitive systems (eg. WinCE).
2495          * While look-up is case insensitive, the name isn't.
2496          * Therefore we might want to change x.txt to X.txt
2497         */
2498         if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
2499                 force = 1;
2500 #endif
2501
2502         if(yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2503                 /* ENAMETOOLONG */
2504                 return YAFFS_FAIL;
2505
2506         obj = yaffs_FindObjectByName(oldDir, oldName);
2507
2508         if (obj && obj->renameAllowed) {
2509
2510                 /* Now do the handling for an existing target, if there is one */
2511
2512                 existingTarget = yaffs_FindObjectByName(newDir, newName);
2513                 if (existingTarget &&
2514                         existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2515                         !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2516                         /* There is a target that is a non-empty directory, so we fail */
2517                         return YAFFS_FAIL;      /* EEXIST or ENOTEMPTY */
2518                 } else if (existingTarget && existingTarget != obj) {
2519                         /* Nuke the target first, using shadowing,
2520                          * but only if it isn't the same object.
2521                          *
2522                          * Note we must disable gc otherwise it can mess up the shadowing.
2523                          *
2524                          */
2525                         dev->isDoingGC=1;
2526                         yaffs_ChangeObjectName(obj, newDir, newName, force,
2527                                                 existingTarget->objectId);
2528                         existingTarget->isShadowed = 1;
2529                         yaffs_UnlinkObject(existingTarget);
2530                         dev->isDoingGC=0;
2531                 }
2532
2533                 result = yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2534
2535                 yaffs_UpdateParent(oldDir);
2536                 if(newDir != oldDir)
2537                         yaffs_UpdateParent(newDir);
2538                 
2539                 return result;
2540         }
2541         return YAFFS_FAIL;
2542 }
2543
2544 /*------------------------- Block Management and Page Allocation ----------------*/
2545
2546 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
2547 {
2548         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2549
2550         dev->blockInfo = NULL;
2551         dev->chunkBits = NULL;
2552
2553         dev->allocationBlock = -1;      /* force it to get a new one */
2554
2555         /* If the first allocation strategy fails, thry the alternate one */
2556         dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2557         if (!dev->blockInfo) {
2558                 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2559                 dev->blockInfoAlt = 1;
2560         } else
2561                 dev->blockInfoAlt = 0;
2562
2563         if (dev->blockInfo) {
2564                 /* Set up dynamic blockinfo stuff. */
2565                 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2566                 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2567                 if (!dev->chunkBits) {
2568                         dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2569                         dev->chunkBitsAlt = 1;
2570                 } else
2571                         dev->chunkBitsAlt = 0;
2572         }
2573
2574         if (dev->blockInfo && dev->chunkBits) {
2575                 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2576                 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2577                 return YAFFS_OK;
2578         }
2579
2580         return YAFFS_FAIL;
2581 }
2582
2583 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2584 {
2585         if (dev->blockInfoAlt && dev->blockInfo)
2586                 YFREE_ALT(dev->blockInfo);
2587         else if (dev->blockInfo)
2588                 YFREE(dev->blockInfo);
2589
2590         dev->blockInfoAlt = 0;
2591
2592         dev->blockInfo = NULL;
2593
2594         if (dev->chunkBitsAlt && dev->chunkBits)
2595                 YFREE_ALT(dev->chunkBits);
2596         else if (dev->chunkBits)
2597                 YFREE(dev->chunkBits);
2598         dev->chunkBitsAlt = 0;
2599         dev->chunkBits = NULL;
2600 }
2601
2602 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
2603                                         yaffs_BlockInfo *bi)
2604 {
2605         int i;
2606         __u32 seq;
2607         yaffs_BlockInfo *b;
2608
2609         if (!dev->isYaffs2)
2610                 return 1;       /* disqualification only applies to yaffs2. */
2611
2612         if (!bi->hasShrinkHeader)
2613                 return 1;       /* can gc */
2614
2615         /* Find the oldest dirty sequence number if we don't know it and save it
2616          * so we don't have to keep recomputing it.
2617          */
2618         if (!dev->oldestDirtySequence) {
2619                 seq = dev->sequenceNumber;
2620
2621                 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2622                                 i++) {
2623                         b = yaffs_GetBlockInfo(dev, i);
2624                         if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2625                             (b->pagesInUse - b->softDeletions) <
2626                             dev->nChunksPerBlock && b->sequenceNumber < seq) {
2627                                 seq = b->sequenceNumber;
2628                         }
2629                 }
2630                 dev->oldestDirtySequence = seq;
2631         }
2632
2633         /* Can't do gc of this block if there are any blocks older than this one that have
2634          * discarded pages.
2635          */
2636         return (bi->sequenceNumber <= dev->oldestDirtySequence);
2637 }
2638
2639 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2640  * for garbage collection.
2641  */
2642
2643 static int yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
2644                                         int aggressive)
2645 {
2646         int b = dev->currentDirtyChecker;
2647
2648         int i;
2649         int iterations;
2650         int dirtiest = -1;
2651         int pagesInUse = 0;
2652         int prioritised = 0;
2653         yaffs_BlockInfo *bi;
2654         int pendingPrioritisedExist = 0;
2655
2656         /* First let's see if we need to grab a prioritised block */
2657         if (dev->hasPendingPrioritisedGCs) {
2658                 for (i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++) {
2659
2660                         bi = yaffs_GetBlockInfo(dev, i);
2661                         /* yaffs_VerifyBlock(dev,bi,i); */
2662
2663                         if (bi->gcPrioritise) {
2664                                 pendingPrioritisedExist = 1;
2665                                 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2666                                    yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2667                                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
2668                                         dirtiest = i;
2669                                         prioritised = 1;
2670                                         aggressive = 1; /* Fool the non-aggressive skip logiv below */
2671                                 }
2672                         }
2673                 }
2674
2675                 if (!pendingPrioritisedExist) /* None found, so we can clear this */
2676                         dev->hasPendingPrioritisedGCs = 0;
2677         }
2678
2679         /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2680          * search harder.
2681          * else (we're doing a leasurely gc), then we only bother to do this if the
2682          * block has only a few pages in use.
2683          */
2684
2685         dev->nonAggressiveSkip--;
2686
2687         if (!aggressive && (dev->nonAggressiveSkip > 0))
2688                 return -1;
2689
2690         if (!prioritised)
2691                 pagesInUse =
2692                         (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2693
2694         if (aggressive)
2695                 iterations =
2696                     dev->internalEndBlock - dev->internalStartBlock + 1;
2697         else {
2698                 iterations =
2699                     dev->internalEndBlock - dev->internalStartBlock + 1;
2700                 iterations = iterations / 16;
2701                 if (iterations > 200)
2702                         iterations = 200;
2703         }
2704
2705         for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2706                 b++;
2707                 if (b < dev->internalStartBlock || b > dev->internalEndBlock)
2708                         b = dev->internalStartBlock;
2709
2710                 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2711                         T(YAFFS_TRACE_ERROR,
2712                           (TSTR("**>> Block %d is not valid" TENDSTR), b));
2713                         YBUG();
2714                 }
2715
2716                 bi = yaffs_GetBlockInfo(dev, b);
2717
2718                 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2719                         (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2720                                 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2721                         dirtiest = b;
2722                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
2723                 }
2724         }
2725
2726         dev->currentDirtyChecker = b;
2727
2728         if (dirtiest > 0) {
2729                 T(YAFFS_TRACE_GC,
2730                   (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2731                    dev->nChunksPerBlock - pagesInUse, prioritised));
2732         }
2733
2734         dev->oldestDirtySequence = 0;
2735
2736         if (dirtiest > 0)
2737                 dev->nonAggressiveSkip = 4;
2738
2739         return dirtiest;
2740 }
2741
2742 static void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
2743 {
2744         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2745
2746         int erasedOk = 0;
2747
2748         /* If the block is still healthy erase it and mark as clean.
2749          * If the block has had a data failure, then retire it.
2750          */
2751
2752         T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2753                 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2754                 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2755
2756         bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2757
2758         if (!bi->needsRetiring) {
2759                 yaffs_InvalidateCheckpoint(dev);
2760                 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2761                 if (!erasedOk) {
2762                         dev->nErasureFailures++;
2763                         T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2764                           (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2765                 }
2766         }
2767
2768         if (erasedOk &&
2769             ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2770                 int i;
2771                 for (i = 0; i < dev->nChunksPerBlock; i++) {
2772                         if (!yaffs_CheckChunkErased
2773                             (dev, blockNo * dev->nChunksPerBlock + i)) {
2774                                 T(YAFFS_TRACE_ERROR,
2775                                   (TSTR
2776                                    (">>Block %d erasure supposedly OK, but chunk %d not erased"
2777                                     TENDSTR), blockNo, i));
2778                         }
2779                 }
2780         }
2781
2782         if (erasedOk) {
2783                 /* Clean it up... */
2784                 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2785                 dev->nErasedBlocks++;
2786                 bi->pagesInUse = 0;
2787                 bi->softDeletions = 0;
2788                 bi->hasShrinkHeader = 0;
2789                 bi->skipErasedCheck = 1;  /* This is clean, so no need to check */
2790                 bi->gcPrioritise = 0;
2791                 yaffs_ClearChunkBits(dev, blockNo);
2792
2793                 T(YAFFS_TRACE_ERASE,
2794                   (TSTR("Erased block %d" TENDSTR), blockNo));
2795         } else {
2796                 dev->nFreeChunks -= dev->nChunksPerBlock;       /* We lost a block of free space */
2797
2798                 yaffs_RetireBlock(dev, blockNo);
2799                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2800                   (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2801         }
2802 }
2803
2804 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2805 {
2806         int i;
2807
2808         yaffs_BlockInfo *bi;
2809
2810         if (dev->nErasedBlocks < 1) {
2811                 /* Hoosterman we've got a problem.
2812                  * Can't get space to gc
2813                  */
2814                 T(YAFFS_TRACE_ERROR,
2815                   (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2816
2817                 return -1;
2818         }
2819
2820         /* Find an empty block. */
2821
2822         for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2823                 dev->allocationBlockFinder++;
2824                 if (dev->allocationBlockFinder < dev->internalStartBlock
2825                     || dev->allocationBlockFinder > dev->internalEndBlock) {
2826                         dev->allocationBlockFinder = dev->internalStartBlock;
2827                 }
2828
2829                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2830
2831                 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2832                         bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2833                         dev->sequenceNumber++;
2834                         bi->sequenceNumber = dev->sequenceNumber;
2835                         dev->nErasedBlocks--;
2836                         T(YAFFS_TRACE_ALLOCATE,
2837                           (TSTR("Allocated block %d, seq  %d, %d left" TENDSTR),
2838                            dev->allocationBlockFinder, dev->sequenceNumber,
2839                            dev->nErasedBlocks));
2840                         return dev->allocationBlockFinder;
2841                 }
2842         }
2843
2844         T(YAFFS_TRACE_ALWAYS,
2845           (TSTR
2846            ("yaffs tragedy: no more erased blocks, but there should have been %d"
2847             TENDSTR), dev->nErasedBlocks));
2848
2849         return -1;
2850 }
2851
2852
2853
2854 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2855 {
2856         if (!dev->nCheckpointBlocksRequired &&
2857            dev->isYaffs2) {
2858                 /* Not a valid value so recalculate */
2859                 int nBytes = 0;
2860                 int nBlocks;
2861                 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2862                 int tnodeSize;
2863
2864                 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2865
2866                 if (tnodeSize < sizeof(yaffs_Tnode))
2867                         tnodeSize = sizeof(yaffs_Tnode);
2868
2869                 nBytes += sizeof(yaffs_CheckpointValidity);
2870                 nBytes += sizeof(yaffs_CheckpointDevice);
2871                 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2872                 nBytes += devBlocks * dev->chunkBitmapStride;
2873                 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2874                 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2875                 nBytes += sizeof(yaffs_CheckpointValidity);
2876                 nBytes += sizeof(__u32); /* checksum*/
2877
2878                 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2879
2880                 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2881
2882                 dev->nCheckpointBlocksRequired = nBlocks;
2883         }
2884
2885         return dev->nCheckpointBlocksRequired;
2886 }
2887
2888 /*
2889  * Check if there's space to allocate...
2890  * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2891  */
2892 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev)
2893 {
2894         int reservedChunks;
2895         int reservedBlocks = dev->nReservedBlocks;
2896         int checkpointBlocks;
2897
2898         if (dev->isYaffs2) {
2899                 checkpointBlocks =  yaffs_CalcCheckpointBlocksRequired(dev) -
2900                                     dev->blocksInCheckpoint;
2901                 if (checkpointBlocks < 0)
2902                         checkpointBlocks = 0;
2903         } else {
2904                 checkpointBlocks = 0;
2905         }
2906
2907         reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2908
2909         return (dev->nFreeChunks > reservedChunks);
2910 }
2911
2912 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
2913                 yaffs_BlockInfo **blockUsedPtr)
2914 {
2915         int retVal;
2916         yaffs_BlockInfo *bi;
2917
2918         if (dev->allocationBlock < 0) {
2919                 /* Get next block to allocate off */
2920                 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2921                 dev->allocationPage = 0;
2922         }
2923
2924         if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2925                 /* Not enough space to allocate unless we're allowed to use the reserve. */
2926                 return -1;
2927         }
2928
2929         if (dev->nErasedBlocks < dev->nReservedBlocks
2930                         && dev->allocationPage == 0) {
2931                 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2932         }
2933
2934         /* Next page please.... */
2935         if (dev->allocationBlock >= 0) {
2936                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2937
2938                 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2939                         dev->allocationPage;
2940                 bi->pagesInUse++;
2941                 yaffs_SetChunkBit(dev, dev->allocationBlock,
2942                                 dev->allocationPage);
2943
2944                 dev->allocationPage++;
2945
2946                 dev->nFreeChunks--;
2947
2948                 /* If the block is full set the state to full */
2949                 if (dev->allocationPage >= dev->nChunksPerBlock) {
2950                         bi->blockState = YAFFS_BLOCK_STATE_FULL;
2951                         dev->allocationBlock = -1;
2952                 }
2953
2954                 if (blockUsedPtr)
2955                         *blockUsedPtr = bi;
2956
2957                 return retVal;
2958         }
2959
2960         T(YAFFS_TRACE_ERROR,
2961                         (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2962
2963         return -1;
2964 }
2965
2966 static int yaffs_GetErasedChunks(yaffs_Device *dev)
2967 {
2968         int n;
2969
2970         n = dev->nErasedBlocks * dev->nChunksPerBlock;
2971
2972         if (dev->allocationBlock > 0)
2973                 n += (dev->nChunksPerBlock - dev->allocationPage);
2974
2975         return n;
2976
2977 }
2978
2979 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
2980                 int wholeBlock)
2981 {
2982         int oldChunk;
2983         int newChunk;
2984         int markNAND;
2985         int retVal = YAFFS_OK;
2986         int cleanups = 0;
2987         int i;
2988         int isCheckpointBlock;
2989         int matchingChunk;
2990         int maxCopies;
2991
2992         int chunksBefore = yaffs_GetErasedChunks(dev);
2993         int chunksAfter;
2994
2995         yaffs_ExtendedTags tags;
2996
2997         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2998
2999         yaffs_Object *object;
3000
3001         isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3002
3003
3004         T(YAFFS_TRACE_TRACING,
3005                         (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3006                          block,
3007                          bi->pagesInUse,
3008                          bi->hasShrinkHeader,
3009                          wholeBlock));
3010
3011         /*yaffs_VerifyFreeChunks(dev); */
3012
3013         if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
3014                 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3015         
3016         bi->hasShrinkHeader = 0;        /* clear the flag so that the block can erase */
3017
3018         /* Take off the number of soft deleted entries because
3019          * they're going to get really deleted during GC.
3020          */
3021         if(dev->gcChunk == 0) /* first time through for this block */
3022                 dev->nFreeChunks -= bi->softDeletions;
3023
3024         dev->isDoingGC = 1;
3025
3026         if (isCheckpointBlock ||
3027                         !yaffs_StillSomeChunkBits(dev, block)) {
3028                 T(YAFFS_TRACE_TRACING,
3029                                 (TSTR
3030                                  ("Collecting block %d that has no chunks in use" TENDSTR),
3031                                  block));
3032                 yaffs_BlockBecameDirty(dev, block);
3033         } else {
3034
3035                 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3036
3037                 yaffs_VerifyBlock(dev, bi, block);
3038
3039                 maxCopies = (wholeBlock) ? dev->nChunksPerBlock : 10;
3040                 oldChunk = block * dev->nChunksPerBlock + dev->gcChunk;
3041
3042                 for (/* init already done */;
3043                      retVal == YAFFS_OK &&
3044                      dev->gcChunk < dev->nChunksPerBlock &&
3045                      (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
3046                      maxCopies > 0;
3047                      dev->gcChunk++, oldChunk++) {
3048                         if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3049
3050                                 /* This page is in use and might need to be copied off */
3051
3052                                 maxCopies--;
3053
3054                                 markNAND = 1;
3055
3056                                 yaffs_InitialiseTags(&tags);
3057
3058                                 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3059                                                                 buffer, &tags);
3060
3061                                 object =
3062                                     yaffs_FindObjectByNumber(dev,
3063                                                              tags.objectId);
3064
3065                                 T(YAFFS_TRACE_GC_DETAIL,
3066                                   (TSTR
3067                                    ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3068                                    dev->gcChunk, tags.objectId, tags.chunkId,
3069                                    tags.byteCount));
3070
3071                                 if (object && !yaffs_SkipVerification(dev)) {
3072                                         if (tags.chunkId == 0)
3073                                                 matchingChunk = object->hdrChunk;
3074                                         else if (object->softDeleted)
3075                                                 matchingChunk = oldChunk; /* Defeat the test */
3076                                         else
3077                                                 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
3078
3079                                         if (oldChunk != matchingChunk)
3080                                                 T(YAFFS_TRACE_ERROR,
3081                                                   (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3082                                                   oldChunk, matchingChunk, tags.objectId, tags.chunkId));
3083
3084                                 }
3085
3086                                 if (!object) {
3087                                         T(YAFFS_TRACE_ERROR,
3088                                           (TSTR
3089                                            ("page %d in gc has no object: %d %d %d "
3090                                             TENDSTR), oldChunk,
3091                                             tags.objectId, tags.chunkId, tags.byteCount));
3092                                 }
3093
3094                                 if (object &&
3095                                     object->deleted &&
3096                                     object->softDeleted &&
3097                                     tags.chunkId != 0) {
3098                                         /* Data chunk in a soft deleted file, throw it away
3099                                          * It's a soft deleted data chunk,
3100                                          * No need to copy this, just forget about it and
3101                                          * fix up the object.
3102                                          */
3103
3104                                         object->nDataChunks--;
3105
3106                                         if (object->nDataChunks <= 0) {
3107                                                 /* remeber to clean up the object */
3108                                                 dev->gcCleanupList[cleanups] =
3109                                                     tags.objectId;
3110                                                 cleanups++;
3111                                         }
3112                                         markNAND = 0;
3113                                 } else if (0) {
3114                                         /* Todo object && object->deleted && object->nDataChunks == 0 */
3115                                         /* Deleted object header with no data chunks.
3116                                          * Can be discarded and the file deleted.
3117                                          */
3118                                         object->hdrChunk = 0;
3119                                         yaffs_FreeTnode(object->myDev,
3120                                                         object->variant.
3121                                                         fileVariant.top);
3122                                         object->variant.fileVariant.top = NULL;
3123                                         yaffs_DoGenericObjectDeletion(object);
3124
3125                                 } else if (object) {
3126                                         /* It's either a data chunk in a live file or
3127                                          * an ObjectHeader, so we're interested in it.
3128                                          * NB Need to keep the ObjectHeaders of deleted files
3129                                          * until the whole file has been deleted off
3130                                          */
3131                                         tags.serialNumber++;
3132
3133                                         dev->nGCCopies++;
3134
3135                                         if (tags.chunkId == 0) {
3136                                                 /* It is an object Id,
3137                                                  * We need to nuke the shrinkheader flags first
3138                                                  * Also need to clean up shadowing.
3139                                                  * We no longer want the shrinkHeader flag since its work is done
3140                                                  * and if it is left in place it will mess up scanning.
3141                                                  */
3142
3143                                                 yaffs_ObjectHeader *oh;
3144                                                 oh = (yaffs_ObjectHeader *)buffer;
3145                                                 oh->isShrink = 0;
3146                                                 tags.extraIsShrinkHeader = 0;
3147                                                 oh->shadowsObject = 0;
3148                                                 oh->inbandShadowsObject = 0;
3149                                                 tags.extraShadows = 0;
3150
3151                                                 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
3152                                         }
3153
3154                                         newChunk =
3155                                             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3156
3157                                         if (newChunk < 0) {
3158                                                 retVal = YAFFS_FAIL;
3159                                         } else {
3160
3161                                                 /* Ok, now fix up the Tnodes etc. */
3162
3163                                                 if (tags.chunkId == 0) {
3164                                                         /* It's a header */
3165                                                         object->hdrChunk =  newChunk;
3166                                                         object->serial =   tags.serialNumber;
3167                                                 } else {
3168                                                         /* It's a data chunk */
3169                                                         yaffs_PutChunkIntoFile
3170                                                             (object,
3171                                                              tags.chunkId,
3172                                                              newChunk, 0);
3173                                                 }
3174                                         }
3175                                 }
3176
3177                                 if (retVal == YAFFS_OK)
3178                                         yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3179
3180                         }
3181                 }
3182
3183                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3184
3185
3186                 /* Do any required cleanups */
3187                 for (i = 0; i < cleanups; i++) {
3188                         /* Time to delete the file too */
3189                         object =
3190                             yaffs_FindObjectByNumber(dev,
3191                                                      dev->gcCleanupList[i]);
3192                         if (object) {
3193                                 yaffs_FreeTnode(dev,
3194                                                 object->variant.fileVariant.
3195                                                 top);
3196                                 object->variant.fileVariant.top = NULL;
3197                                 T(YAFFS_TRACE_GC,
3198                                   (TSTR
3199                                    ("yaffs: About to finally delete object %d"
3200                                     TENDSTR), object->objectId));
3201                                 yaffs_DoGenericObjectDeletion(object);
3202                                 object->myDev->nDeletedFiles--;
3203                         }
3204
3205                 }
3206
3207         }
3208
3209         yaffs_VerifyCollectedBlock(dev, bi, block);
3210
3211         chunksAfter = yaffs_GetErasedChunks(dev);
3212         if (chunksBefore >= chunksAfter) {
3213                 T(YAFFS_TRACE_GC,
3214                   (TSTR
3215                    ("gc did not increase free chunks before %d after %d"
3216                     TENDSTR), chunksBefore, chunksAfter));
3217         }
3218
3219         /* If the gc completed then clear the current gcBlock so that we find another. */
3220         if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING) {
3221                 dev->gcBlock = -1;
3222                 dev->gcChunk = 0;
3223         }
3224
3225         dev->isDoingGC = 0;
3226
3227         return retVal;
3228 }
3229
3230 /* New garbage collector
3231  * If we're very low on erased blocks then we do aggressive garbage collection
3232  * otherwise we do "leasurely" garbage collection.
3233  * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3234  * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3235  *
3236  * The idea is to help clear out space in a more spread-out manner.
3237  * Dunno if it really does anything useful.
3238  */
3239 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
3240 {
3241         int block;
3242         int aggressive;
3243         int gcOk = YAFFS_OK;
3244         int maxTries = 0;
3245
3246         int checkpointBlockAdjust;
3247
3248         if (dev->isDoingGC) {
3249                 /* Bail out so we don't get recursive gc */
3250                 return YAFFS_OK;
3251         }
3252
3253         /* This loop should pass the first time.
3254          * We'll only see looping here if the erase of the collected block fails.
3255          */
3256
3257         do {
3258                 maxTries++;
3259
3260                 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3261                 if (checkpointBlockAdjust < 0)
3262                         checkpointBlockAdjust = 0;
3263
3264                 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3265                         /* We need a block soon...*/
3266                         aggressive = 1;
3267                 } else {
3268                         /* We're in no hurry */
3269                         aggressive = 0;
3270                 }
3271
3272                 if (dev->gcBlock <= 0) {
3273                         dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3274                         dev->gcChunk = 0;
3275                 }
3276
3277                 block = dev->gcBlock;
3278
3279                 if (block > 0) {
3280                         dev->garbageCollections++;
3281                         if (!aggressive)
3282                                 dev->passiveGarbageCollections++;
3283
3284                         T(YAFFS_TRACE_GC,
3285                           (TSTR
3286                            ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3287                            dev->nErasedBlocks, aggressive));
3288
3289                         gcOk = yaffs_GarbageCollectBlock(dev, block, aggressive);
3290                 }
3291
3292                 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3293                         T(YAFFS_TRACE_GC,
3294                           (TSTR
3295                            ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3296                             TENDSTR), dev->nErasedBlocks, maxTries, block));
3297                 }
3298         } while ((dev->nErasedBlocks < dev->nReservedBlocks) &&
3299                  (block > 0) &&
3300                  (maxTries < 2));
3301
3302         return aggressive ? gcOk : YAFFS_OK;
3303 }
3304
3305 /*-------------------------  TAGS --------------------------------*/
3306
3307 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
3308                            int chunkInObject)
3309 {
3310         return (tags->chunkId == chunkInObject &&
3311                 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3312
3313 }
3314
3315
3316 /*-------------------- Data file manipulation -----------------*/
3317
3318 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
3319                                  yaffs_ExtendedTags *tags)
3320 {
3321         /*Get the Tnode, then get the level 0 offset chunk offset */
3322         yaffs_Tnode *tn;
3323         int theChunk = -1;
3324         yaffs_ExtendedTags localTags;
3325         int retVal = -1;
3326
3327         yaffs_Device *dev = in->myDev;
3328
3329         if (!tags) {
3330                 /* Passed a NULL, so use our own tags space */
3331                 tags = &localTags;
3332         }
3333
3334         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3335
3336         if (tn) {
3337                 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3338
3339                 retVal =
3340                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3341                                            chunkInInode);
3342         }
3343         return retVal;
3344 }
3345
3346 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
3347                                           yaffs_ExtendedTags *tags)
3348 {
3349         /* Get the Tnode, then get the level 0 offset chunk offset */
3350         yaffs_Tnode *tn;
3351         int theChunk = -1;
3352         yaffs_ExtendedTags localTags;
3353
3354         yaffs_Device *dev = in->myDev;
3355         int retVal = -1;
3356
3357         if (!tags) {
3358                 /* Passed a NULL, so use our own tags space */
3359                 tags = &localTags;
3360         }
3361
3362         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3363
3364         if (tn) {
3365
3366                 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3367
3368                 retVal =
3369                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3370                                            chunkInInode);
3371
3372                 /* Delete the entry in the filestructure (if found) */
3373                 if (retVal != -1)
3374                         yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, 0);
3375         }
3376
3377         return retVal;
3378 }
3379
3380 #ifdef YAFFS_PARANOID
3381
3382 static int yaffs_CheckFileSanity(yaffs_Object *in)
3383 {
3384         int chunk;
3385         int nChunks;
3386         int fSize;
3387         int failed = 0;
3388         int objId;
3389         yaffs_Tnode *tn;
3390         yaffs_Tags localTags;
3391         yaffs_Tags *tags = &localTags;
3392         int theChunk;
3393         int chunkDeleted;
3394
3395         if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3396                 return YAFFS_FAIL;
3397
3398         objId = in->objectId;
3399         fSize = in->variant.fileVariant.fileSize;
3400         nChunks =
3401             (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3402
3403         for (chunk = 1; chunk <= nChunks; chunk++) {
3404                 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3405                                            chunk);
3406
3407                 if (tn) {
3408
3409                         theChunk = yaffs_GetChunkGroupBase(dev, tn, chunk);
3410
3411                         if (yaffs_CheckChunkBits
3412                             (dev, theChunk / dev->nChunksPerBlock,
3413                              theChunk % dev->nChunksPerBlock)) {
3414
3415                                 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3416                                                             tags,
3417                                                             &chunkDeleted);
3418                                 if (yaffs_TagsMatch
3419                                     (tags, in->objectId, chunk, chunkDeleted)) {
3420                                         /* found it; */
3421
3422                                 }
3423                         } else {
3424
3425                                 failed = 1;
3426                         }
3427
3428                 } else {
3429                         /* T(("No level 0 found for %d\n", chunk)); */
3430                 }
3431         }
3432
3433         return failed ? YAFFS_FAIL : YAFFS_OK;
3434 }
3435
3436 #endif
3437
3438 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
3439                                   int chunkInNAND, int inScan)
3440 {
3441         /* NB inScan is zero unless scanning.
3442          * For forward scanning, inScan is > 0;
3443          * for backward scanning inScan is < 0
3444          *
3445          * chunkInNAND = 0 is a dummy insert to make sure the tnodes are there.
3446          */
3447
3448         yaffs_Tnode *tn;
3449         yaffs_Device *dev = in->myDev;
3450         int existingChunk;
3451         yaffs_ExtendedTags existingTags;
3452         yaffs_ExtendedTags newTags;
3453         unsigned existingSerial, newSerial;
3454
3455         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3456                 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3457                  * If it is not during Scanning then something went wrong!
3458                  */
3459                 if (!inScan) {
3460                         T(YAFFS_TRACE_ERROR,
3461                           (TSTR
3462                            ("yaffs tragedy:attempt to put data chunk into a non-file"
3463                             TENDSTR)));
3464                         YBUG();
3465                 }
3466
3467                 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3468                 return YAFFS_OK;
3469         }
3470
3471         tn = yaffs_AddOrFindLevel0Tnode(dev,
3472                                         &in->variant.fileVariant,
3473                                         chunkInInode,
3474                                         NULL);
3475         if (!tn)
3476                 return YAFFS_FAIL;
3477         
3478         if(!chunkInNAND)
3479                 /* Dummy insert, bail now */
3480                 return YAFFS_OK;
3481                 
3482
3483         existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3484
3485         if (inScan != 0) {
3486                 /* If we're scanning then we need to test for duplicates
3487                  * NB This does not need to be efficient since it should only ever
3488                  * happen when the power fails during a write, then only one
3489                  * chunk should ever be affected.
3490                  *
3491                  * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3492                  * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3493                  */
3494
3495                 if (existingChunk > 0) {
3496                         /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3497                          *    thus we have to do a FindChunkInFile to get the real chunk id.
3498                          *
3499                          * We have a duplicate now we need to decide which one to use:
3500                          *
3501                          * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3502                          * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3503                          * YAFFS1: Get both sets of tags and compare serial numbers.
3504                          */
3505
3506                         if (inScan > 0) {
3507                                 /* Only do this for forward scanning */
3508                                 yaffs_ReadChunkWithTagsFromNAND(dev,
3509                                                                 chunkInNAND,
3510                                                                 NULL, &newTags);
3511
3512                                 /* Do a proper find */
3513                                 existingChunk =
3514                                     yaffs_FindChunkInFile(in, chunkInInode,
3515                                                           &existingTags);
3516                         }
3517
3518                         if (existingChunk <= 0) {
3519                                 /*Hoosterman - how did this happen? */
3520
3521                                 T(YAFFS_TRACE_ERROR,
3522                                   (TSTR
3523                                    ("yaffs tragedy: existing chunk < 0 in scan"
3524                                     TENDSTR)));
3525
3526                         }
3527
3528                         /* NB The deleted flags should be false, otherwise the chunks will
3529                          * not be loaded during a scan
3530                          */
3531
3532                         if (inScan > 0) {
3533                                 newSerial = newTags.serialNumber;
3534                                 existingSerial = existingTags.serialNumber;
3535                         }
3536
3537                         if ((inScan > 0) &&
3538                             (in->myDev->isYaffs2 ||
3539                              existingChunk <= 0 ||
3540                              ((existingSerial + 1) & 3) == newSerial)) {
3541                                 /* Forward scanning.
3542                                  * Use new
3543                                  * Delete the old one and drop through to update the tnode
3544                                  */
3545                                 yaffs_DeleteChunk(dev, existingChunk, 1,
3546                                                   __LINE__);
3547                         } else {
3548                                 /* Backward scanning or we want to use the existing one
3549                                  * Use existing.
3550                                  * Delete the new one and return early so that the tnode isn't changed
3551                                  */
3552                                 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3553                                                   __LINE__);
3554                                 return YAFFS_OK;
3555                         }
3556                 }
3557
3558         }
3559
3560         if (existingChunk == 0)
3561                 in->nDataChunks++;
3562
3563         yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
3564
3565         return YAFFS_OK;
3566 }
3567
3568 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
3569                                         __u8 *buffer)
3570 {
3571         int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3572
3573         if (chunkInNAND >= 0)
3574                 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3575                                                 buffer, NULL);
3576         else {
3577                 T(YAFFS_TRACE_NANDACCESS,
3578                   (TSTR("Chunk %d not found zero instead" TENDSTR),
3579                    chunkInNAND));
3580                 /* get sane (zero) data if you read a hole */
3581                 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3582                 return 0;
3583         }
3584
3585 }
3586
3587 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
3588 {
3589         int block;
3590         int page;
3591         yaffs_ExtendedTags tags;
3592         yaffs_BlockInfo *bi;
3593
3594         if (chunkId <= 0)
3595                 return;
3596
3597         dev->nDeletions++;
3598         block = chunkId / dev->nChunksPerBlock;
3599         page = chunkId % dev->nChunksPerBlock;
3600
3601
3602         if (!yaffs_CheckChunkBit(dev, block, page))
3603                 T(YAFFS_TRACE_VERIFY,
3604                         (TSTR("Deleting invalid chunk %d"TENDSTR),
3605                          chunkId));
3606
3607         bi = yaffs_GetBlockInfo(dev, block);
3608
3609         T(YAFFS_TRACE_DELETION,
3610           (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3611
3612         if (markNAND &&
3613             bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3614
3615                 yaffs_InitialiseTags(&tags);
3616
3617                 tags.chunkDeleted = 1;
3618
3619                 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3620                 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3621         } else {
3622                 dev->nUnmarkedDeletions++;
3623         }
3624
3625         /* Pull out of the management area.
3626          * If the whole block became dirty, this will kick off an erasure.
3627          */
3628         if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3629             bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3630             bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3631             bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3632                 dev->nFreeChunks++;
3633
3634                 yaffs_ClearChunkBit(dev, block, page);
3635
3636                 bi->pagesInUse--;
3637
3638                 if (bi->pagesInUse == 0 &&
3639                     !bi->hasShrinkHeader &&
3640                     bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3641                     bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3642                         yaffs_BlockBecameDirty(dev, block);
3643                 }
3644
3645         }
3646
3647 }
3648
3649 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
3650                                         const __u8 *buffer, int nBytes,
3651                                         int useReserve)
3652 {
3653         /* Find old chunk Need to do this to get serial number
3654          * Write new one and patch into tree.
3655          * Invalidate old tags.
3656          */
3657
3658         int prevChunkId;
3659         yaffs_ExtendedTags prevTags;
3660
3661         int newChunkId;
3662         yaffs_ExtendedTags newTags;
3663
3664         yaffs_Device *dev = in->myDev;
3665
3666         yaffs_CheckGarbageCollection(dev);
3667
3668         /* Get the previous chunk at this location in the file if it exists */
3669         prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3670
3671         /* Set up new tags */
3672         yaffs_InitialiseTags(&newTags);
3673
3674         newTags.chunkId = chunkInInode;
3675         newTags.objectId = in->objectId;
3676         newTags.serialNumber =
3677             (prevChunkId > 0) ? prevTags.serialNumber + 1 : 1;
3678         newTags.byteCount = nBytes;
3679
3680         if (nBytes < 1 || nBytes > dev->totalBytesPerChunk) {
3681                 T(YAFFS_TRACE_ERROR,
3682                 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3683                 YBUG();
3684         }
3685         
3686         /*
3687          * If there isn't already a chunk there then do a dummy
3688          * insert to make sue we have the desired tnode structure.
3689          */
3690         if(prevChunkId < 1 &&
3691                 yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0) != YAFFS_OK)
3692                 return -1;
3693                 
3694         newChunkId =
3695             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3696                                               useReserve);
3697
3698         if (newChunkId > 0) {
3699                 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3700
3701                 if (prevChunkId > 0)
3702                         yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3703
3704                 yaffs_CheckFileSanity(in);
3705         }
3706         return newChunkId;
3707
3708 }
3709
3710 /* UpdateObjectHeader updates the header on NAND for an object.
3711  * If name is not NULL, then that new name is used.
3712  */
3713 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
3714                              int isShrink, int shadows)
3715 {
3716
3717         yaffs_BlockInfo *bi;
3718
3719         yaffs_Device *dev = in->myDev;
3720
3721         int prevChunkId;
3722         int retVal = 0;
3723         int result = 0;
3724
3725         int newChunkId;
3726         yaffs_ExtendedTags newTags;
3727         yaffs_ExtendedTags oldTags;
3728         YCHAR *alias = NULL;
3729
3730         __u8 *buffer = NULL;
3731         YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3732
3733         yaffs_ObjectHeader *oh = NULL;
3734
3735         yaffs_strcpy(oldName, _Y("silly old name"));
3736
3737
3738         if (!in->fake ||
3739                 in == dev->rootDir || /* The rootDir should also be saved */
3740                 force) {
3741
3742                 yaffs_CheckGarbageCollection(dev);
3743                 yaffs_CheckObjectDetailsLoaded(in);
3744
3745                 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3746                 oh = (yaffs_ObjectHeader *) buffer;
3747
3748                 prevChunkId = in->hdrChunk;
3749
3750                 if (prevChunkId > 0) {
3751                         result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3752                                                         buffer, &oldTags);
3753
3754                         yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
3755
3756                         memcpy(oldName, oh->name, sizeof(oh->name));
3757                 }
3758
3759                 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3760
3761                 oh->type = in->variantType;
3762                 oh->yst_mode = in->yst_mode;
3763                 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3764
3765 #ifdef CONFIG_YAFFS_WINCE
3766                 oh->win_atime[0] = in->win_atime[0];
3767                 oh->win_ctime[0] = in->win_ctime[0];
3768                 oh->win_mtime[0] = in->win_mtime[0];
3769                 oh->win_atime[1] = in->win_atime[1];
3770                 oh->win_ctime[1] = in->win_ctime[1];
3771                 oh->win_mtime[1] = in->win_mtime[1];
3772 #else
3773                 oh->yst_uid = in->yst_uid;
3774                 oh->yst_gid = in->yst_gid;
3775                 oh->yst_atime = in->yst_atime;
3776                 oh->yst_mtime = in->yst_mtime;
3777                 oh->yst_ctime = in->yst_ctime;
3778                 oh->yst_rdev = in->yst_rdev;
3779 #endif
3780                 if (in->parent)
3781                         oh->parentObjectId = in->parent->objectId;
3782                 else
3783                         oh->parentObjectId = 0;
3784
3785                 if (name && *name) {
3786                         memset(oh->name, 0, sizeof(oh->name));
3787                         yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3788                 } else if (prevChunkId > 0)
3789                         memcpy(oh->name, oldName, sizeof(oh->name));
3790                 else
3791                         memset(oh->name, 0, sizeof(oh->name));
3792
3793                 oh->isShrink = isShrink;
3794
3795                 switch (in->variantType) {
3796                 case YAFFS_OBJECT_TYPE_UNKNOWN:
3797                         /* Should not happen */
3798                         break;
3799                 case YAFFS_OBJECT_TYPE_FILE:
3800                         oh->fileSize =
3801                             (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3802                              || oh->parentObjectId ==
3803                              YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3804                             fileVariant.fileSize;
3805                         break;
3806                 case YAFFS_OBJECT_TYPE_HARDLINK:
3807                         oh->equivalentObjectId =
3808                             in->variant.hardLinkVariant.equivalentObjectId;
3809                         break;
3810                 case YAFFS_OBJECT_TYPE_SPECIAL:
3811                         /* Do nothing */
3812                         break;
3813                 case YAFFS_OBJECT_TYPE_DIRECTORY:
3814                         /* Do nothing */
3815                         break;
3816                 case YAFFS_OBJECT_TYPE_SYMLINK:
3817                         alias = in->variant.symLinkVariant.alias;
3818                         if(!alias)
3819                                 alias = _Y("no alias");
3820                         yaffs_strncpy(oh->alias,
3821                                         alias,
3822                                       YAFFS_MAX_ALIAS_LENGTH);
3823                         oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3824                         break;
3825                 }
3826
3827                 /* Tags */
3828                 yaffs_InitialiseTags(&newTags);
3829                 in->serial++;
3830                 newTags.chunkId = 0;
3831                 newTags.objectId = in->objectId;
3832                 newTags.serialNumber = in->serial;
3833
3834                 /* Add extra info for file header */
3835
3836                 newTags.extraHeaderInfoAvailable = 1;
3837                 newTags.extraParentObjectId = oh->parentObjectId;
3838                 newTags.extraFileLength = oh->fileSize;
3839                 newTags.extraIsShrinkHeader = oh->isShrink;
3840                 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3841                 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3842                 newTags.extraObjectType = in->variantType;
3843
3844                 yaffs_VerifyObjectHeader(in, oh, &newTags, 1);
3845
3846                 /* Create new chunk in NAND */
3847                 newChunkId =
3848                     yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3849                                                       (prevChunkId > 0) ? 1 : 0);
3850
3851                 if (newChunkId >= 0) {
3852
3853                         in->hdrChunk = newChunkId;
3854
3855                         if (prevChunkId > 0) {
3856                                 yaffs_DeleteChunk(dev, prevChunkId, 1,
3857                                                   __LINE__);
3858                         }
3859
3860                         if (!yaffs_ObjectHasCachedWriteData(in))
3861                                 in->dirty = 0;
3862
3863                         /* If this was a shrink, then mark the block that the chunk lives on */
3864                         if (isShrink) {
3865                                 bi = yaffs_GetBlockInfo(in->myDev,
3866                                         newChunkId / in->myDev->nChunksPerBlock);
3867                                 bi->hasShrinkHeader = 1;
3868                         }
3869
3870                 }
3871
3872                 retVal = newChunkId;
3873
3874         }
3875
3876         if (buffer)
3877                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3878
3879         return retVal;
3880 }
3881
3882 /*------------------------ Short Operations Cache ----------------------------------------
3883  *   In many situations where there is no high level buffering (eg WinCE) a lot of
3884  *   reads might be short sequential reads, and a lot of writes may be short
3885  *   sequential writes. eg. scanning/writing a jpeg file.
3886  *   In these cases, a short read/write cache can provide a huge perfomance benefit
3887  *   with dumb-as-a-rock code.
3888  *   In Linux, the page cache provides read buffering aand the short op cache provides write
3889  *   buffering.
3890  *
3891  *   There are a limited number (~10) of cache chunks per device so that we don't
3892  *   need a very intelligent search.
3893  */
3894
3895 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3896 {
3897         yaffs_Device *dev = obj->myDev;
3898         int i;
3899         yaffs_ChunkCache *cache;
3900         int nCaches = obj->myDev->nShortOpCaches;
3901
3902         for (i = 0; i < nCaches; i++) {
3903                 cache = &dev->srCache[i];
3904                 if (cache->object == obj &&
3905                     cache->dirty)
3906                         return 1;
3907         }
3908
3909         return 0;
3910 }
3911
3912
3913 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
3914 {
3915         yaffs_Device *dev = obj->myDev;
3916         int lowest = -99;       /* Stop compiler whining. */
3917         int i;
3918         yaffs_ChunkCache *cache;
3919         int chunkWritten = 0;
3920         int nCaches = obj->myDev->nShortOpCaches;
3921
3922         if (nCaches > 0) {
3923                 do {
3924                         cache = NULL;
3925
3926                         /* Find the dirty cache for this object with the lowest chunk id. */
3927                         for (i = 0; i < nCaches; i++) {
3928                                 if (dev->srCache[i].object == obj &&
3929                                     dev->srCache[i].dirty) {
3930                                         if (!cache
3931                                             || dev->srCache[i].chunkId <
3932                                             lowest) {
3933                                                 cache = &dev->srCache[i];
3934                                                 lowest = cache->chunkId;
3935                                         }
3936                                 }
3937                         }
3938
3939                         if (cache && !cache->locked) {
3940                                 /* Write it out and free it up */
3941
3942                                 chunkWritten =
3943                                     yaffs_WriteChunkDataToObject(cache->object,
3944                                                                  cache->chunkId,
3945                                                                  cache->data,
3946                                                                  cache->nBytes,
3947                                                                  1);
3948                                 cache->dirty = 0;
3949                                 cache->object = NULL;
3950                         }
3951
3952                 } while (cache && chunkWritten > 0);
3953
3954                 if (cache) {
3955                         /* Hoosterman, disk full while writing cache out. */
3956                         T(YAFFS_TRACE_ERROR,
3957                           (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3958
3959                 }
3960         }
3961
3962 }
3963
3964 /*yaffs_FlushEntireDeviceCache(dev)
3965  *
3966  *
3967  */
3968
3969 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3970 {
3971         yaffs_Object *obj;
3972         int nCaches = dev->nShortOpCaches;
3973         int i;
3974
3975         /* Find a dirty object in the cache and flush it...
3976          * until there are no further dirty objects.
3977          */
3978         do {
3979                 obj = NULL;
3980                 for (i = 0; i < nCaches && !obj; i++) {
3981                         if (dev->srCache[i].object &&
3982                             dev->srCache[i].dirty)
3983                                 obj = dev->srCache[i].object;
3984
3985                 }
3986                 if (obj)
3987                         yaffs_FlushFilesChunkCache(obj);
3988
3989         } while (obj);
3990
3991 }
3992
3993
3994 /* Grab us a cache chunk for use.
3995  * First look for an empty one.
3996  * Then look for the least recently used non-dirty one.
3997  * Then look for the least recently used dirty one...., flush and look again.
3998  */
3999 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
4000 {
4001         int i;
4002
4003         if (dev->nShortOpCaches > 0) {
4004                 for (i = 0; i < dev->nShortOpCaches; i++) {
4005                         if (!dev->srCache[i].object)
4006                                 return &dev->srCache[i];
4007                 }
4008         }
4009
4010         return NULL;
4011 }
4012
4013 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
4014 {
4015         yaffs_ChunkCache *cache;
4016         yaffs_Object *theObj;
4017         int usage;
4018         int i;
4019         int pushout;
4020
4021         if (dev->nShortOpCaches > 0) {
4022                 /* Try find a non-dirty one... */
4023
4024                 cache = yaffs_GrabChunkCacheWorker(dev);
4025
4026                 if (!cache) {
4027                         /* They were all dirty, find the last recently used object and flush
4028                          * its cache, then  find again.
4029                          * NB what's here is not very accurate, we actually flush the object
4030                          * the last recently used page.
4031                          */
4032
4033                         /* With locking we can't assume we can use entry zero */
4034
4035                         theObj = NULL;
4036                         usage = -1;
4037                         cache = NULL;
4038                         pushout = -1;
4039
4040                         for (i = 0; i < dev->nShortOpCaches; i++) {
4041                                 if (dev->srCache[i].object &&
4042                                     !dev->srCache[i].locked &&
4043                                     (dev->srCache[i].lastUse < usage || !cache)) {
4044                                         usage = dev->srCache[i].lastUse;
4045                                         theObj = dev->srCache[i].object;
4046                                         cache = &dev->srCache[i];
4047                                         pushout = i;
4048                                 }
4049                         }
4050
4051                         if (!cache || cache->dirty) {
4052                                 /* Flush and try again */
4053                                 yaffs_FlushFilesChunkCache(theObj);
4054                                 cache = yaffs_GrabChunkCacheWorker(dev);
4055                         }
4056
4057                 }
4058                 return cache;
4059         } else
4060                 return NULL;
4061
4062 }
4063
4064 /* Find a cached chunk */
4065 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj,
4066                                               int chunkId)
4067 {
4068         yaffs_Device *dev = obj->myDev;
4069         int i;
4070         if (dev->nShortOpCaches > 0) {
4071                 for (i = 0; i < dev->nShortOpCaches; i++) {
4072                         if (dev->srCache[i].object == obj &&
4073                             dev->srCache[i].chunkId == chunkId) {
4074                                 dev->cacheHits++;
4075
4076                                 return &dev->srCache[i];
4077                         }
4078                 }
4079         }
4080         return NULL;
4081 }
4082
4083 /* Mark the chunk for the least recently used algorithym */
4084 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache,
4085                                 int isAWrite)
4086 {
4087
4088         if (dev->nShortOpCaches > 0) {
4089                 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4090                         /* Reset the cache usages */
4091                         int i;
4092                         for (i = 1; i < dev->nShortOpCaches; i++)
4093                                 dev->srCache[i].lastUse = 0;
4094
4095                         dev->srLastUse = 0;
4096                 }
4097
4098                 dev->srLastUse++;
4099
4100                 cache->lastUse = dev->srLastUse;
4101
4102                 if (isAWrite)
4103                         cache->dirty = 1;
4104         }
4105 }
4106
4107 /* Invalidate a single cache page.
4108  * Do this when a whole page gets written,
4109  * ie the short cache for this page is no longer valid.
4110  */
4111 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
4112 {
4113         if (object->myDev->nShortOpCaches > 0) {
4114                 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4115
4116                 if (cache)
4117                         cache->object = NULL;
4118         }
4119 }
4120
4121 /* Invalidate all the cache pages associated with this object
4122  * Do this whenever ther file is deleted or resized.
4123  */
4124 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
4125 {
4126         int i;
4127         yaffs_Device *dev = in->myDev;
4128
4129         if (dev->nShortOpCaches > 0) {
4130                 /* Invalidate it. */
4131                 for (i = 0; i < dev->nShortOpCaches; i++) {
4132                         if (dev->srCache[i].object == in)
4133                                 dev->srCache[i].object = NULL;
4134                 }
4135         }
4136 }
4137
4138 /*--------------------- Checkpointing --------------------*/
4139
4140
4141 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev, int head)
4142 {
4143         yaffs_CheckpointValidity cp;
4144
4145         memset(&cp, 0, sizeof(cp));
4146
4147         cp.structType = sizeof(cp);
4148         cp.magic = YAFFS_MAGIC;
4149         cp.version = YAFFS_CHECKPOINT_VERSION;
4150         cp.head = (head) ? 1 : 0;
4151
4152         return (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp)) ?
4153                 1 : 0;
4154 }
4155
4156 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4157 {
4158         yaffs_CheckpointValidity cp;
4159         int ok;
4160
4161         ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4162
4163         if (ok)
4164                 ok = (cp.structType == sizeof(cp)) &&
4165                      (cp.magic == YAFFS_MAGIC) &&
4166                      (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4167                      (cp.head == ((head) ? 1 : 0));
4168         return ok ? 1 : 0;
4169 }
4170
4171 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4172                                            yaffs_Device *dev)
4173 {
4174         cp->nErasedBlocks = dev->nErasedBlocks;
4175         cp->allocationBlock = dev->allocationBlock;
4176         cp->allocationPage = dev->allocationPage;
4177         cp->nFreeChunks = dev->nFreeChunks;
4178
4179         cp->nDeletedFiles = dev->nDeletedFiles;
4180         cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4181         cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4182         cp->sequenceNumber = dev->sequenceNumber;
4183         cp->oldestDirtySequence = dev->oldestDirtySequence;
4184
4185 }
4186
4187 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4188                                            yaffs_CheckpointDevice *cp)
4189 {
4190         dev->nErasedBlocks = cp->nErasedBlocks;
4191         dev->allocationBlock = cp->allocationBlock;
4192         dev->allocationPage = cp->allocationPage;
4193         dev->nFreeChunks = cp->nFreeChunks;
4194
4195         dev->nDeletedFiles = cp->nDeletedFiles;
4196         dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4197         dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4198         dev->sequenceNumber = cp->sequenceNumber;
4199         dev->oldestDirtySequence = cp->oldestDirtySequence;
4200 }
4201
4202
4203 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4204 {
4205         yaffs_CheckpointDevice cp;
4206         __u32 nBytes;
4207         __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4208
4209         int ok;
4210
4211         /* Write device runtime values*/
4212         yaffs_DeviceToCheckpointDevice(&cp, dev);
4213         cp.structType = sizeof(cp);
4214
4215         ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4216
4217         /* Write block info */
4218         if (ok) {
4219                 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4220                 ok = (yaffs_CheckpointWrite(dev, dev->blockInfo, nBytes) == nBytes);
4221         }
4222
4223         /* Write chunk bits */
4224         if (ok) {
4225                 nBytes = nBlocks * dev->chunkBitmapStride;
4226                 ok = (yaffs_CheckpointWrite(dev, dev->chunkBits, nBytes) == nBytes);
4227         }
4228         return   ok ? 1 : 0;
4229
4230 }
4231
4232 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4233 {
4234         yaffs_CheckpointDevice cp;
4235         __u32 nBytes;
4236         __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4237
4238         int ok;
4239
4240         ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4241         if (!ok)
4242                 return 0;
4243
4244         if (cp.structType != sizeof(cp))
4245                 return 0;
4246
4247
4248         yaffs_CheckpointDeviceToDevice(dev, &cp);
4249
4250         nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4251
4252         ok = (yaffs_CheckpointRead(dev, dev->blockInfo, nBytes) == nBytes);
4253
4254         if (!ok)
4255                 return 0;
4256         nBytes = nBlocks * dev->chunkBitmapStride;
4257
4258         ok = (yaffs_CheckpointRead(dev, dev->chunkBits, nBytes) == nBytes);
4259
4260         return ok ? 1 : 0;
4261 }
4262
4263 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4264                                            yaffs_Object *obj)
4265 {
4266
4267         cp->objectId = obj->objectId;
4268         cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4269         cp->hdrChunk = obj->hdrChunk;
4270         cp->variantType = obj->variantType;
4271         cp->deleted = obj->deleted;
4272         cp->softDeleted = obj->softDeleted;
4273         cp->unlinked = obj->unlinked;
4274         cp->fake = obj->fake;
4275         cp->renameAllowed = obj->renameAllowed;
4276         cp->unlinkAllowed = obj->unlinkAllowed;
4277         cp->serial = obj->serial;
4278         cp->nDataChunks = obj->nDataChunks;
4279
4280         if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4281                 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4282         else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4283                 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4284 }
4285
4286 static int yaffs_CheckpointObjectToObject(yaffs_Object *obj, yaffs_CheckpointObject *cp)
4287 {
4288
4289         yaffs_Object *parent;
4290
4291         if (obj->variantType != cp->variantType) {
4292                 T(YAFFS_TRACE_ERROR, (TSTR("Checkpoint read object %d type %d "
4293                         TCONT("chunk %d does not match existing object type %d")
4294                         TENDSTR), cp->objectId, cp->variantType, cp->hdrChunk,
4295                         obj->variantType));
4296                 return 0;
4297         }
4298
4299         obj->objectId = cp->objectId;
4300
4301         if (cp->parentId)
4302                 parent = yaffs_FindOrCreateObjectByNumber(
4303                                         obj->myDev,
4304                                         cp->parentId,
4305                                         YAFFS_OBJECT_TYPE_DIRECTORY);
4306         else
4307                 parent = NULL;
4308
4309         if (parent) {
4310                 if (parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4311                         T(YAFFS_TRACE_ALWAYS, (TSTR("Checkpoint read object %d parent %d type %d"
4312                                 TCONT(" chunk %d Parent type, %d, not directory")
4313                                 TENDSTR),
4314                                 cp->objectId, cp->parentId, cp->variantType,
4315                                 cp->hdrChunk, parent->variantType));
4316                         return 0;
4317                 }
4318                 yaffs_AddObjectToDirectory(parent, obj);
4319         }
4320
4321         obj->hdrChunk = cp->hdrChunk;
4322         obj->variantType = cp->variantType;
4323         obj->deleted = cp->deleted;
4324         obj->softDeleted = cp->softDeleted;
4325         obj->unlinked = cp->unlinked;
4326         obj->fake = cp->fake;
4327         obj->renameAllowed = cp->renameAllowed;
4328         obj->unlinkAllowed = cp->unlinkAllowed;
4329         obj->serial = cp->serial;
4330         obj->nDataChunks = cp->nDataChunks;
4331
4332         if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4333                 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4334         else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4335                 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4336
4337         if (obj->hdrChunk > 0)
4338                 obj->lazyLoaded = 1;
4339         return 1;
4340 }
4341
4342
4343
4344 static int yaffs_CheckpointTnodeWorker(yaffs_Object *in, yaffs_Tnode *tn,
4345                                         __u32 level, int chunkOffset)
4346 {
4347         int i;
4348         yaffs_Device *dev = in->myDev;
4349         int ok = 1;
4350         int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4351
4352         if (tnodeSize < sizeof(yaffs_Tnode))
4353                 tnodeSize = sizeof(yaffs_Tnode);
4354
4355
4356         if (tn) {
4357                 if (level > 0) {
4358
4359                         for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
4360                                 if (tn->internal[i]) {
4361                                         ok = yaffs_CheckpointTnodeWorker(in,
4362                                                         tn->internal[i],
4363                                                         level - 1,
4364                                                         (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4365                                 }
4366                         }
4367                 } else if (level == 0) {
4368                         __u32 baseOffset = chunkOffset <<  YAFFS_TNODES_LEVEL0_BITS;
4369                         ok = (yaffs_CheckpointWrite(dev, &baseOffset, sizeof(baseOffset)) == sizeof(baseOffset));
4370                         if (ok)
4371                                 ok = (yaffs_CheckpointWrite(dev, tn, tnodeSize) == tnodeSize);
4372                 }
4373         }
4374
4375         return ok;
4376
4377 }
4378
4379 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4380 {
4381         __u32 endMarker = ~0;
4382         int ok = 1;
4383
4384         if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4385                 ok = yaffs_CheckpointTnodeWorker(obj,
4386                                             obj->variant.fileVariant.top,
4387                                             obj->variant.fileVariant.topLevel,
4388                                             0);
4389                 if (ok)
4390                         ok = (yaffs_CheckpointWrite(obj->myDev, &endMarker, sizeof(endMarker)) ==
4391                                 sizeof(endMarker));
4392         }
4393
4394         return ok ? 1 : 0;
4395 }
4396
4397 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4398 {
4399         __u32 baseChunk;
4400         int ok = 1;
4401         yaffs_Device *dev = obj->myDev;
4402         yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4403         yaffs_Tnode *tn;
4404         int nread = 0;
4405         int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4406
4407         if (tnodeSize < sizeof(yaffs_Tnode))
4408                 tnodeSize = sizeof(yaffs_Tnode);
4409
4410         ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4411
4412         while (ok && (~baseChunk)) {
4413                 nread++;
4414                 /* Read level 0 tnode */
4415
4416
4417                 tn = yaffs_GetTnodeRaw(dev);
4418                 if (tn)
4419                         ok = (yaffs_CheckpointRead(dev, tn, tnodeSize) == tnodeSize);
4420                 else
4421                         ok = 0;
4422
4423                 if (tn && ok)
4424                         ok = yaffs_AddOrFindLevel0Tnode(dev,
4425                                                         fileStructPtr,
4426                                                         baseChunk,
4427                                                         tn) ? 1 : 0;
4428
4429                 if (ok)
4430                         ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4431
4432         }
4433
4434         T(YAFFS_TRACE_CHECKPOINT, (
4435                 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4436                 nread, baseChunk, ok));
4437
4438         return ok ? 1 : 0;
4439 }
4440
4441
4442 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4443 {
4444         yaffs_Object *obj;
4445         yaffs_CheckpointObject cp;
4446         int i;
4447         int ok = 1;
4448         struct ylist_head *lh;
4449
4450
4451         /* Iterate through the objects in each hash entry,
4452          * dumping them to the checkpointing stream.
4453          */
4454
4455         for (i = 0; ok &&  i <  YAFFS_NOBJECT_BUCKETS; i++) {
4456                 ylist_for_each(lh, &dev->objectBucket[i].list) {
4457                         if (lh) {
4458                                 obj = ylist_entry(lh, yaffs_Object, hashLink);
4459                                 if (!obj->deferedFree) {
4460                                         yaffs_ObjectToCheckpointObject(&cp, obj);
4461                                         cp.structType = sizeof(cp);
4462
4463                                         T(YAFFS_TRACE_CHECKPOINT, (
4464                                                 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %x" TENDSTR),
4465                                                 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk, (unsigned) obj));
4466
4467                                         ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4468
4469                                         if (ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4470                                                 ok = yaffs_WriteCheckpointTnodes(obj);
4471                                 }
4472                         }
4473                 }
4474         }
4475
4476         /* Dump end of list */
4477         memset(&cp, 0xFF, sizeof(yaffs_CheckpointObject));
4478         cp.structType = sizeof(cp);
4479
4480         if (ok)
4481                 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4482
4483         return ok ? 1 : 0;
4484 }
4485
4486 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4487 {
4488         yaffs_Object *obj;
4489         yaffs_CheckpointObject cp;
4490         int ok = 1;
4491         int done = 0;
4492         yaffs_Object *hardList = NULL;
4493
4494         while (ok && !done) {
4495                 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4496                 if (cp.structType != sizeof(cp)) {
4497                         T(YAFFS_TRACE_CHECKPOINT, (TSTR("struct size %d instead of %d ok %d"TENDSTR),
4498                                 cp.structType, sizeof(cp), ok));
4499                         ok = 0;
4500                 }
4501
4502                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4503                         cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk));
4504
4505                 if (ok && cp.objectId == ~0)
4506                         done = 1;
4507                 else if (ok) {
4508                         obj = yaffs_FindOrCreateObjectByNumber(dev, cp.objectId, cp.variantType);
4509                         if (obj) {
4510                                 ok = yaffs_CheckpointObjectToObject(obj, &cp);
4511                                 if (!ok)
4512                                         break;
4513                                 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4514                                         ok = yaffs_ReadCheckpointTnodes(obj);
4515                                 } else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4516                                         obj->hardLinks.next =
4517                                                 (struct ylist_head *) hardList;
4518                                         hardList = obj;
4519                                 }
4520                         } else
4521                                 ok = 0;
4522                 }
4523         }
4524
4525         if (ok)
4526                 yaffs_HardlinkFixup(dev, hardList);
4527
4528         return ok ? 1 : 0;
4529 }
4530
4531 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4532 {
4533         __u32 checkpointSum;
4534         int ok;
4535
4536         yaffs_GetCheckpointSum(dev, &checkpointSum);
4537
4538         ok = (yaffs_CheckpointWrite(dev, &checkpointSum, sizeof(checkpointSum)) == sizeof(checkpointSum));
4539
4540         if (!ok)
4541                 return 0;
4542
4543         return 1;
4544 }
4545
4546 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4547 {
4548         __u32 checkpointSum0;
4549         __u32 checkpointSum1;
4550         int ok;
4551
4552         yaffs_GetCheckpointSum(dev, &checkpointSum0);
4553
4554         ok = (yaffs_CheckpointRead(dev, &checkpointSum1, sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4555
4556         if (!ok)
4557                 return 0;
4558
4559         if (checkpointSum0 != checkpointSum1)
4560                 return 0;
4561
4562         return 1;
4563 }
4564
4565
4566 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4567 {
4568         int ok = 1;
4569
4570         if (dev->skipCheckpointWrite || !dev->isYaffs2) {
4571                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint write" TENDSTR)));
4572                 ok = 0;
4573         }
4574
4575         if (ok)
4576                 ok = yaffs_CheckpointOpen(dev, 1);
4577
4578         if (ok) {
4579                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4580                 ok = yaffs_WriteCheckpointValidityMarker(dev, 1);
4581         }
4582         if (ok) {
4583                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint device" TENDSTR)));
4584                 ok = yaffs_WriteCheckpointDevice(dev);
4585         }
4586         if (ok) {
4587                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint objects" TENDSTR)));
4588                 ok = yaffs_WriteCheckpointObjects(dev);
4589         }
4590         if (ok) {
4591                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4592                 ok = yaffs_WriteCheckpointValidityMarker(dev, 0);
4593         }
4594
4595         if (ok)
4596                 ok = yaffs_WriteCheckpointSum(dev);
4597
4598         if (!yaffs_CheckpointClose(dev))
4599                 ok = 0;
4600
4601         if (ok)
4602                 dev->isCheckpointed = 1;
4603         else
4604                 dev->isCheckpointed = 0;
4605
4606         return dev->isCheckpointed;
4607 }
4608
4609 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4610 {
4611         int ok = 1;
4612
4613         if (dev->skipCheckpointRead || !dev->isYaffs2) {
4614                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint read" TENDSTR)));
4615                 ok = 0;
4616         }
4617
4618         if (ok)
4619                 ok = yaffs_CheckpointOpen(dev, 0); /* open for read */
4620
4621         if (ok) {
4622                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4623                 ok = yaffs_ReadCheckpointValidityMarker(dev, 1);
4624         }
4625         if (ok) {
4626                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint device" TENDSTR)));
4627                 ok = yaffs_ReadCheckpointDevice(dev);
4628         }
4629         if (ok) {
4630                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint objects" TENDSTR)));
4631                 ok = yaffs_ReadCheckpointObjects(dev);
4632         }
4633         if (ok) {
4634                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4635                 ok = yaffs_ReadCheckpointValidityMarker(dev, 0);
4636         }
4637
4638         if (ok) {
4639                 ok = yaffs_ReadCheckpointSum(dev);
4640                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint checksum %d" TENDSTR), ok));
4641         }
4642
4643         if (!yaffs_CheckpointClose(dev))
4644                 ok = 0;
4645
4646         if (ok)
4647                 dev->isCheckpointed = 1;
4648         else
4649                 dev->isCheckpointed = 0;
4650
4651         return ok ? 1 : 0;
4652
4653 }
4654
4655 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4656 {
4657         if (dev->isCheckpointed ||
4658                         dev->blocksInCheckpoint > 0) {
4659                 dev->isCheckpointed = 0;
4660                 yaffs_CheckpointInvalidateStream(dev);
4661                 if (dev->superBlock && dev->markSuperBlockDirty)
4662                         dev->markSuperBlockDirty(dev->superBlock);
4663         }
4664 }
4665
4666
4667 int yaffs_CheckpointSave(yaffs_Device *dev)
4668 {
4669
4670         T(YAFFS_TRACE_CHECKPOINT, (TSTR("save entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4671
4672         yaffs_VerifyObjects(dev);
4673         yaffs_VerifyBlocks(dev);
4674         yaffs_VerifyFreeChunks(dev);
4675
4676         if (!dev->isCheckpointed) {
4677                 yaffs_InvalidateCheckpoint(dev);
4678                 yaffs_WriteCheckpointData(dev);
4679         }
4680
4681         T(YAFFS_TRACE_ALWAYS, (TSTR("save exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4682
4683         return dev->isCheckpointed;
4684 }
4685
4686 int yaffs_CheckpointRestore(yaffs_Device *dev)
4687 {
4688         int retval;
4689         T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4690
4691         retval = yaffs_ReadCheckpointData(dev);
4692
4693         if (dev->isCheckpointed) {
4694                 yaffs_VerifyObjects(dev);
4695                 yaffs_VerifyBlocks(dev);
4696                 yaffs_VerifyFreeChunks(dev);
4697         }
4698
4699         T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4700
4701         return retval;
4702 }
4703
4704 /*--------------------- File read/write ------------------------
4705  * Read and write have very similar structures.
4706  * In general the read/write has three parts to it
4707  * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4708  * Some complete chunks
4709  * An incomplete chunk to end off with
4710  *
4711  * Curve-balls: the first chunk might also be the last chunk.
4712  */
4713
4714 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 *buffer, loff_t offset,
4715                         int nBytes)
4716 {
4717
4718         int chunk;
4719         __u32 start;
4720         int nToCopy;
4721         int n = nBytes;
4722         int nDone = 0;
4723         yaffs_ChunkCache *cache;
4724
4725         yaffs_Device *dev;
4726
4727         dev = in->myDev;
4728
4729         while (n > 0) {
4730                 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4731                 /* start = offset % dev->nDataBytesPerChunk; */
4732                 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4733                 chunk++;
4734
4735                 /* OK now check for the curveball where the start and end are in
4736                  * the same chunk.
4737                  */
4738                 if ((start + n) < dev->nDataBytesPerChunk)
4739                         nToCopy = n;
4740                 else
4741                         nToCopy = dev->nDataBytesPerChunk - start;
4742
4743                 cache = yaffs_FindChunkCache(in, chunk);
4744
4745                 /* If the chunk is already in the cache or it is less than a whole chunk
4746                  * or we're using inband tags then use the cache (if there is caching)
4747                  * else bypass the cache.
4748                  */
4749                 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4750                         if (dev->nShortOpCaches > 0) {
4751
4752                                 /* If we can't find the data in the cache, then load it up. */
4753
4754                                 if (!cache) {
4755                                         cache = yaffs_GrabChunkCache(in->myDev);
4756                                         cache->object = in;
4757                                         cache->chunkId = chunk;
4758                                         cache->dirty = 0;
4759                                         cache->locked = 0;
4760                                         yaffs_ReadChunkDataFromObject(in, chunk,
4761                                                                       cache->
4762                                                                       data);
4763                                         cache->nBytes = 0;
4764                                 }
4765
4766                                 yaffs_UseChunkCache(dev, cache, 0);
4767
4768                                 cache->locked = 1;
4769
4770
4771                                 memcpy(buffer, &cache->data[start], nToCopy);
4772
4773                                 cache->locked = 0;
4774                         } else {
4775                                 /* Read into the local buffer then copy..*/
4776
4777                                 __u8 *localBuffer =
4778                                     yaffs_GetTempBuffer(dev, __LINE__);
4779                                 yaffs_ReadChunkDataFromObject(in, chunk,
4780                                                               localBuffer);
4781
4782                                 memcpy(buffer, &localBuffer[start], nToCopy);
4783
4784
4785                                 yaffs_ReleaseTempBuffer(dev, localBuffer,
4786                                                         __LINE__);
4787                         }
4788
4789                 } else {
4790
4791                         /* A full chunk. Read directly into the supplied buffer. */
4792                         yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4793
4794                 }
4795
4796                 n -= nToCopy;
4797                 offset += nToCopy;
4798                 buffer += nToCopy;
4799                 nDone += nToCopy;
4800
4801         }
4802
4803         return nDone;
4804 }
4805
4806 int yaffs_WriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
4807                         int nBytes, int writeThrough)
4808 {
4809
4810         int chunk;
4811         __u32 start;
4812         int nToCopy;
4813         int n = nBytes;
4814         int nDone = 0;
4815         int nToWriteBack;
4816         int startOfWrite = offset;
4817         int chunkWritten = 0;
4818         __u32 nBytesRead;
4819         __u32 chunkStart;
4820
4821         yaffs_Device *dev;
4822
4823         dev = in->myDev;
4824
4825         while (n > 0 && chunkWritten >= 0) {
4826                 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4827                 /* start = offset % dev->nDataBytesPerChunk; */
4828                 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4829
4830                 if (chunk * dev->nDataBytesPerChunk + start != offset ||
4831                                 start >= dev->nDataBytesPerChunk) {
4832                         T(YAFFS_TRACE_ERROR, (
4833                            TSTR("AddrToChunk of offset %d gives chunk %d start %d"
4834                            TENDSTR),
4835                            (int)offset, chunk, start));
4836                 }
4837                 chunk++;
4838
4839                 /* OK now check for the curveball where the start and end are in
4840                  * the same chunk.
4841                  */
4842
4843                 if ((start + n) < dev->nDataBytesPerChunk) {
4844                         nToCopy = n;
4845
4846                         /* Now folks, to calculate how many bytes to write back....
4847                          * If we're overwriting and not writing to then end of file then
4848                          * we need to write back as much as was there before.
4849                          */
4850
4851                         chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
4852
4853                         if (chunkStart > in->variant.fileVariant.fileSize)
4854                                 nBytesRead = 0; /* Past end of file */
4855                         else
4856                                 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
4857
4858                         if (nBytesRead > dev->nDataBytesPerChunk)
4859                                 nBytesRead = dev->nDataBytesPerChunk;
4860
4861                         nToWriteBack =
4862                             (nBytesRead >
4863                              (start + n)) ? nBytesRead : (start + n);
4864
4865                         if (nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
4866                                 YBUG();
4867
4868                 } else {
4869                         nToCopy = dev->nDataBytesPerChunk - start;
4870                         nToWriteBack = dev->nDataBytesPerChunk;
4871                 }
4872
4873                 if (nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4874                         /* An incomplete start or end chunk (or maybe both start and end chunk),
4875                          * or we're using inband tags, so we want to use the cache buffers.
4876                          */
4877                         if (dev->nShortOpCaches > 0) {
4878                                 yaffs_ChunkCache *cache;
4879                                 /* If we can't find the data in the cache, then load the cache */
4880                                 cache = yaffs_FindChunkCache(in, chunk);
4881
4882                                 if (!cache
4883                                     && yaffs_CheckSpaceForAllocation(in->
4884                                                                      myDev)) {
4885                                         cache = yaffs_GrabChunkCache(in->myDev);
4886                                         cache->object = in;
4887                                         cache->chunkId = chunk;
4888                                         cache->dirty = 0;
4889                                         cache->locked = 0;
4890                                         yaffs_ReadChunkDataFromObject(in, chunk,
4891                                                                       cache->
4892                                                                       data);
4893                                 } else if (cache &&
4894                                         !cache->dirty &&
4895                                         !yaffs_CheckSpaceForAllocation(in->myDev)) {
4896                                         /* Drop the cache if it was a read cache item and
4897                                          * no space check has been made for it.
4898                                          */
4899                                          cache = NULL;
4900                                 }
4901
4902                                 if (cache) {
4903                                         yaffs_UseChunkCache(dev, cache, 1);
4904                                         cache->locked = 1;
4905
4906
4907                                         memcpy(&cache->data[start], buffer,
4908                                                nToCopy);
4909
4910
4911                                         cache->locked = 0;
4912                                         cache->nBytes = nToWriteBack;
4913
4914                                         if (writeThrough) {
4915                                                 chunkWritten =
4916                                                     yaffs_WriteChunkDataToObject
4917                                                     (cache->object,
4918                                                      cache->chunkId,
4919                                                      cache->data, cache->nBytes,
4920                                                      1);
4921                                                 cache->dirty = 0;
4922                                         }
4923
4924                                 } else {
4925                                         chunkWritten = -1;      /* fail the write */
4926                                 }
4927                         } else {
4928                                 /* An incomplete start or end chunk (or maybe both start and end chunk)
4929                                  * Read into the local buffer then copy, then copy over and write back.
4930                                  */
4931
4932                                 __u8 *localBuffer =
4933                                     yaffs_GetTempBuffer(dev, __LINE__);
4934
4935                                 yaffs_ReadChunkDataFromObject(in, chunk,
4936                                                               localBuffer);
4937
4938
4939
4940                                 memcpy(&localBuffer[start], buffer, nToCopy);
4941
4942                                 chunkWritten =
4943                                     yaffs_WriteChunkDataToObject(in, chunk,
4944                                                                  localBuffer,
4945                                                                  nToWriteBack,
4946                                                                  0);
4947
4948                                 yaffs_ReleaseTempBuffer(dev, localBuffer,
4949                                                         __LINE__);
4950
4951                         }
4952
4953                 } else {
4954                         /* A full chunk. Write directly from the supplied buffer. */
4955
4956
4957
4958                         chunkWritten =
4959                             yaffs_WriteChunkDataToObject(in, chunk, buffer,
4960                                                          dev->nDataBytesPerChunk,
4961                                                          0);
4962
4963                         /* Since we've overwritten the cached data, we better invalidate it. */
4964                         yaffs_InvalidateChunkCache(in, chunk);
4965                 }
4966
4967                 if (chunkWritten >= 0) {
4968                         n -= nToCopy;
4969                         offset += nToCopy;
4970                         buffer += nToCopy;
4971                         nDone += nToCopy;
4972                 }
4973
4974         }
4975
4976         /* Update file object */
4977
4978         if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
4979                 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
4980
4981         in->dirty = 1;
4982
4983         return nDone;
4984 }
4985
4986
4987 /* ---------------------- File resizing stuff ------------------ */
4988
4989 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
4990 {
4991
4992         yaffs_Device *dev = in->myDev;
4993         int oldFileSize = in->variant.fileVariant.fileSize;
4994
4995         int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
4996
4997         int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
4998             dev->nDataBytesPerChunk;
4999         int i;
5000         int chunkId;
5001
5002         /* Delete backwards so that we don't end up with holes if
5003          * power is lost part-way through the operation.
5004          */
5005         for (i = lastDel; i >= startDel; i--) {
5006                 /* NB this could be optimised somewhat,
5007                  * eg. could retrieve the tags and write them without
5008                  * using yaffs_DeleteChunk
5009                  */
5010
5011                 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5012                 if (chunkId > 0) {
5013                         if (chunkId <
5014                             (dev->internalStartBlock * dev->nChunksPerBlock)
5015                             || chunkId >=
5016                             ((dev->internalEndBlock +
5017                               1) * dev->nChunksPerBlock)) {
5018                                 T(YAFFS_TRACE_ALWAYS,
5019                                   (TSTR("Found daft chunkId %d for %d" TENDSTR),
5020                                    chunkId, i));
5021                         } else {
5022                                 in->nDataChunks--;
5023                                 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5024                         }
5025                 }
5026         }
5027
5028 }
5029
5030 int yaffs_ResizeFile(yaffs_Object *in, loff_t newSize)
5031 {
5032
5033         int oldFileSize = in->variant.fileVariant.fileSize;
5034         __u32 newSizeOfPartialChunk;
5035         int newFullChunks;
5036
5037         yaffs_Device *dev = in->myDev;
5038
5039         yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5040
5041         yaffs_FlushFilesChunkCache(in);
5042         yaffs_InvalidateWholeChunkCache(in);
5043
5044         yaffs_CheckGarbageCollection(dev);
5045
5046         if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
5047                 return YAFFS_FAIL;
5048
5049         if (newSize == oldFileSize)
5050                 return YAFFS_OK;
5051
5052         if (newSize < oldFileSize) {
5053
5054                 yaffs_PruneResizedChunks(in, newSize);
5055
5056                 if (newSizeOfPartialChunk != 0) {
5057                         int lastChunk = 1 + newFullChunks;
5058
5059                         __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5060
5061                         /* Got to read and rewrite the last chunk with its new size and zero pad */
5062                         yaffs_ReadChunkDataFromObject(in, lastChunk,
5063                                                       localBuffer);
5064
5065                         memset(localBuffer + newSizeOfPartialChunk, 0,
5066                                dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5067
5068                         yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5069                                                      newSizeOfPartialChunk, 1);
5070
5071                         yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5072                 }
5073
5074                 in->variant.fileVariant.fileSize = newSize;
5075
5076                 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5077         } else {
5078                 /* newsSize > oldFileSize */
5079                 in->variant.fileVariant.fileSize = newSize;
5080         }
5081
5082
5083         /* Write a new object header to reflect the resize.
5084          * show we've shrunk the file, if need be
5085          * Do this only if the file is not in the deleted directories
5086          * and is not shadowed.
5087          */
5088         if (in->parent &&
5089             !in->isShadowed &&
5090             in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5091             in->parent->objectId != YAFFS_OBJECTID_DELETED)
5092                 yaffs_UpdateObjectHeader(in, NULL, 0,
5093                                          (newSize < oldFileSize) ? 1 : 0, 0);
5094
5095         return YAFFS_OK;
5096 }
5097
5098 loff_t yaffs_GetFileSize(yaffs_Object *obj)
5099 {
5100         YCHAR *alias = NULL;
5101         obj = yaffs_GetEquivalentObject(obj);
5102
5103         switch (obj->variantType) {
5104         case YAFFS_OBJECT_TYPE_FILE:
5105                 return obj->variant.fileVariant.fileSize;
5106         case YAFFS_OBJECT_TYPE_SYMLINK:
5107                 alias = obj->variant.symLinkVariant.alias;
5108                 if(!alias)
5109                         return 0;
5110                 return yaffs_strlen(alias);
5111         default:
5112                 return 0;
5113         }
5114 }
5115
5116
5117
5118 int yaffs_FlushFile(yaffs_Object *in, int updateTime, int dataSync)
5119 {
5120         int retVal;
5121         if (in->dirty) {
5122                 yaffs_FlushFilesChunkCache(in);
5123                 if(dataSync) /* Only sync data */
5124                         retVal=YAFFS_OK;
5125                 else {
5126                         if (updateTime) {
5127 #ifdef CONFIG_YAFFS_WINCE
5128                                 yfsd_WinFileTimeNow(in->win_mtime);
5129 #else
5130
5131                                 in->yst_mtime = Y_CURRENT_TIME;
5132
5133 #endif
5134                         }
5135
5136                         retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5137                                 0) ? YAFFS_OK : YAFFS_FAIL;
5138                 }
5139         } else {
5140                 retVal = YAFFS_OK;
5141         }
5142
5143         return retVal;
5144
5145 }
5146
5147 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
5148 {
5149
5150         /* First off, invalidate the file's data in the cache, without flushing. */
5151         yaffs_InvalidateWholeChunkCache(in);
5152
5153         if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5154                 /* Move to the unlinked directory so we have a record that it was deleted. */
5155                 yaffs_ChangeObjectName(in, in->myDev->deletedDir, _Y("deleted"), 0, 0);
5156
5157         }
5158
5159         yaffs_RemoveObjectFromDirectory(in);
5160         yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5161         in->hdrChunk = 0;
5162
5163         yaffs_FreeObject(in);
5164         return YAFFS_OK;
5165
5166 }
5167
5168 /* yaffs_DeleteFile deletes the whole file data
5169  * and the inode associated with the file.
5170  * It does not delete the links associated with the file.
5171  */
5172 static int yaffs_UnlinkFileIfNeeded(yaffs_Object *in)
5173 {
5174
5175         int retVal;
5176         int immediateDeletion = 0;
5177
5178 #ifdef __KERNEL__
5179         if (!in->myInode)
5180                 immediateDeletion = 1;
5181 #else
5182         if (in->inUse <= 0)
5183                 immediateDeletion = 1;
5184 #endif
5185
5186         if (immediateDeletion) {
5187                 retVal =
5188                     yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5189                                            _Y("deleted"), 0, 0);
5190                 T(YAFFS_TRACE_TRACING,
5191                   (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5192                    in->objectId));
5193                 in->deleted = 1;
5194                 in->myDev->nDeletedFiles++;
5195                 if (1 || in->myDev->isYaffs2)
5196                         yaffs_ResizeFile(in, 0);
5197                 yaffs_SoftDeleteFile(in);
5198         } else {
5199                 retVal =
5200                     yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5201                                            _Y("unlinked"), 0, 0);
5202         }
5203
5204
5205         return retVal;
5206 }
5207
5208 int yaffs_DeleteFile(yaffs_Object *in)
5209 {
5210         int retVal = YAFFS_OK;
5211         int deleted = in->deleted;
5212
5213         yaffs_ResizeFile(in, 0);
5214
5215         if (in->nDataChunks > 0) {
5216                 /* Use soft deletion if there is data in the file.
5217                  * That won't be the case if it has been resized to zero.
5218                  */
5219                 if (!in->unlinked)
5220                         retVal = yaffs_UnlinkFileIfNeeded(in);
5221
5222                 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5223                         in->deleted = 1;
5224                         deleted = 1;
5225                         in->myDev->nDeletedFiles++;
5226                         yaffs_SoftDeleteFile(in);
5227                 }
5228                 return deleted ? YAFFS_OK : YAFFS_FAIL;
5229         } else {
5230                 /* The file has no data chunks so we toss it immediately */
5231                 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5232                 in->variant.fileVariant.top = NULL;
5233                 yaffs_DoGenericObjectDeletion(in);
5234
5235                 return YAFFS_OK;
5236         }
5237 }
5238
5239 static int yaffs_IsNonEmptyDirectory(yaffs_Object *obj)
5240 {
5241         return (obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) &&
5242                 !(ylist_empty(&obj->variant.directoryVariant.children));
5243 }
5244
5245 static int yaffs_DeleteDirectory(yaffs_Object *obj)
5246 {
5247         /* First check that the directory is empty. */
5248         if (yaffs_IsNonEmptyDirectory(obj))
5249                 return YAFFS_FAIL;
5250
5251         return yaffs_DoGenericObjectDeletion(obj);
5252 }
5253
5254 static int yaffs_DeleteSymLink(yaffs_Object *in)
5255 {
5256         if(in->variant.symLinkVariant.alias)
5257                 YFREE(in->variant.symLinkVariant.alias);
5258         in->variant.symLinkVariant.alias=NULL;
5259
5260         return yaffs_DoGenericObjectDeletion(in);
5261 }
5262
5263 static int yaffs_DeleteHardLink(yaffs_Object *in)
5264 {
5265         /* remove this hardlink from the list assocaited with the equivalent
5266          * object
5267          */
5268         ylist_del_init(&in->hardLinks);
5269         return yaffs_DoGenericObjectDeletion(in);
5270 }
5271
5272 int yaffs_DeleteObject(yaffs_Object *obj)
5273 {
5274 int retVal = -1;
5275         switch (obj->variantType) {
5276         case YAFFS_OBJECT_TYPE_FILE:
5277                 retVal = yaffs_DeleteFile(obj);
5278                 break;
5279         case YAFFS_OBJECT_TYPE_DIRECTORY:
5280                 return yaffs_DeleteDirectory(obj);
5281                 break;
5282         case YAFFS_OBJECT_TYPE_SYMLINK:
5283                 retVal = yaffs_DeleteSymLink(obj);
5284                 break;
5285         case YAFFS_OBJECT_TYPE_HARDLINK:
5286                 retVal = yaffs_DeleteHardLink(obj);
5287                 break;
5288         case YAFFS_OBJECT_TYPE_SPECIAL:
5289                 retVal = yaffs_DoGenericObjectDeletion(obj);
5290                 break;
5291         case YAFFS_OBJECT_TYPE_UNKNOWN:
5292                 retVal = 0;
5293                 break;          /* should not happen. */
5294         }
5295
5296         return retVal;
5297 }
5298
5299 static int yaffs_UnlinkWorker(yaffs_Object *obj)
5300 {
5301
5302         int immediateDeletion = 0;
5303
5304 #ifdef __KERNEL__
5305         if (!obj->myInode)
5306                 immediateDeletion = 1;
5307 #else
5308         if (obj->inUse <= 0)
5309                 immediateDeletion = 1;
5310 #endif
5311
5312         if(obj)
5313                 yaffs_UpdateParent(obj->parent);
5314
5315         if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5316                 return yaffs_DeleteHardLink(obj);
5317         } else if (!ylist_empty(&obj->hardLinks)) {
5318                 /* Curve ball: We're unlinking an object that has a hardlink.
5319                  *
5320                  * This problem arises because we are not strictly following
5321                  * The Linux link/inode model.
5322                  *
5323                  * We can't really delete the object.
5324                  * Instead, we do the following:
5325                  * - Select a hardlink.
5326                  * - Unhook it from the hard links
5327                  * - Unhook it from its parent directory (so that the rename can work)
5328                  * - Rename the object to the hardlink's name.
5329                  * - Delete the hardlink
5330                  */
5331
5332                 yaffs_Object *hl;
5333                 int retVal;
5334                 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5335
5336                 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5337
5338                 ylist_del_init(&hl->hardLinks);
5339                 ylist_del_init(&hl->siblings);
5340
5341                 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5342
5343                 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
5344
5345                 if (retVal == YAFFS_OK)
5346                         retVal = yaffs_DoGenericObjectDeletion(hl);
5347
5348                 return retVal;
5349
5350         } else if (immediateDeletion) {
5351                 switch (obj->variantType) {
5352                 case YAFFS_OBJECT_TYPE_FILE:
5353                         return yaffs_DeleteFile(obj);
5354                         break;
5355                 case YAFFS_OBJECT_TYPE_DIRECTORY:
5356                         return yaffs_DeleteDirectory(obj);
5357                         break;
5358                 case YAFFS_OBJECT_TYPE_SYMLINK:
5359                         return yaffs_DeleteSymLink(obj);
5360                         break;
5361                 case YAFFS_OBJECT_TYPE_SPECIAL:
5362                         return yaffs_DoGenericObjectDeletion(obj);
5363                         break;
5364                 case YAFFS_OBJECT_TYPE_HARDLINK:
5365                 case YAFFS_OBJECT_TYPE_UNKNOWN:
5366                 default:
5367                         return YAFFS_FAIL;
5368                 }
5369         } else if(yaffs_IsNonEmptyDirectory(obj))
5370                 return YAFFS_FAIL;
5371         else
5372                 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
5373                                            _Y("unlinked"), 0, 0);
5374 }
5375
5376
5377 static int yaffs_UnlinkObject(yaffs_Object *obj)
5378 {
5379
5380         if (obj && obj->unlinkAllowed)
5381                 return yaffs_UnlinkWorker(obj);
5382
5383         return YAFFS_FAIL;
5384
5385 }
5386 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
5387 {
5388         yaffs_Object *obj;
5389
5390         obj = yaffs_FindObjectByName(dir, name);
5391         return yaffs_UnlinkObject(obj);
5392 }
5393
5394 /*----------------------- Initialisation Scanning ---------------------- */
5395
5396 static void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
5397                                 int backwardScanning)
5398 {
5399         yaffs_Object *obj;
5400
5401         if (!backwardScanning) {
5402                 /* Handle YAFFS1 forward scanning case
5403                  * For YAFFS1 we always do the deletion
5404                  */
5405
5406         } else {
5407                 /* Handle YAFFS2 case (backward scanning)
5408                  * If the shadowed object exists then ignore.
5409                  */
5410                 obj = yaffs_FindObjectByNumber(dev, objId);
5411                 if(obj)
5412                         return;
5413         }
5414
5415         /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5416          * We put it in unlinked dir to be cleaned up after the scanning
5417          */
5418         obj =
5419             yaffs_FindOrCreateObjectByNumber(dev, objId,
5420                                              YAFFS_OBJECT_TYPE_FILE);
5421         if (!obj)
5422                 return;
5423         obj->isShadowed = 1;
5424         yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5425         obj->variant.fileVariant.shrinkSize = 0;
5426         obj->valid = 1;         /* So that we don't read any other info for this file */
5427
5428 }
5429
5430 typedef struct {
5431         int seq;
5432         int block;
5433 } yaffs_BlockIndex;
5434
5435
5436 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5437 {
5438         yaffs_Object *hl;
5439         yaffs_Object *in;
5440
5441         while (hardList) {
5442                 hl = hardList;
5443                 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5444
5445                 in = yaffs_FindObjectByNumber(dev,
5446                                               hl->variant.hardLinkVariant.
5447                                               equivalentObjectId);
5448
5449                 if (in) {
5450                         /* Add the hardlink pointers */
5451                         hl->variant.hardLinkVariant.equivalentObject = in;
5452                         ylist_add(&hl->hardLinks, &in->hardLinks);
5453                 } else {
5454                         /* Todo Need to report/handle this better.
5455                          * Got a problem... hardlink to a non-existant object
5456                          */
5457                         hl->variant.hardLinkVariant.equivalentObject = NULL;
5458                         YINIT_LIST_HEAD(&hl->hardLinks);
5459
5460                 }
5461         }
5462 }
5463
5464
5465
5466
5467
5468 static int ybicmp(const void *a, const void *b)
5469 {
5470         register int aseq = ((yaffs_BlockIndex *)a)->seq;
5471         register int bseq = ((yaffs_BlockIndex *)b)->seq;
5472         register int ablock = ((yaffs_BlockIndex *)a)->block;
5473         register int bblock = ((yaffs_BlockIndex *)b)->block;
5474         if (aseq == bseq)
5475                 return ablock - bblock;
5476         else
5477                 return aseq - bseq;
5478 }
5479
5480
5481 struct yaffs_ShadowFixerStruct {
5482         int objectId;
5483         int shadowedId;
5484         struct yaffs_ShadowFixerStruct *next;
5485 };
5486
5487
5488 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5489 {
5490         /*
5491         *  Sort out state of unlinked and deleted objects after scanning.
5492         */
5493         struct ylist_head *i;
5494         struct ylist_head *n;
5495         yaffs_Object *l;
5496
5497         /* Soft delete all the unlinked files */
5498         ylist_for_each_safe(i, n,
5499                 &dev->unlinkedDir->variant.directoryVariant.children) {
5500                 if (i) {
5501                         l = ylist_entry(i, yaffs_Object, siblings);
5502                         yaffs_DeleteObject(l);
5503                 }
5504         }
5505
5506         ylist_for_each_safe(i, n,
5507                 &dev->deletedDir->variant.directoryVariant.children) {
5508                 if (i) {
5509                         l = ylist_entry(i, yaffs_Object, siblings);
5510                         yaffs_DeleteObject(l);
5511                 }
5512         }
5513
5514 }
5515
5516 /*
5517  * This code iterates through all the objects making sure that they are rooted.
5518  * Any unrooted objects are re-rooted in lost+found.
5519  * An object needs to be in one of:
5520  * - Directly under deleted, unlinked
5521  * - Directly or indirectly under root.
5522  *
5523  * Note:
5524  *  This code assumes that we don't ever change the current relationships between
5525  *  directories:
5526  *   rootDir->parent == unlinkedDir->parent == deletedDir->parent == NULL
5527  *   lostNfound->parent == rootDir
5528  *
5529  * This fixes the problem where directories might have inadvertently been deleted
5530  * leaving the object "hanging" without being rooted in the directory tree.
5531  */
5532  
5533 static int yaffs_HasNULLParent(yaffs_Device *dev, yaffs_Object *obj)
5534 {
5535         return (obj == dev->deletedDir ||
5536                 obj == dev->unlinkedDir||
5537                 obj == dev->rootDir);
5538 }
5539
5540 static void yaffs_FixHangingObjects(yaffs_Device *dev)
5541 {
5542         yaffs_Object *obj;
5543         yaffs_Object *parent;
5544         int i;
5545         struct ylist_head *lh;
5546         struct ylist_head *n;
5547         int depthLimit;
5548         int hanging;
5549
5550
5551         /* Iterate through the objects in each hash entry,
5552          * looking at each object.
5553          * Make sure it is rooted.
5554          */
5555
5556         for (i = 0; i <  YAFFS_NOBJECT_BUCKETS; i++) {
5557                 ylist_for_each_safe(lh, n, &dev->objectBucket[i].list) {
5558                         if (lh) {
5559                                 obj = ylist_entry(lh, yaffs_Object, hashLink);
5560                                 parent= obj->parent;
5561                                 
5562                                 if(yaffs_HasNULLParent(dev,obj)){
5563                                         /* These directories are not hanging */
5564                                         hanging = 0;
5565                                 }
5566                                 else if(!parent || parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5567                                         hanging = 1;
5568                                 else if(yaffs_HasNULLParent(dev,parent))
5569                                         hanging = 0;
5570                                 else {
5571                                         /*
5572                                          * Need to follow the parent chain to see if it is hanging.
5573                                          */
5574                                         hanging = 0;
5575                                         depthLimit=100;
5576
5577                                         while(parent != dev->rootDir &&
5578                                                 parent->parent &&
5579                                                 parent->parent->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
5580                                                 depthLimit > 0){
5581                                                 parent = parent->parent;
5582                                                 depthLimit--;
5583                                         }
5584                                         if(parent != dev->rootDir)
5585                                                 hanging = 1;
5586                                 }
5587                                 if(hanging){
5588                                         T(YAFFS_TRACE_SCAN,
5589                                           (TSTR("Hanging object %d moved to lost and found" TENDSTR),
5590                                                 obj->objectId));
5591                                         yaffs_AddObjectToDirectory(dev->lostNFoundDir,obj);
5592                                 }
5593                         }
5594                 }
5595         }
5596 }
5597
5598
5599 /*
5600  * Delete directory contents for cleaning up lost and found.
5601  */
5602 static void yaffs_DeleteDirectoryContents(yaffs_Object *dir)
5603 {
5604         yaffs_Object *obj;
5605         struct ylist_head *lh;
5606         struct ylist_head *n;
5607
5608         if(dir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5609                 YBUG();
5610         
5611         ylist_for_each_safe(lh, n, &dir->variant.directoryVariant.children) {
5612                 if (lh) {
5613                         obj = ylist_entry(lh, yaffs_Object, siblings);
5614                         if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
5615                                 yaffs_DeleteDirectoryContents(obj);
5616
5617                         T(YAFFS_TRACE_SCAN,
5618                                 (TSTR("Deleting lost_found object %d" TENDSTR),
5619                                 obj->objectId));
5620
5621                         /* Need to use UnlinkObject since Delete would not handle
5622                          * hardlinked objects correctly.
5623                          */
5624                         yaffs_UnlinkObject(obj); 
5625                 }
5626         }
5627                         
5628 }
5629
5630 static void yaffs_EmptyLostAndFound(yaffs_Device *dev)
5631 {
5632         yaffs_DeleteDirectoryContents(dev->lostNFoundDir);
5633 }
5634
5635 static int yaffs_Scan(yaffs_Device *dev)
5636 {
5637         yaffs_ExtendedTags tags;
5638         int blk;
5639         int blockIterator;
5640         int startIterator;
5641         int endIterator;
5642         int result;
5643
5644         int chunk;
5645         int c;
5646         int deleted;
5647         yaffs_BlockState state;
5648         yaffs_Object *hardList = NULL;
5649         yaffs_BlockInfo *bi;
5650         __u32 sequenceNumber;
5651         yaffs_ObjectHeader *oh;
5652         yaffs_Object *in;
5653         yaffs_Object *parent;
5654
5655         int alloc_failed = 0;
5656
5657         struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5658
5659
5660         __u8 *chunkData;
5661
5662
5663
5664         T(YAFFS_TRACE_SCAN,
5665           (TSTR("yaffs_Scan starts  intstartblk %d intendblk %d..." TENDSTR),
5666            dev->internalStartBlock, dev->internalEndBlock));
5667
5668         chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5669
5670         dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5671
5672         /* Scan all the blocks to determine their state */
5673         for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5674                 bi = yaffs_GetBlockInfo(dev, blk);
5675                 yaffs_ClearChunkBits(dev, blk);
5676                 bi->pagesInUse = 0;
5677                 bi->softDeletions = 0;
5678
5679                 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5680
5681                 bi->blockState = state;
5682                 bi->sequenceNumber = sequenceNumber;
5683
5684                 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
5685                         bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
5686
5687                 T(YAFFS_TRACE_SCAN_DEBUG,
5688                   (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5689                    state, sequenceNumber));
5690
5691                 if (state == YAFFS_BLOCK_STATE_DEAD) {
5692                         T(YAFFS_TRACE_BAD_BLOCKS,
5693                           (TSTR("block %d is bad" TENDSTR), blk));
5694                 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5695                         T(YAFFS_TRACE_SCAN_DEBUG,
5696                           (TSTR("Block empty " TENDSTR)));
5697                         dev->nErasedBlocks++;
5698                         dev->nFreeChunks += dev->nChunksPerBlock;
5699                 }
5700         }
5701
5702         startIterator = dev->internalStartBlock;
5703         endIterator = dev->internalEndBlock;
5704
5705         /* For each block.... */
5706         for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5707              blockIterator++) {
5708
5709                 YYIELD();
5710
5711                 YYIELD();
5712
5713                 blk = blockIterator;
5714
5715                 bi = yaffs_GetBlockInfo(dev, blk);
5716                 state = bi->blockState;
5717
5718                 deleted = 0;
5719
5720                 /* For each chunk in each block that needs scanning....*/
5721                 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5722                      state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5723                         /* Read the tags and decide what to do */
5724                         chunk = blk * dev->nChunksPerBlock + c;
5725
5726                         result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5727                                                         &tags);
5728
5729                         /* Let's have a good look at this chunk... */
5730
5731                         if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
5732                                 /* YAFFS1 only...
5733                                  * A deleted chunk
5734                                  */
5735                                 deleted++;
5736                                 dev->nFreeChunks++;
5737                                 /*T((" %d %d deleted\n",blk,c)); */
5738                         } else if (!tags.chunkUsed) {
5739                                 /* An unassigned chunk in the block
5740                                  * This means that either the block is empty or
5741                                  * this is the one being allocated from
5742                                  */
5743
5744                                 if (c == 0) {
5745                                         /* We're looking at the first chunk in the block so the block is unused */
5746                                         state = YAFFS_BLOCK_STATE_EMPTY;
5747                                         dev->nErasedBlocks++;
5748                                 } else {
5749                                         /* this is the block being allocated from */
5750                                         T(YAFFS_TRACE_SCAN,
5751                                           (TSTR
5752                                            (" Allocating from %d %d" TENDSTR),
5753                                            blk, c));
5754                                         state = YAFFS_BLOCK_STATE_ALLOCATING;
5755                                         dev->allocationBlock = blk;
5756                                         dev->allocationPage = c;
5757                                         dev->allocationBlockFinder = blk;
5758                                         /* Set it to here to encourage the allocator to go forth from here. */
5759
5760                                 }
5761
5762                                 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5763                         } else if (tags.chunkId > 0) {
5764                                 /* chunkId > 0 so it is a data chunk... */
5765                                 unsigned int endpos;
5766
5767                                 yaffs_SetChunkBit(dev, blk, c);
5768                                 bi->pagesInUse++;
5769
5770                                 in = yaffs_FindOrCreateObjectByNumber(dev,
5771                                                                       tags.
5772                                                                       objectId,
5773                                                                       YAFFS_OBJECT_TYPE_FILE);
5774                                 /* PutChunkIntoFile checks for a clash (two data chunks with
5775                                  * the same chunkId).
5776                                  */
5777
5778                                 if (!in)
5779                                         alloc_failed = 1;
5780
5781                                 if (in) {
5782                                         if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, 1))
5783                                                 alloc_failed = 1;
5784                                 }
5785
5786                                 endpos =
5787                                     (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5788                                     tags.byteCount;
5789                                 if (in &&
5790                                     in->variantType == YAFFS_OBJECT_TYPE_FILE
5791                                     && in->variant.fileVariant.scannedFileSize <
5792                                     endpos) {
5793                                         in->variant.fileVariant.
5794                                             scannedFileSize = endpos;
5795                                         if (!dev->useHeaderFileSize) {
5796                                                 in->variant.fileVariant.
5797                                                     fileSize =
5798                                                     in->variant.fileVariant.
5799                                                     scannedFileSize;
5800                                         }
5801
5802                                 }
5803                                 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));   */
5804                         } else {
5805                                 /* chunkId == 0, so it is an ObjectHeader.
5806                                  * Thus, we read in the object header and make the object
5807                                  */
5808                                 yaffs_SetChunkBit(dev, blk, c);
5809                                 bi->pagesInUse++;
5810
5811                                 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5812                                                                 chunkData,
5813                                                                 NULL);
5814
5815                                 oh = (yaffs_ObjectHeader *) chunkData;
5816
5817                                 in = yaffs_FindObjectByNumber(dev,
5818                                                               tags.objectId);
5819                                 if (in && in->variantType != oh->type) {
5820                                         /* This should not happen, but somehow
5821                                          * Wev'e ended up with an objectId that has been reused but not yet
5822                                          * deleted, and worse still it has changed type. Delete the old object.
5823                                          */
5824
5825                                         yaffs_DeleteObject(in);
5826
5827                                         in = 0;
5828                                 }
5829
5830                                 in = yaffs_FindOrCreateObjectByNumber(dev,
5831                                                                       tags.
5832                                                                       objectId,
5833                                                                       oh->type);
5834
5835                                 if (!in)
5836                                         alloc_failed = 1;
5837
5838                                 if (in && oh->shadowsObject > 0) {
5839
5840                                         struct yaffs_ShadowFixerStruct *fixer;
5841                                         fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
5842                                         if (fixer) {
5843                                                 fixer->next = shadowFixerList;
5844                                                 shadowFixerList = fixer;
5845                                                 fixer->objectId = tags.objectId;
5846                                                 fixer->shadowedId = oh->shadowsObject;
5847                                         }
5848
5849                                 }
5850
5851                                 if (in && in->valid) {
5852                                         /* We have already filled this one. We have a duplicate and need to resolve it. */
5853
5854                                         unsigned existingSerial = in->serial;
5855                                         unsigned newSerial = tags.serialNumber;
5856
5857                                         if (((existingSerial + 1) & 3) == newSerial) {
5858                                                 /* Use new one - destroy the exisiting one */
5859                                                 yaffs_DeleteChunk(dev,
5860                                                                   in->hdrChunk,
5861                                                                   1, __LINE__);
5862                                                 in->valid = 0;
5863                                         } else {
5864                                                 /* Use existing - destroy this one. */
5865                                                 yaffs_DeleteChunk(dev, chunk, 1,
5866                                                                   __LINE__);
5867                                         }
5868                                 }
5869
5870                                 if (in && !in->valid &&
5871                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
5872                                      tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5873                                         /* We only load some info, don't fiddle with directory structure */
5874                                         in->valid = 1;
5875                                         in->variantType = oh->type;
5876
5877                                         in->yst_mode = oh->yst_mode;
5878 #ifdef CONFIG_YAFFS_WINCE
5879                                         in->win_atime[0] = oh->win_atime[0];
5880                                         in->win_ctime[0] = oh->win_ctime[0];
5881                                         in->win_mtime[0] = oh->win_mtime[0];
5882                                         in->win_atime[1] = oh->win_atime[1];
5883                                         in->win_ctime[1] = oh->win_ctime[1];
5884                                         in->win_mtime[1] = oh->win_mtime[1];
5885 #else
5886                                         in->yst_uid = oh->yst_uid;
5887                                         in->yst_gid = oh->yst_gid;
5888                                         in->yst_atime = oh->yst_atime;
5889                                         in->yst_mtime = oh->yst_mtime;
5890                                         in->yst_ctime = oh->yst_ctime;
5891                                         in->yst_rdev = oh->yst_rdev;
5892 #endif
5893                                         in->hdrChunk = chunk;
5894                                         in->serial = tags.serialNumber;
5895
5896                                 } else if (in && !in->valid) {
5897                                         /* we need to load this info */
5898
5899                                         in->valid = 1;
5900                                         in->variantType = oh->type;
5901
5902                                         in->yst_mode = oh->yst_mode;
5903 #ifdef CONFIG_YAFFS_WINCE
5904                                         in->win_atime[0] = oh->win_atime[0];
5905                                         in->win_ctime[0] = oh->win_ctime[0];
5906                                         in->win_mtime[0] = oh->win_mtime[0];
5907                                         in->win_atime[1] = oh->win_atime[1];
5908                                         in->win_ctime[1] = oh->win_ctime[1];
5909                                         in->win_mtime[1] = oh->win_mtime[1];
5910 #else
5911                                         in->yst_uid = oh->yst_uid;
5912                                         in->yst_gid = oh->yst_gid;
5913                                         in->yst_atime = oh->yst_atime;
5914                                         in->yst_mtime = oh->yst_mtime;
5915                                         in->yst_ctime = oh->yst_ctime;
5916                                         in->yst_rdev = oh->yst_rdev;
5917 #endif
5918                                         in->hdrChunk = chunk;
5919                                         in->serial = tags.serialNumber;
5920
5921                                         yaffs_SetObjectName(in, oh->name);
5922                                         in->dirty = 0;
5923
5924                                         /* directory stuff...
5925                                          * hook up to parent
5926                                          */
5927
5928                                         parent =
5929                                             yaffs_FindOrCreateObjectByNumber
5930                                             (dev, oh->parentObjectId,
5931                                              YAFFS_OBJECT_TYPE_DIRECTORY);
5932                                         if (!parent)
5933                                                 alloc_failed = 1;
5934                                         if (parent && parent->variantType ==
5935                                             YAFFS_OBJECT_TYPE_UNKNOWN) {
5936                                                 /* Set up as a directory */
5937                                                 parent->variantType =
5938                                                         YAFFS_OBJECT_TYPE_DIRECTORY;
5939                                                 YINIT_LIST_HEAD(&parent->variant.
5940                                                                 directoryVariant.
5941                                                                 children);
5942                                         } else if (!parent || parent->variantType !=
5943                                                    YAFFS_OBJECT_TYPE_DIRECTORY) {
5944                                                 /* Hoosterman, another problem....
5945                                                  * We're trying to use a non-directory as a directory
5946                                                  */
5947
5948                                                 T(YAFFS_TRACE_ERROR,
5949                                                   (TSTR
5950                                                    ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
5951                                                     TENDSTR)));
5952                                                 parent = dev->lostNFoundDir;
5953                                         }
5954
5955                                         yaffs_AddObjectToDirectory(parent, in);
5956
5957                                         if (0 && (parent == dev->deletedDir ||
5958                                                   parent == dev->unlinkedDir)) {
5959                                                 in->deleted = 1;        /* If it is unlinked at start up then it wants deleting */
5960                                                 dev->nDeletedFiles++;
5961                                         }
5962                                         /* Note re hardlinks.
5963                                          * Since we might scan a hardlink before its equivalent object is scanned
5964                                          * we put them all in a list.
5965                                          * After scanning is complete, we should have all the objects, so we run through this
5966                                          * list and fix up all the chains.
5967                                          */
5968
5969                                         switch (in->variantType) {
5970                                         case YAFFS_OBJECT_TYPE_UNKNOWN:
5971                                                 /* Todo got a problem */
5972                                                 break;
5973                                         case YAFFS_OBJECT_TYPE_FILE:
5974                                                 if (dev->useHeaderFileSize)
5975
5976                                                         in->variant.fileVariant.
5977                                                             fileSize =
5978                                                             oh->fileSize;
5979
5980                                                 break;
5981                                         case YAFFS_OBJECT_TYPE_HARDLINK:
5982                                                 in->variant.hardLinkVariant.
5983                                                         equivalentObjectId =
5984                                                         oh->equivalentObjectId;
5985                                                 in->hardLinks.next =
5986                                                         (struct ylist_head *)
5987                                                         hardList;
5988                                                 hardList = in;
5989                                                 break;
5990                                         case YAFFS_OBJECT_TYPE_DIRECTORY:
5991                                                 /* Do nothing */
5992                                                 break;
5993                                         case YAFFS_OBJECT_TYPE_SPECIAL:
5994                                                 /* Do nothing */
5995                                                 break;
5996                                         case YAFFS_OBJECT_TYPE_SYMLINK:
5997                                                 in->variant.symLinkVariant.alias =
5998                                                     yaffs_CloneString(oh->alias);
5999                                                 if (!in->variant.symLinkVariant.alias)
6000                                                         alloc_failed = 1;
6001                                                 break;
6002                                         }
6003
6004 /*
6005                                         if (parent == dev->deletedDir) {
6006                                                 yaffs_DestroyObject(in);
6007                                                 bi->hasShrinkHeader = 1;
6008                                         }
6009 */
6010                                 }
6011                         }
6012                 }
6013
6014                 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6015                         /* If we got this far while scanning, then the block is fully allocated.*/
6016                         state = YAFFS_BLOCK_STATE_FULL;
6017                 }
6018
6019                 bi->blockState = state;
6020
6021                 /* Now let's see if it was dirty */
6022                 if (bi->pagesInUse == 0 &&
6023                     !bi->hasShrinkHeader &&
6024                     bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6025                         yaffs_BlockBecameDirty(dev, blk);
6026                 }
6027
6028         }
6029
6030
6031         /* Ok, we've done all the scanning.
6032          * Fix up the hard link chains.
6033          * We should now have scanned all the objects, now it's time to add these
6034          * hardlinks.
6035          */
6036
6037         yaffs_HardlinkFixup(dev, hardList);
6038
6039         /* Fix up any shadowed objects */
6040         {
6041                 struct yaffs_ShadowFixerStruct *fixer;
6042                 yaffs_Object *obj;
6043
6044                 while (shadowFixerList) {
6045                         fixer = shadowFixerList;
6046                         shadowFixerList = fixer->next;
6047                         /* Complete the rename transaction by deleting the shadowed object
6048                          * then setting the object header to unshadowed.
6049                          */
6050                         obj = yaffs_FindObjectByNumber(dev, fixer->shadowedId);
6051                         if (obj)
6052                                 yaffs_DeleteObject(obj);
6053
6054                         obj = yaffs_FindObjectByNumber(dev, fixer->objectId);
6055
6056                         if (obj)
6057                                 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6058
6059                         YFREE(fixer);
6060                 }
6061         }
6062
6063         yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6064
6065         if (alloc_failed)
6066                 return YAFFS_FAIL;
6067
6068         T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
6069
6070
6071         return YAFFS_OK;
6072 }
6073
6074 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
6075 {
6076         __u8 *chunkData;
6077         yaffs_ObjectHeader *oh;
6078         yaffs_Device *dev;
6079         yaffs_ExtendedTags tags;
6080         int result;
6081         int alloc_failed = 0;
6082
6083         if (!in)
6084                 return;
6085
6086         dev = in->myDev;
6087
6088 #if 0
6089         T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
6090                 in->objectId,
6091                 in->lazyLoaded ? "not yet" : "already"));
6092 #endif
6093
6094         if (in->lazyLoaded && in->hdrChunk > 0) {
6095                 in->lazyLoaded = 0;
6096                 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6097
6098                 result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
6099                 oh = (yaffs_ObjectHeader *) chunkData;
6100
6101                 in->yst_mode = oh->yst_mode;
6102 #ifdef CONFIG_YAFFS_WINCE
6103                 in->win_atime[0] = oh->win_atime[0];
6104                 in->win_ctime[0] = oh->win_ctime[0];
6105                 in->win_mtime[0] = oh->win_mtime[0];
6106                 in->win_atime[1] = oh->win_atime[1];
6107                 in->win_ctime[1] = oh->win_ctime[1];
6108                 in->win_mtime[1] = oh->win_mtime[1];
6109 #else
6110                 in->yst_uid = oh->yst_uid;
6111                 in->yst_gid = oh->yst_gid;
6112                 in->yst_atime = oh->yst_atime;
6113                 in->yst_mtime = oh->yst_mtime;
6114                 in->yst_ctime = oh->yst_ctime;
6115                 in->yst_rdev = oh->yst_rdev;
6116
6117 #endif
6118                 yaffs_SetObjectName(in, oh->name);
6119
6120                 if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6121                         in->variant.symLinkVariant.alias =
6122                                                     yaffs_CloneString(oh->alias);
6123                         if (!in->variant.symLinkVariant.alias)
6124                                 alloc_failed = 1; /* Not returned to caller */
6125                 }
6126
6127                 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6128         }
6129 }
6130
6131 static int yaffs_ScanBackwards(yaffs_Device *dev)
6132 {
6133         yaffs_ExtendedTags tags;
6134         int blk;
6135         int blockIterator;
6136         int startIterator;
6137         int endIterator;
6138         int nBlocksToScan = 0;
6139
6140         int chunk;
6141         int result;
6142         int c;
6143         int deleted;
6144         yaffs_BlockState state;
6145         yaffs_Object *hardList = NULL;
6146         yaffs_BlockInfo *bi;
6147         __u32 sequenceNumber;
6148         yaffs_ObjectHeader *oh;
6149         yaffs_Object *in;
6150         yaffs_Object *parent;
6151         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6152         int itsUnlinked;
6153         __u8 *chunkData;
6154
6155         int fileSize;
6156         int isShrink;
6157         int foundChunksInBlock;
6158         int equivalentObjectId;
6159         int alloc_failed = 0;
6160
6161
6162         yaffs_BlockIndex *blockIndex = NULL;
6163         int altBlockIndex = 0;
6164
6165         if (!dev->isYaffs2) {
6166                 T(YAFFS_TRACE_SCAN,
6167                   (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6168                 return YAFFS_FAIL;
6169         }
6170
6171         T(YAFFS_TRACE_SCAN,
6172           (TSTR
6173            ("yaffs_ScanBackwards starts  intstartblk %d intendblk %d..."
6174             TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6175
6176
6177         dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6178
6179         blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6180
6181         if (!blockIndex) {
6182                 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6183                 altBlockIndex = 1;
6184         }
6185
6186         if (!blockIndex) {
6187                 T(YAFFS_TRACE_SCAN,
6188                   (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6189                 return YAFFS_FAIL;
6190         }
6191
6192         dev->blocksInCheckpoint = 0;
6193
6194         chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6195
6196         /* Scan all the blocks to determine their state */
6197         for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6198                 bi = yaffs_GetBlockInfo(dev, blk);
6199                 yaffs_ClearChunkBits(dev, blk);
6200                 bi->pagesInUse = 0;
6201                 bi->softDeletions = 0;
6202
6203                 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6204
6205                 bi->blockState = state;
6206                 bi->sequenceNumber = sequenceNumber;
6207
6208                 if (bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6209                         bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6210                 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6211                         bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6212
6213                 T(YAFFS_TRACE_SCAN_DEBUG,
6214                   (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6215                    state, sequenceNumber));
6216
6217
6218                 if (state == YAFFS_BLOCK_STATE_CHECKPOINT) {
6219                         dev->blocksInCheckpoint++;
6220
6221                 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6222                         T(YAFFS_TRACE_BAD_BLOCKS,
6223                           (TSTR("block %d is bad" TENDSTR), blk));
6224                 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6225                         T(YAFFS_TRACE_SCAN_DEBUG,
6226                           (TSTR("Block empty " TENDSTR)));
6227                         dev->nErasedBlocks++;
6228                         dev->nFreeChunks += dev->nChunksPerBlock;
6229                 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6230
6231                         /* Determine the highest sequence number */
6232                         if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6233                             sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6234
6235                                 blockIndex[nBlocksToScan].seq = sequenceNumber;
6236                                 blockIndex[nBlocksToScan].block = blk;
6237
6238                                 nBlocksToScan++;
6239
6240                                 if (sequenceNumber >= dev->sequenceNumber)
6241                                         dev->sequenceNumber = sequenceNumber;
6242                         } else {
6243                                 /* TODO: Nasty sequence number! */
6244                                 T(YAFFS_TRACE_SCAN,
6245                                   (TSTR
6246                                    ("Block scanning block %d has bad sequence number %d"
6247                                     TENDSTR), blk, sequenceNumber));
6248
6249                         }
6250                 }
6251         }
6252
6253         T(YAFFS_TRACE_SCAN,
6254         (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6255
6256
6257
6258         YYIELD();
6259
6260         /* Sort the blocks */
6261 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6262         {
6263                 /* Use qsort now. */
6264                 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6265         }
6266 #else
6267         {
6268                 /* Dungy old bubble sort... */
6269
6270                 yaffs_BlockIndex temp;
6271                 int i;
6272                 int j;
6273
6274                 for (i = 0; i < nBlocksToScan; i++)
6275                         for (j = i + 1; j < nBlocksToScan; j++)
6276                                 if (blockIndex[i].seq > blockIndex[j].seq) {
6277                                         temp = blockIndex[j];
6278                                         blockIndex[j] = blockIndex[i];
6279                                         blockIndex[i] = temp;
6280                                 }
6281         }
6282 #endif
6283
6284         YYIELD();
6285
6286         T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6287
6288         /* Now scan the blocks looking at the data. */
6289         startIterator = 0;
6290         endIterator = nBlocksToScan - 1;
6291         T(YAFFS_TRACE_SCAN_DEBUG,
6292           (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6293
6294         /* For each block.... backwards */
6295         for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6296                         blockIterator--) {
6297                 /* Cooperative multitasking! This loop can run for so
6298                    long that watchdog timers expire. */
6299                 YYIELD();
6300
6301                 /* get the block to scan in the correct order */
6302                 blk = blockIndex[blockIterator].block;
6303
6304                 bi = yaffs_GetBlockInfo(dev, blk);
6305
6306
6307                 state = bi->blockState;
6308
6309                 deleted = 0;
6310
6311                 /* For each chunk in each block that needs scanning.... */
6312                 foundChunksInBlock = 0;
6313                 for (c = dev->nChunksPerBlock - 1;
6314                      !alloc_failed && c >= 0 &&
6315                      (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6316                       state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6317                         /* Scan backwards...
6318                          * Read the tags and decide what to do
6319                          */
6320
6321                         chunk = blk * dev->nChunksPerBlock + c;
6322
6323                         result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6324                                                         &tags);
6325
6326                         /* Let's have a good look at this chunk... */
6327
6328                         if (!tags.chunkUsed) {
6329                                 /* An unassigned chunk in the block.
6330                                  * If there are used chunks after this one, then
6331                                  * it is a chunk that was skipped due to failing the erased
6332                                  * check. Just skip it so that it can be deleted.
6333                                  * But, more typically, We get here when this is an unallocated
6334                                  * chunk and his means that either the block is empty or
6335                                  * this is the one being allocated from
6336                                  */
6337
6338                                 if (foundChunksInBlock) {
6339                                         /* This is a chunk that was skipped due to failing the erased check */
6340                                 } else if (c == 0) {
6341                                         /* We're looking at the first chunk in the block so the block is unused */
6342                                         state = YAFFS_BLOCK_STATE_EMPTY;
6343                                         dev->nErasedBlocks++;
6344                                 } else {
6345                                         if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6346                                             state == YAFFS_BLOCK_STATE_ALLOCATING) {
6347                                                 if (dev->sequenceNumber == bi->sequenceNumber) {
6348                                                         /* this is the block being allocated from */
6349
6350                                                         T(YAFFS_TRACE_SCAN,
6351                                                           (TSTR
6352                                                            (" Allocating from %d %d"
6353                                                             TENDSTR), blk, c));
6354
6355                                                         state = YAFFS_BLOCK_STATE_ALLOCATING;
6356                                                         dev->allocationBlock = blk;
6357                                                         dev->allocationPage = c;
6358                                                         dev->allocationBlockFinder = blk;
6359                                                 } else {
6360                                                         /* This is a partially written block that is not
6361                                                          * the current allocation block. This block must have
6362                                                          * had a write failure, so set up for retirement.
6363                                                          */
6364
6365                                                          /* bi->needsRetiring = 1; ??? TODO */
6366                                                          bi->gcPrioritise = 1;
6367
6368                                                          T(YAFFS_TRACE_ALWAYS,
6369                                                          (TSTR("Partially written block %d detected" TENDSTR),
6370                                                          blk));
6371                                                 }
6372                                         }
6373                                 }
6374
6375                                 dev->nFreeChunks++;
6376
6377                         } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED) {
6378                                 T(YAFFS_TRACE_SCAN,
6379                                   (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
6380                                   blk, c));
6381
6382                                   dev->nFreeChunks++;
6383
6384                         } else if (tags.chunkId > 0) {
6385                                 /* chunkId > 0 so it is a data chunk... */
6386                                 unsigned int endpos;
6387                                 __u32 chunkBase =
6388                                     (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6389
6390                                 foundChunksInBlock = 1;
6391
6392
6393                                 yaffs_SetChunkBit(dev, blk, c);
6394                                 bi->pagesInUse++;
6395
6396                                 in = yaffs_FindOrCreateObjectByNumber(dev,
6397                                                                       tags.
6398                                                                       objectId,
6399                                                                       YAFFS_OBJECT_TYPE_FILE);
6400                                 if (!in) {
6401                                         /* Out of memory */
6402                                         alloc_failed = 1;
6403                                 }
6404
6405                                 if (in &&
6406                                     in->variantType == YAFFS_OBJECT_TYPE_FILE
6407                                     && chunkBase <
6408                                     in->variant.fileVariant.shrinkSize) {
6409                                         /* This has not been invalidated by a resize */
6410                                         if (!yaffs_PutChunkIntoFile(in, tags.chunkId,
6411                                                                chunk, -1)) {
6412                                                 alloc_failed = 1;
6413                                         }
6414
6415                                         /* File size is calculated by looking at the data chunks if we have not
6416                                          * seen an object header yet. Stop this practice once we find an object header.
6417                                          */
6418                                         endpos =
6419                                             (tags.chunkId -
6420                                              1) * dev->nDataBytesPerChunk +
6421                                             tags.byteCount;
6422
6423                                         if (!in->valid &&       /* have not got an object header yet */
6424                                             in->variant.fileVariant.
6425                                             scannedFileSize < endpos) {
6426                                                 in->variant.fileVariant.
6427                                                     scannedFileSize = endpos;
6428                                                 in->variant.fileVariant.
6429                                                     fileSize =
6430                                                     in->variant.fileVariant.
6431                                                     scannedFileSize;
6432                                         }
6433
6434                                 } else if (in) {
6435                                         /* This chunk has been invalidated by a resize, so delete */
6436                                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6437
6438                                 }
6439                         } else {
6440                                 /* chunkId == 0, so it is an ObjectHeader.
6441                                  * Thus, we read in the object header and make the object
6442                                  */
6443                                 foundChunksInBlock = 1;
6444
6445                                 yaffs_SetChunkBit(dev, blk, c);
6446                                 bi->pagesInUse++;
6447
6448                                 oh = NULL;
6449                                 in = NULL;
6450
6451                                 if (tags.extraHeaderInfoAvailable) {
6452                                         in = yaffs_FindOrCreateObjectByNumber
6453                                             (dev, tags.objectId,
6454                                              tags.extraObjectType);
6455                                         if (!in)
6456                                                 alloc_failed = 1;
6457                                 }
6458
6459                                 if (!in ||
6460                                     (!in->valid && dev->disableLazyLoad) ||
6461                                     tags.extraShadows ||
6462                                     (!in->valid &&
6463                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
6464                                      tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))) {
6465
6466                                         /* If we don't have  valid info then we need to read the chunk
6467                                          * TODO In future we can probably defer reading the chunk and
6468                                          * living with invalid data until needed.
6469                                          */
6470
6471                                         result = yaffs_ReadChunkWithTagsFromNAND(dev,
6472                                                                         chunk,
6473                                                                         chunkData,
6474                                                                         NULL);
6475
6476                                         oh = (yaffs_ObjectHeader *) chunkData;
6477
6478                                         if (dev->inbandTags) {
6479                                                 /* Fix up the header if they got corrupted by inband tags */
6480                                                 oh->shadowsObject = oh->inbandShadowsObject;
6481                                                 oh->isShrink = oh->inbandIsShrink;
6482                                         }
6483
6484                                         if (!in) {
6485                                                 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6486                                                 if (!in)
6487                                                         alloc_failed = 1;
6488                                         }
6489
6490                                 }
6491
6492                                 if (!in) {
6493                                         /* TODO Hoosterman we have a problem! */
6494                                         T(YAFFS_TRACE_ERROR,
6495                                           (TSTR
6496                                            ("yaffs tragedy: Could not make object for object  %d at chunk %d during scan"
6497                                             TENDSTR), tags.objectId, chunk));
6498                                         continue;
6499                                 }
6500
6501                                 if (in->valid) {
6502                                         /* We have already filled this one.
6503                                          * We have a duplicate that will be discarded, but
6504                                          * we first have to suck out resize info if it is a file.
6505                                          */
6506
6507                                         if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6508                                              ((oh &&
6509                                                oh->type == YAFFS_OBJECT_TYPE_FILE) ||
6510                                               (tags.extraHeaderInfoAvailable  &&
6511                                                tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))) {
6512                                                 __u32 thisSize =
6513                                                     (oh) ? oh->fileSize : tags.
6514                                                     extraFileLength;
6515                                                 __u32 parentObjectId =
6516                                                     (oh) ? oh->
6517                                                     parentObjectId : tags.
6518                                                     extraParentObjectId;
6519
6520
6521                                                 isShrink =
6522                                                     (oh) ? oh->isShrink : tags.
6523                                                     extraIsShrinkHeader;
6524
6525                                                 /* If it is deleted (unlinked at start also means deleted)
6526                                                  * we treat the file size as being zeroed at this point.
6527                                                  */
6528                                                 if (parentObjectId ==
6529                                                     YAFFS_OBJECTID_DELETED
6530                                                     || parentObjectId ==
6531                                                     YAFFS_OBJECTID_UNLINKED) {
6532                                                         thisSize = 0;
6533                                                         isShrink = 1;
6534                                                 }
6535
6536                                                 if (isShrink &&
6537                                                     in->variant.fileVariant.
6538                                                     shrinkSize > thisSize) {
6539                                                         in->variant.fileVariant.
6540                                                             shrinkSize =
6541                                                             thisSize;
6542                                                 }
6543
6544                                                 if (isShrink)
6545                                                         bi->hasShrinkHeader = 1;
6546
6547                                         }
6548                                         /* Use existing - destroy this one. */
6549                                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6550
6551                                 }
6552
6553                                 if (!in->valid && in->variantType !=
6554                                     (oh ? oh->type : tags.extraObjectType))
6555                                         T(YAFFS_TRACE_ERROR, (
6556                                                 TSTR("yaffs tragedy: Bad object type, "
6557                                             TCONT("%d != %d, for object %d at chunk ")
6558                                             TCONT("%d during scan")
6559                                                 TENDSTR), oh ?
6560                                             oh->type : tags.extraObjectType,
6561                                             in->variantType, tags.objectId,
6562                                             chunk));
6563
6564                                 if (!in->valid &&
6565                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
6566                                      tags.objectId ==
6567                                      YAFFS_OBJECTID_LOSTNFOUND)) {
6568                                         /* We only load some info, don't fiddle with directory structure */
6569                                         in->valid = 1;
6570
6571                                         if (oh) {
6572                                                 in->variantType = oh->type;
6573
6574                                                 in->yst_mode = oh->yst_mode;
6575 #ifdef CONFIG_YAFFS_WINCE
6576                                                 in->win_atime[0] = oh->win_atime[0];
6577                                                 in->win_ctime[0] = oh->win_ctime[0];
6578                                                 in->win_mtime[0] = oh->win_mtime[0];
6579                                                 in->win_atime[1] = oh->win_atime[1];
6580                                                 in->win_ctime[1] = oh->win_ctime[1];
6581                                                 in->win_mtime[1] = oh->win_mtime[1];
6582 #else
6583                                                 in->yst_uid = oh->yst_uid;
6584                                                 in->yst_gid = oh->yst_gid;
6585                                                 in->yst_atime = oh->yst_atime;
6586                                                 in->yst_mtime = oh->yst_mtime;
6587                                                 in->yst_ctime = oh->yst_ctime;
6588                                                 in->yst_rdev = oh->yst_rdev;
6589
6590 #endif
6591                                         } else {
6592                                                 in->variantType = tags.extraObjectType;
6593                                                 in->lazyLoaded = 1;
6594                                         }
6595
6596                                         in->hdrChunk = chunk;
6597
6598                                 } else if (!in->valid) {
6599                                         /* we need to load this info */
6600
6601                                         in->valid = 1;
6602                                         in->hdrChunk = chunk;
6603
6604                                         if (oh) {
6605                                                 in->variantType = oh->type;
6606
6607                                                 in->yst_mode = oh->yst_mode;
6608 #ifdef CONFIG_YAFFS_WINCE
6609                                                 in->win_atime[0] = oh->win_atime[0];
6610                                                 in->win_ctime[0] = oh->win_ctime[0];
6611                                                 in->win_mtime[0] = oh->win_mtime[0];
6612                                                 in->win_atime[1] = oh->win_atime[1];
6613                                                 in->win_ctime[1] = oh->win_ctime[1];
6614                                                 in->win_mtime[1] = oh->win_mtime[1];
6615 #else
6616                                                 in->yst_uid = oh->yst_uid;
6617                                                 in->yst_gid = oh->yst_gid;
6618                                                 in->yst_atime = oh->yst_atime;
6619                                                 in->yst_mtime = oh->yst_mtime;
6620                                                 in->yst_ctime = oh->yst_ctime;
6621                                                 in->yst_rdev = oh->yst_rdev;
6622 #endif
6623
6624                                                 if (oh->shadowsObject > 0)
6625                                                         yaffs_HandleShadowedObject(dev,
6626                                                                            oh->
6627                                                                            shadowsObject,
6628                                                                            1);
6629
6630
6631                                                 yaffs_SetObjectName(in, oh->name);
6632                                                 parent =
6633                                                     yaffs_FindOrCreateObjectByNumber
6634                                                         (dev, oh->parentObjectId,
6635                                                          YAFFS_OBJECT_TYPE_DIRECTORY);
6636
6637                                                  fileSize = oh->fileSize;
6638                                                  isShrink = oh->isShrink;
6639                                                  equivalentObjectId = oh->equivalentObjectId;
6640
6641                                         } else {
6642                                                 in->variantType = tags.extraObjectType;
6643                                                 parent =
6644                                                     yaffs_FindOrCreateObjectByNumber
6645                                                         (dev, tags.extraParentObjectId,
6646                                                          YAFFS_OBJECT_TYPE_DIRECTORY);
6647                                                  fileSize = tags.extraFileLength;
6648                                                  isShrink = tags.extraIsShrinkHeader;
6649                                                  equivalentObjectId = tags.extraEquivalentObjectId;
6650                                                 in->lazyLoaded = 1;
6651
6652                                         }
6653                                         in->dirty = 0;
6654
6655                                         if (!parent)
6656                                                 alloc_failed = 1;
6657
6658                                         /* directory stuff...
6659                                          * hook up to parent
6660                                          */
6661
6662                                         if (parent && parent->variantType ==
6663                                             YAFFS_OBJECT_TYPE_UNKNOWN) {
6664                                                 /* Set up as a directory */
6665                                                 parent->variantType =
6666                                                         YAFFS_OBJECT_TYPE_DIRECTORY;
6667                                                 YINIT_LIST_HEAD(&parent->variant.
6668                                                         directoryVariant.
6669                                                         children);
6670                                         } else if (!parent || parent->variantType !=
6671                                                    YAFFS_OBJECT_TYPE_DIRECTORY) {
6672                                                 /* Hoosterman, another problem....
6673                                                  * We're trying to use a non-directory as a directory
6674                                                  */
6675
6676                                                 T(YAFFS_TRACE_ERROR,
6677                                                   (TSTR
6678                                                    ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6679                                                     TENDSTR)));
6680                                                 parent = dev->lostNFoundDir;
6681                                         }
6682
6683                                         yaffs_AddObjectToDirectory(parent, in);
6684
6685                                         itsUnlinked = (parent == dev->deletedDir) ||
6686                                                       (parent == dev->unlinkedDir);
6687
6688                                         if (isShrink) {
6689                                                 /* Mark the block as having a shrinkHeader */
6690                                                 bi->hasShrinkHeader = 1;
6691                                         }
6692
6693                                         /* Note re hardlinks.
6694                                          * Since we might scan a hardlink before its equivalent object is scanned
6695                                          * we put them all in a list.
6696                                          * After scanning is complete, we should have all the objects, so we run
6697                                          * through this list and fix up all the chains.
6698                                          */
6699
6700                                         switch (in->variantType) {
6701                                         case YAFFS_OBJECT_TYPE_UNKNOWN:
6702                                                 /* Todo got a problem */
6703                                                 break;
6704                                         case YAFFS_OBJECT_TYPE_FILE:
6705
6706                                                 if (in->variant.fileVariant.
6707                                                     scannedFileSize < fileSize) {
6708                                                         /* This covers the case where the file size is greater
6709                                                          * than where the data is
6710                                                          * This will happen if the file is resized to be larger
6711                                                          * than its current data extents.
6712                                                          */
6713                                                         in->variant.fileVariant.fileSize = fileSize;
6714                                                         in->variant.fileVariant.scannedFileSize =
6715                                                             in->variant.fileVariant.fileSize;
6716                                                 }
6717
6718                                                 if (isShrink &&
6719                                                     in->variant.fileVariant.shrinkSize > fileSize) {
6720                                                         in->variant.fileVariant.shrinkSize = fileSize;
6721                                                 }
6722
6723                                                 break;
6724                                         case YAFFS_OBJECT_TYPE_HARDLINK:
6725                                                 if (!itsUnlinked) {
6726                                                         in->variant.hardLinkVariant.equivalentObjectId =
6727                                                                 equivalentObjectId;
6728                                                         in->hardLinks.next =
6729                                                                 (struct ylist_head *) hardList;
6730                                                         hardList = in;
6731                                                 }
6732                                                 break;
6733                                         case YAFFS_OBJECT_TYPE_DIRECTORY:
6734                                                 /* Do nothing */
6735                                                 break;
6736                                         case YAFFS_OBJECT_TYPE_SPECIAL:
6737                                                 /* Do nothing */
6738                                                 break;
6739                                         case YAFFS_OBJECT_TYPE_SYMLINK:
6740                                                 if (oh) {
6741                                                         in->variant.symLinkVariant.alias =
6742                                                                 yaffs_CloneString(oh->alias);
6743                                                         if (!in->variant.symLinkVariant.alias)
6744                                                                 alloc_failed = 1;
6745                                                 }
6746                                                 break;
6747                                         }
6748
6749                                 }
6750
6751                         }
6752
6753                 } /* End of scanning for each chunk */
6754
6755                 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6756                         /* If we got this far while scanning, then the block is fully allocated. */
6757                         state = YAFFS_BLOCK_STATE_FULL;
6758                 }
6759
6760                 bi->blockState = state;
6761
6762                 /* Now let's see if it was dirty */
6763                 if (bi->pagesInUse == 0 &&
6764                     !bi->hasShrinkHeader &&
6765                     bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6766                         yaffs_BlockBecameDirty(dev, blk);
6767                 }
6768
6769         }
6770
6771         if (altBlockIndex)
6772                 YFREE_ALT(blockIndex);
6773         else
6774                 YFREE(blockIndex);
6775
6776         /* Ok, we've done all the scanning.
6777          * Fix up the hard link chains.
6778          * We should now have scanned all the objects, now it's time to add these
6779          * hardlinks.
6780          */
6781         yaffs_HardlinkFixup(dev, hardList);
6782
6783
6784         yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6785
6786         if (alloc_failed)
6787                 return YAFFS_FAIL;
6788
6789         T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6790
6791         return YAFFS_OK;
6792 }
6793
6794 /*------------------------------  Directory Functions ----------------------------- */
6795
6796 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
6797 {
6798         struct ylist_head *lh;
6799         yaffs_Object *listObj;
6800
6801         int count = 0;
6802
6803         if (!obj) {
6804                 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
6805                 YBUG();
6806                 return;
6807         }
6808
6809         if (yaffs_SkipVerification(obj->myDev))
6810                 return;
6811
6812         if (!obj->parent) {
6813                 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
6814                 YBUG();
6815                 return;
6816         }
6817
6818         if (obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6819                 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
6820                 YBUG();
6821         }
6822
6823         /* Iterate through the objects in each hash entry */
6824
6825         ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
6826                 if (lh) {
6827                         listObj = ylist_entry(lh, yaffs_Object, siblings);
6828                         yaffs_VerifyObject(listObj);
6829                         if (obj == listObj)
6830                                 count++;
6831                 }
6832          }
6833
6834         if (count != 1) {
6835                 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR), count));
6836                 YBUG();
6837         }
6838 }
6839
6840 static void yaffs_VerifyDirectory(yaffs_Object *directory)
6841 {
6842         struct ylist_head *lh;
6843         yaffs_Object *listObj;
6844
6845         if (!directory) {
6846                 YBUG();
6847                 return;
6848         }
6849
6850         if (yaffs_SkipFullVerification(directory->myDev))
6851                 return;
6852
6853         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6854                 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR), directory->variantType));
6855                 YBUG();
6856         }
6857
6858         /* Iterate through the objects in each hash entry */
6859
6860         ylist_for_each(lh, &directory->variant.directoryVariant.children) {
6861                 if (lh) {
6862                         listObj = ylist_entry(lh, yaffs_Object, siblings);
6863                         if (listObj->parent != directory) {
6864                                 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR), listObj->parent));
6865                                 YBUG();
6866                         }
6867                         yaffs_VerifyObjectInDirectory(listObj);
6868                 }
6869         }
6870 }
6871
6872 /*
6873  *yaffs_UpdateParent() handles fixing a directories mtime and ctime when a new
6874  * link (ie. name) is created or deleted in the directory.
6875  *
6876  * ie.
6877  *   create dir/a : update dir's mtime/ctime
6878  *   rm dir/a:   update dir's mtime/ctime
6879  *   modify dir/a: don't update dir's mtimme/ctime
6880  */
6881  
6882 static void yaffs_UpdateParent(yaffs_Object *obj)
6883 {
6884         if(!obj)
6885                 return;
6886
6887         obj->dirty = 1;
6888         obj->yst_mtime = obj->yst_ctime = Y_CURRENT_TIME;
6889
6890         yaffs_UpdateObjectHeader(obj,NULL,0,0,0);
6891 }
6892
6893 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
6894 {
6895         yaffs_Device *dev = obj->myDev;
6896         yaffs_Object *parent;
6897
6898         yaffs_VerifyObjectInDirectory(obj);
6899         parent = obj->parent;
6900
6901         yaffs_VerifyDirectory(parent);
6902
6903         if (dev && dev->removeObjectCallback)
6904                 dev->removeObjectCallback(obj);
6905
6906
6907         ylist_del_init(&obj->siblings);
6908         obj->parent = NULL;
6909         
6910         yaffs_VerifyDirectory(parent);
6911 }
6912
6913 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
6914                                         yaffs_Object *obj)
6915 {
6916         if (!directory) {
6917                 T(YAFFS_TRACE_ALWAYS,
6918                   (TSTR
6919                    ("tragedy: Trying to add an object to a null pointer directory"
6920                     TENDSTR)));
6921                 YBUG();
6922                 return;
6923         }
6924         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6925                 T(YAFFS_TRACE_ALWAYS,
6926                   (TSTR
6927                    ("tragedy: Trying to add an object to a non-directory"
6928                     TENDSTR)));
6929                 YBUG();
6930         }
6931
6932         if (obj->siblings.prev == NULL) {
6933                 /* Not initialised */
6934                 YBUG();
6935         }
6936
6937
6938         yaffs_VerifyDirectory(directory);
6939
6940         yaffs_RemoveObjectFromDirectory(obj);
6941
6942
6943         /* Now add it */
6944         ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
6945         obj->parent = directory;
6946
6947         if (directory == obj->myDev->unlinkedDir
6948                         || directory == obj->myDev->deletedDir) {
6949                 obj->unlinked = 1;
6950                 obj->myDev->nUnlinkedFiles++;
6951                 obj->renameAllowed = 0;
6952         }
6953
6954         yaffs_VerifyDirectory(directory);
6955         yaffs_VerifyObjectInDirectory(obj);
6956 }
6957
6958 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
6959                                      const YCHAR *name)
6960 {
6961         int sum;
6962
6963         struct ylist_head *i;
6964         YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
6965
6966         yaffs_Object *l;
6967
6968         if (!name)
6969                 return NULL;
6970
6971         if (!directory) {
6972                 T(YAFFS_TRACE_ALWAYS,
6973                   (TSTR
6974                    ("tragedy: yaffs_FindObjectByName: null pointer directory"
6975                     TENDSTR)));
6976                 YBUG();
6977                 return NULL;
6978         }
6979         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6980                 T(YAFFS_TRACE_ALWAYS,
6981                   (TSTR
6982                    ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
6983                 YBUG();
6984         }
6985
6986         sum = yaffs_CalcNameSum(name);
6987
6988         ylist_for_each(i, &directory->variant.directoryVariant.children) {
6989                 if (i) {
6990                         l = ylist_entry(i, yaffs_Object, siblings);
6991
6992                         if (l->parent != directory)
6993                                 YBUG();
6994
6995                         yaffs_CheckObjectDetailsLoaded(l);
6996
6997                         /* Special case for lost-n-found */
6998                         if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
6999                                 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
7000                                         return l;
7001                         } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
7002                                 /* LostnFound chunk called Objxxx
7003                                  * Do a real check
7004                                  */
7005                                 yaffs_GetObjectName(l, buffer,
7006                                                     YAFFS_MAX_NAME_LENGTH + 1);
7007                                 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
7008                                         return l;
7009                         }
7010                 }
7011         }
7012
7013         return NULL;
7014 }
7015
7016
7017 #if 0
7018 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
7019                                         int (*fn) (yaffs_Object *))
7020 {
7021         struct ylist_head *i;
7022         yaffs_Object *l;
7023
7024         if (!theDir) {
7025                 T(YAFFS_TRACE_ALWAYS,
7026                   (TSTR
7027                    ("tragedy: yaffs_FindObjectByName: null pointer directory"
7028                     TENDSTR)));
7029                 YBUG();
7030                 return YAFFS_FAIL;
7031         }
7032         if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7033                 T(YAFFS_TRACE_ALWAYS,
7034                   (TSTR
7035                    ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7036                 YBUG();
7037                 return YAFFS_FAIL;
7038         }
7039
7040         ylist_for_each(i, &theDir->variant.directoryVariant.children) {
7041                 if (i) {
7042                         l = ylist_entry(i, yaffs_Object, siblings);
7043                         if (l && !fn(l))
7044                                 return YAFFS_FAIL;
7045                 }
7046         }
7047
7048         return YAFFS_OK;
7049
7050 }
7051 #endif
7052
7053 /* GetEquivalentObject dereferences any hard links to get to the
7054  * actual object.
7055  */
7056
7057 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
7058 {
7059         if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
7060                 /* We want the object id of the equivalent object, not this one */
7061                 obj = obj->variant.hardLinkVariant.equivalentObject;
7062                 yaffs_CheckObjectDetailsLoaded(obj);
7063         }
7064         return obj;
7065 }
7066
7067 int yaffs_GetObjectName(yaffs_Object *obj, YCHAR *name, int buffSize)
7068 {
7069         memset(name, 0, buffSize * sizeof(YCHAR));
7070
7071         yaffs_CheckObjectDetailsLoaded(obj);
7072
7073         if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7074                 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
7075         } else if (obj->hdrChunk <= 0) {
7076                 YCHAR locName[20];
7077                 YCHAR numString[20];
7078                 YCHAR *x = &numString[19];
7079                 unsigned v = obj->objectId;
7080                 numString[19] = 0;
7081                 while (v > 0) {
7082                         x--;
7083                         *x = '0' + (v % 10);
7084                         v /= 10;
7085                 }
7086                 /* make up a name */
7087                 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
7088                 yaffs_strcat(locName, x);
7089                 yaffs_strncpy(name, locName, buffSize - 1);
7090
7091         }
7092 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
7093         else if (obj->shortName[0])
7094                 yaffs_strcpy(name, obj->shortName);
7095 #endif
7096         else {
7097                 int result;
7098                 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
7099
7100                 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
7101
7102                 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
7103
7104                 if (obj->hdrChunk > 0) {
7105                         result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
7106                                                         obj->hdrChunk, buffer,
7107                                                         NULL);
7108                 }
7109                 yaffs_strncpy(name, oh->name, buffSize - 1);
7110
7111                 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
7112         }
7113
7114         return yaffs_strlen(name);
7115 }
7116
7117 int yaffs_GetObjectFileLength(yaffs_Object *obj)
7118 {
7119         /* Dereference any hard linking */
7120         obj = yaffs_GetEquivalentObject(obj);
7121
7122         if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
7123                 return obj->variant.fileVariant.fileSize;
7124         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
7125                 if(!obj->variant.symLinkVariant.alias)
7126                         return 0;
7127                 return yaffs_strlen(obj->variant.symLinkVariant.alias);
7128         } else {
7129                 /* Only a directory should drop through to here */
7130                 return obj->myDev->nDataBytesPerChunk;
7131         }
7132 }
7133
7134 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
7135 {
7136         int count = 0;
7137         struct ylist_head *i;
7138
7139         if (!obj->unlinked)
7140                 count++;                /* the object itself */
7141
7142         ylist_for_each(i, &obj->hardLinks)
7143                 count++;                /* add the hard links; */
7144
7145         return count;
7146 }
7147
7148 int yaffs_GetObjectInode(yaffs_Object *obj)
7149 {
7150         obj = yaffs_GetEquivalentObject(obj);
7151
7152         return obj->objectId;
7153 }
7154
7155 unsigned yaffs_GetObjectType(yaffs_Object *obj)
7156 {
7157         obj = yaffs_GetEquivalentObject(obj);
7158
7159         switch (obj->variantType) {
7160         case YAFFS_OBJECT_TYPE_FILE:
7161                 return DT_REG;
7162                 break;
7163         case YAFFS_OBJECT_TYPE_DIRECTORY:
7164                 return DT_DIR;
7165                 break;
7166         case YAFFS_OBJECT_TYPE_SYMLINK:
7167                 return DT_LNK;
7168                 break;
7169         case YAFFS_OBJECT_TYPE_HARDLINK:
7170                 return DT_REG;
7171                 break;
7172         case YAFFS_OBJECT_TYPE_SPECIAL:
7173                 if (S_ISFIFO(obj->yst_mode))
7174                         return DT_FIFO;
7175                 if (S_ISCHR(obj->yst_mode))
7176                         return DT_CHR;
7177                 if (S_ISBLK(obj->yst_mode))
7178                         return DT_BLK;
7179                 if (S_ISSOCK(obj->yst_mode))
7180                         return DT_SOCK;
7181         default:
7182                 return DT_REG;
7183                 break;
7184         }
7185 }
7186
7187 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
7188 {
7189         obj = yaffs_GetEquivalentObject(obj);
7190         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
7191                 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7192         else
7193                 return yaffs_CloneString(_Y(""));
7194 }
7195
7196 #ifndef CONFIG_YAFFS_WINCE
7197
7198 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
7199 {
7200         unsigned int valid = attr->ia_valid;
7201
7202         if (valid & ATTR_MODE)
7203                 obj->yst_mode = attr->ia_mode;
7204         if (valid & ATTR_UID)
7205                 obj->yst_uid = attr->ia_uid;
7206         if (valid & ATTR_GID)
7207                 obj->yst_gid = attr->ia_gid;
7208
7209         if (valid & ATTR_ATIME)
7210                 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7211         if (valid & ATTR_CTIME)
7212                 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7213         if (valid & ATTR_MTIME)
7214                 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7215
7216         if (valid & ATTR_SIZE)
7217                 yaffs_ResizeFile(obj, attr->ia_size);
7218
7219         yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7220
7221         return YAFFS_OK;
7222
7223 }
7224 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
7225 {
7226         unsigned int valid = 0;
7227
7228         attr->ia_mode = obj->yst_mode;
7229         valid |= ATTR_MODE;
7230         attr->ia_uid = obj->yst_uid;
7231         valid |= ATTR_UID;
7232         attr->ia_gid = obj->yst_gid;
7233         valid |= ATTR_GID;
7234
7235         Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7236         valid |= ATTR_ATIME;
7237         Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7238         valid |= ATTR_CTIME;
7239         Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7240         valid |= ATTR_MTIME;
7241
7242         attr->ia_size = yaffs_GetFileSize(obj);
7243         valid |= ATTR_SIZE;
7244
7245         attr->ia_valid = valid;
7246
7247         return YAFFS_OK;
7248 }
7249
7250 #endif
7251
7252 #if 0
7253 int yaffs_DumpObject(yaffs_Object *obj)
7254 {
7255         YCHAR name[257];
7256
7257         yaffs_GetObjectName(obj, name, YAFFS_MAX_NAME_LENGTH + 1);
7258
7259         T(YAFFS_TRACE_ALWAYS,
7260           (TSTR
7261            ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7262             " chunk %d type %d size %d\n"
7263             TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7264            obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7265            yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7266
7267         return YAFFS_OK;
7268 }
7269 #endif
7270
7271 /*---------------------------- Initialisation code -------------------------------------- */
7272
7273 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
7274 {
7275
7276         /* Common functions, gotta have */
7277         if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
7278                 return 0;
7279
7280 #ifdef CONFIG_YAFFS_YAFFS2
7281
7282         /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7283         if (dev->writeChunkWithTagsToNAND &&
7284             dev->readChunkWithTagsFromNAND &&
7285             !dev->writeChunkToNAND &&
7286             !dev->readChunkFromNAND &&
7287             dev->markNANDBlockBad && dev->queryNANDBlock)
7288                 return 1;
7289 #endif
7290
7291         /* Can use the "spare" style interface for yaffs1 */
7292         if (!dev->isYaffs2 &&
7293             !dev->writeChunkWithTagsToNAND &&
7294             !dev->readChunkWithTagsFromNAND &&
7295             dev->writeChunkToNAND &&
7296             dev->readChunkFromNAND &&
7297             !dev->markNANDBlockBad && !dev->queryNANDBlock)
7298                 return 1;
7299
7300         return 0;               /* bad */
7301 }
7302
7303
7304 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7305 {
7306         /* Initialise the unlinked, deleted, root and lost and found directories */
7307
7308         dev->lostNFoundDir = dev->rootDir =  NULL;
7309         dev->unlinkedDir = dev->deletedDir = NULL;
7310
7311         dev->unlinkedDir =
7312             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7313
7314         dev->deletedDir =
7315             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7316
7317         dev->rootDir =
7318             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7319                                       YAFFS_ROOT_MODE | S_IFDIR);
7320         dev->lostNFoundDir =
7321             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7322                                       YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7323
7324         if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
7325                 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7326                 return YAFFS_OK;
7327         }
7328
7329         return YAFFS_FAIL;
7330 }
7331
7332 int yaffs_GutsInitialise(yaffs_Device *dev)
7333 {
7334         int init_failed = 0;
7335         unsigned x;
7336         int bits;
7337
7338         T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7339
7340         /* Check stuff that must be set */
7341
7342         if (!dev) {
7343                 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7344                 return YAFFS_FAIL;
7345         }
7346
7347         dev->internalStartBlock = dev->startBlock;
7348         dev->internalEndBlock = dev->endBlock;
7349         dev->blockOffset = 0;
7350         dev->chunkOffset = 0;
7351         dev->nFreeChunks = 0;
7352
7353         dev->gcBlock = -1;
7354
7355         if (dev->startBlock == 0) {
7356                 dev->internalStartBlock = dev->startBlock + 1;
7357                 dev->internalEndBlock = dev->endBlock + 1;
7358                 dev->blockOffset = 1;
7359                 dev->chunkOffset = dev->nChunksPerBlock;
7360         }
7361
7362         /* Check geometry parameters. */
7363
7364         if ((!dev->inbandTags && dev->isYaffs2 && dev->totalBytesPerChunk < 1024) ||
7365             (!dev->isYaffs2 && dev->totalBytesPerChunk < 512) ||
7366             (dev->inbandTags && !dev->isYaffs2) ||
7367              dev->nChunksPerBlock < 2 ||
7368              dev->nReservedBlocks < 2 ||
7369              dev->internalStartBlock <= 0 ||
7370              dev->internalEndBlock <= 0 ||
7371              dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2)) {   /* otherwise it is too small */
7372                 T(YAFFS_TRACE_ALWAYS,
7373                   (TSTR
7374                    ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7375                     TENDSTR), dev->totalBytesPerChunk, dev->isYaffs2 ? "2" : "", dev->inbandTags));
7376                 return YAFFS_FAIL;
7377         }
7378
7379         if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7380                 T(YAFFS_TRACE_ALWAYS,
7381                   (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7382                 return YAFFS_FAIL;
7383         }
7384
7385         /* Sort out space for inband tags, if required */
7386         if (dev->inbandTags)
7387                 dev->nDataBytesPerChunk = dev->totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7388         else
7389                 dev->nDataBytesPerChunk = dev->totalBytesPerChunk;
7390
7391         /* Got the right mix of functions? */
7392         if (!yaffs_CheckDevFunctions(dev)) {
7393                 /* Function missing */
7394                 T(YAFFS_TRACE_ALWAYS,
7395                   (TSTR
7396                    ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7397
7398                 return YAFFS_FAIL;
7399         }
7400
7401         /* This is really a compilation check. */
7402         if (!yaffs_CheckStructures()) {
7403                 T(YAFFS_TRACE_ALWAYS,
7404                   (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7405                 return YAFFS_FAIL;
7406         }
7407
7408         if (dev->isMounted) {
7409                 T(YAFFS_TRACE_ALWAYS,
7410                   (TSTR("yaffs: device already mounted\n" TENDSTR)));
7411                 return YAFFS_FAIL;
7412         }
7413
7414         /* Finished with most checks. One or two more checks happen later on too. */
7415
7416         dev->isMounted = 1;
7417
7418         /* OK now calculate a few things for the device */
7419
7420         /*
7421          *  Calculate all the chunk size manipulation numbers:
7422          */
7423         x = dev->nDataBytesPerChunk;
7424         /* We always use dev->chunkShift and dev->chunkDiv */
7425         dev->chunkShift = Shifts(x);
7426         x >>= dev->chunkShift;
7427         dev->chunkDiv = x;
7428         /* We only use chunk mask if chunkDiv is 1 */
7429         dev->chunkMask = (1<<dev->chunkShift) - 1;
7430
7431         /*
7432          * Calculate chunkGroupBits.
7433          * We need to find the next power of 2 > than internalEndBlock
7434          */
7435
7436         x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7437
7438         bits = ShiftsGE(x);
7439
7440         /* Set up tnode width if wide tnodes are enabled. */
7441         if (!dev->wideTnodesDisabled) {
7442                 /* bits must be even so that we end up with 32-bit words */
7443                 if (bits & 1)
7444                         bits++;
7445                 if (bits < 16)
7446                         dev->tnodeWidth = 16;
7447                 else
7448                         dev->tnodeWidth = bits;
7449         } else
7450                 dev->tnodeWidth = 16;
7451
7452         dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7453
7454         /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7455          * so if the bitwidth of the
7456          * chunk range we're using is greater than 16 we need
7457          * to figure out chunk shift and chunkGroupSize
7458          */
7459
7460         if (bits <= dev->tnodeWidth)
7461                 dev->chunkGroupBits = 0;
7462         else
7463                 dev->chunkGroupBits = bits - dev->tnodeWidth;
7464
7465
7466         dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7467
7468         if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7469                 /* We have a problem because the soft delete won't work if
7470                  * the chunk group size > chunks per block.
7471                  * This can be remedied by using larger "virtual blocks".
7472                  */
7473                 T(YAFFS_TRACE_ALWAYS,
7474                   (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7475
7476                 return YAFFS_FAIL;
7477         }
7478
7479         /* OK, we've finished verifying the device, lets continue with initialisation */
7480
7481         /* More device initialisation */
7482         dev->garbageCollections = 0;
7483         dev->passiveGarbageCollections = 0;
7484         dev->currentDirtyChecker = 0;
7485         dev->bufferedBlock = -1;
7486         dev->doingBufferedBlockRewrite = 0;
7487         dev->nDeletedFiles = 0;
7488         dev->nBackgroundDeletions = 0;
7489         dev->nUnlinkedFiles = 0;
7490         dev->eccFixed = 0;
7491         dev->eccUnfixed = 0;
7492         dev->tagsEccFixed = 0;
7493         dev->tagsEccUnfixed = 0;
7494         dev->nErasureFailures = 0;
7495         dev->nErasedBlocks = 0;
7496         dev->isDoingGC = 0;
7497         dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7498
7499         /* Initialise temporary buffers and caches. */
7500         if (!yaffs_InitialiseTempBuffers(dev))
7501                 init_failed = 1;
7502
7503         dev->srCache = NULL;
7504         dev->gcCleanupList = NULL;
7505
7506
7507         if (!init_failed &&
7508             dev->nShortOpCaches > 0) {
7509                 int i;
7510                 void *buf;
7511                 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7512
7513                 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
7514                         dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7515
7516                 dev->srCache =  YMALLOC(srCacheBytes);
7517
7518                 buf = (__u8 *) dev->srCache;
7519
7520                 if (dev->srCache)
7521                         memset(dev->srCache, 0, srCacheBytes);
7522
7523                 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7524                         dev->srCache[i].object = NULL;
7525                         dev->srCache[i].lastUse = 0;
7526                         dev->srCache[i].dirty = 0;
7527                         dev->srCache[i].data = buf = YMALLOC_DMA(dev->totalBytesPerChunk);
7528                 }
7529                 if (!buf)
7530                         init_failed = 1;
7531
7532                 dev->srLastUse = 0;
7533         }
7534
7535         dev->cacheHits = 0;
7536
7537         if (!init_failed) {
7538                 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7539                 if (!dev->gcCleanupList)
7540                         init_failed = 1;
7541         }
7542
7543         if (dev->isYaffs2)
7544                 dev->useHeaderFileSize = 1;
7545
7546         if (!init_failed && !yaffs_InitialiseBlocks(dev))
7547                 init_failed = 1;
7548
7549         yaffs_InitialiseTnodes(dev);
7550         yaffs_InitialiseObjects(dev);
7551
7552         if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7553                 init_failed = 1;
7554
7555
7556         if (!init_failed) {
7557                 /* Now scan the flash. */
7558                 if (dev->isYaffs2) {
7559                         if (yaffs_CheckpointRestore(dev)) {
7560                                 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7561                                 T(YAFFS_TRACE_ALWAYS,
7562                                   (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7563                         } else {
7564
7565                                 /* Clean up the mess caused by an aborted checkpoint load
7566                                  * and scan backwards.
7567                                  */
7568                                 yaffs_DeinitialiseBlocks(dev);
7569                                 yaffs_DeinitialiseTnodes(dev);
7570                                 yaffs_DeinitialiseObjects(dev);
7571
7572
7573                                 dev->nErasedBlocks = 0;
7574                                 dev->nFreeChunks = 0;
7575                                 dev->allocationBlock = -1;
7576                                 dev->allocationPage = -1;
7577                                 dev->nDeletedFiles = 0;
7578                                 dev->nUnlinkedFiles = 0;
7579                                 dev->nBackgroundDeletions = 0;
7580                                 dev->oldestDirtySequence = 0;
7581
7582                                 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7583                                         init_failed = 1;
7584
7585                                 yaffs_InitialiseTnodes(dev);
7586                                 yaffs_InitialiseObjects(dev);
7587
7588                                 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7589                                         init_failed = 1;
7590
7591                                 if (!init_failed && !yaffs_ScanBackwards(dev))
7592                                         init_failed = 1;
7593                         }
7594                 } else if (!yaffs_Scan(dev))
7595                                 init_failed = 1;
7596
7597                 yaffs_StripDeletedObjects(dev);
7598                 yaffs_FixHangingObjects(dev);
7599                 if(dev->emptyLostAndFound)
7600                         yaffs_EmptyLostAndFound(dev);
7601         }
7602
7603         if (init_failed) {
7604                 /* Clean up the mess */
7605                 T(YAFFS_TRACE_TRACING,
7606                   (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7607
7608                 yaffs_Deinitialise(dev);
7609                 return YAFFS_FAIL;
7610         }
7611
7612         /* Zero out stats */
7613         dev->nPageReads = 0;
7614         dev->nPageWrites = 0;
7615         dev->nBlockErasures = 0;
7616         dev->nGCCopies = 0;
7617         dev->nRetriedWrites = 0;
7618
7619         dev->nRetiredBlocks = 0;
7620
7621         yaffs_VerifyFreeChunks(dev);
7622         yaffs_VerifyBlocks(dev);
7623
7624         /* Clean up any aborted checkpoint data */
7625         if(!dev->isCheckpointed && dev->blocksInCheckpoint > 0)
7626                 yaffs_InvalidateCheckpoint(dev);
7627
7628         T(YAFFS_TRACE_TRACING,
7629           (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7630         return YAFFS_OK;
7631
7632 }
7633
7634 void yaffs_Deinitialise(yaffs_Device *dev)
7635 {
7636         if (dev->isMounted) {
7637                 int i;
7638
7639                 yaffs_DeinitialiseBlocks(dev);
7640                 yaffs_DeinitialiseTnodes(dev);
7641                 yaffs_DeinitialiseObjects(dev);
7642                 if (dev->nShortOpCaches > 0 &&
7643                     dev->srCache) {
7644
7645                         for (i = 0; i < dev->nShortOpCaches; i++) {
7646                                 if (dev->srCache[i].data)
7647                                         YFREE(dev->srCache[i].data);
7648                                 dev->srCache[i].data = NULL;
7649                         }
7650
7651                         YFREE(dev->srCache);
7652                         dev->srCache = NULL;
7653                 }
7654
7655                 YFREE(dev->gcCleanupList);
7656
7657                 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
7658                         YFREE(dev->tempBuffer[i].buffer);
7659
7660                 dev->isMounted = 0;
7661
7662                 if (dev->deinitialiseNAND)
7663                         dev->deinitialiseNAND(dev);
7664         }
7665 }
7666
7667 static int yaffs_CountFreeChunks(yaffs_Device *dev)
7668 {
7669         int nFree;
7670         int b;
7671
7672         yaffs_BlockInfo *blk;
7673
7674         for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7675                         b++) {
7676                 blk = yaffs_GetBlockInfo(dev, b);
7677
7678                 switch (blk->blockState) {
7679                 case YAFFS_BLOCK_STATE_EMPTY:
7680                 case YAFFS_BLOCK_STATE_ALLOCATING:
7681                 case YAFFS_BLOCK_STATE_COLLECTING:
7682                 case YAFFS_BLOCK_STATE_FULL:
7683                         nFree +=
7684                             (dev->nChunksPerBlock - blk->pagesInUse +
7685                              blk->softDeletions);
7686                         break;
7687                 default:
7688                         break;
7689                 }
7690         }
7691
7692         return nFree;
7693 }
7694
7695 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
7696 {
7697         /* This is what we report to the outside world */
7698
7699         int nFree;
7700         int nDirtyCacheChunks;
7701         int blocksForCheckpoint;
7702         int i;
7703
7704 #if 1
7705         nFree = dev->nFreeChunks;
7706 #else
7707         nFree = yaffs_CountFreeChunks(dev);
7708 #endif
7709
7710         nFree += dev->nDeletedFiles;
7711
7712         /* Now count the number of dirty chunks in the cache and subtract those */
7713
7714         for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7715                 if (dev->srCache[i].dirty)
7716                         nDirtyCacheChunks++;
7717         }
7718
7719         nFree -= nDirtyCacheChunks;
7720
7721         nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7722
7723         /* Now we figure out how much to reserve for the checkpoint and report that... */
7724         blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7725         if (blocksForCheckpoint < 0)
7726                 blocksForCheckpoint = 0;
7727
7728         nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7729
7730         if (nFree < 0)
7731                 nFree = 0;
7732
7733         return nFree;
7734
7735 }
7736
7737 static int yaffs_freeVerificationFailures;
7738
7739 static void yaffs_VerifyFreeChunks(yaffs_Device *dev)
7740 {
7741         int counted;
7742         int difference;
7743
7744         if (yaffs_SkipVerification(dev))
7745                 return;
7746
7747         counted = yaffs_CountFreeChunks(dev);
7748
7749         difference = dev->nFreeChunks - counted;
7750
7751         if (difference) {
7752                 T(YAFFS_TRACE_ALWAYS,
7753                   (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7754                    dev->nFreeChunks, counted, difference));
7755                 yaffs_freeVerificationFailures++;
7756         }
7757 }
7758
7759 /*---------------------------------------- YAFFS test code ----------------------*/
7760
7761 #define yaffs_CheckStruct(structure, syze, name) \
7762         do { \
7763                 if (sizeof(structure) != syze) { \
7764                         T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
7765                                 name, syze, sizeof(structure))); \
7766                         return YAFFS_FAIL; \
7767                 } \
7768         } while (0)
7769
7770 static int yaffs_CheckStructures(void)
7771 {
7772 /*      yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
7773 /*      yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
7774 /*      yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
7775 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7776         yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode");
7777 #endif
7778 #ifndef CONFIG_YAFFS_WINCE
7779         yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");
7780 #endif
7781         return YAFFS_OK;
7782 }