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