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