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