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