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