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