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