Fix pruning to work correctly with wide Tnodes
[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.101 2009-12-25 01:53:05 charles Exp $";
16
17 #include "yportenv.h"
18
19 #include "yaffsinterface.h"
20 #include "yaffs_guts.h"
21 #include "yaffs_tagsvalidity.h"
22 #include "yaffs_getblockinfo.h"
23
24 #include "yaffs_tagscompat.h"
25 #ifndef CONFIG_YAFFS_USE_OWN_SORT
26 #include "yaffs_qsort.h"
27 #endif
28 #include "yaffs_nand.h"
29
30 #include "yaffs_checkptrw.h"
31
32 #include "yaffs_nand.h"
33 #include "yaffs_packedtags2.h"
34
35
36 #define YAFFS_PASSIVE_GC_CHUNKS 2
37
38 #include "yaffs_ecc.h"
39
40
41 /* Robustification (if it ever comes about...) */
42 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND);
43 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
44                 int erasedOk);
45 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
46                                 const __u8 *data,
47                                 const yaffs_ExtendedTags *tags);
48 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
49                                 const yaffs_ExtendedTags *tags);
50
51 /* Other local prototypes */
52 static void yaffs_UpdateParent(yaffs_Object *obj);
53 static int yaffs_UnlinkObject(yaffs_Object *obj);
54 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
55
56 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
57
58 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev,
59                                         const __u8 *buffer,
60                                         yaffs_ExtendedTags *tags,
61                                         int useReserve);
62 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
63                                 int chunkInNAND, int inScan);
64
65 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
66                                         yaffs_ObjectType type);
67 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
68                                 yaffs_Object *obj);
69 static int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name,
70                                 int force, int isShrink, int shadows);
71 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
72 static int yaffs_CheckStructures(void);
73 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
74                         int chunkOffset, int *limit);
75 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
76
77 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev, int blockNo);
78
79
80 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
81                                 int chunkInNAND);
82
83 static int yaffs_UnlinkWorker(yaffs_Object *obj);
84
85 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
86                         int chunkInObject);
87
88 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
89                                 yaffs_BlockInfo **blockUsedPtr);
90
91 static void yaffs_VerifyFreeChunks(yaffs_Device *dev);
92
93 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
94
95 static void yaffs_VerifyDirectory(yaffs_Object *directory);
96 #ifdef YAFFS_PARANOID
97 static int yaffs_CheckFileSanity(yaffs_Object *in);
98 #else
99 #define yaffs_CheckFileSanity(in)
100 #endif
101
102 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
103 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
104
105 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
106
107 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
108                                 yaffs_ExtendedTags *tags);
109
110 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
111                 unsigned pos);
112 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
113                                         yaffs_FileStructure *fStruct,
114                                         __u32 chunkId);
115
116 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                 if(level > 0){
1822                         for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1823                                 if (tn->internal[i]) {
1824                                         tn->internal[i] =
1825                                                 yaffs_PruneWorker(dev, tn->internal[i],
1826                                                         level - 1,
1827                                                         (i == 0) ? del0 : 1);
1828                                 }
1829
1830                                 if (tn->internal[i])
1831                                         hasData++;
1832                         }
1833                 } else {
1834                         int tnodeSize;
1835                         __u32 *map = (__u32 *)tn;
1836                         tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1837
1838                         if (tnodeSize < sizeof(yaffs_Tnode))
1839                                 tnodeSize = sizeof(yaffs_Tnode);
1840                         tnodeSize /= sizeof(__u32);
1841
1842                         for(i = 0; !hasData && i < tnodeSize; i++){
1843                                 if(map[i])
1844                                         hasData++;
1845                         }
1846                 }
1847
1848                 if (hasData == 0 && del0) {
1849                         /* Free and return NULL */
1850
1851                         yaffs_FreeTnode(dev, tn);
1852                         tn = NULL;
1853                 }
1854
1855         }
1856
1857         return tn;
1858
1859 }
1860
1861 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1862                                 yaffs_FileStructure *fStruct)
1863 {
1864         int i;
1865         int hasData;
1866         int done = 0;
1867         yaffs_Tnode *tn;
1868
1869         if (fStruct->topLevel > 0) {
1870                 fStruct->top =
1871                     yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1872
1873                 /* Now we have a tree with all the non-zero branches NULL but the height
1874                  * is the same as it was.
1875                  * Let's see if we can trim internal tnodes to shorten the tree.
1876                  * We can do this if only the 0th element in the tnode is in use
1877                  * (ie all the non-zero are NULL)
1878                  */
1879
1880                 while (fStruct->topLevel && !done) {
1881                         tn = fStruct->top;
1882
1883                         hasData = 0;
1884                         for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1885                                 if (tn->internal[i])
1886                                         hasData++;
1887                         }
1888
1889                         if (!hasData) {
1890                                 fStruct->top = tn->internal[0];
1891                                 fStruct->topLevel--;
1892                                 yaffs_FreeTnode(dev, tn);
1893                         } else {
1894                                 done = 1;
1895                         }
1896                 }
1897         }
1898
1899         return YAFFS_OK;
1900 }
1901
1902 /*-------------------- End of File Structure functions.-------------------*/
1903
1904 /* yaffs_CreateFreeObjects creates a bunch more objects and
1905  * adds them to the object free list.
1906  */
1907 static int yaffs_CreateFreeObjects(yaffs_Device *dev, int nObjects)
1908 {
1909         int i;
1910         yaffs_Object *newObjects;
1911         yaffs_ObjectList *list;
1912
1913         if (nObjects < 1)
1914                 return YAFFS_OK;
1915
1916         /* make these things */
1917         newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1918         list = YMALLOC(sizeof(yaffs_ObjectList));
1919
1920         if (!newObjects || !list) {
1921                 if (newObjects){
1922                         YFREE(newObjects);
1923                         newObjects = NULL;
1924                 }
1925                 if (list){
1926                         YFREE(list);
1927                         list = NULL;
1928                 }
1929                 T(YAFFS_TRACE_ALLOCATE,
1930                   (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1931                 return YAFFS_FAIL;
1932         }
1933
1934         /* Hook them into the free list */
1935         for (i = 0; i < nObjects - 1; i++) {
1936                 newObjects[i].siblings.next =
1937                                 (struct ylist_head *)(&newObjects[i + 1]);
1938         }
1939
1940         newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1941         dev->freeObjects = newObjects;
1942         dev->nFreeObjects += nObjects;
1943         dev->nObjectsCreated += nObjects;
1944
1945         /* Now add this bunch of Objects to a list for freeing up. */
1946
1947         list->objects = newObjects;
1948         list->next = dev->allocatedObjectList;
1949         dev->allocatedObjectList = list;
1950
1951         return YAFFS_OK;
1952 }
1953
1954
1955 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1956 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1957 {
1958         yaffs_Object *tn = NULL;
1959
1960 #ifdef VALGRIND_TEST
1961         tn = YMALLOC(sizeof(yaffs_Object));
1962 #else
1963         /* If there are none left make more */
1964         if (!dev->freeObjects)
1965                 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1966
1967         if (dev->freeObjects) {
1968                 tn = dev->freeObjects;
1969                 dev->freeObjects =
1970                         (yaffs_Object *) (dev->freeObjects->siblings.next);
1971                 dev->nFreeObjects--;
1972         }
1973 #endif
1974         if (tn) {
1975                 /* Now sweeten it up... */
1976
1977                 memset(tn, 0, sizeof(yaffs_Object));
1978                 tn->beingCreated = 1;
1979
1980                 tn->myDev = dev;
1981                 tn->hdrChunk = 0;
1982                 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1983                 YINIT_LIST_HEAD(&(tn->hardLinks));
1984                 YINIT_LIST_HEAD(&(tn->hashLink));
1985                 YINIT_LIST_HEAD(&tn->siblings);
1986
1987
1988                 /* Now make the directory sane */
1989                 if (dev->rootDir) {
1990                         tn->parent = dev->rootDir;
1991                         ylist_add(&(tn->siblings), &dev->rootDir->variant.directoryVariant.children);
1992                 }
1993
1994                 /* Add it to the lost and found directory.
1995                  * NB Can't put root or lostNFound in lostNFound so
1996                  * check if lostNFound exists first
1997                  */
1998                 if (dev->lostNFoundDir)
1999                         yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
2000
2001                 tn->beingCreated = 0;
2002         }
2003
2004         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2005
2006         return tn;
2007 }
2008
2009 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
2010                                                __u32 mode)
2011 {
2012
2013         yaffs_Object *obj =
2014             yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
2015         if (obj) {
2016                 obj->fake = 1;          /* it is fake so it might have no NAND presence... */
2017                 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
2018                 obj->unlinkAllowed = 0; /* ... or unlink it */
2019                 obj->deleted = 0;
2020                 obj->unlinked = 0;
2021                 obj->yst_mode = mode;
2022                 obj->myDev = dev;
2023                 obj->hdrChunk = 0;      /* Not a valid chunk. */
2024         }
2025
2026         return obj;
2027
2028 }
2029
2030 static void yaffs_UnhashObject(yaffs_Object *tn)
2031 {
2032         int bucket;
2033         yaffs_Device *dev = tn->myDev;
2034
2035         /* If it is still linked into the bucket list, free from the list */
2036         if (!ylist_empty(&tn->hashLink)) {
2037                 ylist_del_init(&tn->hashLink);
2038                 bucket = yaffs_HashFunction(tn->objectId);
2039                 dev->objectBucket[bucket].count--;
2040         }
2041 }
2042
2043 /*  FreeObject frees up a Object and puts it back on the free list */
2044 static void yaffs_FreeObject(yaffs_Object *tn)
2045 {
2046         yaffs_Device *dev = tn->myDev;
2047
2048 #ifdef __KERNEL__
2049         T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), tn, tn->myInode));
2050 #endif
2051
2052         if (tn->parent)
2053                 YBUG();
2054         if (!ylist_empty(&tn->siblings))
2055                 YBUG();
2056
2057
2058 #ifdef __KERNEL__
2059         if (tn->myInode) {
2060                 /* We're still hooked up to a cached inode.
2061                  * Don't delete now, but mark for later deletion
2062                  */
2063                 tn->deferedFree = 1;
2064                 return;
2065         }
2066 #endif
2067
2068         yaffs_UnhashObject(tn);
2069
2070 #ifdef VALGRIND_TEST
2071         YFREE(tn);
2072         tn = NULL;
2073 #else
2074         /* Link into the free list. */
2075         tn->siblings.next = (struct ylist_head *)(dev->freeObjects);
2076         dev->freeObjects = tn;
2077         dev->nFreeObjects++;
2078 #endif
2079         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
2080 }
2081
2082 #ifdef __KERNEL__
2083
2084 void yaffs_HandleDeferedFree(yaffs_Object *obj)
2085 {
2086         if (obj->deferedFree)
2087                 yaffs_FreeObject(obj);
2088 }
2089
2090 #endif
2091
2092 static void yaffs_DeinitialiseObjects(yaffs_Device *dev)
2093 {
2094         /* Free the list of allocated Objects */
2095
2096         yaffs_ObjectList *tmp;
2097
2098         while (dev->allocatedObjectList) {
2099                 tmp = dev->allocatedObjectList->next;
2100                 YFREE(dev->allocatedObjectList->objects);
2101                 YFREE(dev->allocatedObjectList);
2102
2103                 dev->allocatedObjectList = tmp;
2104         }
2105
2106         dev->freeObjects = NULL;
2107         dev->nFreeObjects = 0;
2108 }
2109
2110 static void yaffs_InitialiseObjects(yaffs_Device *dev)
2111 {
2112         int i;
2113
2114         dev->allocatedObjectList = NULL;
2115         dev->freeObjects = NULL;
2116         dev->nFreeObjects = 0;
2117
2118         for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2119                 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
2120                 dev->objectBucket[i].count = 0;
2121         }
2122 }
2123
2124 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
2125 {
2126         static int x;
2127         int i;
2128         int l = 999;
2129         int lowest = 999999;
2130
2131         /* First let's see if we can find one that's empty. */
2132
2133         for (i = 0; i < 10 && lowest > 0; i++) {
2134                 x++;
2135                 x %= YAFFS_NOBJECT_BUCKETS;
2136                 if (dev->objectBucket[x].count < lowest) {
2137                         lowest = dev->objectBucket[x].count;
2138                         l = x;
2139                 }
2140
2141         }
2142
2143         /* If we didn't find an empty list, then try
2144          * looking a bit further for a short one
2145          */
2146
2147         for (i = 0; i < 10 && lowest > 3; i++) {
2148                 x++;
2149                 x %= YAFFS_NOBJECT_BUCKETS;
2150                 if (dev->objectBucket[x].count < lowest) {
2151                         lowest = dev->objectBucket[x].count;
2152                         l = x;
2153                 }
2154
2155         }
2156
2157         return l;
2158 }
2159
2160 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
2161 {
2162         int bucket = yaffs_FindNiceObjectBucket(dev);
2163
2164         /* Now find an object value that has not already been taken
2165          * by scanning the list.
2166          */
2167
2168         int found = 0;
2169         struct ylist_head *i;
2170
2171         __u32 n = (__u32) bucket;
2172
2173         /* yaffs_CheckObjectHashSanity();  */
2174
2175         while (!found) {
2176                 found = 1;
2177                 n += YAFFS_NOBJECT_BUCKETS;
2178                 if (1 || dev->objectBucket[bucket].count > 0) {
2179                         ylist_for_each(i, &dev->objectBucket[bucket].list) {
2180                                 /* If there is already one in the list */
2181                                 if (i && ylist_entry(i, yaffs_Object,
2182                                                 hashLink)->objectId == n) {
2183                                         found = 0;
2184                                 }
2185                         }
2186                 }
2187         }
2188
2189         return n;
2190 }
2191
2192 static void yaffs_HashObject(yaffs_Object *in)
2193 {
2194         int bucket = yaffs_HashFunction(in->objectId);
2195         yaffs_Device *dev = in->myDev;
2196
2197         ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
2198         dev->objectBucket[bucket].count++;
2199 }
2200
2201 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
2202 {
2203         int bucket = yaffs_HashFunction(number);
2204         struct ylist_head *i;
2205         yaffs_Object *in;
2206
2207         ylist_for_each(i, &dev->objectBucket[bucket].list) {
2208                 /* Look if it is in the list */
2209                 if (i) {
2210                         in = ylist_entry(i, yaffs_Object, hashLink);
2211                         if (in->objectId == number) {
2212 #ifdef __KERNEL__
2213                                 /* Don't tell the VFS about this one if it is defered free */
2214                                 if (in->deferedFree)
2215                                         return NULL;
2216 #endif
2217
2218                                 return in;
2219                         }
2220                 }
2221         }
2222
2223         return NULL;
2224 }
2225
2226 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
2227                                     yaffs_ObjectType type)
2228 {
2229         yaffs_Object *theObject;
2230         yaffs_Tnode *tn = NULL;
2231
2232         if (number < 0)
2233                 number = yaffs_CreateNewObjectNumber(dev);
2234
2235         if (type == YAFFS_OBJECT_TYPE_FILE) {
2236                 tn = yaffs_GetTnode(dev);
2237                 if (!tn)
2238                         return NULL;
2239         }
2240
2241         theObject = yaffs_AllocateEmptyObject(dev);
2242         if (!theObject){
2243                 if(tn)
2244                         yaffs_FreeTnode(dev,tn);
2245                 return NULL;
2246         }
2247
2248
2249         if (theObject) {
2250                 theObject->fake = 0;
2251                 theObject->renameAllowed = 1;
2252                 theObject->unlinkAllowed = 1;
2253                 theObject->objectId = number;
2254                 yaffs_HashObject(theObject);
2255                 theObject->variantType = type;
2256 #ifdef CONFIG_YAFFS_WINCE
2257                 yfsd_WinFileTimeNow(theObject->win_atime);
2258                 theObject->win_ctime[0] = theObject->win_mtime[0] =
2259                     theObject->win_atime[0];
2260                 theObject->win_ctime[1] = theObject->win_mtime[1] =
2261                     theObject->win_atime[1];
2262
2263 #else
2264
2265                 theObject->yst_atime = theObject->yst_mtime =
2266                     theObject->yst_ctime = Y_CURRENT_TIME;
2267 #endif
2268                 switch (type) {
2269                 case YAFFS_OBJECT_TYPE_FILE:
2270                         theObject->variant.fileVariant.fileSize = 0;
2271                         theObject->variant.fileVariant.scannedFileSize = 0;
2272                         theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2273                         theObject->variant.fileVariant.topLevel = 0;
2274                         theObject->variant.fileVariant.top = tn;
2275                         break;
2276                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2277                         YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
2278                                         children);
2279                         break;
2280                 case YAFFS_OBJECT_TYPE_SYMLINK:
2281                 case YAFFS_OBJECT_TYPE_HARDLINK:
2282                 case YAFFS_OBJECT_TYPE_SPECIAL:
2283                         /* No action required */
2284                         break;
2285                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2286                         /* todo this should not happen */
2287                         break;
2288                 }
2289         }
2290
2291         return theObject;
2292 }
2293
2294 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
2295                                                       int number,
2296                                                       yaffs_ObjectType type)
2297 {
2298         yaffs_Object *theObject = NULL;
2299
2300         if (number > 0)
2301                 theObject = yaffs_FindObjectByNumber(dev, number);
2302
2303         if (!theObject)
2304                 theObject = yaffs_CreateNewObject(dev, number, type);
2305
2306         return theObject;
2307
2308 }
2309
2310
2311 static YCHAR *yaffs_CloneString(const YCHAR *str)
2312 {
2313         YCHAR *newStr = NULL;
2314         int len;
2315
2316         if (!str)
2317                 str = _Y("");
2318
2319         len = yaffs_strnlen(str,YAFFS_MAX_ALIAS_LENGTH);
2320         newStr = YMALLOC((len + 1) * sizeof(YCHAR));
2321         if (newStr){
2322                 yaffs_strncpy(newStr, str,len);
2323                 newStr[len] = 0;
2324         }
2325         return newStr;
2326
2327 }
2328
2329 /*
2330  * Mknod (create) a new object.
2331  * equivalentObject only has meaning for a hard link;
2332  * aliasString only has meaning for a symlink.
2333  * rdev only has meaning for devices (a subset of special objects)
2334  */
2335
2336 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2337                                        yaffs_Object *parent,
2338                                        const YCHAR *name,
2339                                        __u32 mode,
2340                                        __u32 uid,
2341                                        __u32 gid,
2342                                        yaffs_Object *equivalentObject,
2343                                        const YCHAR *aliasString, __u32 rdev)
2344 {
2345         yaffs_Object *in;
2346         YCHAR *str = NULL;
2347
2348         yaffs_Device *dev = parent->myDev;
2349
2350         /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2351         if (yaffs_FindObjectByName(parent, name))
2352                 return NULL;
2353
2354         if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
2355                 str = yaffs_CloneString(aliasString);
2356                 if (!str)
2357                         return NULL;
2358         }
2359
2360         in = yaffs_CreateNewObject(dev, -1, type);
2361
2362         if (!in){
2363                 if(str)
2364                         YFREE(str);
2365                 return NULL;
2366         }
2367
2368
2369
2370
2371         if (in) {
2372                 in->hdrChunk = 0;
2373                 in->valid = 1;
2374                 in->variantType = type;
2375
2376                 in->yst_mode = mode;
2377
2378 #ifdef CONFIG_YAFFS_WINCE
2379                 yfsd_WinFileTimeNow(in->win_atime);
2380                 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2381                 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2382
2383 #else
2384                 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2385
2386                 in->yst_rdev = rdev;
2387                 in->yst_uid = uid;
2388                 in->yst_gid = gid;
2389 #endif
2390                 in->nDataChunks = 0;
2391
2392                 yaffs_SetObjectName(in, name);
2393                 in->dirty = 1;
2394
2395                 yaffs_AddObjectToDirectory(parent, in);
2396
2397                 in->myDev = parent->myDev;
2398
2399                 switch (type) {
2400                 case YAFFS_OBJECT_TYPE_SYMLINK:
2401                         in->variant.symLinkVariant.alias = str;
2402                         break;
2403                 case YAFFS_OBJECT_TYPE_HARDLINK:
2404                         in->variant.hardLinkVariant.equivalentObject =
2405                                 equivalentObject;
2406                         in->variant.hardLinkVariant.equivalentObjectId =
2407                                 equivalentObject->objectId;
2408                         ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
2409                         break;
2410                 case YAFFS_OBJECT_TYPE_FILE:
2411                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2412                 case YAFFS_OBJECT_TYPE_SPECIAL:
2413                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2414                         /* do nothing */
2415                         break;
2416                 }
2417
2418                 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2419                         /* Could not create the object header, fail the creation */
2420                         yaffs_DeleteObject(in);
2421                         in = NULL;
2422                 }
2423
2424                 yaffs_UpdateParent(parent);
2425         }
2426
2427         return in;
2428 }
2429
2430 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
2431                         __u32 mode, __u32 uid, __u32 gid)
2432 {
2433         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2434                                 uid, gid, NULL, NULL, 0);
2435 }
2436
2437 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
2438                                 __u32 mode, __u32 uid, __u32 gid)
2439 {
2440         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2441                                  mode, uid, gid, NULL, NULL, 0);
2442 }
2443
2444 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
2445                                 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2446 {
2447         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2448                                  uid, gid, NULL, NULL, rdev);
2449 }
2450
2451 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
2452                                 __u32 mode, __u32 uid, __u32 gid,
2453                                 const YCHAR *alias)
2454 {
2455         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2456                                 uid, gid, NULL, alias, 0);
2457 }
2458
2459 /* yaffs_Link returns the object id of the equivalent object.*/
2460 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
2461                         yaffs_Object *equivalentObject)
2462 {
2463         /* Get the real object in case we were fed a hard link as an equivalent object */
2464         equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2465
2466         if (yaffs_MknodObject
2467             (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2468              equivalentObject, NULL, 0)) {
2469                 return equivalentObject;
2470         } else {
2471                 return NULL;
2472         }
2473
2474 }
2475
2476 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
2477                                 const YCHAR *newName, int force, int shadows)
2478 {
2479         int unlinkOp;
2480         int deleteOp;
2481
2482         yaffs_Object *existingTarget;
2483
2484         if (newDir == NULL)
2485                 newDir = obj->parent;   /* use the old directory */
2486
2487         if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2488                 T(YAFFS_TRACE_ALWAYS,
2489                   (TSTR
2490                    ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
2491                     TENDSTR)));
2492                 YBUG();
2493         }
2494
2495         /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2496         if (obj->myDev->isYaffs2)
2497                 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2498         else
2499                 unlinkOp = (newDir == obj->myDev->unlinkedDir
2500                             && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2501
2502         deleteOp = (newDir == obj->myDev->deletedDir);
2503
2504         existingTarget = yaffs_FindObjectByName(newDir, newName);
2505
2506         /* If the object is a file going into the unlinked directory,
2507          *   then it is OK to just stuff it in since duplicate names are allowed.
2508          *   else only proceed if the new name does not exist and if we're putting
2509          *   it into a directory.
2510          */
2511         if ((unlinkOp ||
2512              deleteOp ||
2513              force ||
2514              (shadows > 0) ||
2515              !existingTarget) &&
2516             newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2517                 yaffs_SetObjectName(obj, newName);
2518                 obj->dirty = 1;
2519
2520                 yaffs_AddObjectToDirectory(newDir, obj);
2521
2522                 if (unlinkOp)
2523                         obj->unlinked = 1;
2524
2525                 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2526                 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows) >= 0)
2527                         return YAFFS_OK;
2528         }
2529
2530         return YAFFS_FAIL;
2531 }
2532
2533 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
2534                 yaffs_Object *newDir, const YCHAR *newName)
2535 {
2536         yaffs_Object *obj = NULL;
2537         yaffs_Object *existingTarget = NULL;
2538         int force = 0;
2539         int result;
2540         yaffs_Device *dev;
2541
2542
2543         if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2544                 YBUG();
2545         if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
2546                 YBUG();
2547
2548         dev = oldDir->myDev;
2549
2550 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2551         /* Special case for case insemsitive systems (eg. WinCE).
2552          * While look-up is case insensitive, the name isn't.
2553          * Therefore we might want to change x.txt to X.txt
2554         */
2555         if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
2556                 force = 1;
2557 #endif
2558
2559         if(yaffs_strnlen(newName,YAFFS_MAX_NAME_LENGTH+1) > YAFFS_MAX_NAME_LENGTH)
2560                 /* ENAMETOOLONG */
2561                 return YAFFS_FAIL;
2562
2563         obj = yaffs_FindObjectByName(oldDir, oldName);
2564
2565         if (obj && obj->renameAllowed) {
2566
2567                 /* Now do the handling for an existing target, if there is one */
2568
2569                 existingTarget = yaffs_FindObjectByName(newDir, newName);
2570                 if (existingTarget &&
2571                         existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2572                         !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
2573                         /* There is a target that is a non-empty directory, so we fail */
2574                         return YAFFS_FAIL;      /* EEXIST or ENOTEMPTY */
2575                 } else if (existingTarget && existingTarget != obj) {
2576                         /* Nuke the target first, using shadowing,
2577                          * but only if it isn't the same object.
2578                          *
2579                          * Note we must disable gc otherwise it can mess up the shadowing.
2580                          *
2581                          */
2582                         dev->isDoingGC=1;
2583                         yaffs_ChangeObjectName(obj, newDir, newName, force,
2584                                                 existingTarget->objectId);
2585                         existingTarget->isShadowed = 1;
2586                         yaffs_UnlinkObject(existingTarget);
2587                         dev->isDoingGC=0;
2588                 }
2589
2590                 result = yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2591
2592                 yaffs_UpdateParent(oldDir);
2593                 if(newDir != oldDir)
2594                         yaffs_UpdateParent(newDir);
2595                 
2596                 return result;
2597         }
2598         return YAFFS_FAIL;
2599 }
2600
2601 /*------------------------- Block Management and Page Allocation ----------------*/
2602
2603 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
2604 {
2605         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2606
2607         dev->blockInfo = NULL;
2608         dev->chunkBits = NULL;
2609
2610         dev->allocationBlock = -1;      /* force it to get a new one */
2611
2612         /* If the first allocation strategy fails, thry the alternate one */
2613         dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2614         if (!dev->blockInfo) {
2615                 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2616                 dev->blockInfoAlt = 1;
2617         } else
2618                 dev->blockInfoAlt = 0;
2619
2620         if (dev->blockInfo) {
2621                 /* Set up dynamic blockinfo stuff. */
2622                 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2623                 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2624                 if (!dev->chunkBits) {
2625                         dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2626                         dev->chunkBitsAlt = 1;
2627                 } else
2628                         dev->chunkBitsAlt = 0;
2629         }
2630
2631         if (dev->blockInfo && dev->chunkBits) {
2632                 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2633                 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2634                 return YAFFS_OK;
2635         }
2636
2637         return YAFFS_FAIL;
2638 }
2639
2640 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
2641 {
2642         if (dev->blockInfoAlt && dev->blockInfo)
2643                 YFREE_ALT(dev->blockInfo);
2644         else if (dev->blockInfo)
2645                 YFREE(dev->blockInfo);
2646
2647         dev->blockInfoAlt = 0;
2648
2649         dev->blockInfo = NULL;
2650
2651         if (dev->chunkBitsAlt && dev->chunkBits)
2652                 YFREE_ALT(dev->chunkBits);
2653         else if (dev->chunkBits)
2654                 YFREE(dev->chunkBits);
2655         dev->chunkBitsAlt = 0;
2656         dev->chunkBits = NULL;
2657 }
2658
2659 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device *dev,
2660                                         yaffs_BlockInfo *bi)
2661 {
2662         int i;
2663         __u32 seq;
2664         yaffs_BlockInfo *b;
2665
2666         if (!dev->isYaffs2)
2667                 return 1;       /* disqualification only applies to yaffs2. */
2668
2669         if (!bi->hasShrinkHeader)
2670                 return 1;       /* can gc */
2671
2672         /* Find the oldest dirty sequence number if we don't know it and save it
2673          * so we don't have to keep recomputing it.
2674          */
2675         if (!dev->oldestDirtySequence) {
2676                 seq = dev->sequenceNumber;
2677
2678                 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2679                                 i++) {
2680                         b = yaffs_GetBlockInfo(dev, i);
2681                         if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2682                             (b->pagesInUse - b->softDeletions) <
2683                             dev->nChunksPerBlock && b->sequenceNumber < seq) {
2684                                 seq = b->sequenceNumber;
2685                         }
2686                 }
2687                 dev->oldestDirtySequence = seq;
2688         }
2689
2690         /* Can't do gc of this block if there are any blocks older than this one that have
2691          * discarded pages.
2692          */
2693         return (bi->sequenceNumber <= dev->oldestDirtySequence);
2694 }
2695
2696 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2697  * for garbage collection.
2698  */
2699
2700 static int yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
2701                                         int aggressive)
2702 {
2703         int b = dev->currentDirtyChecker;
2704
2705         int i;
2706         int iterations;
2707         int dirtiest = -1;
2708         int pagesInUse = 0;
2709         int prioritised = 0;
2710         yaffs_BlockInfo *bi;
2711         int pendingPrioritisedExist = 0;
2712
2713         /* First let's see if we need to grab a prioritised block */
2714         if (dev->hasPendingPrioritisedGCs) {
2715                 for (i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++) {
2716
2717                         bi = yaffs_GetBlockInfo(dev, i);
2718                         /* yaffs_VerifyBlock(dev,bi,i); */
2719
2720                         if (bi->gcPrioritise) {
2721                                 pendingPrioritisedExist = 1;
2722                                 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2723                                    yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2724                                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
2725                                         dirtiest = i;
2726                                         prioritised = 1;
2727                                         aggressive = 1; /* Fool the non-aggressive skip logiv below */
2728                                 }
2729                         }
2730                 }
2731
2732                 if (!pendingPrioritisedExist) /* None found, so we can clear this */
2733                         dev->hasPendingPrioritisedGCs = 0;
2734         }
2735
2736         /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2737          * search harder.
2738          * else (we're doing a leasurely gc), then we only bother to do this if the
2739          * block has only a few pages in use.
2740          */
2741
2742         dev->nonAggressiveSkip--;
2743
2744         if (!aggressive && (dev->nonAggressiveSkip > 0))
2745                 return -1;
2746
2747         if (!prioritised)
2748                 pagesInUse =
2749                         (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2750
2751         if (aggressive)
2752                 iterations =
2753                     dev->internalEndBlock - dev->internalStartBlock + 1;
2754         else {
2755                 iterations =
2756                     dev->internalEndBlock - dev->internalStartBlock + 1;
2757                 iterations = iterations / 16;
2758                 if (iterations > 200)
2759                         iterations = 200;
2760         }
2761
2762         for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2763                 b++;
2764                 if (b < dev->internalStartBlock || b > dev->internalEndBlock)
2765                         b = dev->internalStartBlock;
2766
2767                 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2768                         T(YAFFS_TRACE_ERROR,
2769                           (TSTR("**>> Block %d is not valid" TENDSTR), b));
2770                         YBUG();
2771                 }
2772
2773                 bi = yaffs_GetBlockInfo(dev, b);
2774
2775                 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2776                         (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2777                                 yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2778                         dirtiest = b;
2779                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
2780                 }
2781         }
2782
2783         dev->currentDirtyChecker = b;
2784
2785         if (dirtiest > 0) {
2786                 T(YAFFS_TRACE_GC,
2787                   (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2788                    dev->nChunksPerBlock - pagesInUse, prioritised));
2789         }
2790
2791         dev->oldestDirtySequence = 0;
2792
2793         if (dirtiest > 0)
2794                 dev->nonAggressiveSkip = 4;
2795
2796         return dirtiest;
2797 }
2798
2799 static void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
2800 {
2801         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2802
2803         int erasedOk = 0;
2804
2805         /* If the block is still healthy erase it and mark as clean.
2806          * If the block has had a data failure, then retire it.
2807          */
2808
2809         T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2810                 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2811                 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2812
2813         bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2814
2815         if (!bi->needsRetiring) {
2816                 yaffs_InvalidateCheckpoint(dev);
2817                 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2818                 if (!erasedOk) {
2819                         dev->nErasureFailures++;
2820                         T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2821                           (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2822                 }
2823         }
2824
2825         if (erasedOk &&
2826             ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2827                 int i;
2828                 for (i = 0; i < dev->nChunksPerBlock; i++) {
2829                         if (!yaffs_CheckChunkErased
2830                             (dev, blockNo * dev->nChunksPerBlock + i)) {
2831                                 T(YAFFS_TRACE_ERROR,
2832                                   (TSTR
2833                                    (">>Block %d erasure supposedly OK, but chunk %d not erased"
2834                                     TENDSTR), blockNo, i));
2835                         }
2836                 }
2837         }
2838
2839         if (erasedOk) {
2840                 /* Clean it up... */
2841                 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2842                 dev->nErasedBlocks++;
2843                 bi->pagesInUse = 0;
2844                 bi->softDeletions = 0;
2845                 bi->hasShrinkHeader = 0;
2846                 bi->skipErasedCheck = 1;  /* This is clean, so no need to check */
2847                 bi->gcPrioritise = 0;
2848                 yaffs_ClearChunkBits(dev, blockNo);
2849
2850                 T(YAFFS_TRACE_ERASE,
2851                   (TSTR("Erased block %d" TENDSTR), blockNo));
2852         } else {
2853                 dev->nFreeChunks -= dev->nChunksPerBlock;       /* We lost a block of free space */
2854
2855                 yaffs_RetireBlock(dev, blockNo);
2856                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2857                   (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2858         }
2859 }
2860
2861 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
2862 {
2863         int i;
2864
2865         yaffs_BlockInfo *bi;
2866
2867         if (dev->nErasedBlocks < 1) {
2868                 /* Hoosterman we've got a problem.
2869                  * Can't get space to gc
2870                  */
2871                 T(YAFFS_TRACE_ERROR,
2872                   (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
2873
2874                 return -1;
2875         }
2876
2877         /* Find an empty block. */
2878
2879         for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2880                 dev->allocationBlockFinder++;
2881                 if (dev->allocationBlockFinder < dev->internalStartBlock
2882                     || dev->allocationBlockFinder > dev->internalEndBlock) {
2883                         dev->allocationBlockFinder = dev->internalStartBlock;
2884                 }
2885
2886                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2887
2888                 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2889                         bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2890                         dev->sequenceNumber++;
2891                         bi->sequenceNumber = dev->sequenceNumber;
2892                         dev->nErasedBlocks--;
2893                         T(YAFFS_TRACE_ALLOCATE,
2894                           (TSTR("Allocated block %d, seq  %d, %d left" TENDSTR),
2895                            dev->allocationBlockFinder, dev->sequenceNumber,
2896                            dev->nErasedBlocks));
2897                         return dev->allocationBlockFinder;
2898                 }
2899         }
2900
2901         T(YAFFS_TRACE_ALWAYS,
2902           (TSTR
2903            ("yaffs tragedy: no more erased blocks, but there should have been %d"
2904             TENDSTR), dev->nErasedBlocks));
2905
2906         return -1;
2907 }
2908
2909
2910
2911 static int yaffs_CalcCheckpointBlocksRequired(yaffs_Device *dev)
2912 {
2913         if (!dev->nCheckpointBlocksRequired &&
2914            dev->isYaffs2) {
2915                 /* Not a valid value so recalculate */
2916                 int nBytes = 0;
2917                 int nBlocks;
2918                 int devBlocks = (dev->endBlock - dev->startBlock + 1);
2919                 int tnodeSize;
2920
2921                 tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
2922
2923                 if (tnodeSize < sizeof(yaffs_Tnode))
2924                         tnodeSize = sizeof(yaffs_Tnode);
2925
2926                 nBytes += sizeof(yaffs_CheckpointValidity);
2927                 nBytes += sizeof(yaffs_CheckpointDevice);
2928                 nBytes += devBlocks * sizeof(yaffs_BlockInfo);
2929                 nBytes += devBlocks * dev->chunkBitmapStride;
2930                 nBytes += (sizeof(yaffs_CheckpointObject) + sizeof(__u32)) * (dev->nObjectsCreated - dev->nFreeObjects);
2931                 nBytes += (tnodeSize + sizeof(__u32)) * (dev->nTnodesCreated - dev->nFreeTnodes);
2932                 nBytes += sizeof(yaffs_CheckpointValidity);
2933                 nBytes += sizeof(__u32); /* checksum*/
2934
2935                 /* Round up and add 2 blocks to allow for some bad blocks, so add 3 */
2936
2937                 nBlocks = (nBytes/(dev->nDataBytesPerChunk * dev->nChunksPerBlock)) + 3;
2938
2939                 dev->nCheckpointBlocksRequired = nBlocks;
2940         }
2941
2942         return dev->nCheckpointBlocksRequired;
2943 }
2944
2945 /*
2946  * Check if there's space to allocate...
2947  * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2948  */
2949 static int yaffs_CheckSpaceForAllocation(yaffs_Device *dev)
2950 {
2951         int reservedChunks;
2952         int reservedBlocks = dev->nReservedBlocks;
2953         int checkpointBlocks;
2954
2955         if (dev->isYaffs2) {
2956                 checkpointBlocks =  yaffs_CalcCheckpointBlocksRequired(dev) -
2957                                     dev->blocksInCheckpoint;
2958                 if (checkpointBlocks < 0)
2959                         checkpointBlocks = 0;
2960         } else {
2961                 checkpointBlocks = 0;
2962         }
2963
2964         reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2965
2966         return (dev->nFreeChunks > reservedChunks);
2967 }
2968
2969 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
2970                 yaffs_BlockInfo **blockUsedPtr)
2971 {
2972         int retVal;
2973         yaffs_BlockInfo *bi;
2974
2975         if (dev->allocationBlock < 0) {
2976                 /* Get next block to allocate off */
2977                 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2978                 dev->allocationPage = 0;
2979         }
2980
2981         if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2982                 /* Not enough space to allocate unless we're allowed to use the reserve. */
2983                 return -1;
2984         }
2985
2986         if (dev->nErasedBlocks < dev->nReservedBlocks
2987                         && dev->allocationPage == 0) {
2988                 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2989         }
2990
2991         /* Next page please.... */
2992         if (dev->allocationBlock >= 0) {
2993                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2994
2995                 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2996                         dev->allocationPage;
2997                 bi->pagesInUse++;
2998                 yaffs_SetChunkBit(dev, dev->allocationBlock,
2999                                 dev->allocationPage);
3000
3001                 dev->allocationPage++;
3002
3003                 dev->nFreeChunks--;
3004
3005                 /* If the block is full set the state to full */
3006                 if (dev->allocationPage >= dev->nChunksPerBlock) {
3007                         bi->blockState = YAFFS_BLOCK_STATE_FULL;
3008                         dev->allocationBlock = -1;
3009                 }
3010
3011                 if (blockUsedPtr)
3012                         *blockUsedPtr = bi;
3013
3014                 return retVal;
3015         }
3016
3017         T(YAFFS_TRACE_ERROR,
3018                         (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
3019
3020         return -1;
3021 }
3022
3023 static int yaffs_GetErasedChunks(yaffs_Device *dev)
3024 {
3025         int n;
3026
3027         n = dev->nErasedBlocks * dev->nChunksPerBlock;
3028
3029         if (dev->allocationBlock > 0)
3030                 n += (dev->nChunksPerBlock - dev->allocationPage);
3031
3032         return n;
3033
3034 }
3035
3036 /*
3037  * yaffs_SkipRestOfBlock() skips over the rest of the allocation block
3038  * if we don't want to write to it.
3039  */
3040 static void yaffs_SkipRestOfBlock(yaffs_Device *dev)
3041 {
3042         if(dev->allocationBlock > 0){
3043                 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
3044                 if(bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING){
3045                         bi->blockState = YAFFS_BLOCK_STATE_FULL;
3046                         dev->allocationBlock = -1;
3047                 }
3048         }
3049 }
3050
3051
3052 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
3053                 int wholeBlock)
3054 {
3055         int oldChunk;
3056         int newChunk;
3057         int markNAND;
3058         int retVal = YAFFS_OK;
3059         int cleanups = 0;
3060         int i;
3061         int isCheckpointBlock;
3062         int matchingChunk;
3063         int maxCopies;
3064
3065         int chunksBefore = yaffs_GetErasedChunks(dev);
3066         int chunksAfter;
3067
3068         yaffs_ExtendedTags tags;
3069
3070         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
3071
3072         yaffs_Object *object;
3073
3074         isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
3075
3076
3077         T(YAFFS_TRACE_TRACING,
3078                         (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
3079                          block,
3080                          bi->pagesInUse,
3081                          bi->hasShrinkHeader,
3082                          wholeBlock));
3083
3084         /*yaffs_VerifyFreeChunks(dev); */
3085
3086         if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
3087                 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
3088         
3089         bi->hasShrinkHeader = 0;        /* clear the flag so that the block can erase */
3090
3091         /* Take off the number of soft deleted entries because
3092          * they're going to get really deleted during GC.
3093          */
3094         if(dev->gcChunk == 0) /* first time through for this block */
3095                 dev->nFreeChunks -= bi->softDeletions;
3096
3097         dev->isDoingGC = 1;
3098
3099         if (isCheckpointBlock ||
3100                         !yaffs_StillSomeChunkBits(dev, block)) {
3101                 T(YAFFS_TRACE_TRACING,
3102                                 (TSTR
3103                                  ("Collecting block %d that has no chunks in use" TENDSTR),
3104                                  block));
3105                 yaffs_BlockBecameDirty(dev, block);
3106         } else {
3107
3108                 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
3109
3110                 yaffs_VerifyBlock(dev, bi, block);
3111
3112                 maxCopies = (wholeBlock) ? dev->nChunksPerBlock : 10;
3113                 oldChunk = block * dev->nChunksPerBlock + dev->gcChunk;
3114
3115                 for (/* init already done */;
3116                      retVal == YAFFS_OK &&
3117                      dev->gcChunk < dev->nChunksPerBlock &&
3118                      (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
3119                      maxCopies > 0;
3120                      dev->gcChunk++, oldChunk++) {
3121                         if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
3122
3123                                 /* This page is in use and might need to be copied off */
3124
3125                                 maxCopies--;
3126
3127                                 markNAND = 1;
3128
3129                                 yaffs_InitialiseTags(&tags);
3130
3131                                 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
3132                                                                 buffer, &tags);
3133
3134                                 object =
3135                                     yaffs_FindObjectByNumber(dev,
3136                                                              tags.objectId);
3137
3138                                 T(YAFFS_TRACE_GC_DETAIL,
3139                                   (TSTR
3140                                    ("Collecting chunk in block %d, %d %d %d " TENDSTR),
3141                                    dev->gcChunk, tags.objectId, tags.chunkId,
3142                                    tags.byteCount));
3143
3144                                 if (object && !yaffs_SkipVerification(dev)) {
3145                                         if (tags.chunkId == 0)
3146                                                 matchingChunk = object->hdrChunk;
3147                                         else if (object->softDeleted)
3148                                                 matchingChunk = oldChunk; /* Defeat the test */
3149                                         else
3150                                                 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
3151
3152                                         if (oldChunk != matchingChunk)
3153                                                 T(YAFFS_TRACE_ERROR,
3154                                                   (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
3155                                                   oldChunk, matchingChunk, tags.objectId, tags.chunkId));
3156
3157                                 }
3158
3159                                 if (!object) {
3160                                         T(YAFFS_TRACE_ERROR,
3161                                           (TSTR
3162                                            ("page %d in gc has no object: %d %d %d "
3163                                             TENDSTR), oldChunk,
3164                                             tags.objectId, tags.chunkId, tags.byteCount));
3165                                 }
3166
3167                                 if (object &&
3168                                     object->deleted &&
3169                                     object->softDeleted &&
3170                                     tags.chunkId != 0) {
3171                                         /* Data chunk in a soft deleted file, throw it away
3172                                          * It's a soft deleted data chunk,
3173                                          * No need to copy this, just forget about it and
3174                                          * fix up the object.
3175                                          */
3176
3177                                         object->nDataChunks--;
3178
3179                                         if (object->nDataChunks <= 0) {
3180                                                 /* remeber to clean up the object */
3181                                                 dev->gcCleanupList[cleanups] =
3182                                                     tags.objectId;
3183                                                 cleanups++;
3184                                         }
3185                                         markNAND = 0;
3186                                 } else if (0) {
3187                                         /* Todo object && object->deleted && object->nDataChunks == 0 */
3188                                         /* Deleted object header with no data chunks.
3189                                          * Can be discarded and the file deleted.
3190                                          */
3191                                         object->hdrChunk = 0;
3192                                         yaffs_FreeTnode(object->myDev,
3193                                                         object->variant.
3194                                                         fileVariant.top);
3195                                         object->variant.fileVariant.top = NULL;
3196                                         yaffs_DoGenericObjectDeletion(object);
3197
3198                                 } else if (object) {
3199                                         /* It's either a data chunk in a live file or
3200                                          * an ObjectHeader, so we're interested in it.
3201                                          * NB Need to keep the ObjectHeaders of deleted files
3202                                          * until the whole file has been deleted off
3203                                          */
3204                                         tags.serialNumber++;
3205
3206                                         dev->nGCCopies++;
3207
3208                                         if (tags.chunkId == 0) {
3209                                                 /* It is an object Id,
3210                                                  * We need to nuke the shrinkheader flags first
3211                                                  * Also need to clean up shadowing.
3212                                                  * We no longer want the shrinkHeader flag since its work is done
3213                                                  * and if it is left in place it will mess up scanning.
3214                                                  */
3215
3216                                                 yaffs_ObjectHeader *oh;
3217                                                 oh = (yaffs_ObjectHeader *)buffer;
3218                                                 oh->isShrink = 0;
3219                                                 tags.extraIsShrinkHeader = 0;
3220                                                 oh->shadowsObject = 0;
3221                                                 oh->inbandShadowsObject = 0;
3222                                                 tags.extraShadows = 0;
3223
3224                                                 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
3225                                         }
3226
3227                                         newChunk =
3228                                             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3229
3230                                         if (newChunk < 0) {
3231                                                 retVal = YAFFS_FAIL;
3232                                         } else {
3233
3234                                                 /* Ok, now fix up the Tnodes etc. */
3235
3236                                                 if (tags.chunkId == 0) {
3237                                                         /* It's a header */
3238                                                         object->hdrChunk =  newChunk;
3239                                                         object->serial =   tags.serialNumber;
3240                                                 } else {
3241                                                         /* It's a data chunk */
3242                                                         yaffs_PutChunkIntoFile
3243                                                             (object,
3244                                                              tags.chunkId,
3245                                                              newChunk, 0);
3246                                                 }
3247                                         }
3248                                 }
3249
3250                                 if (retVal == YAFFS_OK)
3251                                         yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3252
3253                         }
3254                 }
3255
3256                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3257
3258
3259                 /* Do any required cleanups */
3260                 for (i = 0; i < cleanups; i++) {
3261                         /* Time to delete the file too */
3262                         object =
3263                             yaffs_FindObjectByNumber(dev,
3264                                                      dev->gcCleanupList[i]);
3265                         if (object) {
3266                                 yaffs_FreeTnode(dev,
3267                                                 object->variant.fileVariant.
3268                                                 top);
3269                                 object->variant.fileVariant.top = NULL;
3270                                 T(YAFFS_TRACE_GC,
3271                                   (TSTR
3272                                    ("yaffs: About to finally delete object %d"
3273                                     TENDSTR), object->objectId));
3274                                 yaffs_DoGenericObjectDeletion(object);
3275                                 object->myDev->nDeletedFiles--;
3276                         }
3277
3278                 }
3279
3280         }
3281
3282         yaffs_VerifyCollectedBlock(dev, bi, block);
3283
3284         chunksAfter = yaffs_GetErasedChunks(dev);
3285         if (chunksBefore >= chunksAfter) {
3286                 T(YAFFS_TRACE_GC,
3287                   (TSTR
3288                    ("gc did not increase free chunks before %d after %d"
3289                     TENDSTR), chunksBefore, chunksAfter));
3290         }
3291
3292         /* If the gc completed then clear the current gcBlock so that we find another. */
3293         if (bi->blockState != YAFFS_BLOCK_STATE_COLLECTING) {
3294                 dev->gcBlock = -1;
3295                 dev->gcChunk = 0;
3296         }
3297
3298         dev->isDoingGC = 0;
3299
3300         return retVal;
3301 }
3302
3303 /* New garbage collector
3304  * If we're very low on erased blocks then we do aggressive garbage collection
3305  * otherwise we do "leasurely" garbage collection.
3306  * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3307  * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3308  *
3309  * The idea is to help clear out space in a more spread-out manner.
3310  * Dunno if it really does anything useful.
3311  */
3312 static int yaffs_CheckGarbageCollection(yaffs_Device *dev)
3313 {
3314         int block;
3315         int aggressive;
3316         int gcOk = YAFFS_OK;
3317         int maxTries = 0;
3318
3319         int checkpointBlockAdjust;
3320
3321         if (dev->isDoingGC) {
3322                 /* Bail out so we don't get recursive gc */
3323                 return YAFFS_OK;
3324         }
3325
3326         /* This loop should pass the first time.
3327          * We'll only see looping here if the erase of the collected block fails.
3328          */
3329
3330         do {
3331                 maxTries++;
3332
3333                 checkpointBlockAdjust = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
3334                 if (checkpointBlockAdjust < 0)
3335                         checkpointBlockAdjust = 0;
3336
3337                 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3338                         /* We need a block soon...*/
3339                         aggressive = 1;
3340                 } else {
3341                         /* We're in no hurry */
3342                         aggressive = 0;
3343                 }
3344
3345                 if (dev->gcBlock <= 0) {
3346                         dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3347                         dev->gcChunk = 0;
3348                 }
3349
3350                 block = dev->gcBlock;
3351
3352                 if (block > 0) {
3353                         dev->garbageCollections++;
3354                         if (!aggressive)
3355                                 dev->passiveGarbageCollections++;
3356
3357                         T(YAFFS_TRACE_GC,
3358                           (TSTR
3359                            ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3360                            dev->nErasedBlocks, aggressive));
3361
3362                         gcOk = yaffs_GarbageCollectBlock(dev, block, aggressive);
3363                 }
3364
3365                 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3366                         T(YAFFS_TRACE_GC,
3367                           (TSTR
3368                            ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3369                             TENDSTR), dev->nErasedBlocks, maxTries, block));
3370                 }
3371         } while ((dev->nErasedBlocks < dev->nReservedBlocks) &&
3372                  (block > 0) &&
3373                  (maxTries < 2));
3374
3375         return aggressive ? gcOk : YAFFS_OK;
3376 }
3377
3378 /*-------------------------  TAGS --------------------------------*/
3379
3380 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
3381                            int chunkInObject)
3382 {
3383         return (tags->chunkId == chunkInObject &&
3384                 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3385
3386 }
3387
3388
3389 /*-------------------- Data file manipulation -----------------*/
3390
3391 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
3392                                  yaffs_ExtendedTags *tags)
3393 {
3394         /*Get the Tnode, then get the level 0 offset chunk offset */
3395         yaffs_Tnode *tn;
3396         int theChunk = -1;
3397         yaffs_ExtendedTags localTags;
3398         int retVal = -1;
3399
3400         yaffs_Device *dev = in->myDev;
3401
3402         if (!tags) {
3403                 /* Passed a NULL, so use our own tags space */
3404                 tags = &localTags;
3405         }
3406
3407         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3408
3409         if (tn) {
3410                 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3411
3412                 retVal =
3413                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3414                                            chunkInInode);
3415         }
3416         return retVal;
3417 }
3418
3419 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
3420                                           yaffs_ExtendedTags *tags)
3421 {
3422         /* Get the Tnode, then get the level 0 offset chunk offset */
3423         yaffs_Tnode *tn;
3424         int theChunk = -1;
3425         yaffs_ExtendedTags localTags;
3426
3427         yaffs_Device *dev = in->myDev;
3428         int retVal = -1;
3429
3430         if (!tags) {
3431                 /* Passed a NULL, so use our own tags space */
3432                 tags = &localTags;
3433         }
3434
3435         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3436
3437         if (tn) {
3438
3439                 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3440
3441                 retVal =
3442                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3443                                            chunkInInode);
3444
3445                 /* Delete the entry in the filestructure (if found) */
3446                 if (retVal != -1)
3447                         yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, 0);
3448         }
3449
3450         return retVal;
3451 }
3452
3453 #ifdef YAFFS_PARANOID
3454
3455 static int yaffs_CheckFileSanity(yaffs_Object *in)
3456 {
3457         int chunk;
3458         int nChunks;
3459         int fSize;
3460         int failed = 0;
3461         int objId;
3462         yaffs_Tnode *tn;
3463         yaffs_Tags localTags;
3464         yaffs_Tags *tags = &localTags;
3465         int theChunk;
3466         int chunkDeleted;
3467
3468         if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3469                 return YAFFS_FAIL;
3470
3471         objId = in->objectId;
3472         fSize = in->variant.fileVariant.fileSize;
3473         nChunks =
3474             (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3475
3476         for (chunk = 1; chunk <= nChunks; chunk++) {
3477                 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3478                                            chunk);
3479
3480                 if (tn) {
3481
3482                         theChunk = yaffs_GetChunkGroupBase(dev, tn, chunk);
3483
3484                         if (yaffs_CheckChunkBits
3485                             (dev, theChunk / dev->nChunksPerBlock,
3486                              theChunk % dev->nChunksPerBlock)) {
3487
3488                                 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3489                                                             tags,
3490                                                             &chunkDeleted);
3491                                 if (yaffs_TagsMatch
3492                                     (tags, in->objectId, chunk, chunkDeleted)) {
3493                                         /* found it; */
3494
3495                                 }
3496                         } else {
3497
3498                                 failed = 1;
3499                         }
3500
3501                 } else {
3502                         /* T(("No level 0 found for %d\n", chunk)); */
3503                 }
3504         }
3505
3506         return failed ? YAFFS_FAIL : YAFFS_OK;
3507 }
3508
3509 #endif
3510
3511 static int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
3512                                   int chunkInNAND, int inScan)
3513 {
3514         /* NB inScan is zero unless scanning.
3515          * For forward scanning, inScan is > 0;
3516          * for backward scanning inScan is < 0
3517          *
3518          * chunkInNAND = 0 is a dummy insert to make sure the tnodes are there.
3519          */
3520
3521         yaffs_Tnode *tn;
3522         yaffs_Device *dev = in->myDev;
3523         int existingChunk;
3524         yaffs_ExtendedTags existingTags;
3525         yaffs_ExtendedTags newTags;
3526         unsigned existingSerial, newSerial;
3527
3528         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3529                 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3530                  * If it is not during Scanning then something went wrong!
3531                  */
3532                 if (!inScan) {
3533                         T(YAFFS_TRACE_ERROR,
3534                           (TSTR
3535                            ("yaffs tragedy:attempt to put data chunk into a non-file"
3536                             TENDSTR)));
3537                         YBUG();
3538                 }
3539
3540                 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3541                 return YAFFS_OK;
3542         }
3543
3544         tn = yaffs_AddOrFindLevel0Tnode(dev,
3545                                         &in->variant.fileVariant,
3546                                         chunkInInode,
3547                                         NULL);
3548         if (!tn)
3549                 return YAFFS_FAIL;
3550         
3551         if(!chunkInNAND)
3552                 /* Dummy insert, bail now */
3553                 return YAFFS_OK;
3554                 
3555
3556         existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
3557
3558         if (inScan != 0) {
3559                 /* If we're scanning then we need to test for duplicates
3560                  * NB This does not need to be efficient since it should only ever
3561                  * happen when the power fails during a write, then only one
3562                  * chunk should ever be affected.
3563                  *
3564                  * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3565                  * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3566                  */
3567
3568                 if (existingChunk > 0) {
3569                         /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3570                          *    thus we have to do a FindChunkInFile to get the real chunk id.
3571                          *
3572                          * We have a duplicate now we need to decide which one to use:
3573                          *
3574                          * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3575                          * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3576                          * YAFFS1: Get both sets of tags and compare serial numbers.
3577                          */
3578
3579                         if (inScan > 0) {
3580                                 /* Only do this for forward scanning */
3581                                 yaffs_ReadChunkWithTagsFromNAND(dev,
3582                                                                 chunkInNAND,
3583                                                                 NULL, &newTags);
3584
3585                                 /* Do a proper find */
3586                                 existingChunk =
3587                                     yaffs_FindChunkInFile(in, chunkInInode,
3588                                                           &existingTags);
3589                         }
3590
3591                         if (existingChunk <= 0) {
3592                                 /*Hoosterman - how did this happen? */
3593
3594                                 T(YAFFS_TRACE_ERROR,
3595                                   (TSTR
3596                                    ("yaffs tragedy: existing chunk < 0 in scan"
3597                                     TENDSTR)));
3598
3599                         }
3600
3601                         /* NB The deleted flags should be false, otherwise the chunks will
3602                          * not be loaded during a scan
3603                          */
3604
3605                         if (inScan > 0) {
3606                                 newSerial = newTags.serialNumber;
3607                                 existingSerial = existingTags.serialNumber;
3608                         }
3609
3610                         if ((inScan > 0) &&
3611                             (in->myDev->isYaffs2 ||
3612                              existingChunk <= 0 ||
3613                              ((existingSerial + 1) & 3) == newSerial)) {
3614                                 /* Forward scanning.
3615                                  * Use new
3616                                  * Delete the old one and drop through to update the tnode
3617                                  */
3618                                 yaffs_DeleteChunk(dev, existingChunk, 1,
3619                                                   __LINE__);
3620                         } else {
3621                                 /* Backward scanning or we want to use the existing one
3622                                  * Use existing.
3623                                  * Delete the new one and return early so that the tnode isn't changed
3624                                  */
3625                                 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3626                                                   __LINE__);
3627                                 return YAFFS_OK;
3628                         }
3629                 }
3630
3631         }
3632
3633         if (existingChunk == 0)
3634                 in->nDataChunks++;
3635
3636         yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
3637
3638         return YAFFS_OK;
3639 }
3640
3641 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
3642                                         __u8 *buffer)
3643 {
3644         int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3645
3646         if (chunkInNAND >= 0)
3647                 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3648                                                 buffer, NULL);
3649         else {
3650                 T(YAFFS_TRACE_NANDACCESS,
3651                   (TSTR("Chunk %d not found zero instead" TENDSTR),
3652                    chunkInNAND));
3653                 /* get sane (zero) data if you read a hole */
3654                 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
3655                 return 0;
3656         }
3657
3658 }
3659
3660 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
3661 {
3662         int block;
3663         int page;
3664         yaffs_ExtendedTags tags;
3665         yaffs_BlockInfo *bi;
3666
3667         if (chunkId <= 0)
3668                 return;
3669
3670         dev->nDeletions++;
3671         block = chunkId / dev->nChunksPerBlock;
3672         page = chunkId % dev->nChunksPerBlock;
3673
3674
3675         if (!yaffs_CheckChunkBit(dev, block, page))
3676                 T(YAFFS_TRACE_VERIFY,
3677                         (TSTR("Deleting invalid chunk %d"TENDSTR),
3678                          chunkId));
3679
3680         bi = yaffs_GetBlockInfo(dev, block);
3681
3682         T(YAFFS_TRACE_DELETION,
3683           (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3684
3685         if (markNAND &&
3686             bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3687
3688                 yaffs_InitialiseTags(&tags);
3689
3690                 tags.chunkDeleted = 1;
3691
3692                 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3693                 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3694         } else {
3695                 dev->nUnmarkedDeletions++;
3696         }
3697
3698         /* Pull out of the management area.
3699          * If the whole block became dirty, this will kick off an erasure.
3700          */
3701         if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3702             bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3703             bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3704             bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3705                 dev->nFreeChunks++;
3706
3707                 yaffs_ClearChunkBit(dev, block, page);
3708
3709                 bi->pagesInUse--;
3710
3711                 if (bi->pagesInUse == 0 &&
3712                     !bi->hasShrinkHeader &&
3713                     bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3714                     bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3715                         yaffs_BlockBecameDirty(dev, block);
3716                 }
3717
3718         }
3719
3720 }
3721
3722 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
3723                                         const __u8 *buffer, int nBytes,
3724                                         int useReserve)
3725 {
3726         /* Find old chunk Need to do this to get serial number
3727          * Write new one and patch into tree.
3728          * Invalidate old tags.
3729          */
3730
3731         int prevChunkId;
3732         yaffs_ExtendedTags prevTags;
3733
3734         int newChunkId;
3735         yaffs_ExtendedTags newTags;
3736
3737         yaffs_Device *dev = in->myDev;
3738
3739         yaffs_CheckGarbageCollection(dev);
3740
3741         /* Get the previous chunk at this location in the file if it exists */
3742         prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3743
3744         /* Set up new tags */
3745         yaffs_InitialiseTags(&newTags);
3746
3747         newTags.chunkId = chunkInInode;
3748         newTags.objectId = in->objectId;
3749         newTags.serialNumber =
3750             (prevChunkId > 0) ? prevTags.serialNumber + 1 : 1;
3751         newTags.byteCount = nBytes;
3752
3753         if (nBytes < 1 || nBytes > dev->totalBytesPerChunk) {
3754                 T(YAFFS_TRACE_ERROR,
3755                 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
3756                 YBUG();
3757         }
3758         
3759         /*
3760          * If there isn't already a chunk there then do a dummy
3761          * insert to make sue we have the desired tnode structure.
3762          */
3763         if(prevChunkId < 1 &&
3764                 yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0) != YAFFS_OK)
3765                 return -1;
3766                 
3767         newChunkId =
3768             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3769                                               useReserve);
3770
3771         if (newChunkId > 0) {
3772                 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3773
3774                 if (prevChunkId > 0)
3775                         yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3776
3777                 yaffs_CheckFileSanity(in);
3778         }
3779         return newChunkId;
3780
3781 }
3782
3783 /* UpdateObjectHeader updates the header on NAND for an object.
3784  * If name is not NULL, then that new name is used.
3785  */
3786 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
3787                              int isShrink, int shadows)
3788 {
3789
3790         yaffs_BlockInfo *bi;
3791
3792         yaffs_Device *dev = in->myDev;
3793
3794         int prevChunkId;
3795         int retVal = 0;
3796         int result = 0;
3797
3798         int newChunkId;
3799         yaffs_ExtendedTags newTags;
3800         yaffs_ExtendedTags oldTags;
3801         YCHAR *alias = NULL;
3802
3803         __u8 *buffer = NULL;
3804         YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3805
3806         yaffs_ObjectHeader *oh = NULL;
3807
3808         yaffs_strcpy(oldName, _Y("silly old name"));
3809
3810
3811         if (!in->fake ||
3812                 in == dev->rootDir || /* The rootDir should also be saved */
3813                 force) {
3814
3815                 yaffs_CheckGarbageCollection(dev);
3816                 yaffs_CheckObjectDetailsLoaded(in);
3817
3818                 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3819                 oh = (yaffs_ObjectHeader *) buffer;
3820
3821                 prevChunkId = in->hdrChunk;
3822
3823                 if (prevChunkId > 0) {
3824                         result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3825                                                         buffer, &oldTags);
3826
3827                         yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
3828
3829                         memcpy(oldName, oh->name, sizeof(oh->name));
3830                 }
3831
3832                 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3833
3834                 oh->type = in->variantType;
3835                 oh->yst_mode = in->yst_mode;
3836                 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3837
3838 #ifdef CONFIG_YAFFS_WINCE
3839                 oh->win_atime[0] = in->win_atime[0];
3840                 oh->win_ctime[0] = in->win_ctime[0];
3841                 oh->win_mtime[0] = in->win_mtime[0];
3842                 oh->win_atime[1] = in->win_atime[1];
3843                 oh->win_ctime[1] = in->win_ctime[1];
3844                 oh->win_mtime[1] = in->win_mtime[1];
3845 #else
3846                 oh->yst_uid = in->yst_uid;
3847                 oh->yst_gid = in->yst_gid;
3848                 oh->yst_atime = in->yst_atime;
3849                 oh->yst_mtime = in->yst_mtime;
3850                 oh->yst_ctime = in->yst_ctime;
3851                 oh->yst_rdev = in->yst_rdev;
3852 #endif
3853                 if (in->parent)
3854                         oh->parentObjectId = in->parent->objectId;
3855                 else
3856                         oh->parentObjectId = 0;
3857
3858                 if (name && *name) {
3859                         memset(oh->name, 0, sizeof(oh->name));
3860                         yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3861                 } else if (prevChunkId > 0)
3862                         memcpy(oh->name, oldName, sizeof(oh->name));
3863                 else
3864                         memset(oh->name, 0, sizeof(oh->name));
3865
3866                 oh->isShrink = isShrink;
3867
3868                 switch (in->variantType) {
3869                 case YAFFS_OBJECT_TYPE_UNKNOWN:
3870                         /* Should not happen */
3871                         break;
3872                 case YAFFS_OBJECT_TYPE_FILE:
3873                         oh->fileSize =
3874                             (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3875                              || oh->parentObjectId ==
3876                              YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3877                             fileVariant.fileSize;
3878                         break;
3879                 case YAFFS_OBJECT_TYPE_HARDLINK:
3880                         oh->equivalentObjectId =
3881                             in->variant.hardLinkVariant.equivalentObjectId;
3882                         break;
3883                 case YAFFS_OBJECT_TYPE_SPECIAL:
3884                         /* Do nothing */
3885                         break;
3886                 case YAFFS_OBJECT_TYPE_DIRECTORY:
3887                         /* Do nothing */
3888                         break;
3889                 case YAFFS_OBJECT_TYPE_SYMLINK:
3890                         alias = in->variant.symLinkVariant.alias;
3891                         if(!alias)
3892                                 alias = _Y("no alias");
3893                         yaffs_strncpy(oh->alias,
3894                                         alias,
3895                                       YAFFS_MAX_ALIAS_LENGTH);
3896                         oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3897                         break;
3898                 }
3899
3900                 /* Tags */
3901                 yaffs_InitialiseTags(&newTags);
3902                 in->serial++;
3903                 newTags.chunkId = 0;
3904                 newTags.objectId = in->objectId;
3905                 newTags.serialNumber = in->serial;
3906
3907                 /* Add extra info for file header */
3908
3909                 newTags.extraHeaderInfoAvailable = 1;
3910                 newTags.extraParentObjectId = oh->parentObjectId;
3911                 newTags.extraFileLength = oh->fileSize;
3912                 newTags.extraIsShrinkHeader = oh->isShrink;
3913                 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3914                 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3915                 newTags.extraObjectType = in->variantType;
3916
3917                 yaffs_VerifyObjectHeader(in, oh, &newTags, 1);
3918
3919                 /* Create new chunk in NAND */
3920                 newChunkId =
3921                     yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3922                                                       (prevChunkId > 0) ? 1 : 0);
3923
3924                 if (newChunkId >= 0) {
3925
3926                         in->hdrChunk = newChunkId;
3927
3928                         if (prevChunkId > 0) {
3929                                 yaffs_DeleteChunk(dev, prevChunkId, 1,
3930                                                   __LINE__);
3931                         }
3932
3933                         if (!yaffs_ObjectHasCachedWriteData(in))
3934                                 in->dirty = 0;
3935
3936                         /* If this was a shrink, then mark the block that the chunk lives on */
3937                         if (isShrink) {
3938                                 bi = yaffs_GetBlockInfo(in->myDev,
3939                                         newChunkId / in->myDev->nChunksPerBlock);
3940                                 bi->hasShrinkHeader = 1;
3941                         }
3942
3943                 }
3944
3945                 retVal = newChunkId;
3946
3947         }
3948
3949         if (buffer)
3950                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3951
3952         return retVal;
3953 }
3954
3955 /*------------------------ Short Operations Cache ----------------------------------------
3956  *   In many situations where there is no high level buffering (eg WinCE) a lot of
3957  *   reads might be short sequential reads, and a lot of writes may be short
3958  *   sequential writes. eg. scanning/writing a jpeg file.
3959  *   In these cases, a short read/write cache can provide a huge perfomance benefit
3960  *   with dumb-as-a-rock code.
3961  *   In Linux, the page cache provides read buffering aand the short op cache provides write
3962  *   buffering.
3963  *
3964  *   There are a limited number (~10) of cache chunks per device so that we don't
3965  *   need a very intelligent search.
3966  */
3967
3968 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3969 {
3970         yaffs_Device *dev = obj->myDev;
3971         int i;
3972         yaffs_ChunkCache *cache;
3973         int nCaches = obj->myDev->nShortOpCaches;
3974
3975         for (i = 0; i < nCaches; i++) {
3976                 cache = &dev->srCache[i];
3977                 if (cache->object == obj &&
3978                     cache->dirty)
3979                         return 1;
3980         }
3981
3982         return 0;
3983 }
3984
3985
3986 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
3987 {
3988         yaffs_Device *dev = obj->myDev;
3989         int lowest = -99;       /* Stop compiler whining. */
3990         int i;
3991         yaffs_ChunkCache *cache;
3992         int chunkWritten = 0;
3993         int nCaches = obj->myDev->nShortOpCaches;
3994
3995         if (nCaches > 0) {
3996                 do {
3997                         cache = NULL;
3998
3999                         /* Find the dirty cache for this object with the lowest chunk id. */
4000                         for (i = 0; i < nCaches; i++) {
4001                                 if (dev->srCache[i].object == obj &&
4002                                     dev->srCache[i].dirty) {
4003                                         if (!cache
4004                                             || dev->srCache[i].chunkId <
4005                                             lowest) {
4006                                                 cache = &dev->srCache[i];
4007                                                 lowest = cache->chunkId;
4008                                         }
4009                                 }
4010                         }
4011
4012                         if (cache && !cache->locked) {
4013                                 /* Write it out and free it up */
4014
4015                                 chunkWritten =
4016                                     yaffs_WriteChunkDataToObject(cache->object,
4017                                                                  cache->chunkId,
4018                                                                  cache->data,
4019                                                                  cache->nBytes,
4020                                                                  1);
4021                                 cache->dirty = 0;
4022                                 cache->object = NULL;
4023                         }
4024
4025                 } while (cache && chunkWritten > 0);
4026
4027                 if (cache) {
4028                         /* Hoosterman, disk full while writing cache out. */
4029                         T(YAFFS_TRACE_ERROR,
4030                           (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
4031
4032                 }
4033         }
4034
4035 }
4036
4037 /*yaffs_FlushEntireDeviceCache(dev)
4038  *
4039  *
4040  */
4041
4042 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
4043 {
4044         yaffs_Object *obj;
4045         int nCaches = dev->nShortOpCaches;
4046         int i;
4047
4048         /* Find a dirty object in the cache and flush it...
4049          * until there are no further dirty objects.
4050          */
4051         do {
4052                 obj = NULL;
4053                 for (i = 0; i < nCaches && !obj; i++) {
4054                         if (dev->srCache[i].object &&
4055                             dev->srCache[i].dirty)
4056                                 obj = dev->srCache[i].object;
4057
4058                 }
4059                 if (obj)
4060                         yaffs_FlushFilesChunkCache(obj);
4061
4062         } while (obj);
4063
4064 }
4065
4066
4067 /* Grab us a cache chunk for use.
4068  * First look for an empty one.
4069  * Then look for the least recently used non-dirty one.
4070  * Then look for the least recently used dirty one...., flush and look again.
4071  */
4072 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
4073 {
4074         int i;
4075
4076         if (dev->nShortOpCaches > 0) {
4077                 for (i = 0; i < dev->nShortOpCaches; i++) {
4078                         if (!dev->srCache[i].object)
4079                                 return &dev->srCache[i];
4080                 }
4081         }
4082
4083         return NULL;
4084 }
4085
4086 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
4087 {
4088         yaffs_ChunkCache *cache;
4089         yaffs_Object *theObj;
4090         int usage;
4091         int i;
4092         int pushout;
4093
4094         if (dev->nShortOpCaches > 0) {
4095                 /* Try find a non-dirty one... */
4096
4097                 cache = yaffs_GrabChunkCacheWorker(dev);
4098
4099                 if (!cache) {
4100                         /* They were all dirty, find the last recently used object and flush
4101                          * its cache, then  find again.
4102                          * NB what's here is not very accurate, we actually flush the object
4103                          * the last recently used page.
4104                          */
4105
4106                         /* With locking we can't assume we can use entry zero */
4107
4108                         theObj = NULL;
4109                         usage = -1;
4110                         cache = NULL;
4111                         pushout = -1;
4112
4113                         for (i = 0; i < dev->nShortOpCaches; i++) {
4114                                 if (dev->srCache[i].object &&
4115                                     !dev->srCache[i].locked &&
4116                                     (dev->srCache[i].lastUse < usage || !cache)) {
4117                                         usage = dev->srCache[i].lastUse;
4118                                         theObj = dev->srCache[i].object;
4119                                         cache = &dev->srCache[i];
4120                                         pushout = i;
4121                                 }
4122                         }
4123
4124                         if (!cache || cache->dirty) {
4125                                 /* Flush and try again */
4126                                 yaffs_FlushFilesChunkCache(theObj);
4127                                 cache = yaffs_GrabChunkCacheWorker(dev);
4128                         }
4129
4130                 }
4131                 return cache;
4132         } else
4133                 return NULL;
4134
4135 }
4136
4137 /* Find a cached chunk */
4138 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj,
4139                                               int chunkId)
4140 {
4141         yaffs_Device *dev = obj->myDev;
4142         int i;
4143         if (dev->nShortOpCaches > 0) {
4144                 for (i = 0; i < dev->nShortOpCaches; i++) {
4145                         if (dev->srCache[i].object == obj &&
4146                             dev->srCache[i].chunkId == chunkId) {
4147                                 dev->cacheHits++;
4148
4149                                 return &dev->srCache[i];
4150                         }
4151                 }
4152         }
4153         return NULL;
4154 }
4155
4156 /* Mark the chunk for the least recently used algorithym */
4157 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache,
4158                                 int isAWrite)
4159 {
4160
4161         if (dev->nShortOpCaches > 0) {
4162                 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
4163                         /* Reset the cache usages */
4164                         int i;
4165                         for (i = 1; i < dev->nShortOpCaches; i++)
4166                                 dev->srCache[i].lastUse = 0;
4167
4168                         dev->srLastUse = 0;
4169                 }
4170
4171                 dev->srLastUse++;
4172
4173                 cache->lastUse = dev->srLastUse;
4174
4175                 if (isAWrite)
4176                         cache->dirty = 1;
4177         }
4178 }
4179
4180 /* Invalidate a single cache page.
4181  * Do this when a whole page gets written,
4182  * ie the short cache for this page is no longer valid.
4183  */
4184 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
4185 {
4186         if (object->myDev->nShortOpCaches > 0) {
4187                 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
4188
4189                 if (cache)
4190                         cache->object = NULL;
4191         }
4192 }
4193
4194 /* Invalidate all the cache pages associated with this object
4195  * Do this whenever ther file is deleted or resized.
4196  */
4197 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
4198 {
4199         int i;
4200         yaffs_Device *dev = in->myDev;
4201
4202         if (dev->nShortOpCaches > 0) {
4203                 /* Invalidate it. */
4204                 for (i = 0; i < dev->nShortOpCaches; i++) {
4205                         if (dev->srCache[i].object == in)
4206                                 dev->srCache[i].object = NULL;
4207                 }
4208         }
4209 }
4210
4211 /*--------------------- Checkpointing --------------------*/
4212
4213
4214 static int yaffs_WriteCheckpointValidityMarker(yaffs_Device *dev, int head)
4215 {
4216         yaffs_CheckpointValidity cp;
4217
4218         memset(&cp, 0, sizeof(cp));
4219
4220         cp.structType = sizeof(cp);
4221         cp.magic = YAFFS_MAGIC;
4222         cp.version = YAFFS_CHECKPOINT_VERSION;
4223         cp.head = (head) ? 1 : 0;
4224
4225         return (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp)) ?
4226                 1 : 0;
4227 }
4228
4229 static int yaffs_ReadCheckpointValidityMarker(yaffs_Device *dev, int head)
4230 {
4231         yaffs_CheckpointValidity cp;
4232         int ok;
4233
4234         ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4235
4236         if (ok)
4237                 ok = (cp.structType == sizeof(cp)) &&
4238                      (cp.magic == YAFFS_MAGIC) &&
4239                      (cp.version == YAFFS_CHECKPOINT_VERSION) &&
4240                      (cp.head == ((head) ? 1 : 0));
4241         return ok ? 1 : 0;
4242 }
4243
4244 static void yaffs_DeviceToCheckpointDevice(yaffs_CheckpointDevice *cp,
4245                                            yaffs_Device *dev)
4246 {
4247         cp->nErasedBlocks = dev->nErasedBlocks;
4248         cp->allocationBlock = dev->allocationBlock;
4249         cp->allocationPage = dev->allocationPage;
4250         cp->nFreeChunks = dev->nFreeChunks;
4251
4252         cp->nDeletedFiles = dev->nDeletedFiles;
4253         cp->nUnlinkedFiles = dev->nUnlinkedFiles;
4254         cp->nBackgroundDeletions = dev->nBackgroundDeletions;
4255         cp->sequenceNumber = dev->sequenceNumber;
4256         cp->oldestDirtySequence = dev->oldestDirtySequence;
4257
4258 }
4259
4260 static void yaffs_CheckpointDeviceToDevice(yaffs_Device *dev,
4261                                            yaffs_CheckpointDevice *cp)
4262 {
4263         dev->nErasedBlocks = cp->nErasedBlocks;
4264         dev->allocationBlock = cp->allocationBlock;
4265         dev->allocationPage = cp->allocationPage;
4266         dev->nFreeChunks = cp->nFreeChunks;
4267
4268         dev->nDeletedFiles = cp->nDeletedFiles;
4269         dev->nUnlinkedFiles = cp->nUnlinkedFiles;
4270         dev->nBackgroundDeletions = cp->nBackgroundDeletions;
4271         dev->sequenceNumber = cp->sequenceNumber;
4272         dev->oldestDirtySequence = cp->oldestDirtySequence;
4273 }
4274
4275
4276 static int yaffs_WriteCheckpointDevice(yaffs_Device *dev)
4277 {
4278         yaffs_CheckpointDevice cp;
4279         __u32 nBytes;
4280         __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4281
4282         int ok;
4283
4284         /* Write device runtime values*/
4285         yaffs_DeviceToCheckpointDevice(&cp, dev);
4286         cp.structType = sizeof(cp);
4287
4288         ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4289
4290         /* Write block info */
4291         if (ok) {
4292                 nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4293                 ok = (yaffs_CheckpointWrite(dev, dev->blockInfo, nBytes) == nBytes);
4294         }
4295
4296         /* Write chunk bits */
4297         if (ok) {
4298                 nBytes = nBlocks * dev->chunkBitmapStride;
4299                 ok = (yaffs_CheckpointWrite(dev, dev->chunkBits, nBytes) == nBytes);
4300         }
4301         return   ok ? 1 : 0;
4302
4303 }
4304
4305 static int yaffs_ReadCheckpointDevice(yaffs_Device *dev)
4306 {
4307         yaffs_CheckpointDevice cp;
4308         __u32 nBytes;
4309         __u32 nBlocks = (dev->internalEndBlock - dev->internalStartBlock + 1);
4310
4311         int ok;
4312
4313         ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4314         if (!ok)
4315                 return 0;
4316
4317         if (cp.structType != sizeof(cp))
4318                 return 0;
4319
4320
4321         yaffs_CheckpointDeviceToDevice(dev, &cp);
4322
4323         nBytes = nBlocks * sizeof(yaffs_BlockInfo);
4324
4325         ok = (yaffs_CheckpointRead(dev, dev->blockInfo, nBytes) == nBytes);
4326
4327         if (!ok)
4328                 return 0;
4329         nBytes = nBlocks * dev->chunkBitmapStride;
4330
4331         ok = (yaffs_CheckpointRead(dev, dev->chunkBits, nBytes) == nBytes);
4332
4333         return ok ? 1 : 0;
4334 }
4335
4336 static void yaffs_ObjectToCheckpointObject(yaffs_CheckpointObject *cp,
4337                                            yaffs_Object *obj)
4338 {
4339
4340         cp->objectId = obj->objectId;
4341         cp->parentId = (obj->parent) ? obj->parent->objectId : 0;
4342         cp->hdrChunk = obj->hdrChunk;
4343         cp->variantType = obj->variantType;
4344         cp->deleted = obj->deleted;
4345         cp->softDeleted = obj->softDeleted;
4346         cp->unlinked = obj->unlinked;
4347         cp->fake = obj->fake;
4348         cp->renameAllowed = obj->renameAllowed;
4349         cp->unlinkAllowed = obj->unlinkAllowed;
4350         cp->serial = obj->serial;
4351         cp->nDataChunks = obj->nDataChunks;
4352
4353         if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4354                 cp->fileSizeOrEquivalentObjectId = obj->variant.fileVariant.fileSize;
4355         else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4356                 cp->fileSizeOrEquivalentObjectId = obj->variant.hardLinkVariant.equivalentObjectId;
4357 }
4358
4359 static int yaffs_CheckpointObjectToObject(yaffs_Object *obj, yaffs_CheckpointObject *cp)
4360 {
4361
4362         yaffs_Object *parent;
4363
4364         if (obj->variantType != cp->variantType) {
4365                 T(YAFFS_TRACE_ERROR, (TSTR("Checkpoint read object %d type %d "
4366                         TCONT("chunk %d does not match existing object type %d")
4367                         TENDSTR), cp->objectId, cp->variantType, cp->hdrChunk,
4368                         obj->variantType));
4369                 return 0;
4370         }
4371
4372         obj->objectId = cp->objectId;
4373
4374         if (cp->parentId)
4375                 parent = yaffs_FindOrCreateObjectByNumber(
4376                                         obj->myDev,
4377                                         cp->parentId,
4378                                         YAFFS_OBJECT_TYPE_DIRECTORY);
4379         else
4380                 parent = NULL;
4381
4382         if (parent) {
4383                 if (parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4384                         T(YAFFS_TRACE_ALWAYS, (TSTR("Checkpoint read object %d parent %d type %d"
4385                                 TCONT(" chunk %d Parent type, %d, not directory")
4386                                 TENDSTR),
4387                                 cp->objectId, cp->parentId, cp->variantType,
4388                                 cp->hdrChunk, parent->variantType));
4389                         return 0;
4390                 }
4391                 yaffs_AddObjectToDirectory(parent, obj);
4392         }
4393
4394         obj->hdrChunk = cp->hdrChunk;
4395         obj->variantType = cp->variantType;
4396         obj->deleted = cp->deleted;
4397         obj->softDeleted = cp->softDeleted;
4398         obj->unlinked = cp->unlinked;
4399         obj->fake = cp->fake;
4400         obj->renameAllowed = cp->renameAllowed;
4401         obj->unlinkAllowed = cp->unlinkAllowed;
4402         obj->serial = cp->serial;
4403         obj->nDataChunks = cp->nDataChunks;
4404
4405         if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4406                 obj->variant.fileVariant.fileSize = cp->fileSizeOrEquivalentObjectId;
4407         else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK)
4408                 obj->variant.hardLinkVariant.equivalentObjectId = cp->fileSizeOrEquivalentObjectId;
4409
4410         if (obj->hdrChunk > 0)
4411                 obj->lazyLoaded = 1;
4412         return 1;
4413 }
4414
4415
4416
4417 static int yaffs_CheckpointTnodeWorker(yaffs_Object *in, yaffs_Tnode *tn,
4418                                         __u32 level, int chunkOffset)
4419 {
4420         int i;
4421         yaffs_Device *dev = in->myDev;
4422         int ok = 1;
4423         int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4424
4425         if (tnodeSize < sizeof(yaffs_Tnode))
4426                 tnodeSize = sizeof(yaffs_Tnode);
4427
4428
4429         if (tn) {
4430                 if (level > 0) {
4431
4432                         for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++) {
4433                                 if (tn->internal[i]) {
4434                                         ok = yaffs_CheckpointTnodeWorker(in,
4435                                                         tn->internal[i],
4436                                                         level - 1,
4437                                                         (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
4438                                 }
4439                         }
4440                 } else if (level == 0) {
4441                         __u32 baseOffset = chunkOffset <<  YAFFS_TNODES_LEVEL0_BITS;
4442                         ok = (yaffs_CheckpointWrite(dev, &baseOffset, sizeof(baseOffset)) == sizeof(baseOffset));
4443                         if (ok)
4444                                 ok = (yaffs_CheckpointWrite(dev, tn, tnodeSize) == tnodeSize);
4445                 }
4446         }
4447
4448         return ok;
4449
4450 }
4451
4452 static int yaffs_WriteCheckpointTnodes(yaffs_Object *obj)
4453 {
4454         __u32 endMarker = ~0;
4455         int ok = 1;
4456
4457         if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4458                 ok = yaffs_CheckpointTnodeWorker(obj,
4459                                             obj->variant.fileVariant.top,
4460                                             obj->variant.fileVariant.topLevel,
4461                                             0);
4462                 if (ok)
4463                         ok = (yaffs_CheckpointWrite(obj->myDev, &endMarker, sizeof(endMarker)) ==
4464                                 sizeof(endMarker));
4465         }
4466
4467         return ok ? 1 : 0;
4468 }
4469
4470 static int yaffs_ReadCheckpointTnodes(yaffs_Object *obj)
4471 {
4472         __u32 baseChunk;
4473         int ok = 1;
4474         yaffs_Device *dev = obj->myDev;
4475         yaffs_FileStructure *fileStructPtr = &obj->variant.fileVariant;
4476         yaffs_Tnode *tn;
4477         int nread = 0;
4478         int tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
4479
4480         if (tnodeSize < sizeof(yaffs_Tnode))
4481                 tnodeSize = sizeof(yaffs_Tnode);
4482
4483         ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4484
4485         while (ok && (~baseChunk)) {
4486                 nread++;
4487                 /* Read level 0 tnode */
4488
4489
4490                 tn = yaffs_GetTnodeRaw(dev);
4491                 if (tn)
4492                         ok = (yaffs_CheckpointRead(dev, tn, tnodeSize) == tnodeSize);
4493                 else
4494                         ok = 0;
4495
4496                 if (tn && ok)
4497                         ok = yaffs_AddOrFindLevel0Tnode(dev,
4498                                                         fileStructPtr,
4499                                                         baseChunk,
4500                                                         tn) ? 1 : 0;
4501
4502                 if (ok)
4503                         ok = (yaffs_CheckpointRead(dev, &baseChunk, sizeof(baseChunk)) == sizeof(baseChunk));
4504
4505         }
4506
4507         T(YAFFS_TRACE_CHECKPOINT, (
4508                 TSTR("Checkpoint read tnodes %d records, last %d. ok %d" TENDSTR),
4509                 nread, baseChunk, ok));
4510
4511         return ok ? 1 : 0;
4512 }
4513
4514
4515 static int yaffs_WriteCheckpointObjects(yaffs_Device *dev)
4516 {
4517         yaffs_Object *obj;
4518         yaffs_CheckpointObject cp;
4519         int i;
4520         int ok = 1;
4521         struct ylist_head *lh;
4522
4523
4524         /* Iterate through the objects in each hash entry,
4525          * dumping them to the checkpointing stream.
4526          */
4527
4528         for (i = 0; ok &&  i <  YAFFS_NOBJECT_BUCKETS; i++) {
4529                 ylist_for_each(lh, &dev->objectBucket[i].list) {
4530                         if (lh) {
4531                                 obj = ylist_entry(lh, yaffs_Object, hashLink);
4532                                 if (!obj->deferedFree) {
4533                                         yaffs_ObjectToCheckpointObject(&cp, obj);
4534                                         cp.structType = sizeof(cp);
4535
4536                                         T(YAFFS_TRACE_CHECKPOINT, (
4537                                                 TSTR("Checkpoint write object %d parent %d type %d chunk %d obj addr %p" TENDSTR),
4538                                                 cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk, obj));
4539
4540                                         ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4541
4542                                         if (ok && obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4543                                                 ok = yaffs_WriteCheckpointTnodes(obj);
4544                                 }
4545                         }
4546                 }
4547         }
4548
4549         /* Dump end of list */
4550         memset(&cp, 0xFF, sizeof(yaffs_CheckpointObject));
4551         cp.structType = sizeof(cp);
4552
4553         if (ok)
4554                 ok = (yaffs_CheckpointWrite(dev, &cp, sizeof(cp)) == sizeof(cp));
4555
4556         return ok ? 1 : 0;
4557 }
4558
4559 static int yaffs_ReadCheckpointObjects(yaffs_Device *dev)
4560 {
4561         yaffs_Object *obj;
4562         yaffs_CheckpointObject cp;
4563         int ok = 1;
4564         int done = 0;
4565         yaffs_Object *hardList = NULL;
4566
4567         while (ok && !done) {
4568                 ok = (yaffs_CheckpointRead(dev, &cp, sizeof(cp)) == sizeof(cp));
4569                 if (cp.structType != sizeof(cp)) {
4570                         T(YAFFS_TRACE_CHECKPOINT, (TSTR("struct size %d instead of %d ok %d"TENDSTR),
4571                                 cp.structType, (int)sizeof(cp), ok));
4572                         ok = 0;
4573                 }
4574
4575                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("Checkpoint read object %d parent %d type %d chunk %d " TENDSTR),
4576                         cp.objectId, cp.parentId, cp.variantType, cp.hdrChunk));
4577
4578                 if (ok && cp.objectId == ~0)
4579                         done = 1;
4580                 else if (ok) {
4581                         obj = yaffs_FindOrCreateObjectByNumber(dev, cp.objectId, cp.variantType);
4582                         if (obj) {
4583                                 ok = yaffs_CheckpointObjectToObject(obj, &cp);
4584                                 if (!ok)
4585                                         break;
4586                                 if (obj->variantType == YAFFS_OBJECT_TYPE_FILE) {
4587                                         ok = yaffs_ReadCheckpointTnodes(obj);
4588                                 } else if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4589                                         obj->hardLinks.next =
4590                                                 (struct ylist_head *) hardList;
4591                                         hardList = obj;
4592                                 }
4593                         } else
4594                                 ok = 0;
4595                 }
4596         }
4597
4598         if (ok)
4599                 yaffs_HardlinkFixup(dev, hardList);
4600
4601         return ok ? 1 : 0;
4602 }
4603
4604 static int yaffs_WriteCheckpointSum(yaffs_Device *dev)
4605 {
4606         __u32 checkpointSum;
4607         int ok;
4608
4609         yaffs_GetCheckpointSum(dev, &checkpointSum);
4610
4611         ok = (yaffs_CheckpointWrite(dev, &checkpointSum, sizeof(checkpointSum)) == sizeof(checkpointSum));
4612
4613         if (!ok)
4614                 return 0;
4615
4616         return 1;
4617 }
4618
4619 static int yaffs_ReadCheckpointSum(yaffs_Device *dev)
4620 {
4621         __u32 checkpointSum0;
4622         __u32 checkpointSum1;
4623         int ok;
4624
4625         yaffs_GetCheckpointSum(dev, &checkpointSum0);
4626
4627         ok = (yaffs_CheckpointRead(dev, &checkpointSum1, sizeof(checkpointSum1)) == sizeof(checkpointSum1));
4628
4629         if (!ok)
4630                 return 0;
4631
4632         if (checkpointSum0 != checkpointSum1)
4633                 return 0;
4634
4635         return 1;
4636 }
4637
4638
4639 static int yaffs_WriteCheckpointData(yaffs_Device *dev)
4640 {
4641         int ok = 1;
4642
4643         if (dev->skipCheckpointWrite || !dev->isYaffs2) {
4644                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint write" TENDSTR)));
4645                 ok = 0;
4646         }
4647
4648         if (ok)
4649                 ok = yaffs_CheckpointOpen(dev, 1);
4650
4651         if (ok) {
4652                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4653                 ok = yaffs_WriteCheckpointValidityMarker(dev, 1);
4654         }
4655         if (ok) {
4656                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint device" TENDSTR)));
4657                 ok = yaffs_WriteCheckpointDevice(dev);
4658         }
4659         if (ok) {
4660                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint objects" TENDSTR)));
4661                 ok = yaffs_WriteCheckpointObjects(dev);
4662         }
4663         if (ok) {
4664                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("write checkpoint validity" TENDSTR)));
4665                 ok = yaffs_WriteCheckpointValidityMarker(dev, 0);
4666         }
4667
4668         if (ok)
4669                 ok = yaffs_WriteCheckpointSum(dev);
4670
4671         if (!yaffs_CheckpointClose(dev))
4672                 ok = 0;
4673
4674         if (ok)
4675                 dev->isCheckpointed = 1;
4676         else
4677                 dev->isCheckpointed = 0;
4678
4679         return dev->isCheckpointed;
4680 }
4681
4682 static int yaffs_ReadCheckpointData(yaffs_Device *dev)
4683 {
4684         int ok = 1;
4685
4686         if (dev->skipCheckpointRead || !dev->isYaffs2) {
4687                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("skipping checkpoint read" TENDSTR)));
4688                 ok = 0;
4689         }
4690
4691         if (ok)
4692                 ok = yaffs_CheckpointOpen(dev, 0); /* open for read */
4693
4694         if (ok) {
4695                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4696                 ok = yaffs_ReadCheckpointValidityMarker(dev, 1);
4697         }
4698         if (ok) {
4699                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint device" TENDSTR)));
4700                 ok = yaffs_ReadCheckpointDevice(dev);
4701         }
4702         if (ok) {
4703                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint objects" TENDSTR)));
4704                 ok = yaffs_ReadCheckpointObjects(dev);
4705         }
4706         if (ok) {
4707                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint validity" TENDSTR)));
4708                 ok = yaffs_ReadCheckpointValidityMarker(dev, 0);
4709         }
4710
4711         if (ok) {
4712                 ok = yaffs_ReadCheckpointSum(dev);
4713                 T(YAFFS_TRACE_CHECKPOINT, (TSTR("read checkpoint checksum %d" TENDSTR), ok));
4714         }
4715
4716         if (!yaffs_CheckpointClose(dev))
4717                 ok = 0;
4718
4719         if (ok)
4720                 dev->isCheckpointed = 1;
4721         else
4722                 dev->isCheckpointed = 0;
4723
4724         return ok ? 1 : 0;
4725
4726 }
4727
4728 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev)
4729 {
4730         if (dev->isCheckpointed ||
4731                         dev->blocksInCheckpoint > 0) {
4732                 dev->isCheckpointed = 0;
4733                 yaffs_CheckpointInvalidateStream(dev);
4734                 if (dev->superBlock && dev->markSuperBlockDirty)
4735                         dev->markSuperBlockDirty(dev->superBlock);
4736         }
4737 }
4738
4739
4740 int yaffs_CheckpointSave(yaffs_Device *dev)
4741 {
4742
4743         T(YAFFS_TRACE_CHECKPOINT, (TSTR("save entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4744
4745         yaffs_VerifyObjects(dev);
4746         yaffs_VerifyBlocks(dev);
4747         yaffs_VerifyFreeChunks(dev);
4748
4749         if (!dev->isCheckpointed) {
4750                 yaffs_InvalidateCheckpoint(dev);
4751                 yaffs_WriteCheckpointData(dev);
4752         }
4753
4754         T(YAFFS_TRACE_ALWAYS, (TSTR("save exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4755
4756         return dev->isCheckpointed;
4757 }
4758
4759 int yaffs_CheckpointRestore(yaffs_Device *dev)
4760 {
4761         int retval;
4762         T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore entry: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4763
4764         retval = yaffs_ReadCheckpointData(dev);
4765
4766         if (dev->isCheckpointed) {
4767                 yaffs_VerifyObjects(dev);
4768                 yaffs_VerifyBlocks(dev);
4769                 yaffs_VerifyFreeChunks(dev);
4770         }
4771
4772         T(YAFFS_TRACE_CHECKPOINT, (TSTR("restore exit: isCheckpointed %d"TENDSTR), dev->isCheckpointed));
4773
4774         return retval;
4775 }
4776
4777 /*--------------------- File read/write ------------------------
4778  * Read and write have very similar structures.
4779  * In general the read/write has three parts to it
4780  * An incomplete chunk to start with (if the read/write is not chunk-aligned)
4781  * Some complete chunks
4782  * An incomplete chunk to end off with
4783  *
4784  * Curve-balls: the first chunk might also be the last chunk.
4785  */
4786
4787 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 *buffer, loff_t offset,
4788                         int nBytes)
4789 {
4790
4791         int chunk;
4792         __u32 start;
4793         int nToCopy;
4794         int n = nBytes;
4795         int nDone = 0;
4796         yaffs_ChunkCache *cache;
4797
4798         yaffs_Device *dev;
4799
4800         dev = in->myDev;
4801
4802         while (n > 0) {
4803                 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4804                 /* start = offset % dev->nDataBytesPerChunk; */
4805                 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4806                 chunk++;
4807
4808                 /* OK now check for the curveball where the start and end are in
4809                  * the same chunk.
4810                  */
4811                 if ((start + n) < dev->nDataBytesPerChunk)
4812                         nToCopy = n;
4813                 else
4814                         nToCopy = dev->nDataBytesPerChunk - start;
4815
4816                 cache = yaffs_FindChunkCache(in, chunk);
4817
4818                 /* If the chunk is already in the cache or it is less than a whole chunk
4819                  * or we're using inband tags then use the cache (if there is caching)
4820                  * else bypass the cache.
4821                  */
4822                 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4823                         if (dev->nShortOpCaches > 0) {
4824
4825                                 /* If we can't find the data in the cache, then load it up. */
4826
4827                                 if (!cache) {
4828                                         cache = yaffs_GrabChunkCache(in->myDev);
4829                                         cache->object = in;
4830                                         cache->chunkId = chunk;
4831                                         cache->dirty = 0;
4832                                         cache->locked = 0;
4833                                         yaffs_ReadChunkDataFromObject(in, chunk,
4834                                                                       cache->
4835                                                                       data);
4836                                         cache->nBytes = 0;
4837                                 }
4838
4839                                 yaffs_UseChunkCache(dev, cache, 0);
4840
4841                                 cache->locked = 1;
4842
4843
4844                                 memcpy(buffer, &cache->data[start], nToCopy);
4845
4846                                 cache->locked = 0;
4847                         } else {
4848                                 /* Read into the local buffer then copy..*/
4849
4850                                 __u8 *localBuffer =
4851                                     yaffs_GetTempBuffer(dev, __LINE__);
4852                                 yaffs_ReadChunkDataFromObject(in, chunk,
4853                                                               localBuffer);
4854
4855                                 memcpy(buffer, &localBuffer[start], nToCopy);
4856
4857
4858                                 yaffs_ReleaseTempBuffer(dev, localBuffer,
4859                                                         __LINE__);
4860                         }
4861
4862                 } else {
4863
4864                         /* A full chunk. Read directly into the supplied buffer. */
4865                         yaffs_ReadChunkDataFromObject(in, chunk, buffer);
4866
4867                 }
4868
4869                 n -= nToCopy;
4870                 offset += nToCopy;
4871                 buffer += nToCopy;
4872                 nDone += nToCopy;
4873
4874         }
4875
4876         return nDone;
4877 }
4878
4879 int yaffs_WriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
4880                         int nBytes, int writeThrough)
4881 {
4882
4883         int chunk;
4884         __u32 start;
4885         int nToCopy;
4886         int n = nBytes;
4887         int nDone = 0;
4888         int nToWriteBack;
4889         int startOfWrite = offset;
4890         int chunkWritten = 0;
4891         __u32 nBytesRead;
4892         __u32 chunkStart;
4893
4894         yaffs_Device *dev;
4895
4896         dev = in->myDev;
4897
4898         while (n > 0 && chunkWritten >= 0) {
4899                 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
4900                 /* start = offset % dev->nDataBytesPerChunk; */
4901                 yaffs_AddrToChunk(dev, offset, &chunk, &start);
4902
4903                 if (chunk * dev->nDataBytesPerChunk + start != offset ||
4904                                 start >= dev->nDataBytesPerChunk) {
4905                         T(YAFFS_TRACE_ERROR, (
4906                            TSTR("AddrToChunk of offset %d gives chunk %d start %d"
4907                            TENDSTR),
4908                            (int)offset, chunk, start));
4909                 }
4910                 chunk++;
4911
4912                 /* OK now check for the curveball where the start and end are in
4913                  * the same chunk.
4914                  */
4915
4916                 if ((start + n) < dev->nDataBytesPerChunk) {
4917                         nToCopy = n;
4918
4919                         /* Now folks, to calculate how many bytes to write back....
4920                          * If we're overwriting and not writing to then end of file then
4921                          * we need to write back as much as was there before.
4922                          */
4923
4924                         chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
4925
4926                         if (chunkStart > in->variant.fileVariant.fileSize)
4927                                 nBytesRead = 0; /* Past end of file */
4928                         else
4929                                 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
4930
4931                         if (nBytesRead > dev->nDataBytesPerChunk)
4932                                 nBytesRead = dev->nDataBytesPerChunk;
4933
4934                         nToWriteBack =
4935                             (nBytesRead >
4936                              (start + n)) ? nBytesRead : (start + n);
4937
4938                         if (nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
4939                                 YBUG();
4940
4941                 } else {
4942                         nToCopy = dev->nDataBytesPerChunk - start;
4943                         nToWriteBack = dev->nDataBytesPerChunk;
4944                 }
4945
4946                 if (nToCopy != dev->nDataBytesPerChunk || dev->inbandTags) {
4947                         /* An incomplete start or end chunk (or maybe both start and end chunk),
4948                          * or we're using inband tags, so we want to use the cache buffers.
4949                          */
4950                         if (dev->nShortOpCaches > 0) {
4951                                 yaffs_ChunkCache *cache;
4952                                 /* If we can't find the data in the cache, then load the cache */
4953                                 cache = yaffs_FindChunkCache(in, chunk);
4954
4955                                 if (!cache
4956                                     && yaffs_CheckSpaceForAllocation(in->
4957                                                                      myDev)) {
4958                                         cache = yaffs_GrabChunkCache(in->myDev);
4959                                         cache->object = in;
4960                                         cache->chunkId = chunk;
4961                                         cache->dirty = 0;
4962                                         cache->locked = 0;
4963                                         yaffs_ReadChunkDataFromObject(in, chunk,
4964                                                                       cache->
4965                                                                       data);
4966                                 } else if (cache &&
4967                                         !cache->dirty &&
4968                                         !yaffs_CheckSpaceForAllocation(in->myDev)) {
4969                                         /* Drop the cache if it was a read cache item and
4970                                          * no space check has been made for it.
4971                                          */
4972                                          cache = NULL;
4973                                 }
4974
4975                                 if (cache) {
4976                                         yaffs_UseChunkCache(dev, cache, 1);
4977                                         cache->locked = 1;
4978
4979
4980                                         memcpy(&cache->data[start], buffer,
4981                                                nToCopy);
4982
4983
4984                                         cache->locked = 0;
4985                                         cache->nBytes = nToWriteBack;
4986
4987                                         if (writeThrough) {
4988                                                 chunkWritten =
4989                                                     yaffs_WriteChunkDataToObject
4990                                                     (cache->object,
4991                                                      cache->chunkId,
4992                                                      cache->data, cache->nBytes,
4993                                                      1);
4994                                                 cache->dirty = 0;
4995                                         }
4996
4997                                 } else {
4998                                         chunkWritten = -1;      /* fail the write */
4999                                 }
5000                         } else {
5001                                 /* An incomplete start or end chunk (or maybe both start and end chunk)
5002                                  * Read into the local buffer then copy, then copy over and write back.
5003                                  */
5004
5005                                 __u8 *localBuffer =
5006                                     yaffs_GetTempBuffer(dev, __LINE__);
5007
5008                                 yaffs_ReadChunkDataFromObject(in, chunk,
5009                                                               localBuffer);
5010
5011
5012
5013                                 memcpy(&localBuffer[start], buffer, nToCopy);
5014
5015                                 chunkWritten =
5016                                     yaffs_WriteChunkDataToObject(in, chunk,
5017                                                                  localBuffer,
5018                                                                  nToWriteBack,
5019                                                                  0);
5020
5021                                 yaffs_ReleaseTempBuffer(dev, localBuffer,
5022                                                         __LINE__);
5023
5024                         }
5025
5026                 } else {
5027                         /* A full chunk. Write directly from the supplied buffer. */
5028
5029
5030
5031                         chunkWritten =
5032                             yaffs_WriteChunkDataToObject(in, chunk, buffer,
5033                                                          dev->nDataBytesPerChunk,
5034                                                          0);
5035
5036                         /* Since we've overwritten the cached data, we better invalidate it. */
5037                         yaffs_InvalidateChunkCache(in, chunk);
5038                 }
5039
5040                 if (chunkWritten >= 0) {
5041                         n -= nToCopy;
5042                         offset += nToCopy;
5043                         buffer += nToCopy;
5044                         nDone += nToCopy;
5045                 }
5046
5047         }
5048
5049         /* Update file object */
5050
5051         if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
5052                 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
5053
5054         in->dirty = 1;
5055
5056         return nDone;
5057 }
5058
5059
5060 /* ---------------------- File resizing stuff ------------------ */
5061
5062 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
5063 {
5064
5065         yaffs_Device *dev = in->myDev;
5066         int oldFileSize = in->variant.fileVariant.fileSize;
5067
5068         int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
5069
5070         int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
5071             dev->nDataBytesPerChunk;
5072         int i;
5073         int chunkId;
5074
5075         /* Delete backwards so that we don't end up with holes if
5076          * power is lost part-way through the operation.
5077          */
5078         for (i = lastDel; i >= startDel; i--) {
5079                 /* NB this could be optimised somewhat,
5080                  * eg. could retrieve the tags and write them without
5081                  * using yaffs_DeleteChunk
5082                  */
5083
5084                 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
5085                 if (chunkId > 0) {
5086                         if (chunkId <
5087                             (dev->internalStartBlock * dev->nChunksPerBlock)
5088                             || chunkId >=
5089                             ((dev->internalEndBlock +
5090                               1) * dev->nChunksPerBlock)) {
5091                                 T(YAFFS_TRACE_ALWAYS,
5092                                   (TSTR("Found daft chunkId %d for %d" TENDSTR),
5093                                    chunkId, i));
5094                         } else {
5095                                 in->nDataChunks--;
5096                                 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
5097                         }
5098                 }
5099         }
5100
5101 }
5102
5103 int yaffs_ResizeFile(yaffs_Object *in, loff_t newSize)
5104 {
5105
5106         int oldFileSize = in->variant.fileVariant.fileSize;
5107         __u32 newSizeOfPartialChunk;
5108         int newFullChunks;
5109
5110         yaffs_Device *dev = in->myDev;
5111
5112         yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
5113
5114         yaffs_FlushFilesChunkCache(in);
5115         yaffs_InvalidateWholeChunkCache(in);
5116
5117         yaffs_CheckGarbageCollection(dev);
5118
5119         if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
5120                 return YAFFS_FAIL;
5121
5122         if (newSize == oldFileSize)
5123                 return YAFFS_OK;
5124
5125         if (newSize < oldFileSize) {
5126
5127                 yaffs_PruneResizedChunks(in, newSize);
5128
5129                 if (newSizeOfPartialChunk != 0) {
5130                         int lastChunk = 1 + newFullChunks;
5131
5132                         __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
5133
5134                         /* Got to read and rewrite the last chunk with its new size and zero pad */
5135                         yaffs_ReadChunkDataFromObject(in, lastChunk,
5136                                                       localBuffer);
5137
5138                         memset(localBuffer + newSizeOfPartialChunk, 0,
5139                                dev->nDataBytesPerChunk - newSizeOfPartialChunk);
5140
5141                         yaffs_WriteChunkDataToObject(in, lastChunk, localBuffer,
5142                                                      newSizeOfPartialChunk, 1);
5143
5144                         yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
5145                 }
5146
5147                 in->variant.fileVariant.fileSize = newSize;
5148
5149                 yaffs_PruneFileStructure(dev, &in->variant.fileVariant);
5150         } else {
5151                 /* newsSize > oldFileSize */
5152                 in->variant.fileVariant.fileSize = newSize;
5153         }
5154
5155
5156         /* Write a new object header to reflect the resize.
5157          * show we've shrunk the file, if need be
5158          * Do this only if the file is not in the deleted directories
5159          * and is not shadowed.
5160          */
5161         if (in->parent &&
5162             !in->isShadowed &&
5163             in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
5164             in->parent->objectId != YAFFS_OBJECTID_DELETED)
5165                 yaffs_UpdateObjectHeader(in, NULL, 0,
5166                                          (newSize < oldFileSize) ? 1 : 0, 0);
5167
5168         return YAFFS_OK;
5169 }
5170
5171 loff_t yaffs_GetFileSize(yaffs_Object *obj)
5172 {
5173         YCHAR *alias = NULL;
5174         obj = yaffs_GetEquivalentObject(obj);
5175
5176         switch (obj->variantType) {
5177         case YAFFS_OBJECT_TYPE_FILE:
5178                 return obj->variant.fileVariant.fileSize;
5179         case YAFFS_OBJECT_TYPE_SYMLINK:
5180                 alias = obj->variant.symLinkVariant.alias;
5181                 if(!alias)
5182                         return 0;
5183                 return yaffs_strnlen(alias,YAFFS_MAX_ALIAS_LENGTH);
5184         default:
5185                 return 0;
5186         }
5187 }
5188
5189
5190
5191 int yaffs_FlushFile(yaffs_Object *in, int updateTime, int dataSync)
5192 {
5193         int retVal;
5194         if (in->dirty) {
5195                 yaffs_FlushFilesChunkCache(in);
5196                 if(dataSync) /* Only sync data */
5197                         retVal=YAFFS_OK;
5198                 else {
5199                         if (updateTime) {
5200 #ifdef CONFIG_YAFFS_WINCE
5201                                 yfsd_WinFileTimeNow(in->win_mtime);
5202 #else
5203
5204                                 in->yst_mtime = Y_CURRENT_TIME;
5205
5206 #endif
5207                         }
5208
5209                         retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0) >=
5210                                 0) ? YAFFS_OK : YAFFS_FAIL;
5211                 }
5212         } else {
5213                 retVal = YAFFS_OK;
5214         }
5215
5216         return retVal;
5217
5218 }
5219
5220 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
5221 {
5222
5223         /* First off, invalidate the file's data in the cache, without flushing. */
5224         yaffs_InvalidateWholeChunkCache(in);
5225
5226         if (in->myDev->isYaffs2 && (in->parent != in->myDev->deletedDir)) {
5227                 /* Move to the unlinked directory so we have a record that it was deleted. */
5228                 yaffs_ChangeObjectName(in, in->myDev->deletedDir, _Y("deleted"), 0, 0);
5229
5230         }
5231
5232         yaffs_RemoveObjectFromDirectory(in);
5233         yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
5234         in->hdrChunk = 0;
5235
5236         yaffs_FreeObject(in);
5237         return YAFFS_OK;
5238
5239 }
5240
5241 /* yaffs_DeleteFile deletes the whole file data
5242  * and the inode associated with the file.
5243  * It does not delete the links associated with the file.
5244  */
5245 static int yaffs_UnlinkFileIfNeeded(yaffs_Object *in)
5246 {
5247
5248         int retVal;
5249         int immediateDeletion = 0;
5250
5251 #ifdef __KERNEL__
5252         if (!in->myInode)
5253                 immediateDeletion = 1;
5254 #else
5255         if (in->inUse <= 0)
5256                 immediateDeletion = 1;
5257 #endif
5258
5259         if (immediateDeletion) {
5260                 retVal =
5261                     yaffs_ChangeObjectName(in, in->myDev->deletedDir,
5262                                            _Y("deleted"), 0, 0);
5263                 T(YAFFS_TRACE_TRACING,
5264                   (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
5265                    in->objectId));
5266                 in->deleted = 1;
5267                 in->myDev->nDeletedFiles++;
5268                 if (1 || in->myDev->isYaffs2)
5269                         yaffs_ResizeFile(in, 0);
5270                 yaffs_SoftDeleteFile(in);
5271         } else {
5272                 retVal =
5273                     yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
5274                                            _Y("unlinked"), 0, 0);
5275         }
5276
5277
5278         return retVal;
5279 }
5280
5281 int yaffs_DeleteFile(yaffs_Object *in)
5282 {
5283         int retVal = YAFFS_OK;
5284         int deleted = in->deleted;
5285
5286         yaffs_ResizeFile(in, 0);
5287
5288         if (in->nDataChunks > 0) {
5289                 /* Use soft deletion if there is data in the file.
5290                  * That won't be the case if it has been resized to zero.
5291                  */
5292                 if (!in->unlinked)
5293                         retVal = yaffs_UnlinkFileIfNeeded(in);
5294
5295                 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
5296                         in->deleted = 1;
5297                         deleted = 1;
5298                         in->myDev->nDeletedFiles++;
5299                         yaffs_SoftDeleteFile(in);
5300                 }
5301                 return deleted ? YAFFS_OK : YAFFS_FAIL;
5302         } else {
5303                 /* The file has no data chunks so we toss it immediately */
5304                 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
5305                 in->variant.fileVariant.top = NULL;
5306                 yaffs_DoGenericObjectDeletion(in);
5307
5308                 return YAFFS_OK;
5309         }
5310 }
5311
5312 static int yaffs_IsNonEmptyDirectory(yaffs_Object *obj)
5313 {
5314         return (obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) &&
5315                 !(ylist_empty(&obj->variant.directoryVariant.children));
5316 }
5317
5318 static int yaffs_DeleteDirectory(yaffs_Object *obj)
5319 {
5320         /* First check that the directory is empty. */
5321         if (yaffs_IsNonEmptyDirectory(obj))
5322                 return YAFFS_FAIL;
5323
5324         return yaffs_DoGenericObjectDeletion(obj);
5325 }
5326
5327 static int yaffs_DeleteSymLink(yaffs_Object *in)
5328 {
5329         if(in->variant.symLinkVariant.alias)
5330                 YFREE(in->variant.symLinkVariant.alias);
5331         in->variant.symLinkVariant.alias=NULL;
5332
5333         return yaffs_DoGenericObjectDeletion(in);
5334 }
5335
5336 static int yaffs_DeleteHardLink(yaffs_Object *in)
5337 {
5338         /* remove this hardlink from the list assocaited with the equivalent
5339          * object
5340          */
5341         ylist_del_init(&in->hardLinks);
5342         return yaffs_DoGenericObjectDeletion(in);
5343 }
5344
5345 int yaffs_DeleteObject(yaffs_Object *obj)
5346 {
5347 int retVal = -1;
5348         switch (obj->variantType) {
5349         case YAFFS_OBJECT_TYPE_FILE:
5350                 retVal = yaffs_DeleteFile(obj);
5351                 break;
5352         case YAFFS_OBJECT_TYPE_DIRECTORY:
5353                 return yaffs_DeleteDirectory(obj);
5354                 break;
5355         case YAFFS_OBJECT_TYPE_SYMLINK:
5356                 retVal = yaffs_DeleteSymLink(obj);
5357                 break;
5358         case YAFFS_OBJECT_TYPE_HARDLINK:
5359                 retVal = yaffs_DeleteHardLink(obj);
5360                 break;
5361         case YAFFS_OBJECT_TYPE_SPECIAL:
5362                 retVal = yaffs_DoGenericObjectDeletion(obj);
5363                 break;
5364         case YAFFS_OBJECT_TYPE_UNKNOWN:
5365                 retVal = 0;
5366                 break;          /* should not happen. */
5367         }
5368
5369         return retVal;
5370 }
5371
5372 static int yaffs_UnlinkWorker(yaffs_Object *obj)
5373 {
5374
5375         int immediateDeletion = 0;
5376
5377 #ifdef __KERNEL__
5378         if (!obj->myInode)
5379                 immediateDeletion = 1;
5380 #else
5381         if (obj->inUse <= 0)
5382                 immediateDeletion = 1;
5383 #endif
5384
5385         if(obj)
5386                 yaffs_UpdateParent(obj->parent);
5387
5388         if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
5389                 return yaffs_DeleteHardLink(obj);
5390         } else if (!ylist_empty(&obj->hardLinks)) {
5391                 /* Curve ball: We're unlinking an object that has a hardlink.
5392                  *
5393                  * This problem arises because we are not strictly following
5394                  * The Linux link/inode model.
5395                  *
5396                  * We can't really delete the object.
5397                  * Instead, we do the following:
5398                  * - Select a hardlink.
5399                  * - Unhook it from the hard links
5400                  * - Unhook it from its parent directory (so that the rename can work)
5401                  * - Rename the object to the hardlink's name.
5402                  * - Delete the hardlink
5403                  */
5404
5405                 yaffs_Object *hl;
5406                 int retVal;
5407                 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
5408
5409                 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
5410
5411                 ylist_del_init(&hl->hardLinks);
5412                 ylist_del_init(&hl->siblings);
5413
5414                 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
5415
5416                 retVal = yaffs_ChangeObjectName(obj, hl->parent, name, 0, 0);
5417
5418                 if (retVal == YAFFS_OK)
5419                         retVal = yaffs_DoGenericObjectDeletion(hl);
5420
5421                 return retVal;
5422
5423         } else if (immediateDeletion) {
5424                 switch (obj->variantType) {
5425                 case YAFFS_OBJECT_TYPE_FILE:
5426                         return yaffs_DeleteFile(obj);
5427                         break;
5428                 case YAFFS_OBJECT_TYPE_DIRECTORY:
5429                         return yaffs_DeleteDirectory(obj);
5430                         break;
5431                 case YAFFS_OBJECT_TYPE_SYMLINK:
5432                         return yaffs_DeleteSymLink(obj);
5433                         break;
5434                 case YAFFS_OBJECT_TYPE_SPECIAL:
5435                         return yaffs_DoGenericObjectDeletion(obj);
5436                         break;
5437                 case YAFFS_OBJECT_TYPE_HARDLINK:
5438                 case YAFFS_OBJECT_TYPE_UNKNOWN:
5439                 default:
5440                         return YAFFS_FAIL;
5441                 }
5442         } else if(yaffs_IsNonEmptyDirectory(obj))
5443                 return YAFFS_FAIL;
5444         else
5445                 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
5446                                            _Y("unlinked"), 0, 0);
5447 }
5448
5449
5450 static int yaffs_UnlinkObject(yaffs_Object *obj)
5451 {
5452
5453         if (obj && obj->unlinkAllowed)
5454                 return yaffs_UnlinkWorker(obj);
5455
5456         return YAFFS_FAIL;
5457
5458 }
5459 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
5460 {
5461         yaffs_Object *obj;
5462
5463         obj = yaffs_FindObjectByName(dir, name);
5464         return yaffs_UnlinkObject(obj);
5465 }
5466
5467 /*----------------------- Initialisation Scanning ---------------------- */
5468
5469 static void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
5470                                 int backwardScanning)
5471 {
5472         yaffs_Object *obj;
5473
5474         if (!backwardScanning) {
5475                 /* Handle YAFFS1 forward scanning case
5476                  * For YAFFS1 we always do the deletion
5477                  */
5478
5479         } else {
5480                 /* Handle YAFFS2 case (backward scanning)
5481                  * If the shadowed object exists then ignore.
5482                  */
5483                 obj = yaffs_FindObjectByNumber(dev, objId);
5484                 if(obj)
5485                         return;
5486         }
5487
5488         /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
5489          * We put it in unlinked dir to be cleaned up after the scanning
5490          */
5491         obj =
5492             yaffs_FindOrCreateObjectByNumber(dev, objId,
5493                                              YAFFS_OBJECT_TYPE_FILE);
5494         if (!obj)
5495                 return;
5496         obj->isShadowed = 1;
5497         yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
5498         obj->variant.fileVariant.shrinkSize = 0;
5499         obj->valid = 1;         /* So that we don't read any other info for this file */
5500
5501 }
5502
5503 typedef struct {
5504         int seq;
5505         int block;
5506 } yaffs_BlockIndex;
5507
5508
5509 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
5510 {
5511         yaffs_Object *hl;
5512         yaffs_Object *in;
5513
5514         while (hardList) {
5515                 hl = hardList;
5516                 hardList = (yaffs_Object *) (hardList->hardLinks.next);
5517
5518                 in = yaffs_FindObjectByNumber(dev,
5519                                               hl->variant.hardLinkVariant.
5520                                               equivalentObjectId);
5521
5522                 if (in) {
5523                         /* Add the hardlink pointers */
5524                         hl->variant.hardLinkVariant.equivalentObject = in;
5525                         ylist_add(&hl->hardLinks, &in->hardLinks);
5526                 } else {
5527                         /* Todo Need to report/handle this better.
5528                          * Got a problem... hardlink to a non-existant object
5529                          */
5530                         hl->variant.hardLinkVariant.equivalentObject = NULL;
5531                         YINIT_LIST_HEAD(&hl->hardLinks);
5532
5533                 }
5534         }
5535 }
5536
5537
5538
5539
5540
5541 static int ybicmp(const void *a, const void *b)
5542 {
5543         register int aseq = ((yaffs_BlockIndex *)a)->seq;
5544         register int bseq = ((yaffs_BlockIndex *)b)->seq;
5545         register int ablock = ((yaffs_BlockIndex *)a)->block;
5546         register int bblock = ((yaffs_BlockIndex *)b)->block;
5547         if (aseq == bseq)
5548                 return ablock - bblock;
5549         else
5550                 return aseq - bseq;
5551 }
5552
5553
5554 struct yaffs_ShadowFixerStruct {
5555         int objectId;
5556         int shadowedId;
5557         struct yaffs_ShadowFixerStruct *next;
5558 };
5559
5560
5561 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
5562 {
5563         /*
5564         *  Sort out state of unlinked and deleted objects after scanning.
5565         */
5566         struct ylist_head *i;
5567         struct ylist_head *n;
5568         yaffs_Object *l;
5569
5570         /* Soft delete all the unlinked files */
5571         ylist_for_each_safe(i, n,
5572                 &dev->unlinkedDir->variant.directoryVariant.children) {
5573                 if (i) {
5574                         l = ylist_entry(i, yaffs_Object, siblings);
5575                         yaffs_DeleteObject(l);
5576                 }
5577         }
5578
5579         ylist_for_each_safe(i, n,
5580                 &dev->deletedDir->variant.directoryVariant.children) {
5581                 if (i) {
5582                         l = ylist_entry(i, yaffs_Object, siblings);
5583                         yaffs_DeleteObject(l);
5584                 }
5585         }
5586
5587 }
5588
5589 /*
5590  * This code iterates through all the objects making sure that they are rooted.
5591  * Any unrooted objects are re-rooted in lost+found.
5592  * An object needs to be in one of:
5593  * - Directly under deleted, unlinked
5594  * - Directly or indirectly under root.
5595  *
5596  * Note:
5597  *  This code assumes that we don't ever change the current relationships between
5598  *  directories:
5599  *   rootDir->parent == unlinkedDir->parent == deletedDir->parent == NULL
5600  *   lostNfound->parent == rootDir
5601  *
5602  * This fixes the problem where directories might have inadvertently been deleted
5603  * leaving the object "hanging" without being rooted in the directory tree.
5604  */
5605  
5606 static int yaffs_HasNULLParent(yaffs_Device *dev, yaffs_Object *obj)
5607 {
5608         return (obj == dev->deletedDir ||
5609                 obj == dev->unlinkedDir||
5610                 obj == dev->rootDir);
5611 }
5612
5613 static void yaffs_FixHangingObjects(yaffs_Device *dev)
5614 {
5615         yaffs_Object *obj;
5616         yaffs_Object *parent;
5617         int i;
5618         struct ylist_head *lh;
5619         struct ylist_head *n;
5620         int depthLimit;
5621         int hanging;
5622
5623
5624         /* Iterate through the objects in each hash entry,
5625          * looking at each object.
5626          * Make sure it is rooted.
5627          */
5628
5629         for (i = 0; i <  YAFFS_NOBJECT_BUCKETS; i++) {
5630                 ylist_for_each_safe(lh, n, &dev->objectBucket[i].list) {
5631                         if (lh) {
5632                                 obj = ylist_entry(lh, yaffs_Object, hashLink);
5633                                 parent= obj->parent;
5634                                 
5635                                 if(yaffs_HasNULLParent(dev,obj)){
5636                                         /* These directories are not hanging */
5637                                         hanging = 0;
5638                                 }
5639                                 else if(!parent || parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5640                                         hanging = 1;
5641                                 else if(yaffs_HasNULLParent(dev,parent))
5642                                         hanging = 0;
5643                                 else {
5644                                         /*
5645                                          * Need to follow the parent chain to see if it is hanging.
5646                                          */
5647                                         hanging = 0;
5648                                         depthLimit=100;
5649
5650                                         while(parent != dev->rootDir &&
5651                                                 parent->parent &&
5652                                                 parent->parent->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
5653                                                 depthLimit > 0){
5654                                                 parent = parent->parent;
5655                                                 depthLimit--;
5656                                         }
5657                                         if(parent != dev->rootDir)
5658                                                 hanging = 1;
5659                                 }
5660                                 if(hanging){
5661                                         T(YAFFS_TRACE_SCAN,
5662                                           (TSTR("Hanging object %d moved to lost and found" TENDSTR),
5663                                                 obj->objectId));
5664                                         yaffs_AddObjectToDirectory(dev->lostNFoundDir,obj);
5665                                 }
5666                         }
5667                 }
5668         }
5669 }
5670
5671
5672 /*
5673  * Delete directory contents for cleaning up lost and found.
5674  */
5675 static void yaffs_DeleteDirectoryContents(yaffs_Object *dir)
5676 {
5677         yaffs_Object *obj;
5678         struct ylist_head *lh;
5679         struct ylist_head *n;
5680
5681         if(dir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
5682                 YBUG();
5683         
5684         ylist_for_each_safe(lh, n, &dir->variant.directoryVariant.children) {
5685                 if (lh) {
5686                         obj = ylist_entry(lh, yaffs_Object, siblings);
5687                         if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
5688                                 yaffs_DeleteDirectoryContents(obj);
5689
5690                         T(YAFFS_TRACE_SCAN,
5691                                 (TSTR("Deleting lost_found object %d" TENDSTR),
5692                                 obj->objectId));
5693
5694                         /* Need to use UnlinkObject since Delete would not handle
5695                          * hardlinked objects correctly.
5696                          */
5697                         yaffs_UnlinkObject(obj); 
5698                 }
5699         }
5700                         
5701 }
5702
5703 static void yaffs_EmptyLostAndFound(yaffs_Device *dev)
5704 {
5705         yaffs_DeleteDirectoryContents(dev->lostNFoundDir);
5706 }
5707
5708 static int yaffs_Scan(yaffs_Device *dev)
5709 {
5710         yaffs_ExtendedTags tags;
5711         int blk;
5712         int blockIterator;
5713         int startIterator;
5714         int endIterator;
5715         int result;
5716
5717         int chunk;
5718         int c;
5719         int deleted;
5720         yaffs_BlockState state;
5721         yaffs_Object *hardList = NULL;
5722         yaffs_BlockInfo *bi;
5723         __u32 sequenceNumber;
5724         yaffs_ObjectHeader *oh;
5725         yaffs_Object *in;
5726         yaffs_Object *parent;
5727
5728         int alloc_failed = 0;
5729
5730         struct yaffs_ShadowFixerStruct *shadowFixerList = NULL;
5731
5732
5733         __u8 *chunkData;
5734
5735
5736
5737         T(YAFFS_TRACE_SCAN,
5738           (TSTR("yaffs_Scan starts  intstartblk %d intendblk %d..." TENDSTR),
5739            dev->internalStartBlock, dev->internalEndBlock));
5740
5741         chunkData = yaffs_GetTempBuffer(dev, __LINE__);
5742
5743         dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
5744
5745         /* Scan all the blocks to determine their state */
5746         for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
5747                 bi = yaffs_GetBlockInfo(dev, blk);
5748                 yaffs_ClearChunkBits(dev, blk);
5749                 bi->pagesInUse = 0;
5750                 bi->softDeletions = 0;
5751
5752                 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
5753
5754                 bi->blockState = state;
5755                 bi->sequenceNumber = sequenceNumber;
5756
5757                 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
5758                         bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
5759
5760                 T(YAFFS_TRACE_SCAN_DEBUG,
5761                   (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
5762                    state, sequenceNumber));
5763
5764                 if (state == YAFFS_BLOCK_STATE_DEAD) {
5765                         T(YAFFS_TRACE_BAD_BLOCKS,
5766                           (TSTR("block %d is bad" TENDSTR), blk));
5767                 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
5768                         T(YAFFS_TRACE_SCAN_DEBUG,
5769                           (TSTR("Block empty " TENDSTR)));
5770                         dev->nErasedBlocks++;
5771                         dev->nFreeChunks += dev->nChunksPerBlock;
5772                 }
5773         }
5774
5775         startIterator = dev->internalStartBlock;
5776         endIterator = dev->internalEndBlock;
5777
5778         /* For each block.... */
5779         for (blockIterator = startIterator; !alloc_failed && blockIterator <= endIterator;
5780              blockIterator++) {
5781
5782                 YYIELD();
5783
5784                 YYIELD();
5785
5786                 blk = blockIterator;
5787
5788                 bi = yaffs_GetBlockInfo(dev, blk);
5789                 state = bi->blockState;
5790
5791                 deleted = 0;
5792
5793                 /* For each chunk in each block that needs scanning....*/
5794                 for (c = 0; !alloc_failed && c < dev->nChunksPerBlock &&
5795                      state == YAFFS_BLOCK_STATE_NEEDS_SCANNING; c++) {
5796                         /* Read the tags and decide what to do */
5797                         chunk = blk * dev->nChunksPerBlock + c;
5798
5799                         result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
5800                                                         &tags);
5801
5802                         /* Let's have a good look at this chunk... */
5803
5804                         if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED || tags.chunkDeleted) {
5805                                 /* YAFFS1 only...
5806                                  * A deleted chunk
5807                                  */
5808                                 deleted++;
5809                                 dev->nFreeChunks++;
5810                                 /*T((" %d %d deleted\n",blk,c)); */
5811                         } else if (!tags.chunkUsed) {
5812                                 /* An unassigned chunk in the block
5813                                  * This means that either the block is empty or
5814                                  * this is the one being allocated from
5815                                  */
5816
5817                                 if (c == 0) {
5818                                         /* We're looking at the first chunk in the block so the block is unused */
5819                                         state = YAFFS_BLOCK_STATE_EMPTY;
5820                                         dev->nErasedBlocks++;
5821                                 } else {
5822                                         /* this is the block being allocated from */
5823                                         T(YAFFS_TRACE_SCAN,
5824                                           (TSTR
5825                                            (" Allocating from %d %d" TENDSTR),
5826                                            blk, c));
5827                                         state = YAFFS_BLOCK_STATE_ALLOCATING;
5828                                         dev->allocationBlock = blk;
5829                                         dev->allocationPage = c;
5830                                         dev->allocationBlockFinder = blk;
5831                                         /* Set block finder here to encourage the allocator to go forth from here. */
5832
5833                                 }
5834
5835                                 dev->nFreeChunks += (dev->nChunksPerBlock - c);
5836                         } else if (tags.chunkId > 0) {
5837                                 /* chunkId > 0 so it is a data chunk... */
5838                                 unsigned int endpos;
5839
5840                                 yaffs_SetChunkBit(dev, blk, c);
5841                                 bi->pagesInUse++;
5842
5843                                 in = yaffs_FindOrCreateObjectByNumber(dev,
5844                                                                       tags.
5845                                                                       objectId,
5846                                                                       YAFFS_OBJECT_TYPE_FILE);
5847                                 /* PutChunkIntoFile checks for a clash (two data chunks with
5848                                  * the same chunkId).
5849                                  */
5850
5851                                 if (!in)
5852                                         alloc_failed = 1;
5853
5854                                 if (in) {
5855                                         if (!yaffs_PutChunkIntoFile(in, tags.chunkId, chunk, 1))
5856                                                 alloc_failed = 1;
5857                                 }
5858
5859                                 endpos =
5860                                     (tags.chunkId - 1) * dev->nDataBytesPerChunk +
5861                                     tags.byteCount;
5862                                 if (in &&
5863                                     in->variantType == YAFFS_OBJECT_TYPE_FILE
5864                                     && in->variant.fileVariant.scannedFileSize <
5865                                     endpos) {
5866                                         in->variant.fileVariant.
5867                                             scannedFileSize = endpos;
5868                                         if (!dev->useHeaderFileSize) {
5869                                                 in->variant.fileVariant.
5870                                                     fileSize =
5871                                                     in->variant.fileVariant.
5872                                                     scannedFileSize;
5873                                         }
5874
5875                                 }
5876                                 /* T((" %d %d data %d %d\n",blk,c,tags.objectId,tags.chunkId));   */
5877                         } else {
5878                                 /* chunkId == 0, so it is an ObjectHeader.
5879                                  * Thus, we read in the object header and make the object
5880                                  */
5881                                 yaffs_SetChunkBit(dev, blk, c);
5882                                 bi->pagesInUse++;
5883
5884                                 result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk,
5885                                                                 chunkData,
5886                                                                 NULL);
5887
5888                                 oh = (yaffs_ObjectHeader *) chunkData;
5889
5890                                 in = yaffs_FindObjectByNumber(dev,
5891                                                               tags.objectId);
5892                                 if (in && in->variantType != oh->type) {
5893                                         /* This should not happen, but somehow
5894                                          * Wev'e ended up with an objectId that has been reused but not yet
5895                                          * deleted, and worse still it has changed type. Delete the old object.
5896                                          */
5897
5898                                         yaffs_DeleteObject(in);
5899
5900                                         in = 0;
5901                                 }
5902
5903                                 in = yaffs_FindOrCreateObjectByNumber(dev,
5904                                                                       tags.
5905                                                                       objectId,
5906                                                                       oh->type);
5907
5908                                 if (!in)
5909                                         alloc_failed = 1;
5910
5911                                 if (in && oh->shadowsObject > 0) {
5912
5913                                         struct yaffs_ShadowFixerStruct *fixer;
5914                                         fixer = YMALLOC(sizeof(struct yaffs_ShadowFixerStruct));
5915                                         if (fixer) {
5916                                                 fixer->next = shadowFixerList;
5917                                                 shadowFixerList = fixer;
5918                                                 fixer->objectId = tags.objectId;
5919                                                 fixer->shadowedId = oh->shadowsObject;
5920                                         }
5921
5922                                 }
5923
5924                                 if (in && in->valid) {
5925                                         /* We have already filled this one. We have a duplicate and need to resolve it. */
5926
5927                                         unsigned existingSerial = in->serial;
5928                                         unsigned newSerial = tags.serialNumber;
5929
5930                                         if (((existingSerial + 1) & 3) == newSerial) {
5931                                                 /* Use new one - destroy the exisiting one */
5932                                                 yaffs_DeleteChunk(dev,
5933                                                                   in->hdrChunk,
5934                                                                   1, __LINE__);
5935                                                 in->valid = 0;
5936                                         } else {
5937                                                 /* Use existing - destroy this one. */
5938                                                 yaffs_DeleteChunk(dev, chunk, 1,
5939                                                                   __LINE__);
5940                                         }
5941                                 }
5942
5943                                 if (in && !in->valid &&
5944                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
5945                                      tags.objectId == YAFFS_OBJECTID_LOSTNFOUND)) {
5946                                         /* We only load some info, don't fiddle with directory structure */
5947                                         in->valid = 1;
5948                                         in->variantType = oh->type;
5949
5950                                         in->yst_mode = oh->yst_mode;
5951 #ifdef CONFIG_YAFFS_WINCE
5952                                         in->win_atime[0] = oh->win_atime[0];
5953                                         in->win_ctime[0] = oh->win_ctime[0];
5954                                         in->win_mtime[0] = oh->win_mtime[0];
5955                                         in->win_atime[1] = oh->win_atime[1];
5956                                         in->win_ctime[1] = oh->win_ctime[1];
5957                                         in->win_mtime[1] = oh->win_mtime[1];
5958 #else
5959                                         in->yst_uid = oh->yst_uid;
5960                                         in->yst_gid = oh->yst_gid;
5961                                         in->yst_atime = oh->yst_atime;
5962                                         in->yst_mtime = oh->yst_mtime;
5963                                         in->yst_ctime = oh->yst_ctime;
5964                                         in->yst_rdev = oh->yst_rdev;
5965 #endif
5966                                         in->hdrChunk = chunk;
5967                                         in->serial = tags.serialNumber;
5968
5969                                 } else if (in && !in->valid) {
5970                                         /* we need to load this info */
5971
5972                                         in->valid = 1;
5973                                         in->variantType = oh->type;
5974
5975                                         in->yst_mode = oh->yst_mode;
5976 #ifdef CONFIG_YAFFS_WINCE
5977                                         in->win_atime[0] = oh->win_atime[0];
5978                                         in->win_ctime[0] = oh->win_ctime[0];
5979                                         in->win_mtime[0] = oh->win_mtime[0];
5980                                         in->win_atime[1] = oh->win_atime[1];
5981                                         in->win_ctime[1] = oh->win_ctime[1];
5982                                         in->win_mtime[1] = oh->win_mtime[1];
5983 #else
5984                                         in->yst_uid = oh->yst_uid;
5985                                         in->yst_gid = oh->yst_gid;
5986                                         in->yst_atime = oh->yst_atime;
5987                                         in->yst_mtime = oh->yst_mtime;
5988                                         in->yst_ctime = oh->yst_ctime;
5989                                         in->yst_rdev = oh->yst_rdev;
5990 #endif
5991                                         in->hdrChunk = chunk;
5992                                         in->serial = tags.serialNumber;
5993
5994                                         yaffs_SetObjectName(in, oh->name);
5995                                         in->dirty = 0;
5996
5997                                         /* directory stuff...
5998                                          * hook up to parent
5999                                          */
6000
6001                                         parent =
6002                                             yaffs_FindOrCreateObjectByNumber
6003                                             (dev, oh->parentObjectId,
6004                                              YAFFS_OBJECT_TYPE_DIRECTORY);
6005                                         if (!parent)
6006                                                 alloc_failed = 1;
6007                                         if (parent && parent->variantType ==
6008                                             YAFFS_OBJECT_TYPE_UNKNOWN) {
6009                                                 /* Set up as a directory */
6010                                                 parent->variantType =
6011                                                         YAFFS_OBJECT_TYPE_DIRECTORY;
6012                                                 YINIT_LIST_HEAD(&parent->variant.
6013                                                                 directoryVariant.
6014                                                                 children);
6015                                         } else if (!parent || parent->variantType !=
6016                                                    YAFFS_OBJECT_TYPE_DIRECTORY) {
6017                                                 /* Hoosterman, another problem....
6018                                                  * We're trying to use a non-directory as a directory
6019                                                  */
6020
6021                                                 T(YAFFS_TRACE_ERROR,
6022                                                   (TSTR
6023                                                    ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6024                                                     TENDSTR)));
6025                                                 parent = dev->lostNFoundDir;
6026                                         }
6027
6028                                         yaffs_AddObjectToDirectory(parent, in);
6029
6030                                         if (0 && (parent == dev->deletedDir ||
6031                                                   parent == dev->unlinkedDir)) {
6032                                                 in->deleted = 1;        /* If it is unlinked at start up then it wants deleting */
6033                                                 dev->nDeletedFiles++;
6034                                         }
6035                                         /* Note re hardlinks.
6036                                          * Since we might scan a hardlink before its equivalent object is scanned
6037                                          * we put them all in a list.
6038                                          * After scanning is complete, we should have all the objects, so we run through this
6039                                          * list and fix up all the chains.
6040                                          */
6041
6042                                         switch (in->variantType) {
6043                                         case YAFFS_OBJECT_TYPE_UNKNOWN:
6044                                                 /* Todo got a problem */
6045                                                 break;
6046                                         case YAFFS_OBJECT_TYPE_FILE:
6047                                                 if (dev->useHeaderFileSize)
6048
6049                                                         in->variant.fileVariant.
6050                                                             fileSize =
6051                                                             oh->fileSize;
6052
6053                                                 break;
6054                                         case YAFFS_OBJECT_TYPE_HARDLINK:
6055                                                 in->variant.hardLinkVariant.
6056                                                         equivalentObjectId =
6057                                                         oh->equivalentObjectId;
6058                                                 in->hardLinks.next =
6059                                                         (struct ylist_head *)
6060                                                         hardList;
6061                                                 hardList = in;
6062                                                 break;
6063                                         case YAFFS_OBJECT_TYPE_DIRECTORY:
6064                                                 /* Do nothing */
6065                                                 break;
6066                                         case YAFFS_OBJECT_TYPE_SPECIAL:
6067                                                 /* Do nothing */
6068                                                 break;
6069                                         case YAFFS_OBJECT_TYPE_SYMLINK:
6070                                                 in->variant.symLinkVariant.alias =
6071                                                     yaffs_CloneString(oh->alias);
6072                                                 if (!in->variant.symLinkVariant.alias)
6073                                                         alloc_failed = 1;
6074                                                 break;
6075                                         }
6076
6077                                 }
6078                         }
6079                 }
6080
6081                 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6082                         /* If we got this far while scanning, then the block is fully allocated.*/
6083                         state = YAFFS_BLOCK_STATE_FULL;
6084                 }
6085
6086                 if (state == YAFFS_BLOCK_STATE_ALLOCATING) {
6087                         /* If the block was partially allocated then treat it as fully allocated.*/
6088                         state = YAFFS_BLOCK_STATE_FULL;
6089                         dev->allocationBlock = -1;
6090                 }
6091
6092                 bi->blockState = state;
6093
6094                 /* Now let's see if it was dirty */
6095                 if (bi->pagesInUse == 0 &&
6096                     !bi->hasShrinkHeader &&
6097                     bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6098                         yaffs_BlockBecameDirty(dev, blk);
6099                 }
6100
6101         }
6102
6103
6104         /* Ok, we've done all the scanning.
6105          * Fix up the hard link chains.
6106          * We should now have scanned all the objects, now it's time to add these
6107          * hardlinks.
6108          */
6109
6110         yaffs_HardlinkFixup(dev, hardList);
6111
6112         /* Fix up any shadowed objects */
6113         {
6114                 struct yaffs_ShadowFixerStruct *fixer;
6115                 yaffs_Object *obj;
6116
6117                 while (shadowFixerList) {
6118                         fixer = shadowFixerList;
6119                         shadowFixerList = fixer->next;
6120                         /* Complete the rename transaction by deleting the shadowed object
6121                          * then setting the object header to unshadowed.
6122                          */
6123                         obj = yaffs_FindObjectByNumber(dev, fixer->shadowedId);
6124                         if (obj)
6125                                 yaffs_DeleteObject(obj);
6126
6127                         obj = yaffs_FindObjectByNumber(dev, fixer->objectId);
6128
6129                         if (obj)
6130                                 yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
6131
6132                         YFREE(fixer);
6133                 }
6134         }
6135
6136         yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6137
6138         if (alloc_failed)
6139                 return YAFFS_FAIL;
6140
6141         T(YAFFS_TRACE_SCAN, (TSTR("yaffs_Scan ends" TENDSTR)));
6142
6143
6144         return YAFFS_OK;
6145 }
6146
6147 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
6148 {
6149         __u8 *chunkData;
6150         yaffs_ObjectHeader *oh;
6151         yaffs_Device *dev;
6152         yaffs_ExtendedTags tags;
6153         int result;
6154         int alloc_failed = 0;
6155
6156         if (!in)
6157                 return;
6158
6159         dev = in->myDev;
6160
6161 #if 0
6162         T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
6163                 in->objectId,
6164                 in->lazyLoaded ? "not yet" : "already"));
6165 #endif
6166
6167         if (in->lazyLoaded && in->hdrChunk > 0) {
6168                 in->lazyLoaded = 0;
6169                 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6170
6171                 result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
6172                 oh = (yaffs_ObjectHeader *) chunkData;
6173
6174                 in->yst_mode = oh->yst_mode;
6175 #ifdef CONFIG_YAFFS_WINCE
6176                 in->win_atime[0] = oh->win_atime[0];
6177                 in->win_ctime[0] = oh->win_ctime[0];
6178                 in->win_mtime[0] = oh->win_mtime[0];
6179                 in->win_atime[1] = oh->win_atime[1];
6180                 in->win_ctime[1] = oh->win_ctime[1];
6181                 in->win_mtime[1] = oh->win_mtime[1];
6182 #else
6183                 in->yst_uid = oh->yst_uid;
6184                 in->yst_gid = oh->yst_gid;
6185                 in->yst_atime = oh->yst_atime;
6186                 in->yst_mtime = oh->yst_mtime;
6187                 in->yst_ctime = oh->yst_ctime;
6188                 in->yst_rdev = oh->yst_rdev;
6189
6190 #endif
6191                 yaffs_SetObjectName(in, oh->name);
6192
6193                 if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
6194                         in->variant.symLinkVariant.alias =
6195                                                     yaffs_CloneString(oh->alias);
6196                         if (!in->variant.symLinkVariant.alias)
6197                                 alloc_failed = 1; /* Not returned to caller */
6198                 }
6199
6200                 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6201         }
6202 }
6203
6204 static int yaffs_ScanBackwards(yaffs_Device *dev)
6205 {
6206         yaffs_ExtendedTags tags;
6207         int blk;
6208         int blockIterator;
6209         int startIterator;
6210         int endIterator;
6211         int nBlocksToScan = 0;
6212
6213         int chunk;
6214         int result;
6215         int c;
6216         int deleted;
6217         yaffs_BlockState state;
6218         yaffs_Object *hardList = NULL;
6219         yaffs_BlockInfo *bi;
6220         __u32 sequenceNumber;
6221         yaffs_ObjectHeader *oh;
6222         yaffs_Object *in;
6223         yaffs_Object *parent;
6224         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
6225         int itsUnlinked;
6226         __u8 *chunkData;
6227
6228         int fileSize;
6229         int isShrink;
6230         int foundChunksInBlock;
6231         int equivalentObjectId;
6232         int alloc_failed = 0;
6233
6234
6235         yaffs_BlockIndex *blockIndex = NULL;
6236         int altBlockIndex = 0;
6237
6238         if (!dev->isYaffs2) {
6239                 T(YAFFS_TRACE_SCAN,
6240                   (TSTR("yaffs_ScanBackwards is only for YAFFS2!" TENDSTR)));
6241                 return YAFFS_FAIL;
6242         }
6243
6244         T(YAFFS_TRACE_SCAN,
6245           (TSTR
6246            ("yaffs_ScanBackwards starts  intstartblk %d intendblk %d..."
6247             TENDSTR), dev->internalStartBlock, dev->internalEndBlock));
6248
6249
6250         dev->sequenceNumber = YAFFS_LOWEST_SEQUENCE_NUMBER;
6251
6252         blockIndex = YMALLOC(nBlocks * sizeof(yaffs_BlockIndex));
6253
6254         if (!blockIndex) {
6255                 blockIndex = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockIndex));
6256                 altBlockIndex = 1;
6257         }
6258
6259         if (!blockIndex) {
6260                 T(YAFFS_TRACE_SCAN,
6261                   (TSTR("yaffs_Scan() could not allocate block index!" TENDSTR)));
6262                 return YAFFS_FAIL;
6263         }
6264
6265         dev->blocksInCheckpoint = 0;
6266
6267         chunkData = yaffs_GetTempBuffer(dev, __LINE__);
6268
6269         /* Scan all the blocks to determine their state */
6270         for (blk = dev->internalStartBlock; blk <= dev->internalEndBlock; blk++) {
6271                 bi = yaffs_GetBlockInfo(dev, blk);
6272                 yaffs_ClearChunkBits(dev, blk);
6273                 bi->pagesInUse = 0;
6274                 bi->softDeletions = 0;
6275
6276                 yaffs_QueryInitialBlockState(dev, blk, &state, &sequenceNumber);
6277
6278                 bi->blockState = state;
6279                 bi->sequenceNumber = sequenceNumber;
6280
6281                 if (bi->sequenceNumber == YAFFS_SEQUENCE_CHECKPOINT_DATA)
6282                         bi->blockState = state = YAFFS_BLOCK_STATE_CHECKPOINT;
6283                 if (bi->sequenceNumber == YAFFS_SEQUENCE_BAD_BLOCK)
6284                         bi->blockState = state = YAFFS_BLOCK_STATE_DEAD;
6285
6286                 T(YAFFS_TRACE_SCAN_DEBUG,
6287                   (TSTR("Block scanning block %d state %d seq %d" TENDSTR), blk,
6288                    state, sequenceNumber));
6289
6290
6291                 if (state == YAFFS_BLOCK_STATE_CHECKPOINT) {
6292                         dev->blocksInCheckpoint++;
6293
6294                 } else if (state == YAFFS_BLOCK_STATE_DEAD) {
6295                         T(YAFFS_TRACE_BAD_BLOCKS,
6296                           (TSTR("block %d is bad" TENDSTR), blk));
6297                 } else if (state == YAFFS_BLOCK_STATE_EMPTY) {
6298                         T(YAFFS_TRACE_SCAN_DEBUG,
6299                           (TSTR("Block empty " TENDSTR)));
6300                         dev->nErasedBlocks++;
6301                         dev->nFreeChunks += dev->nChunksPerBlock;
6302                 } else if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6303
6304                         /* Determine the highest sequence number */
6305                         if (sequenceNumber >= YAFFS_LOWEST_SEQUENCE_NUMBER &&
6306                             sequenceNumber < YAFFS_HIGHEST_SEQUENCE_NUMBER) {
6307
6308                                 blockIndex[nBlocksToScan].seq = sequenceNumber;
6309                                 blockIndex[nBlocksToScan].block = blk;
6310
6311                                 nBlocksToScan++;
6312
6313                                 if (sequenceNumber >= dev->sequenceNumber)
6314                                         dev->sequenceNumber = sequenceNumber;
6315                         } else {
6316                                 /* TODO: Nasty sequence number! */
6317                                 T(YAFFS_TRACE_SCAN,
6318                                   (TSTR
6319                                    ("Block scanning block %d has bad sequence number %d"
6320                                     TENDSTR), blk, sequenceNumber));
6321
6322                         }
6323                 }
6324         }
6325
6326         T(YAFFS_TRACE_SCAN,
6327         (TSTR("%d blocks to be sorted..." TENDSTR), nBlocksToScan));
6328
6329
6330
6331         YYIELD();
6332
6333         /* Sort the blocks */
6334 #ifndef CONFIG_YAFFS_USE_OWN_SORT
6335         {
6336                 /* Use qsort now. */
6337                 yaffs_qsort(blockIndex, nBlocksToScan, sizeof(yaffs_BlockIndex), ybicmp);
6338         }
6339 #else
6340         {
6341                 /* Dungy old bubble sort... */
6342
6343                 yaffs_BlockIndex temp;
6344                 int i;
6345                 int j;
6346
6347                 for (i = 0; i < nBlocksToScan; i++)
6348                         for (j = i + 1; j < nBlocksToScan; j++)
6349                                 if (blockIndex[i].seq > blockIndex[j].seq) {
6350                                         temp = blockIndex[j];
6351                                         blockIndex[j] = blockIndex[i];
6352                                         blockIndex[i] = temp;
6353                                 }
6354         }
6355 #endif
6356
6357         YYIELD();
6358
6359         T(YAFFS_TRACE_SCAN, (TSTR("...done" TENDSTR)));
6360
6361         /* Now scan the blocks looking at the data. */
6362         startIterator = 0;
6363         endIterator = nBlocksToScan - 1;
6364         T(YAFFS_TRACE_SCAN_DEBUG,
6365           (TSTR("%d blocks to be scanned" TENDSTR), nBlocksToScan));
6366
6367         /* For each block.... backwards */
6368         for (blockIterator = endIterator; !alloc_failed && blockIterator >= startIterator;
6369                         blockIterator--) {
6370                 /* Cooperative multitasking! This loop can run for so
6371                    long that watchdog timers expire. */
6372                 YYIELD();
6373
6374                 /* get the block to scan in the correct order */
6375                 blk = blockIndex[blockIterator].block;
6376
6377                 bi = yaffs_GetBlockInfo(dev, blk);
6378
6379
6380                 state = bi->blockState;
6381
6382                 deleted = 0;
6383
6384                 /* For each chunk in each block that needs scanning.... */
6385                 foundChunksInBlock = 0;
6386                 for (c = dev->nChunksPerBlock - 1;
6387                      !alloc_failed && c >= 0 &&
6388                      (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6389                       state == YAFFS_BLOCK_STATE_ALLOCATING); c--) {
6390                         /* Scan backwards...
6391                          * Read the tags and decide what to do
6392                          */
6393
6394                         chunk = blk * dev->nChunksPerBlock + c;
6395
6396                         result = yaffs_ReadChunkWithTagsFromNAND(dev, chunk, NULL,
6397                                                         &tags);
6398
6399                         /* Let's have a good look at this chunk... */
6400
6401                         if (!tags.chunkUsed) {
6402                                 /* An unassigned chunk in the block.
6403                                  * If there are used chunks after this one, then
6404                                  * it is a chunk that was skipped due to failing the erased
6405                                  * check. Just skip it so that it can be deleted.
6406                                  * But, more typically, We get here when this is an unallocated
6407                                  * chunk and his means that either the block is empty or
6408                                  * this is the one being allocated from
6409                                  */
6410
6411                                 if (foundChunksInBlock) {
6412                                         /* This is a chunk that was skipped due to failing the erased check */
6413                                 } else if (c == 0) {
6414                                         /* We're looking at the first chunk in the block so the block is unused */
6415                                         state = YAFFS_BLOCK_STATE_EMPTY;
6416                                         dev->nErasedBlocks++;
6417                                 } else {
6418                                         if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
6419                                             state == YAFFS_BLOCK_STATE_ALLOCATING) {
6420                                                 if (dev->sequenceNumber == bi->sequenceNumber) {
6421                                                         /* this is the block being allocated from */
6422
6423                                                         T(YAFFS_TRACE_SCAN,
6424                                                           (TSTR
6425                                                            (" Allocating from %d %d"
6426                                                             TENDSTR), blk, c));
6427
6428                                                         state = YAFFS_BLOCK_STATE_ALLOCATING;
6429                                                         dev->allocationBlock = blk;
6430                                                         dev->allocationPage = c;
6431                                                         dev->allocationBlockFinder = blk;
6432                                                 } else {
6433                                                         /* This is a partially written block that is not
6434                                                          * the current allocation block.
6435                                                          */
6436
6437                                                          T(YAFFS_TRACE_ALWAYS,
6438                                                          (TSTR("Partially written block %d detected" TENDSTR),
6439                                                          blk));
6440                                                 }
6441                                         }
6442                                 }
6443
6444                                 dev->nFreeChunks++;
6445
6446                         } else if (tags.eccResult == YAFFS_ECC_RESULT_UNFIXED) {
6447                                 T(YAFFS_TRACE_SCAN,
6448                                   (TSTR(" Unfixed ECC in chunk(%d:%d), chunk ignored"TENDSTR),
6449                                   blk, c));
6450
6451                                   dev->nFreeChunks++;
6452
6453                         } else if (tags.chunkId > 0) {
6454                                 /* chunkId > 0 so it is a data chunk... */
6455                                 unsigned int endpos;
6456                                 __u32 chunkBase =
6457                                     (tags.chunkId - 1) * dev->nDataBytesPerChunk;
6458
6459                                 foundChunksInBlock = 1;
6460
6461
6462                                 yaffs_SetChunkBit(dev, blk, c);
6463                                 bi->pagesInUse++;
6464
6465                                 in = yaffs_FindOrCreateObjectByNumber(dev,
6466                                                                       tags.
6467                                                                       objectId,
6468                                                                       YAFFS_OBJECT_TYPE_FILE);
6469                                 if (!in) {
6470                                         /* Out of memory */
6471                                         alloc_failed = 1;
6472                                 }
6473
6474                                 if (in &&
6475                                     in->variantType == YAFFS_OBJECT_TYPE_FILE
6476                                     && chunkBase <
6477                                     in->variant.fileVariant.shrinkSize) {
6478                                         /* This has not been invalidated by a resize */
6479                                         if (!yaffs_PutChunkIntoFile(in, tags.chunkId,
6480                                                                chunk, -1)) {
6481                                                 alloc_failed = 1;
6482                                         }
6483
6484                                         /* File size is calculated by looking at the data chunks if we have not
6485                                          * seen an object header yet. Stop this practice once we find an object header.
6486                                          */
6487                                         endpos =
6488                                             (tags.chunkId -
6489                                              1) * dev->nDataBytesPerChunk +
6490                                             tags.byteCount;
6491
6492                                         if (!in->valid &&       /* have not got an object header yet */
6493                                             in->variant.fileVariant.
6494                                             scannedFileSize < endpos) {
6495                                                 in->variant.fileVariant.
6496                                                     scannedFileSize = endpos;
6497                                                 in->variant.fileVariant.
6498                                                     fileSize =
6499                                                     in->variant.fileVariant.
6500                                                     scannedFileSize;
6501                                         }
6502
6503                                 } else if (in) {
6504                                         /* This chunk has been invalidated by a resize, so delete */
6505                                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6506
6507                                 }
6508                         } else {
6509                                 /* chunkId == 0, so it is an ObjectHeader.
6510                                  * Thus, we read in the object header and make the object
6511                                  */
6512                                 foundChunksInBlock = 1;
6513
6514                                 yaffs_SetChunkBit(dev, blk, c);
6515                                 bi->pagesInUse++;
6516
6517                                 oh = NULL;
6518                                 in = NULL;
6519
6520                                 if (tags.extraHeaderInfoAvailable) {
6521                                         in = yaffs_FindOrCreateObjectByNumber
6522                                             (dev, tags.objectId,
6523                                              tags.extraObjectType);
6524                                         if (!in)
6525                                                 alloc_failed = 1;
6526                                 }
6527
6528                                 if (!in ||
6529                                     (!in->valid && dev->disableLazyLoad) ||
6530                                     tags.extraShadows ||
6531                                     (!in->valid &&
6532                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
6533                                      tags.objectId == YAFFS_OBJECTID_LOSTNFOUND))) {
6534
6535                                         /* If we don't have  valid info then we need to read the chunk
6536                                          * TODO In future we can probably defer reading the chunk and
6537                                          * living with invalid data until needed.
6538                                          */
6539
6540                                         result = yaffs_ReadChunkWithTagsFromNAND(dev,
6541                                                                         chunk,
6542                                                                         chunkData,
6543                                                                         NULL);
6544
6545                                         oh = (yaffs_ObjectHeader *) chunkData;
6546
6547                                         if (dev->inbandTags) {
6548                                                 /* Fix up the header if they got corrupted by inband tags */
6549                                                 oh->shadowsObject = oh->inbandShadowsObject;
6550                                                 oh->isShrink = oh->inbandIsShrink;
6551                                         }
6552
6553                                         if (!in) {
6554                                                 in = yaffs_FindOrCreateObjectByNumber(dev, tags.objectId, oh->type);
6555                                                 if (!in)
6556                                                         alloc_failed = 1;
6557                                         }
6558
6559                                 }
6560
6561                                 if (!in) {
6562                                         /* TODO Hoosterman we have a problem! */
6563                                         T(YAFFS_TRACE_ERROR,
6564                                           (TSTR
6565                                            ("yaffs tragedy: Could not make object for object  %d at chunk %d during scan"
6566                                             TENDSTR), tags.objectId, chunk));
6567                                         continue;
6568                                 }
6569
6570                                 if (in->valid) {
6571                                         /* We have already filled this one.
6572                                          * We have a duplicate that will be discarded, but
6573                                          * we first have to suck out resize info if it is a file.
6574                                          */
6575
6576                                         if ((in->variantType == YAFFS_OBJECT_TYPE_FILE) &&
6577                                              ((oh &&
6578                                                oh->type == YAFFS_OBJECT_TYPE_FILE) ||
6579                                               (tags.extraHeaderInfoAvailable  &&
6580                                                tags.extraObjectType == YAFFS_OBJECT_TYPE_FILE))) {
6581                                                 __u32 thisSize =
6582                                                     (oh) ? oh->fileSize : tags.
6583                                                     extraFileLength;
6584                                                 __u32 parentObjectId =
6585                                                     (oh) ? oh->
6586                                                     parentObjectId : tags.
6587                                                     extraParentObjectId;
6588
6589
6590                                                 isShrink =
6591                                                     (oh) ? oh->isShrink : tags.
6592                                                     extraIsShrinkHeader;
6593
6594                                                 /* If it is deleted (unlinked at start also means deleted)
6595                                                  * we treat the file size as being zeroed at this point.
6596                                                  */
6597                                                 if (parentObjectId ==
6598                                                     YAFFS_OBJECTID_DELETED
6599                                                     || parentObjectId ==
6600                                                     YAFFS_OBJECTID_UNLINKED) {
6601                                                         thisSize = 0;
6602                                                         isShrink = 1;
6603                                                 }
6604
6605                                                 if (isShrink &&
6606                                                     in->variant.fileVariant.
6607                                                     shrinkSize > thisSize) {
6608                                                         in->variant.fileVariant.
6609                                                             shrinkSize =
6610                                                             thisSize;
6611                                                 }
6612
6613                                                 if (isShrink)
6614                                                         bi->hasShrinkHeader = 1;
6615
6616                                         }
6617                                         /* Use existing - destroy this one. */
6618                                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
6619
6620                                 }
6621
6622                                 if (!in->valid && in->variantType !=
6623                                     (oh ? oh->type : tags.extraObjectType))
6624                                         T(YAFFS_TRACE_ERROR, (
6625                                                 TSTR("yaffs tragedy: Bad object type, "
6626                                             TCONT("%d != %d, for object %d at chunk ")
6627                                             TCONT("%d during scan")
6628                                                 TENDSTR), oh ?
6629                                             oh->type : tags.extraObjectType,
6630                                             in->variantType, tags.objectId,
6631                                             chunk));
6632
6633                                 if (!in->valid &&
6634                                     (tags.objectId == YAFFS_OBJECTID_ROOT ||
6635                                      tags.objectId ==
6636                                      YAFFS_OBJECTID_LOSTNFOUND)) {
6637                                         /* We only load some info, don't fiddle with directory structure */
6638                                         in->valid = 1;
6639
6640                                         if (oh) {
6641                                                 in->variantType = oh->type;
6642
6643                                                 in->yst_mode = oh->yst_mode;
6644 #ifdef CONFIG_YAFFS_WINCE
6645                                                 in->win_atime[0] = oh->win_atime[0];
6646                                                 in->win_ctime[0] = oh->win_ctime[0];
6647                                                 in->win_mtime[0] = oh->win_mtime[0];
6648                                                 in->win_atime[1] = oh->win_atime[1];
6649                                                 in->win_ctime[1] = oh->win_ctime[1];
6650                                                 in->win_mtime[1] = oh->win_mtime[1];
6651 #else
6652                                                 in->yst_uid = oh->yst_uid;
6653                                                 in->yst_gid = oh->yst_gid;
6654                                                 in->yst_atime = oh->yst_atime;
6655                                                 in->yst_mtime = oh->yst_mtime;
6656                                                 in->yst_ctime = oh->yst_ctime;
6657                                                 in->yst_rdev = oh->yst_rdev;
6658
6659 #endif
6660                                         } else {
6661                                                 in->variantType = tags.extraObjectType;
6662                                                 in->lazyLoaded = 1;
6663                                         }
6664
6665                                         in->hdrChunk = chunk;
6666
6667                                 } else if (!in->valid) {
6668                                         /* we need to load this info */
6669
6670                                         in->valid = 1;
6671                                         in->hdrChunk = chunk;
6672
6673                                         if (oh) {
6674                                                 in->variantType = oh->type;
6675
6676                                                 in->yst_mode = oh->yst_mode;
6677 #ifdef CONFIG_YAFFS_WINCE
6678                                                 in->win_atime[0] = oh->win_atime[0];
6679                                                 in->win_ctime[0] = oh->win_ctime[0];
6680                                                 in->win_mtime[0] = oh->win_mtime[0];
6681                                                 in->win_atime[1] = oh->win_atime[1];
6682                                                 in->win_ctime[1] = oh->win_ctime[1];
6683                                                 in->win_mtime[1] = oh->win_mtime[1];
6684 #else
6685                                                 in->yst_uid = oh->yst_uid;
6686                                                 in->yst_gid = oh->yst_gid;
6687                                                 in->yst_atime = oh->yst_atime;
6688                                                 in->yst_mtime = oh->yst_mtime;
6689                                                 in->yst_ctime = oh->yst_ctime;
6690                                                 in->yst_rdev = oh->yst_rdev;
6691 #endif
6692
6693                                                 if (oh->shadowsObject > 0)
6694                                                         yaffs_HandleShadowedObject(dev,
6695                                                                            oh->
6696                                                                            shadowsObject,
6697                                                                            1);
6698                                                         
6699
6700
6701                                                 yaffs_SetObjectName(in, oh->name);
6702                                                 parent =
6703                                                     yaffs_FindOrCreateObjectByNumber
6704                                                         (dev, oh->parentObjectId,
6705                                                          YAFFS_OBJECT_TYPE_DIRECTORY);
6706
6707                                                  fileSize = oh->fileSize;
6708                                                  isShrink = oh->isShrink;
6709                                                  equivalentObjectId = oh->equivalentObjectId;
6710
6711                                         } else {
6712                                                 in->variantType = tags.extraObjectType;
6713                                                 parent =
6714                                                     yaffs_FindOrCreateObjectByNumber
6715                                                         (dev, tags.extraParentObjectId,
6716                                                          YAFFS_OBJECT_TYPE_DIRECTORY);
6717                                                  fileSize = tags.extraFileLength;
6718                                                  isShrink = tags.extraIsShrinkHeader;
6719                                                  equivalentObjectId = tags.extraEquivalentObjectId;
6720                                                 in->lazyLoaded = 1;
6721
6722                                         }
6723                                         in->dirty = 0;
6724
6725                                         if (!parent)
6726                                                 alloc_failed = 1;
6727
6728                                         /* directory stuff...
6729                                          * hook up to parent
6730                                          */
6731
6732                                         if (parent && parent->variantType ==
6733                                             YAFFS_OBJECT_TYPE_UNKNOWN) {
6734                                                 /* Set up as a directory */
6735                                                 parent->variantType =
6736                                                         YAFFS_OBJECT_TYPE_DIRECTORY;
6737                                                 YINIT_LIST_HEAD(&parent->variant.
6738                                                         directoryVariant.
6739                                                         children);
6740                                         } else if (!parent || parent->variantType !=
6741                                                    YAFFS_OBJECT_TYPE_DIRECTORY) {
6742                                                 /* Hoosterman, another problem....
6743                                                  * We're trying to use a non-directory as a directory
6744                                                  */
6745
6746                                                 T(YAFFS_TRACE_ERROR,
6747                                                   (TSTR
6748                                                    ("yaffs tragedy: attempting to use non-directory as a directory in scan. Put in lost+found."
6749                                                     TENDSTR)));
6750                                                 parent = dev->lostNFoundDir;
6751                                         }
6752
6753                                         yaffs_AddObjectToDirectory(parent, in);
6754
6755                                         itsUnlinked = (parent == dev->deletedDir) ||
6756                                                       (parent == dev->unlinkedDir);
6757
6758                                         if (isShrink) {
6759                                                 /* Mark the block as having a shrinkHeader */
6760                                                 bi->hasShrinkHeader = 1;
6761                                         }
6762
6763                                         /* Note re hardlinks.
6764                                          * Since we might scan a hardlink before its equivalent object is scanned
6765                                          * we put them all in a list.
6766                                          * After scanning is complete, we should have all the objects, so we run
6767                                          * through this list and fix up all the chains.
6768                                          */
6769
6770                                         switch (in->variantType) {
6771                                         case YAFFS_OBJECT_TYPE_UNKNOWN:
6772                                                 /* Todo got a problem */
6773                                                 break;
6774                                         case YAFFS_OBJECT_TYPE_FILE:
6775
6776                                                 if (in->variant.fileVariant.
6777                                                     scannedFileSize < fileSize) {
6778                                                         /* This covers the case where the file size is greater
6779                                                          * than where the data is
6780                                                          * This will happen if the file is resized to be larger
6781                                                          * than its current data extents.
6782                                                          */
6783                                                         in->variant.fileVariant.fileSize = fileSize;
6784                                                         in->variant.fileVariant.scannedFileSize =
6785                                                             in->variant.fileVariant.fileSize;
6786                                                 }
6787
6788                                                 if (isShrink &&
6789                                                     in->variant.fileVariant.shrinkSize > fileSize) {
6790                                                         in->variant.fileVariant.shrinkSize = fileSize;
6791                                                 }
6792
6793                                                 break;
6794                                         case YAFFS_OBJECT_TYPE_HARDLINK:
6795                                                 if (!itsUnlinked) {
6796                                                         in->variant.hardLinkVariant.equivalentObjectId =
6797                                                                 equivalentObjectId;
6798                                                         in->hardLinks.next =
6799                                                                 (struct ylist_head *) hardList;
6800                                                         hardList = in;
6801                                                 }
6802                                                 break;
6803                                         case YAFFS_OBJECT_TYPE_DIRECTORY:
6804                                                 /* Do nothing */
6805                                                 break;
6806                                         case YAFFS_OBJECT_TYPE_SPECIAL:
6807                                                 /* Do nothing */
6808                                                 break;
6809                                         case YAFFS_OBJECT_TYPE_SYMLINK:
6810                                                 if (oh) {
6811                                                         in->variant.symLinkVariant.alias =
6812                                                                 yaffs_CloneString(oh->alias);
6813                                                         if (!in->variant.symLinkVariant.alias)
6814                                                                 alloc_failed = 1;
6815                                                 }
6816                                                 break;
6817                                         }
6818
6819                                 }
6820
6821                         }
6822
6823                 } /* End of scanning for each chunk */
6824
6825                 if (state == YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
6826                         /* If we got this far while scanning, then the block is fully allocated. */
6827                         state = YAFFS_BLOCK_STATE_FULL;
6828                 }
6829
6830
6831                 bi->blockState = state;
6832
6833                 /* Now let's see if it was dirty */
6834                 if (bi->pagesInUse == 0 &&
6835                     !bi->hasShrinkHeader &&
6836                     bi->blockState == YAFFS_BLOCK_STATE_FULL) {
6837                         yaffs_BlockBecameDirty(dev, blk);
6838                 }
6839
6840         }
6841         
6842         yaffs_SkipRestOfBlock(dev);
6843
6844         if (altBlockIndex)
6845                 YFREE_ALT(blockIndex);
6846         else
6847                 YFREE(blockIndex);
6848
6849         /* Ok, we've done all the scanning.
6850          * Fix up the hard link chains.
6851          * We should now have scanned all the objects, now it's time to add these
6852          * hardlinks.
6853          */
6854         yaffs_HardlinkFixup(dev, hardList);
6855
6856
6857         yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
6858
6859         if (alloc_failed)
6860                 return YAFFS_FAIL;
6861
6862         T(YAFFS_TRACE_SCAN, (TSTR("yaffs_ScanBackwards ends" TENDSTR)));
6863
6864         return YAFFS_OK;
6865 }
6866
6867 /*------------------------------  Directory Functions ----------------------------- */
6868
6869 static void yaffs_VerifyObjectInDirectory(yaffs_Object *obj)
6870 {
6871         struct ylist_head *lh;
6872         yaffs_Object *listObj;
6873
6874         int count = 0;
6875
6876         if (!obj) {
6877                 T(YAFFS_TRACE_ALWAYS, (TSTR("No object to verify" TENDSTR)));
6878                 YBUG();
6879                 return;
6880         }
6881
6882         if (yaffs_SkipVerification(obj->myDev))
6883                 return;
6884
6885         if (!obj->parent) {
6886                 T(YAFFS_TRACE_ALWAYS, (TSTR("Object does not have parent" TENDSTR)));
6887                 YBUG();
6888                 return;
6889         }
6890
6891         if (obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6892                 T(YAFFS_TRACE_ALWAYS, (TSTR("Parent is not directory" TENDSTR)));
6893                 YBUG();
6894         }
6895
6896         /* Iterate through the objects in each hash entry */
6897
6898         ylist_for_each(lh, &obj->parent->variant.directoryVariant.children) {
6899                 if (lh) {
6900                         listObj = ylist_entry(lh, yaffs_Object, siblings);
6901                         yaffs_VerifyObject(listObj);
6902                         if (obj == listObj)
6903                                 count++;
6904                 }
6905          }
6906
6907         if (count != 1) {
6908                 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory %d times" TENDSTR), count));
6909                 YBUG();
6910         }
6911 }
6912
6913 static void yaffs_VerifyDirectory(yaffs_Object *directory)
6914 {
6915         struct ylist_head *lh;
6916         yaffs_Object *listObj;
6917
6918         if (!directory) {
6919                 YBUG();
6920                 return;
6921         }
6922
6923         if (yaffs_SkipFullVerification(directory->myDev))
6924                 return;
6925
6926         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6927                 T(YAFFS_TRACE_ALWAYS, (TSTR("Directory has wrong type: %d" TENDSTR), directory->variantType));
6928                 YBUG();
6929         }
6930
6931         /* Iterate through the objects in each hash entry */
6932
6933         ylist_for_each(lh, &directory->variant.directoryVariant.children) {
6934                 if (lh) {
6935                         listObj = ylist_entry(lh, yaffs_Object, siblings);
6936                         if (listObj->parent != directory) {
6937                                 T(YAFFS_TRACE_ALWAYS, (TSTR("Object in directory list has wrong parent %p" TENDSTR), listObj->parent));
6938                                 YBUG();
6939                         }
6940                         yaffs_VerifyObjectInDirectory(listObj);
6941                 }
6942         }
6943 }
6944
6945 /*
6946  *yaffs_UpdateParent() handles fixing a directories mtime and ctime when a new
6947  * link (ie. name) is created or deleted in the directory.
6948  *
6949  * ie.
6950  *   create dir/a : update dir's mtime/ctime
6951  *   rm dir/a:   update dir's mtime/ctime
6952  *   modify dir/a: don't update dir's mtimme/ctime
6953  */
6954  
6955 static void yaffs_UpdateParent(yaffs_Object *obj)
6956 {
6957         if(!obj)
6958                 return;
6959
6960         obj->dirty = 1;
6961         obj->yst_mtime = obj->yst_ctime = Y_CURRENT_TIME;
6962
6963         yaffs_UpdateObjectHeader(obj,NULL,0,0,0);
6964 }
6965
6966 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
6967 {
6968         yaffs_Device *dev = obj->myDev;
6969         yaffs_Object *parent;
6970
6971         yaffs_VerifyObjectInDirectory(obj);
6972         parent = obj->parent;
6973
6974         yaffs_VerifyDirectory(parent);
6975
6976         if (dev && dev->removeObjectCallback)
6977                 dev->removeObjectCallback(obj);
6978
6979
6980         ylist_del_init(&obj->siblings);
6981         obj->parent = NULL;
6982         
6983         yaffs_VerifyDirectory(parent);
6984 }
6985
6986 static void yaffs_AddObjectToDirectory(yaffs_Object *directory,
6987                                         yaffs_Object *obj)
6988 {
6989         if (!directory) {
6990                 T(YAFFS_TRACE_ALWAYS,
6991                   (TSTR
6992                    ("tragedy: Trying to add an object to a null pointer directory"
6993                     TENDSTR)));
6994                 YBUG();
6995                 return;
6996         }
6997         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
6998                 T(YAFFS_TRACE_ALWAYS,
6999                   (TSTR
7000                    ("tragedy: Trying to add an object to a non-directory"
7001                     TENDSTR)));
7002                 YBUG();
7003         }
7004
7005         if (obj->siblings.prev == NULL) {
7006                 /* Not initialised */
7007                 YBUG();
7008         }
7009
7010
7011         yaffs_VerifyDirectory(directory);
7012
7013         yaffs_RemoveObjectFromDirectory(obj);
7014
7015
7016         /* Now add it */
7017         ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
7018         obj->parent = directory;
7019
7020         if (directory == obj->myDev->unlinkedDir
7021                         || directory == obj->myDev->deletedDir) {
7022                 obj->unlinked = 1;
7023                 obj->myDev->nUnlinkedFiles++;
7024                 obj->renameAllowed = 0;
7025         }
7026
7027         yaffs_VerifyDirectory(directory);
7028         yaffs_VerifyObjectInDirectory(obj);
7029 }
7030
7031 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
7032                                      const YCHAR *name)
7033 {
7034         int sum;
7035
7036         struct ylist_head *i;
7037         YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
7038
7039         yaffs_Object *l;
7040
7041         if (!name)
7042                 return NULL;
7043
7044         if (!directory) {
7045                 T(YAFFS_TRACE_ALWAYS,
7046                   (TSTR
7047                    ("tragedy: yaffs_FindObjectByName: null pointer directory"
7048                     TENDSTR)));
7049                 YBUG();
7050                 return NULL;
7051         }
7052         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7053                 T(YAFFS_TRACE_ALWAYS,
7054                   (TSTR
7055                    ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7056                 YBUG();
7057         }
7058
7059         sum = yaffs_CalcNameSum(name);
7060
7061         ylist_for_each(i, &directory->variant.directoryVariant.children) {
7062                 if (i) {
7063                         l = ylist_entry(i, yaffs_Object, siblings);
7064
7065                         if (l->parent != directory)
7066                                 YBUG();
7067
7068                         yaffs_CheckObjectDetailsLoaded(l);
7069
7070                         /* Special case for lost-n-found */
7071                         if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7072                                 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
7073                                         return l;
7074                         } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
7075                                 /* LostnFound chunk called Objxxx
7076                                  * Do a real check
7077                                  */
7078                                 yaffs_GetObjectName(l, buffer,
7079                                                     YAFFS_MAX_NAME_LENGTH + 1);
7080                                 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
7081                                         return l;
7082                         }
7083                 }
7084         }
7085
7086         return NULL;
7087 }
7088
7089
7090 #if 0
7091 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
7092                                         int (*fn) (yaffs_Object *))
7093 {
7094         struct ylist_head *i;
7095         yaffs_Object *l;
7096
7097         if (!theDir) {
7098                 T(YAFFS_TRACE_ALWAYS,
7099                   (TSTR
7100                    ("tragedy: yaffs_FindObjectByName: null pointer directory"
7101                     TENDSTR)));
7102                 YBUG();
7103                 return YAFFS_FAIL;
7104         }
7105         if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
7106                 T(YAFFS_TRACE_ALWAYS,
7107                   (TSTR
7108                    ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
7109                 YBUG();
7110                 return YAFFS_FAIL;
7111         }
7112
7113         ylist_for_each(i, &theDir->variant.directoryVariant.children) {
7114                 if (i) {
7115                         l = ylist_entry(i, yaffs_Object, siblings);
7116                         if (l && !fn(l))
7117                                 return YAFFS_FAIL;
7118                 }
7119         }
7120
7121         return YAFFS_OK;
7122
7123 }
7124 #endif
7125
7126 /* GetEquivalentObject dereferences any hard links to get to the
7127  * actual object.
7128  */
7129
7130 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
7131 {
7132         if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
7133                 /* We want the object id of the equivalent object, not this one */
7134                 obj = obj->variant.hardLinkVariant.equivalentObject;
7135                 yaffs_CheckObjectDetailsLoaded(obj);
7136         }
7137         return obj;
7138 }
7139
7140 int yaffs_GetObjectName(yaffs_Object *obj, YCHAR *name, int buffSize)
7141 {
7142         memset(name, 0, buffSize * sizeof(YCHAR));
7143
7144         yaffs_CheckObjectDetailsLoaded(obj);
7145
7146         if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
7147                 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
7148         } else if (obj->hdrChunk <= 0) {
7149                 YCHAR locName[20];
7150                 YCHAR numString[20];
7151                 YCHAR *x = &numString[19];
7152                 unsigned v = obj->objectId;
7153                 numString[19] = 0;
7154                 while (v > 0) {
7155                         x--;
7156                         *x = '0' + (v % 10);
7157                         v /= 10;
7158                 }
7159                 /* make up a name */
7160                 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
7161                 yaffs_strcat(locName, x);
7162                 yaffs_strncpy(name, locName, buffSize - 1);
7163
7164         }
7165 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
7166         else if (obj->shortName[0])
7167                 yaffs_strncpy(name, obj->shortName,YAFFS_SHORT_NAME_LENGTH+1);
7168 #endif
7169         else {
7170                 int result;
7171                 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
7172
7173                 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
7174
7175                 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
7176
7177                 if (obj->hdrChunk > 0) {
7178                         result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
7179                                                         obj->hdrChunk, buffer,
7180                                                         NULL);
7181                 }
7182                 yaffs_strncpy(name, oh->name, buffSize - 1);
7183                 name[buffSize-1]=0;
7184
7185                 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
7186         }
7187
7188         return yaffs_strnlen(name,buffSize-1);
7189 }
7190
7191 int yaffs_GetObjectFileLength(yaffs_Object *obj)
7192 {
7193         /* Dereference any hard linking */
7194         obj = yaffs_GetEquivalentObject(obj);
7195
7196         if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
7197                 return obj->variant.fileVariant.fileSize;
7198         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
7199                 if(!obj->variant.symLinkVariant.alias)
7200                         return 0;
7201                 return yaffs_strnlen(obj->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
7202         } else {
7203                 /* Only a directory should drop through to here */
7204                 return obj->myDev->nDataBytesPerChunk;
7205         }
7206 }
7207
7208 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
7209 {
7210         int count = 0;
7211         struct ylist_head *i;
7212
7213         if (!obj->unlinked)
7214                 count++;                /* the object itself */
7215
7216         ylist_for_each(i, &obj->hardLinks)
7217                 count++;                /* add the hard links; */
7218
7219         return count;
7220 }
7221
7222 int yaffs_GetObjectInode(yaffs_Object *obj)
7223 {
7224         obj = yaffs_GetEquivalentObject(obj);
7225
7226         return obj->objectId;
7227 }
7228
7229 unsigned yaffs_GetObjectType(yaffs_Object *obj)
7230 {
7231         obj = yaffs_GetEquivalentObject(obj);
7232
7233         switch (obj->variantType) {
7234         case YAFFS_OBJECT_TYPE_FILE:
7235                 return DT_REG;
7236                 break;
7237         case YAFFS_OBJECT_TYPE_DIRECTORY:
7238                 return DT_DIR;
7239                 break;
7240         case YAFFS_OBJECT_TYPE_SYMLINK:
7241                 return DT_LNK;
7242                 break;
7243         case YAFFS_OBJECT_TYPE_HARDLINK:
7244                 return DT_REG;
7245                 break;
7246         case YAFFS_OBJECT_TYPE_SPECIAL:
7247                 if (S_ISFIFO(obj->yst_mode))
7248                         return DT_FIFO;
7249                 if (S_ISCHR(obj->yst_mode))
7250                         return DT_CHR;
7251                 if (S_ISBLK(obj->yst_mode))
7252                         return DT_BLK;
7253                 if (S_ISSOCK(obj->yst_mode))
7254                         return DT_SOCK;
7255         default:
7256                 return DT_REG;
7257                 break;
7258         }
7259 }
7260
7261 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
7262 {
7263         obj = yaffs_GetEquivalentObject(obj);
7264         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
7265                 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
7266         else
7267                 return yaffs_CloneString(_Y(""));
7268 }
7269
7270 #ifndef CONFIG_YAFFS_WINCE
7271
7272 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
7273 {
7274         unsigned int valid = attr->ia_valid;
7275
7276         if (valid & ATTR_MODE)
7277                 obj->yst_mode = attr->ia_mode;
7278         if (valid & ATTR_UID)
7279                 obj->yst_uid = attr->ia_uid;
7280         if (valid & ATTR_GID)
7281                 obj->yst_gid = attr->ia_gid;
7282
7283         if (valid & ATTR_ATIME)
7284                 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
7285         if (valid & ATTR_CTIME)
7286                 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
7287         if (valid & ATTR_MTIME)
7288                 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
7289
7290         if (valid & ATTR_SIZE)
7291                 yaffs_ResizeFile(obj, attr->ia_size);
7292
7293         yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0);
7294
7295         return YAFFS_OK;
7296
7297 }
7298 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
7299 {
7300         unsigned int valid = 0;
7301
7302         attr->ia_mode = obj->yst_mode;
7303         valid |= ATTR_MODE;
7304         attr->ia_uid = obj->yst_uid;
7305         valid |= ATTR_UID;
7306         attr->ia_gid = obj->yst_gid;
7307         valid |= ATTR_GID;
7308
7309         Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
7310         valid |= ATTR_ATIME;
7311         Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
7312         valid |= ATTR_CTIME;
7313         Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
7314         valid |= ATTR_MTIME;
7315
7316         attr->ia_size = yaffs_GetFileSize(obj);
7317         valid |= ATTR_SIZE;
7318
7319         attr->ia_valid = valid;
7320
7321         return YAFFS_OK;
7322 }
7323
7324 #endif
7325
7326 #if 0
7327 int yaffs_DumpObject(yaffs_Object *obj)
7328 {
7329         YCHAR name[257];
7330
7331         yaffs_GetObjectName(obj, name, YAFFS_MAX_NAME_LENGTH + 1);
7332
7333         T(YAFFS_TRACE_ALWAYS,
7334           (TSTR
7335            ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
7336             " chunk %d type %d size %d\n"
7337             TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
7338            obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
7339            yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
7340
7341         return YAFFS_OK;
7342 }
7343 #endif
7344
7345 /*---------------------------- Initialisation code -------------------------------------- */
7346
7347 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
7348 {
7349
7350         /* Common functions, gotta have */
7351         if (!dev->eraseBlockInNAND || !dev->initialiseNAND)
7352                 return 0;
7353
7354 #ifdef CONFIG_YAFFS_YAFFS2
7355
7356         /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
7357         if (dev->writeChunkWithTagsToNAND &&
7358             dev->readChunkWithTagsFromNAND &&
7359             !dev->writeChunkToNAND &&
7360             !dev->readChunkFromNAND &&
7361             dev->markNANDBlockBad && dev->queryNANDBlock)
7362                 return 1;
7363 #endif
7364
7365         /* Can use the "spare" style interface for yaffs1 */
7366         if (!dev->isYaffs2 &&
7367             !dev->writeChunkWithTagsToNAND &&
7368             !dev->readChunkWithTagsFromNAND &&
7369             dev->writeChunkToNAND &&
7370             dev->readChunkFromNAND &&
7371             !dev->markNANDBlockBad && !dev->queryNANDBlock)
7372                 return 1;
7373
7374         return 0;               /* bad */
7375 }
7376
7377
7378 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
7379 {
7380         /* Initialise the unlinked, deleted, root and lost and found directories */
7381
7382         dev->lostNFoundDir = dev->rootDir =  NULL;
7383         dev->unlinkedDir = dev->deletedDir = NULL;
7384
7385         dev->unlinkedDir =
7386             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
7387
7388         dev->deletedDir =
7389             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
7390
7391         dev->rootDir =
7392             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
7393                                       YAFFS_ROOT_MODE | S_IFDIR);
7394         dev->lostNFoundDir =
7395             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
7396                                       YAFFS_LOSTNFOUND_MODE | S_IFDIR);
7397
7398         if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
7399                 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
7400                 return YAFFS_OK;
7401         }
7402
7403         return YAFFS_FAIL;
7404 }
7405
7406 int yaffs_GutsInitialise(yaffs_Device *dev)
7407 {
7408         int init_failed = 0;
7409         unsigned x;
7410         int bits;
7411
7412         T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
7413
7414         /* Check stuff that must be set */
7415
7416         if (!dev) {
7417                 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
7418                 return YAFFS_FAIL;
7419         }
7420
7421         dev->internalStartBlock = dev->startBlock;
7422         dev->internalEndBlock = dev->endBlock;
7423         dev->blockOffset = 0;
7424         dev->chunkOffset = 0;
7425         dev->nFreeChunks = 0;
7426
7427         dev->gcBlock = -1;
7428
7429         if (dev->startBlock == 0) {
7430                 dev->internalStartBlock = dev->startBlock + 1;
7431                 dev->internalEndBlock = dev->endBlock + 1;
7432                 dev->blockOffset = 1;
7433                 dev->chunkOffset = dev->nChunksPerBlock;
7434         }
7435
7436         /* Check geometry parameters. */
7437
7438         if ((!dev->inbandTags && dev->isYaffs2 && dev->totalBytesPerChunk < 1024) ||
7439             (!dev->isYaffs2 && dev->totalBytesPerChunk < 512) ||
7440             (dev->inbandTags && !dev->isYaffs2) ||
7441              dev->nChunksPerBlock < 2 ||
7442              dev->nReservedBlocks < 2 ||
7443              dev->internalStartBlock <= 0 ||
7444              dev->internalEndBlock <= 0 ||
7445              dev->internalEndBlock <= (dev->internalStartBlock + dev->nReservedBlocks + 2)) {   /* otherwise it is too small */
7446                 T(YAFFS_TRACE_ALWAYS,
7447                   (TSTR
7448                    ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
7449                     TENDSTR), dev->totalBytesPerChunk, dev->isYaffs2 ? "2" : "", dev->inbandTags));
7450                 return YAFFS_FAIL;
7451         }
7452
7453         if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
7454                 T(YAFFS_TRACE_ALWAYS,
7455                   (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
7456                 return YAFFS_FAIL;
7457         }
7458
7459         /* Sort out space for inband tags, if required */
7460         if (dev->inbandTags)
7461                 dev->nDataBytesPerChunk = dev->totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
7462         else
7463                 dev->nDataBytesPerChunk = dev->totalBytesPerChunk;
7464
7465         /* Got the right mix of functions? */
7466         if (!yaffs_CheckDevFunctions(dev)) {
7467                 /* Function missing */
7468                 T(YAFFS_TRACE_ALWAYS,
7469                   (TSTR
7470                    ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
7471
7472                 return YAFFS_FAIL;
7473         }
7474
7475         /* This is really a compilation check. */
7476         if (!yaffs_CheckStructures()) {
7477                 T(YAFFS_TRACE_ALWAYS,
7478                   (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
7479                 return YAFFS_FAIL;
7480         }
7481
7482         if (dev->isMounted) {
7483                 T(YAFFS_TRACE_ALWAYS,
7484                   (TSTR("yaffs: device already mounted\n" TENDSTR)));
7485                 return YAFFS_FAIL;
7486         }
7487
7488         /* Finished with most checks. One or two more checks happen later on too. */
7489
7490         dev->isMounted = 1;
7491
7492         /* OK now calculate a few things for the device */
7493
7494         /*
7495          *  Calculate all the chunk size manipulation numbers:
7496          */
7497         x = dev->nDataBytesPerChunk;
7498         /* We always use dev->chunkShift and dev->chunkDiv */
7499         dev->chunkShift = Shifts(x);
7500         x >>= dev->chunkShift;
7501         dev->chunkDiv = x;
7502         /* We only use chunk mask if chunkDiv is 1 */
7503         dev->chunkMask = (1<<dev->chunkShift) - 1;
7504
7505         /*
7506          * Calculate chunkGroupBits.
7507          * We need to find the next power of 2 > than internalEndBlock
7508          */
7509
7510         x = dev->nChunksPerBlock * (dev->internalEndBlock + 1);
7511
7512         bits = ShiftsGE(x);
7513
7514         /* Set up tnode width if wide tnodes are enabled. */
7515         if (!dev->wideTnodesDisabled) {
7516                 /* bits must be even so that we end up with 32-bit words */
7517                 if (bits & 1)
7518                         bits++;
7519                 if (bits < 16)
7520                         dev->tnodeWidth = 16;
7521                 else
7522                         dev->tnodeWidth = bits;
7523         } else
7524                 dev->tnodeWidth = 16;
7525
7526         dev->tnodeMask = (1<<dev->tnodeWidth)-1;
7527
7528         /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
7529          * so if the bitwidth of the
7530          * chunk range we're using is greater than 16 we need
7531          * to figure out chunk shift and chunkGroupSize
7532          */
7533
7534         if (bits <= dev->tnodeWidth)
7535                 dev->chunkGroupBits = 0;
7536         else
7537                 dev->chunkGroupBits = bits - dev->tnodeWidth;
7538
7539
7540         dev->chunkGroupSize = 1 << dev->chunkGroupBits;
7541
7542         if (dev->nChunksPerBlock < dev->chunkGroupSize) {
7543                 /* We have a problem because the soft delete won't work if
7544                  * the chunk group size > chunks per block.
7545                  * This can be remedied by using larger "virtual blocks".
7546                  */
7547                 T(YAFFS_TRACE_ALWAYS,
7548                   (TSTR("yaffs: chunk group too large\n" TENDSTR)));
7549
7550                 return YAFFS_FAIL;
7551         }
7552
7553         /* OK, we've finished verifying the device, lets continue with initialisation */
7554
7555         /* More device initialisation */
7556         dev->garbageCollections = 0;
7557         dev->passiveGarbageCollections = 0;
7558         dev->currentDirtyChecker = 0;
7559         dev->bufferedBlock = -1;
7560         dev->doingBufferedBlockRewrite = 0;
7561         dev->nDeletedFiles = 0;
7562         dev->nBackgroundDeletions = 0;
7563         dev->nUnlinkedFiles = 0;
7564         dev->eccFixed = 0;
7565         dev->eccUnfixed = 0;
7566         dev->tagsEccFixed = 0;
7567         dev->tagsEccUnfixed = 0;
7568         dev->nErasureFailures = 0;
7569         dev->nErasedBlocks = 0;
7570         dev->isDoingGC = 0;
7571         dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
7572
7573         /* Initialise temporary buffers and caches. */
7574         if (!yaffs_InitialiseTempBuffers(dev))
7575                 init_failed = 1;
7576
7577         dev->srCache = NULL;
7578         dev->gcCleanupList = NULL;
7579
7580
7581         if (!init_failed &&
7582             dev->nShortOpCaches > 0) {
7583                 int i;
7584                 void *buf;
7585                 int srCacheBytes = dev->nShortOpCaches * sizeof(yaffs_ChunkCache);
7586
7587                 if (dev->nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
7588                         dev->nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
7589
7590                 dev->srCache =  YMALLOC(srCacheBytes);
7591
7592                 buf = (__u8 *) dev->srCache;
7593
7594                 if (dev->srCache)
7595                         memset(dev->srCache, 0, srCacheBytes);
7596
7597                 for (i = 0; i < dev->nShortOpCaches && buf; i++) {
7598                         dev->srCache[i].object = NULL;
7599                         dev->srCache[i].lastUse = 0;
7600                         dev->srCache[i].dirty = 0;
7601                         dev->srCache[i].data = buf = YMALLOC_DMA(dev->totalBytesPerChunk);
7602                 }
7603                 if (!buf)
7604                         init_failed = 1;
7605
7606                 dev->srLastUse = 0;
7607         }
7608
7609         dev->cacheHits = 0;
7610
7611         if (!init_failed) {
7612                 dev->gcCleanupList = YMALLOC(dev->nChunksPerBlock * sizeof(__u32));
7613                 if (!dev->gcCleanupList)
7614                         init_failed = 1;
7615         }
7616
7617         if (dev->isYaffs2)
7618                 dev->useHeaderFileSize = 1;
7619
7620         if (!init_failed && !yaffs_InitialiseBlocks(dev))
7621                 init_failed = 1;
7622
7623         yaffs_InitialiseTnodes(dev);
7624         yaffs_InitialiseObjects(dev);
7625
7626         if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7627                 init_failed = 1;
7628
7629
7630         if (!init_failed) {
7631                 /* Now scan the flash. */
7632                 if (dev->isYaffs2) {
7633                         if (yaffs_CheckpointRestore(dev)) {
7634                                 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
7635                                 T(YAFFS_TRACE_ALWAYS,
7636                                   (TSTR("yaffs: restored from checkpoint" TENDSTR)));
7637                         } else {
7638
7639                                 /* Clean up the mess caused by an aborted checkpoint load
7640                                  * and scan backwards.
7641                                  */
7642                                 yaffs_DeinitialiseBlocks(dev);
7643                                 yaffs_DeinitialiseTnodes(dev);
7644                                 yaffs_DeinitialiseObjects(dev);
7645
7646
7647                                 dev->nErasedBlocks = 0;
7648                                 dev->nFreeChunks = 0;
7649                                 dev->allocationBlock = -1;
7650                                 dev->allocationPage = -1;
7651                                 dev->nDeletedFiles = 0;
7652                                 dev->nUnlinkedFiles = 0;
7653                                 dev->nBackgroundDeletions = 0;
7654                                 dev->oldestDirtySequence = 0;
7655
7656                                 if (!init_failed && !yaffs_InitialiseBlocks(dev))
7657                                         init_failed = 1;
7658
7659                                 yaffs_InitialiseTnodes(dev);
7660                                 yaffs_InitialiseObjects(dev);
7661
7662                                 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
7663                                         init_failed = 1;
7664
7665                                 if (!init_failed && !yaffs_ScanBackwards(dev))
7666                                         init_failed = 1;
7667                         }
7668                 } else if (!yaffs_Scan(dev))
7669                                 init_failed = 1;
7670
7671                 yaffs_StripDeletedObjects(dev);
7672                 yaffs_FixHangingObjects(dev);
7673                 if(dev->emptyLostAndFound)
7674                         yaffs_EmptyLostAndFound(dev);
7675         }
7676
7677         if (init_failed) {
7678                 /* Clean up the mess */
7679                 T(YAFFS_TRACE_TRACING,
7680                   (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
7681
7682                 yaffs_Deinitialise(dev);
7683                 return YAFFS_FAIL;
7684         }
7685
7686         /* Zero out stats */
7687         dev->nPageReads = 0;
7688         dev->nPageWrites = 0;
7689         dev->nBlockErasures = 0;
7690         dev->nGCCopies = 0;
7691         dev->nRetriedWrites = 0;
7692
7693         dev->nRetiredBlocks = 0;
7694
7695         yaffs_VerifyFreeChunks(dev);
7696         yaffs_VerifyBlocks(dev);
7697
7698         /* Clean up any aborted checkpoint data */
7699         if(!dev->isCheckpointed && dev->blocksInCheckpoint > 0)
7700                 yaffs_InvalidateCheckpoint(dev);
7701
7702         T(YAFFS_TRACE_TRACING,
7703           (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
7704         return YAFFS_OK;
7705
7706 }
7707
7708 void yaffs_Deinitialise(yaffs_Device *dev)
7709 {
7710         if (dev->isMounted) {
7711                 int i;
7712
7713                 yaffs_DeinitialiseBlocks(dev);
7714                 yaffs_DeinitialiseTnodes(dev);
7715                 yaffs_DeinitialiseObjects(dev);
7716                 if (dev->nShortOpCaches > 0 &&
7717                     dev->srCache) {
7718
7719                         for (i = 0; i < dev->nShortOpCaches; i++) {
7720                                 if (dev->srCache[i].data)
7721                                         YFREE(dev->srCache[i].data);
7722                                 dev->srCache[i].data = NULL;
7723                         }
7724
7725                         YFREE(dev->srCache);
7726                         dev->srCache = NULL;
7727                 }
7728
7729                 YFREE(dev->gcCleanupList);
7730
7731                 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
7732                         YFREE(dev->tempBuffer[i].buffer);
7733
7734                 dev->isMounted = 0;
7735
7736                 if (dev->deinitialiseNAND)
7737                         dev->deinitialiseNAND(dev);
7738         }
7739 }
7740
7741 static int yaffs_CountFreeChunks(yaffs_Device *dev)
7742 {
7743         int nFree;
7744         int b;
7745
7746         yaffs_BlockInfo *blk;
7747
7748         for (nFree = 0, b = dev->internalStartBlock; b <= dev->internalEndBlock;
7749                         b++) {
7750                 blk = yaffs_GetBlockInfo(dev, b);
7751
7752                 switch (blk->blockState) {
7753                 case YAFFS_BLOCK_STATE_EMPTY:
7754                 case YAFFS_BLOCK_STATE_ALLOCATING:
7755                 case YAFFS_BLOCK_STATE_COLLECTING:
7756                 case YAFFS_BLOCK_STATE_FULL:
7757                         nFree +=
7758                             (dev->nChunksPerBlock - blk->pagesInUse +
7759                              blk->softDeletions);
7760                         break;
7761                 default:
7762                         break;
7763                 }
7764         }
7765
7766         return nFree;
7767 }
7768
7769 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
7770 {
7771         /* This is what we report to the outside world */
7772
7773         int nFree;
7774         int nDirtyCacheChunks;
7775         int blocksForCheckpoint;
7776         int i;
7777
7778 #if 1
7779         nFree = dev->nFreeChunks;
7780 #else
7781         nFree = yaffs_CountFreeChunks(dev);
7782 #endif
7783
7784         nFree += dev->nDeletedFiles;
7785
7786         /* Now count the number of dirty chunks in the cache and subtract those */
7787
7788         for (nDirtyCacheChunks = 0, i = 0; i < dev->nShortOpCaches; i++) {
7789                 if (dev->srCache[i].dirty)
7790                         nDirtyCacheChunks++;
7791         }
7792
7793         nFree -= nDirtyCacheChunks;
7794
7795         nFree -= ((dev->nReservedBlocks + 1) * dev->nChunksPerBlock);
7796
7797         /* Now we figure out how much to reserve for the checkpoint and report that... */
7798         blocksForCheckpoint = yaffs_CalcCheckpointBlocksRequired(dev) - dev->blocksInCheckpoint;
7799         if (blocksForCheckpoint < 0)
7800                 blocksForCheckpoint = 0;
7801
7802         nFree -= (blocksForCheckpoint * dev->nChunksPerBlock);
7803
7804         if (nFree < 0)
7805                 nFree = 0;
7806
7807         return nFree;
7808
7809 }
7810
7811 static int yaffs_freeVerificationFailures;
7812
7813 static void yaffs_VerifyFreeChunks(yaffs_Device *dev)
7814 {
7815         int counted;
7816         int difference;
7817
7818         if (yaffs_SkipVerification(dev))
7819                 return;
7820
7821         counted = yaffs_CountFreeChunks(dev);
7822
7823         difference = dev->nFreeChunks - counted;
7824
7825         if (difference) {
7826                 T(YAFFS_TRACE_ALWAYS,
7827                   (TSTR("Freechunks verification failure %d %d %d" TENDSTR),
7828                    dev->nFreeChunks, counted, difference));
7829                 yaffs_freeVerificationFailures++;
7830         }
7831 }
7832
7833 /*---------------------------------------- YAFFS test code ----------------------*/
7834
7835 #define yaffs_CheckStruct(structure, syze, name) \
7836         do { \
7837                 if (sizeof(structure) != syze) { \
7838                         T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
7839                                 name, syze, (int) sizeof(structure))); \
7840                         return YAFFS_FAIL; \
7841                 } \
7842         } while (0)
7843
7844 static int yaffs_CheckStructures(void)
7845 {
7846 /*      yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
7847 /*      yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
7848 /*      yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
7849 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
7850 /*      yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode"); */
7851 #endif
7852 #ifndef CONFIG_YAFFS_WINCE
7853         yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");
7854 #endif
7855         return YAFFS_OK;
7856 }