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