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