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