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