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