c81b1e7e35ba5aeb671da38397a10965606f0183
[yaffs2.git] / yaffs_guts.c
1 /*
2  * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
3  *
4  * Copyright (C) 2002-2007 Aleph One Ltd.
5  *   for Toby Churchill Ltd and Brightstar Engineering
6  *
7  * Created by Charles Manning <charles@aleph1.co.uk>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License version 2 as
11  * published by the Free Software Foundation.
12  */
13
14 const char *yaffs_guts_c_version =
15     "$Id: yaffs_guts.c,v 1.49 2007-05-15 20:07:40 charles Exp $";
16
17 #include "yportenv.h"
18
19 #include "yaffsinterface.h"
20 #include "yaffs_guts.h"
21 #include "yaffs_tagsvalidity.h"
22
23 #include "yaffs_tagscompat.h"
24 #ifndef  CONFIG_YAFFS_USE_OWN_SORT
25 #include "yaffs_qsort.h"
26 #endif
27 #include "yaffs_nand.h"
28
29 #include "yaffs_checkptrw.h"
30
31 #include "yaffs_nand.h"
32 #include "yaffs_packedtags2.h"
33
34
35 #ifdef CONFIG_YAFFS_WINCE
36 void yfsd_LockYAFFS(BOOL fsLockOnly);
37 void yfsd_UnlockYAFFS(BOOL fsLockOnly);
38 #endif
39
40 #define YAFFS_PASSIVE_GC_CHUNKS 2
41
42 #include "yaffs_ecc.h"
43
44
45 /* Robustification (if it ever comes about...) */
46 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND);
47 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk);
48 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
49                                      const __u8 * data,
50                                      const yaffs_ExtendedTags * tags);
51 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
52                                     const yaffs_ExtendedTags * tags);
53
54 /* Other local prototypes */
55 static int yaffs_UnlinkObject( yaffs_Object *obj);
56 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
57
58 static void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList);
59
60 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device * dev,
61                                              const __u8 * buffer,
62                                              yaffs_ExtendedTags * tags,
63                                              int useReserve);
64 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
65                                   int chunkInNAND, int inScan);
66
67 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
68                                            yaffs_ObjectType type);
69 static void yaffs_AddObjectToDirectory(yaffs_Object * directory,
70                                        yaffs_Object * obj);
71 static int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name,
72                                     int force, int isShrink, int shadows);
73 static void yaffs_RemoveObjectFromDirectory(yaffs_Object * obj);
74 static int yaffs_CheckStructures(void);
75 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
76                               int chunkOffset, int *limit);
77 static int yaffs_DoGenericObjectDeletion(yaffs_Object * in);
78
79 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device * dev, int blockNo);
80
81 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo);
82 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
83                                     int lineNo);
84
85 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
86                                   int chunkInNAND);
87
88 static int yaffs_UnlinkWorker(yaffs_Object * obj);
89 static void yaffs_DestroyObject(yaffs_Object * obj);
90
91 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
92                            int chunkInObject);
93
94 loff_t yaffs_GetFileSize(yaffs_Object * obj);
95
96 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr);
97
98 static void yaffs_VerifyFreeChunks(yaffs_Device * dev);
99
100 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
101
102 #ifdef YAFFS_PARANOID
103 static int yaffs_CheckFileSanity(yaffs_Object * in);
104 #else
105 #define yaffs_CheckFileSanity(in)
106 #endif
107
108 static void yaffs_InvalidateWholeChunkCache(yaffs_Object * in);
109 static void yaffs_InvalidateChunkCache(yaffs_Object * object, int chunkId);
110
111 static void yaffs_InvalidateCheckpoint(yaffs_Device *dev);
112
113 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
114                                  yaffs_ExtendedTags * tags);
115
116 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos);
117 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
118                                           yaffs_FileStructure * fStruct,
119                                           __u32 chunkId);
120
121
122 /* Function to calculate chunk and offset */
123
124 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, __u32 *chunk, __u32 *offset)
125 {
126         if(dev->chunkShift){
127                 /* Easy-peasy power of 2 case */
128                 *chunk  = (__u32)(addr >> dev->chunkShift);
129                 *offset = (__u32)(addr & dev->chunkMask);
130         }
131         else if(dev->crumbsPerChunk)
132         {
133                 /* Case where we're using "crumbs" */
134                 *offset = (__u32)(addr & dev->crumbMask);
135                 addr >>= dev->crumbShift;
136                 *chunk = ((__u32)addr)/dev->crumbsPerChunk;
137                 *offset += ((addr - (*chunk * dev->crumbsPerChunk)) << dev->crumbShift);
138         }
139         else
140                 YBUG();
141 }
142
143 /* Function to return the number of shifts for a power of 2 greater than or equal 
144  * to the given number
145  * Note we don't try to cater for all possible numbers and this does not have to
146  * be hellishly efficient.
147  */
148  
149 static __u32 ShiftsGE(__u32 x)
150 {
151         int extraBits;
152         int nShifts;
153         
154         nShifts = extraBits = 0;
155         
156         while(x>1){
157                 if(x & 1) extraBits++;
158                 x>>=1;
159                 nShifts++;
160         }
161
162         if(extraBits) 
163                 nShifts++;
164                 
165         return nShifts;
166 }
167
168 /* Function to return the number of shifts to get a 1 in bit 0
169  */
170  
171 static __u32 ShiftDiv(__u32 x)
172 {
173         int nShifts;
174         
175         nShifts =  0;
176         
177         if(!x) return 0;
178         
179         while( !(x&1)){
180                 x>>=1;
181                 nShifts++;
182         }
183                 
184         return nShifts;
185 }
186
187
188
189 /* 
190  * Temporary buffer manipulations.
191  */
192
193 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)       
194 {
195         int i;
196         __u8 *buf = (__u8 *)1;
197                 
198         memset(dev->tempBuffer,0,sizeof(dev->tempBuffer));
199                 
200         for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
201                 dev->tempBuffer[i].line = 0;    /* not in use */
202                 dev->tempBuffer[i].buffer = buf =
203                     YMALLOC_DMA(dev->nDataBytesPerChunk);
204         }
205                 
206         return buf ? YAFFS_OK : YAFFS_FAIL;
207         
208 }
209
210 static __u8 *yaffs_GetTempBuffer(yaffs_Device * dev, int lineNo)
211 {
212         int i, j;
213         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
214                 if (dev->tempBuffer[i].line == 0) {
215                         dev->tempBuffer[i].line = lineNo;
216                         if ((i + 1) > dev->maxTemp) {
217                                 dev->maxTemp = i + 1;
218                                 for (j = 0; j <= i; j++)
219                                         dev->tempBuffer[j].maxLine =
220                                             dev->tempBuffer[j].line;
221                         }
222
223                         return dev->tempBuffer[i].buffer;
224                 }
225         }
226
227         T(YAFFS_TRACE_BUFFERS,
228           (TSTR("Out of temp buffers at line %d, other held by lines:"),
229            lineNo));
230         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
231                 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
232         }
233         T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
234
235         /*
236          * If we got here then we have to allocate an unmanaged one
237          * This is not good.
238          */
239
240         dev->unmanagedTempAllocations++;
241         return YMALLOC(dev->nDataBytesPerChunk);
242
243 }
244
245 static void yaffs_ReleaseTempBuffer(yaffs_Device * dev, __u8 * buffer,
246                                     int lineNo)
247 {
248         int i;
249         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
250                 if (dev->tempBuffer[i].buffer == buffer) {
251                         dev->tempBuffer[i].line = 0;
252                         return;
253                 }
254         }
255
256         if (buffer) {
257                 /* assume it is an unmanaged one. */
258                 T(YAFFS_TRACE_BUFFERS,
259                   (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
260                    lineNo));
261                 YFREE(buffer);
262                 dev->unmanagedTempDeallocations++;
263         }
264
265 }
266
267 /*
268  * Determine if we have a managed buffer.
269  */
270 int yaffs_IsManagedTempBuffer(yaffs_Device * dev, const __u8 * buffer)
271 {
272         int i;
273         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
274                 if (dev->tempBuffer[i].buffer == buffer)
275                         return 1;
276
277         }
278
279     for (i = 0; i < dev->nShortOpCaches; i++) {
280         if( dev->srCache[i].data == buffer )
281             return 1;
282
283     }
284
285     if (buffer == dev->checkpointBuffer)
286       return 1;
287
288     T(YAFFS_TRACE_ALWAYS,
289           (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
290     return 0;
291 }
292
293
294
295 /*
296  * Chunk bitmap manipulations
297  */
298
299 static Y_INLINE __u8 *yaffs_BlockBits(yaffs_Device * dev, int blk)
300 {
301         if (blk < dev->internalStartBlock || blk > dev->internalEndBlock) {
302                 T(YAFFS_TRACE_ERROR,
303                   (TSTR("**>> yaffs: BlockBits block %d is not valid" TENDSTR),
304                    blk));
305                 YBUG();
306         }
307         return dev->chunkBits +
308             (dev->chunkBitmapStride * (blk - dev->internalStartBlock));
309 }
310
311 static Y_INLINE void yaffs_VerifyChunkBitId(yaffs_Device *dev, int blk, int chunk)
312 {
313         if(blk < dev->internalStartBlock || blk > dev->internalEndBlock ||
314            chunk < 0 || chunk >= dev->nChunksPerBlock) {
315            T(YAFFS_TRACE_ERROR,
316             (TSTR("**>> yaffs: Chunk Id (%d:%d) invalid"TENDSTR),blk,chunk));
317             YBUG();
318         }
319 }
320
321 static Y_INLINE void yaffs_ClearChunkBits(yaffs_Device * dev, int blk)
322 {
323         __u8 *blkBits = yaffs_BlockBits(dev, blk);
324
325         memset(blkBits, 0, dev->chunkBitmapStride);
326 }
327
328 static Y_INLINE void yaffs_ClearChunkBit(yaffs_Device * dev, int blk, int chunk)
329 {
330         __u8 *blkBits = yaffs_BlockBits(dev, blk);
331
332         yaffs_VerifyChunkBitId(dev,blk,chunk);
333
334         blkBits[chunk / 8] &= ~(1 << (chunk & 7));
335 }
336
337 static Y_INLINE void yaffs_SetChunkBit(yaffs_Device * dev, int blk, int chunk)
338 {
339         __u8 *blkBits = yaffs_BlockBits(dev, blk);
340         
341         yaffs_VerifyChunkBitId(dev,blk,chunk);
342
343         blkBits[chunk / 8] |= (1 << (chunk & 7));
344 }
345
346 static Y_INLINE int yaffs_CheckChunkBit(yaffs_Device * dev, int blk, int chunk)
347 {
348         __u8 *blkBits = yaffs_BlockBits(dev, blk);
349         yaffs_VerifyChunkBitId(dev,blk,chunk);
350
351         return (blkBits[chunk / 8] & (1 << (chunk & 7))) ? 1 : 0;
352 }
353
354 static Y_INLINE int yaffs_StillSomeChunkBits(yaffs_Device * dev, int blk)
355 {
356         __u8 *blkBits = yaffs_BlockBits(dev, blk);
357         int i;
358         for (i = 0; i < dev->chunkBitmapStride; i++) {
359                 if (*blkBits)
360                         return 1;
361                 blkBits++;
362         }
363         return 0;
364 }
365
366 static int yaffs_CountChunkBits(yaffs_Device * dev, int blk)
367 {
368         __u8 *blkBits = yaffs_BlockBits(dev, blk);
369         int i;
370         int n = 0;
371         for (i = 0; i < dev->chunkBitmapStride; i++) {
372                 __u8 x = *blkBits;
373                 while(x){
374                         if(x & 1)
375                                 n++;
376                         x >>=1;
377                 }
378                         
379                 blkBits++;
380         }
381         return n;
382 }
383
384 /* 
385  * Verification code
386  */
387  
388 static int yaffs_SkipVerification(yaffs_Device *dev)
389 {
390         return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY | YAFFS_TRACE_VERIFY_FULL));
391 }
392
393 static int yaffs_SkipFullVerification(yaffs_Device *dev)
394 {
395         return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_FULL));
396 }
397
398 static int yaffs_SkipNANDVerification(yaffs_Device *dev)
399 {
400         return !(yaffs_traceMask & (YAFFS_TRACE_VERIFY_NAND));
401 }
402
403 static const char * blockStateName[] = {
404 "Unknown",
405 "Needs scanning",
406 "Scanning",
407 "Empty",
408 "Allocating",
409 "Full",
410 "Dirty",
411 "Checkpoint",
412 "Collecting",
413 "Dead"
414 };
415
416 static void yaffs_VerifyBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
417 {
418         int actuallyUsed;
419         int inUse;
420         
421         if(yaffs_SkipVerification(dev))
422                 return;
423                 
424         /* Report illegal runtime states */
425         if(bi->blockState <0 || bi->blockState >= YAFFS_NUMBER_OF_BLOCK_STATES)
426                 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has undefined state %d"TENDSTR),n,bi->blockState));
427                 
428         switch(bi->blockState){
429          case YAFFS_BLOCK_STATE_UNKNOWN:
430          case YAFFS_BLOCK_STATE_SCANNING:
431          case YAFFS_BLOCK_STATE_NEEDS_SCANNING:
432                 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has bad run-state %s"TENDSTR),
433                 n,blockStateName[bi->blockState]));
434         }
435         
436         /* Check pages in use and soft deletions are legal */
437         
438         actuallyUsed = bi->pagesInUse - bi->softDeletions;
439         
440         if(bi->pagesInUse < 0 || bi->pagesInUse > dev->nChunksPerBlock ||
441            bi->softDeletions < 0 || bi->softDeletions > dev->nChunksPerBlock ||
442            actuallyUsed < 0 || actuallyUsed > dev->nChunksPerBlock)
443                 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has illegal values pagesInUsed %d softDeletions %d"TENDSTR),
444                 n,bi->pagesInUse,bi->softDeletions));
445         
446                 
447         /* Check chunk bitmap legal */
448         inUse = yaffs_CountChunkBits(dev,n);
449         if(inUse != bi->pagesInUse)
450                 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has inconsistent values pagesInUse %d counted chunk bits %d"TENDSTR),
451                         n,bi->pagesInUse,inUse));
452         
453         /* Check that the sequence number is valid.
454          * Ten million is legal, but is very unlikely 
455          */
456         if(dev->isYaffs2 && 
457            (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING || bi->blockState == YAFFS_BLOCK_STATE_FULL) &&
458            (bi->sequenceNumber < YAFFS_LOWEST_SEQUENCE_NUMBER || bi->sequenceNumber > 10000000 ))
459                 T(YAFFS_TRACE_VERIFY,(TSTR("Block %d has suspect sequence number of %d"TENDSTR),
460                 n,bi->sequenceNumber));
461                 
462 }
463
464 static void yaffs_VerifyCollectedBlock(yaffs_Device *dev,yaffs_BlockInfo *bi,int n)
465 {
466         yaffs_VerifyBlock(dev,bi,n);
467         
468         /* After collection the block should be in the erased state */
469         /* TODO: This will need to change if we do partial gc */
470         
471         if(bi->blockState != YAFFS_BLOCK_STATE_EMPTY){
472                 T(YAFFS_TRACE_ERROR,(TSTR("Block %d is in state %d after gc, should be erased"TENDSTR),
473                         n,bi->blockState));
474         }
475 }
476
477 static void yaffs_VerifyBlocks(yaffs_Device *dev)
478 {
479         int i;
480         int nBlocksPerState[YAFFS_NUMBER_OF_BLOCK_STATES];
481         int nIllegalBlockStates = 0;
482         
483
484         if(yaffs_SkipVerification(dev))
485                 return;
486
487         memset(nBlocksPerState,0,sizeof(nBlocksPerState));
488
489                 
490         for(i = dev->internalStartBlock; i <= dev->internalEndBlock; i++){
491                 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev,i);
492                 yaffs_VerifyBlock(dev,bi,i);
493
494                 if(bi->blockState >=0 && bi->blockState < YAFFS_NUMBER_OF_BLOCK_STATES)
495                         nBlocksPerState[bi->blockState]++;
496                 else
497                         nIllegalBlockStates++;
498                                         
499         }
500         
501         T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
502         T(YAFFS_TRACE_VERIFY,(TSTR("Block summary"TENDSTR)));
503         
504         T(YAFFS_TRACE_VERIFY,(TSTR("%d blocks have illegal states"TENDSTR),nIllegalBlockStates));
505         if(nBlocksPerState[YAFFS_BLOCK_STATE_ALLOCATING] > 1)
506                 T(YAFFS_TRACE_VERIFY,(TSTR("Too many allocating blocks"TENDSTR)));
507
508         for(i = 0; i < YAFFS_NUMBER_OF_BLOCK_STATES; i++)
509                 T(YAFFS_TRACE_VERIFY,
510                   (TSTR("%s %d blocks"TENDSTR),
511                   blockStateName[i],nBlocksPerState[i]));
512         
513         if(dev->blocksInCheckpoint != nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT])
514                 T(YAFFS_TRACE_VERIFY,
515                  (TSTR("Checkpoint block count wrong dev %d count %d"TENDSTR),
516                  dev->blocksInCheckpoint, nBlocksPerState[YAFFS_BLOCK_STATE_CHECKPOINT]));
517                  
518         if(dev->nErasedBlocks != nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY])
519                 T(YAFFS_TRACE_VERIFY,
520                  (TSTR("Erased block count wrong dev %d count %d"TENDSTR),
521                  dev->nErasedBlocks, nBlocksPerState[YAFFS_BLOCK_STATE_EMPTY]));
522                  
523         if(nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING] > 1)
524                 T(YAFFS_TRACE_VERIFY,
525                  (TSTR("Too many collecting blocks %d (max is 1)"TENDSTR),
526                  nBlocksPerState[YAFFS_BLOCK_STATE_COLLECTING]));
527
528         T(YAFFS_TRACE_VERIFY,(TSTR(""TENDSTR)));
529
530 }
531
532 /*
533  * Verify the object header. oh must be valid, but obj and tags may be NULL in which
534  * case those tests will not be performed.
535  */
536 static void yaffs_VerifyObjectHeader(yaffs_Object *obj, yaffs_ObjectHeader *oh, yaffs_ExtendedTags *tags, int parentCheck)
537 {
538         if(yaffs_SkipVerification(obj->myDev))
539                 return;
540                 
541         if(!(tags && obj && oh)){
542                 T(YAFFS_TRACE_VERIFY,
543                                 (TSTR("Verifying object header tags %x obj %x oh %x"TENDSTR),
544                                 (__u32)tags,(__u32)obj,(__u32)oh));
545                 return;
546         }
547         
548         if(oh->type <= YAFFS_OBJECT_TYPE_UNKNOWN ||
549            oh->type > YAFFS_OBJECT_TYPE_MAX)
550                 T(YAFFS_TRACE_VERIFY,
551                  (TSTR("Obj %d header type is illegal value 0x%x"TENDSTR),
552                  tags->objectId, oh->type));
553
554         if(tags->objectId != obj->objectId)
555                 T(YAFFS_TRACE_VERIFY,
556                  (TSTR("Obj %d header mismatch objectId %d"TENDSTR),
557                  tags->objectId, obj->objectId));
558
559
560         /*
561          * Check that the object's parent ids match if parentCheck requested.
562          * 
563          * Tests do not apply to the root object.
564          */
565         
566         if(parentCheck && tags->objectId > 1 && !obj->parent)
567                 T(YAFFS_TRACE_VERIFY,
568                  (TSTR("Obj %d header mismatch parentId %d obj->parent is NULL"TENDSTR),
569                  tags->objectId, oh->parentObjectId));
570                 
571         
572         if(parentCheck && obj->parent &&
573            oh->parentObjectId != obj->parent->objectId && 
574            (oh->parentObjectId != YAFFS_OBJECTID_UNLINKED ||
575             obj->parent->objectId != YAFFS_OBJECTID_DELETED))
576                 T(YAFFS_TRACE_VERIFY,
577                  (TSTR("Obj %d header mismatch parentId %d parentObjectId %d"TENDSTR),
578                  tags->objectId, oh->parentObjectId, obj->parent->objectId));
579                 
580         
581         if(tags->objectId > 1 && oh->name[0] == 0) /* Null name */
582                 T(YAFFS_TRACE_VERIFY,
583                 (TSTR("Obj %d header name is NULL"TENDSTR),
584                  obj->objectId));
585
586         if(tags->objectId > 1 && ((__u8)(oh->name[0])) == 0xff) /* Trashed name */
587                 T(YAFFS_TRACE_VERIFY,
588                 (TSTR("Obj %d header name is 0xFF"TENDSTR),
589                  obj->objectId));
590 }
591
592
593
594 static int yaffs_VerifyTnodeWorker(yaffs_Object * obj, yaffs_Tnode * tn,
595                                         __u32 level, int chunkOffset)
596 {
597         int i;
598         yaffs_Device *dev = obj->myDev;
599         int ok = 1;
600         int nTnodeBytes = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
601
602         if (tn) {
603                 if (level > 0) {
604
605                         for (i = 0; i < YAFFS_NTNODES_INTERNAL && ok; i++){
606                                 if (tn->internal[i]) {
607                                         ok = yaffs_VerifyTnodeWorker(obj,
608                                                         tn->internal[i],
609                                                         level - 1,
610                                                         (chunkOffset<<YAFFS_TNODES_INTERNAL_BITS) + i);
611                                 }
612                         }
613                 } else if (level == 0) {
614                         int i;
615                         yaffs_ExtendedTags tags;
616                         __u32 objectId = obj->objectId;
617                         
618                         chunkOffset <<=  YAFFS_TNODES_LEVEL0_BITS;
619                         
620                         for(i = 0; i < YAFFS_NTNODES_LEVEL0; i++){
621                                 __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
622                                 
623                                 if(theChunk > 0){
624                                         /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),tags.objectId,tags.chunkId,theChunk)); */
625                                         yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
626                                         if(tags.objectId != objectId || tags.chunkId != chunkOffset){
627                                                 T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
628                                                         objectId, chunkOffset, theChunk,
629                                                         tags.objectId, tags.chunkId));
630                                         }
631                                 }
632                                 chunkOffset++;
633                         }
634                 }
635         }
636
637         return ok;
638
639 }
640
641
642 static void yaffs_VerifyFile(yaffs_Object *obj)
643 {
644         int requiredTallness;
645         int actualTallness;
646         __u32 lastChunk;
647         __u32 x;
648         __u32 i;
649         int ok;
650         yaffs_Device *dev;
651         yaffs_ExtendedTags tags;
652         yaffs_Tnode *tn;
653         __u32 objectId;
654         
655         if(obj && yaffs_SkipVerification(obj->myDev))
656                 return;
657         
658         dev = obj->myDev;
659         objectId = obj->objectId;
660         
661         /* Check file size is consistent with tnode depth */
662         lastChunk =  obj->variant.fileVariant.fileSize / dev->nDataBytesPerChunk + 1;
663         x = lastChunk >> YAFFS_TNODES_LEVEL0_BITS;
664         requiredTallness = 0;
665         while (x> 0) {
666                 x >>= YAFFS_TNODES_INTERNAL_BITS;
667                 requiredTallness++;
668         }
669         
670         actualTallness = obj->variant.fileVariant.topLevel;
671         
672         if(requiredTallness > actualTallness )
673                 T(YAFFS_TRACE_VERIFY,
674                 (TSTR("Obj %d had tnode tallness %d, needs to be %d"TENDSTR),
675                  obj->objectId,actualTallness, requiredTallness));
676         
677         
678         /* Check that the chunks in the tnode tree are all correct. 
679          * We do this by scanning through the tnode tree and
680          * checking the tags for every chunk match.
681          */
682
683         if(yaffs_SkipNANDVerification(dev))
684                 return;
685                 
686         for(i = 1; i <= lastChunk; i++){
687                 tn = yaffs_FindLevel0Tnode(dev, &obj->variant.fileVariant,i);
688
689                 if (tn) {
690                         __u32 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
691                         if(theChunk > 0){
692                                 /* T(~0,(TSTR("verifying (%d:%d) %d"TENDSTR),objectId,i,theChunk)); */
693                                 yaffs_ReadChunkWithTagsFromNAND(dev,theChunk,NULL, &tags);
694                                 if(tags.objectId != objectId || tags.chunkId != i){
695                                         T(~0,(TSTR("Object %d chunkId %d NAND mismatch chunk %d tags (%d:%d)"TENDSTR),
696                                                 objectId, i, theChunk,
697                                                 tags.objectId, tags.chunkId));
698                                 }
699                         }
700                 }
701
702         }
703
704 }
705
706 static void yaffs_VerifyDirectory(yaffs_Object *obj)
707 {
708         if(obj && yaffs_SkipVerification(obj->myDev))
709                 return;
710         
711 }
712
713 static void yaffs_VerifyHardLink(yaffs_Object *obj)
714 {
715         if(obj && yaffs_SkipVerification(obj->myDev))
716                 return;
717                 
718         /* Verify sane equivalent object */
719 }
720
721 static void yaffs_VerifySymlink(yaffs_Object *obj)
722 {
723         if(obj && yaffs_SkipVerification(obj->myDev))
724                 return;
725                 
726         /* Verify symlink string */
727 }
728
729 static void yaffs_VerifySpecial(yaffs_Object *obj)
730 {
731         if(obj && yaffs_SkipVerification(obj->myDev))
732                 return;
733 }
734
735 static void yaffs_VerifyObject(yaffs_Object *obj)
736 {
737         yaffs_Device *dev;
738         
739         __u32 chunkMin;
740         __u32 chunkMax;
741         
742         __u32 chunkIdOk;
743         __u32 chunkIsLive;
744         
745         if(!obj)
746                 return;
747         
748         dev = obj->myDev;
749         
750         if(yaffs_SkipVerification(dev))
751                 return;
752                 
753         /* Check sane object header chunk */
754         
755         chunkMin = dev->internalStartBlock * dev->nChunksPerBlock;
756         chunkMax = (dev->internalEndBlock+1) * dev->nChunksPerBlock - 1;
757         
758         chunkIdOk = (obj->chunkId >= chunkMin && obj->chunkId <= chunkMax);
759         chunkIsLive = chunkIdOk && 
760                         yaffs_CheckChunkBit(dev, 
761                                             obj->chunkId / dev->nChunksPerBlock,
762                                             obj->chunkId % dev->nChunksPerBlock);
763         if(!obj->fake && 
764             (!chunkIdOk || !chunkIsLive)) {
765            T(YAFFS_TRACE_VERIFY,
766            (TSTR("Obj %d has chunkId %d %s %s"TENDSTR),
767            obj->objectId,obj->chunkId,
768            chunkIdOk ? "" : ",out of range",
769            chunkIsLive || !chunkIdOk ? "" : ",marked as deleted"));
770         }
771         
772         if(chunkIdOk && chunkIsLive &&!yaffs_SkipNANDVerification(dev)) {
773                 yaffs_ExtendedTags tags;
774                 yaffs_ObjectHeader *oh;
775                 __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
776                 
777                 oh = (yaffs_ObjectHeader *)buffer;
778                 
779                 yaffs_ReadChunkWithTagsFromNAND(dev, obj->chunkId,buffer, &tags);
780                 
781                 yaffs_VerifyObjectHeader(obj,oh,&tags,1);
782                 
783                 yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
784         }
785         
786         /* Verify it has a parent */
787         if(obj && !obj->fake &&
788            (!obj->parent || obj->parent->myDev != dev)){
789            T(YAFFS_TRACE_VERIFY,
790            (TSTR("Obj %d has parent pointer %p which does not look like an object"TENDSTR),
791            obj->objectId,obj->parent));    
792         }
793         
794         /* Verify parent is a directory */
795         if(obj->parent && obj->parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY){
796            T(YAFFS_TRACE_VERIFY,
797            (TSTR("Obj %d's parent is not a directory (type %d)"TENDSTR),
798            obj->objectId,obj->parent->variantType));       
799         }
800         
801         switch(obj->variantType){
802         case YAFFS_OBJECT_TYPE_FILE:
803                 yaffs_VerifyFile(obj);
804                 break;
805         case YAFFS_OBJECT_TYPE_SYMLINK:
806                 yaffs_VerifySymlink(obj);
807                 break;
808         case YAFFS_OBJECT_TYPE_DIRECTORY:
809                 yaffs_VerifyDirectory(obj);
810                 break;
811         case YAFFS_OBJECT_TYPE_HARDLINK:
812                 yaffs_VerifyHardLink(obj);
813                 break;
814         case YAFFS_OBJECT_TYPE_SPECIAL:
815                 yaffs_VerifySpecial(obj);
816                 break;
817         case YAFFS_OBJECT_TYPE_UNKNOWN:
818         default:
819                 T(YAFFS_TRACE_VERIFY,
820                 (TSTR("Obj %d has illegaltype %d"TENDSTR),
821                 obj->objectId,obj->variantType));          
822                 break;
823         }
824         
825         
826 }
827
828 static void yaffs_VerifyObjects(yaffs_Device *dev)
829 {
830         yaffs_Object *obj;
831         int i;
832         struct list_head *lh;
833
834         if(yaffs_SkipVerification(dev))
835                 return;
836         
837         /* Iterate through the objects in each hash entry */
838          
839          for(i = 0; i <  YAFFS_NOBJECT_BUCKETS; i++){
840                 list_for_each(lh, &dev->objectBucket[i].list) {
841                         if (lh) {
842                                 obj = list_entry(lh, yaffs_Object, hashLink);
843                                 yaffs_VerifyObject(obj);
844                         }
845                 }
846          }
847
848 }
849
850
851 /*
852  *  Simple hash function. Needs to have a reasonable spread
853  */
854  
855 static Y_INLINE int yaffs_HashFunction(int n)
856 {
857         n = abs(n);
858         return (n % YAFFS_NOBJECT_BUCKETS);
859 }
860
861 /*
862  * Access functions to useful fake objects
863  */
864  
865 yaffs_Object *yaffs_Root(yaffs_Device * dev)
866 {
867         return dev->rootDir;
868 }
869
870 yaffs_Object *yaffs_LostNFound(yaffs_Device * dev)
871 {
872         return dev->lostNFoundDir;
873 }
874
875
876 /*
877  *  Erased NAND checking functions
878  */
879  
880 int yaffs_CheckFF(__u8 * buffer, int nBytes)
881 {
882         /* Horrible, slow implementation */
883         while (nBytes--) {
884                 if (*buffer != 0xFF)
885                         return 0;
886                 buffer++;
887         }
888         return 1;
889 }
890
891 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
892                                   int chunkInNAND)
893 {
894
895         int retval = YAFFS_OK;
896         __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
897         yaffs_ExtendedTags tags;
898         int result;
899
900         result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
901         
902         if(tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
903                 retval = YAFFS_FAIL;
904                 
905
906         if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
907                 T(YAFFS_TRACE_NANDACCESS,
908                   (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
909                 retval = YAFFS_FAIL;
910         }
911
912         yaffs_ReleaseTempBuffer(dev, data, __LINE__);
913
914         return retval;
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 chunk;
924
925         int writeOk = 0;
926         int erasedOk = 1;
927         int attempts = 0;
928         yaffs_BlockInfo *bi;
929         
930         yaffs_InvalidateCheckpoint(dev);
931
932         do {
933                 chunk = yaffs_AllocateChunk(dev, useReserve,&bi);
934
935                 if (chunk >= 0) {
936                         /* First check this chunk is erased, if it needs checking.
937                          * The checking policy (unless forced always on) is as follows:
938                          * Check the first page we try to write in a block.
939                          * - If the check passes then we don't need to check any more.
940                          * - If the check fails, we check again...
941                          * If the block has been erased, we don't need to check.
942                          *
943                          * However, if the block has been prioritised for gc, then
944                          * we think there might be something odd about this block
945                          * and stop using it.
946                          *
947                          * Rationale:
948                          * We should only ever see chunks that have not been erased
949                          * if there was a partially written chunk due to power loss
950                          * This checking policy should catch that case with very
951                          * few checks and thus save a lot of checks that are most likely not
952                          * needed.
953                          */
954                          
955                          if(bi->gcPrioritise){
956                                         yaffs_DeleteChunk(dev, chunk, 1, __LINE__);
957                         } else {
958 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
959
960                                 bi->skipErasedCheck = 0;
961
962 #endif
963                                 if(!bi->skipErasedCheck){
964                                         erasedOk = yaffs_CheckChunkErased(dev, chunk);
965                                         if(erasedOk && !bi->gcPrioritise)
966                                                 bi->skipErasedCheck = 1;
967                                 }
968
969                                 if (!erasedOk) {
970                                         T(YAFFS_TRACE_ERROR,
971                                           (TSTR
972                                            ("**>> yaffs chunk %d was not erased"
973                                             TENDSTR), chunk));
974                                 } else {
975                                         writeOk =
976                                             yaffs_WriteChunkWithTagsToNAND(dev, chunk,
977                                                                            data, tags);
978                                 }
979                         
980                                 attempts++;
981
982                                 if (writeOk) {
983                                         /*
984                                          *  Copy the data into the robustification buffer.
985                                          *  NB We do this at the end to prevent duplicates in the case of a write error.
986                                          *  Todo
987                                          */
988                                         yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
989                                 
990                                 } else {
991                                         /* The erased check or write failed */
992                                         yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
993                                 }
994                         }
995                 }
996
997         } while (chunk >= 0 && !writeOk);
998
999         if (attempts > 1) {
1000                 T(YAFFS_TRACE_ERROR,
1001                   (TSTR("**>> yaffs write required %d attempts" TENDSTR),
1002                    attempts));
1003                 dev->nRetriedWrites += (attempts - 1);
1004         }
1005
1006         return chunk;
1007 }
1008
1009 /*
1010  * Block retiring for handling a broken block.
1011  */
1012  
1013 static void yaffs_RetireBlock(yaffs_Device * dev, int blockInNAND)
1014 {
1015         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1016
1017         yaffs_InvalidateCheckpoint(dev);
1018         
1019         yaffs_MarkBlockBad(dev, blockInNAND);
1020
1021         bi->blockState = YAFFS_BLOCK_STATE_DEAD;
1022         bi->gcPrioritise = 0;
1023         bi->needsRetiring = 0;
1024
1025         dev->nRetiredBlocks++;
1026 }
1027
1028 /*
1029  * Functions for robustisizing TODO
1030  *
1031  */
1032  
1033 static void yaffs_HandleWriteChunkOk(yaffs_Device * dev, int chunkInNAND,
1034                                      const __u8 * data,
1035                                      const yaffs_ExtendedTags * tags)
1036 {
1037 }
1038
1039 static void yaffs_HandleUpdateChunk(yaffs_Device * dev, int chunkInNAND,
1040                                     const yaffs_ExtendedTags * tags)
1041 {
1042 }
1043
1044 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
1045 {
1046         if(!bi->gcPrioritise){
1047                 bi->gcPrioritise = 1;
1048                 dev->hasPendingPrioritisedGCs = 1;
1049                 bi->chunkErrorStrikes ++;
1050                 
1051                 if(bi->chunkErrorStrikes > 3){
1052                         bi->needsRetiring = 1; /* Too many stikes, so retire this */
1053                         T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
1054
1055                 }
1056                 
1057         }
1058 }
1059
1060 static void yaffs_HandleWriteChunkError(yaffs_Device * dev, int chunkInNAND, int erasedOk)
1061 {
1062
1063         int blockInNAND = chunkInNAND / dev->nChunksPerBlock;
1064         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
1065
1066         yaffs_HandleChunkError(dev,bi);
1067                 
1068         
1069         if(erasedOk ) {
1070                 /* Was an actual write failure, so mark the block for retirement  */
1071                 bi->needsRetiring = 1;
1072                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1073                   (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
1074
1075                 
1076         }
1077         
1078         /* Delete the chunk */
1079         yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
1080 }
1081
1082
1083 /*---------------- Name handling functions ------------*/ 
1084
1085 static __u16 yaffs_CalcNameSum(const YCHAR * name)
1086 {
1087         __u16 sum = 0;
1088         __u16 i = 1;
1089
1090         YUCHAR *bname = (YUCHAR *) name;
1091         if (bname) {
1092                 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
1093
1094 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1095                         sum += yaffs_toupper(*bname) * i;
1096 #else
1097                         sum += (*bname) * i;
1098 #endif
1099                         i++;
1100                         bname++;
1101                 }
1102         }
1103         return sum;
1104 }
1105
1106 static void yaffs_SetObjectName(yaffs_Object * obj, const YCHAR * name)
1107 {
1108 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
1109         if (name && yaffs_strlen(name) <= YAFFS_SHORT_NAME_LENGTH) {
1110                 yaffs_strcpy(obj->shortName, name);
1111         } else {
1112                 obj->shortName[0] = _Y('\0');
1113         }
1114 #endif
1115         obj->sum = yaffs_CalcNameSum(name);
1116 }
1117
1118 /*-------------------- TNODES -------------------
1119
1120  * List of spare tnodes
1121  * The list is hooked together using the first pointer
1122  * in the tnode.
1123  */
1124  
1125 /* yaffs_CreateTnodes creates a bunch more tnodes and
1126  * adds them to the tnode free list.
1127  * Don't use this function directly
1128  */
1129
1130 static int yaffs_CreateTnodes(yaffs_Device * dev, int nTnodes)
1131 {
1132         int i;
1133         int tnodeSize;
1134         yaffs_Tnode *newTnodes;
1135         __u8 *mem;
1136         yaffs_Tnode *curr;
1137         yaffs_Tnode *next;
1138         yaffs_TnodeList *tnl;
1139
1140         if (nTnodes < 1)
1141                 return YAFFS_OK;
1142                 
1143         /* Calculate the tnode size in bytes for variable width tnode support.
1144          * Must be a multiple of 32-bits  */
1145         tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
1146
1147         /* make these things */
1148
1149         newTnodes = YMALLOC(nTnodes * tnodeSize);
1150         mem = (__u8 *)newTnodes;
1151
1152         if (!newTnodes) {
1153                 T(YAFFS_TRACE_ERROR,
1154                   (TSTR("yaffs: Could not allocate Tnodes" TENDSTR)));
1155                 return YAFFS_FAIL;
1156         }
1157
1158         /* Hook them into the free list */
1159 #if 0
1160         for (i = 0; i < nTnodes - 1; i++) {
1161                 newTnodes[i].internal[0] = &newTnodes[i + 1];
1162 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1163                 newTnodes[i].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1164 #endif
1165         }
1166
1167         newTnodes[nTnodes - 1].internal[0] = dev->freeTnodes;
1168 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1169         newTnodes[nTnodes - 1].internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1170 #endif
1171         dev->freeTnodes = newTnodes;
1172 #else
1173         /* New hookup for wide tnodes */
1174         for(i = 0; i < nTnodes -1; i++) {
1175                 curr = (yaffs_Tnode *) &mem[i * tnodeSize];
1176                 next = (yaffs_Tnode *) &mem[(i+1) * tnodeSize];
1177                 curr->internal[0] = next;
1178         }
1179         
1180         curr = (yaffs_Tnode *) &mem[(nTnodes - 1) * tnodeSize];
1181         curr->internal[0] = dev->freeTnodes;
1182         dev->freeTnodes = (yaffs_Tnode *)mem;
1183
1184 #endif
1185
1186
1187         dev->nFreeTnodes += nTnodes;
1188         dev->nTnodesCreated += nTnodes;
1189
1190         /* Now add this bunch of tnodes to a list for freeing up.
1191          * NB If we can't add this to the management list it isn't fatal
1192          * but it just means we can't free this bunch of tnodes later.
1193          */
1194          
1195         tnl = YMALLOC(sizeof(yaffs_TnodeList));
1196         if (!tnl) {
1197                 T(YAFFS_TRACE_ERROR,
1198                   (TSTR
1199                    ("yaffs: Could not add tnodes to management list" TENDSTR)));
1200                    return YAFFS_FAIL;
1201
1202         } else {
1203                 tnl->tnodes = newTnodes;
1204                 tnl->next = dev->allocatedTnodeList;
1205                 dev->allocatedTnodeList = tnl;
1206         }
1207
1208         T(YAFFS_TRACE_ALLOCATE, (TSTR("yaffs: Tnodes added" TENDSTR)));
1209
1210         return YAFFS_OK;
1211 }
1212
1213 /* GetTnode gets us a clean tnode. Tries to make allocate more if we run out */
1214
1215 static yaffs_Tnode *yaffs_GetTnodeRaw(yaffs_Device * dev)
1216 {
1217         yaffs_Tnode *tn = NULL;
1218
1219         /* If there are none left make more */
1220         if (!dev->freeTnodes) {
1221                 yaffs_CreateTnodes(dev, YAFFS_ALLOCATION_NTNODES);
1222         }
1223
1224         if (dev->freeTnodes) {
1225                 tn = dev->freeTnodes;
1226 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1227                 if (tn->internal[YAFFS_NTNODES_INTERNAL] != (void *)1) {
1228                         /* Hoosterman, this thing looks like it isn't in the list */
1229                         T(YAFFS_TRACE_ALWAYS,
1230                           (TSTR("yaffs: Tnode list bug 1" TENDSTR)));
1231                 }
1232 #endif
1233                 dev->freeTnodes = dev->freeTnodes->internal[0];
1234                 dev->nFreeTnodes--;
1235         }
1236
1237         return tn;
1238 }
1239
1240 static yaffs_Tnode *yaffs_GetTnode(yaffs_Device * dev)
1241 {
1242         yaffs_Tnode *tn = yaffs_GetTnodeRaw(dev);
1243         
1244         if(tn)
1245                 memset(tn, 0, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1246
1247         return tn;      
1248 }
1249
1250 /* FreeTnode frees up a tnode and puts it back on the free list */
1251 static void yaffs_FreeTnode(yaffs_Device * dev, yaffs_Tnode * tn)
1252 {
1253         if (tn) {
1254 #ifdef CONFIG_YAFFS_TNODE_LIST_DEBUG
1255                 if (tn->internal[YAFFS_NTNODES_INTERNAL] != 0) {
1256                         /* Hoosterman, this thing looks like it is already in the list */
1257                         T(YAFFS_TRACE_ALWAYS,
1258                           (TSTR("yaffs: Tnode list bug 2" TENDSTR)));
1259                 }
1260                 tn->internal[YAFFS_NTNODES_INTERNAL] = (void *)1;
1261 #endif
1262                 tn->internal[0] = dev->freeTnodes;
1263                 dev->freeTnodes = tn;
1264                 dev->nFreeTnodes++;
1265         }
1266 }
1267
1268 static void yaffs_DeinitialiseTnodes(yaffs_Device * dev)
1269 {
1270         /* Free the list of allocated tnodes */
1271         yaffs_TnodeList *tmp;
1272
1273         while (dev->allocatedTnodeList) {
1274                 tmp = dev->allocatedTnodeList->next;
1275
1276                 YFREE(dev->allocatedTnodeList->tnodes);
1277                 YFREE(dev->allocatedTnodeList);
1278                 dev->allocatedTnodeList = tmp;
1279
1280         }
1281
1282         dev->freeTnodes = NULL;
1283         dev->nFreeTnodes = 0;
1284 }
1285
1286 static void yaffs_InitialiseTnodes(yaffs_Device * dev)
1287 {
1288         dev->allocatedTnodeList = NULL;
1289         dev->freeTnodes = NULL;
1290         dev->nFreeTnodes = 0;
1291         dev->nTnodesCreated = 0;
1292
1293 }
1294
1295
1296 void yaffs_PutLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos, unsigned val)
1297 {
1298   __u32 *map = (__u32 *)tn;
1299   __u32 bitInMap;
1300   __u32 bitInWord;
1301   __u32 wordInMap;
1302   __u32 mask;
1303   
1304   pos &= YAFFS_TNODES_LEVEL0_MASK;
1305   val >>= dev->chunkGroupBits;
1306   
1307   bitInMap = pos * dev->tnodeWidth;
1308   wordInMap = bitInMap /32;
1309   bitInWord = bitInMap & (32 -1);
1310   
1311   mask = dev->tnodeMask << bitInWord;
1312   
1313   map[wordInMap] &= ~mask;
1314   map[wordInMap] |= (mask & (val << bitInWord));
1315   
1316   if(dev->tnodeWidth > (32-bitInWord)) {
1317     bitInWord = (32 - bitInWord);
1318     wordInMap++;;
1319     mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
1320     map[wordInMap] &= ~mask;
1321     map[wordInMap] |= (mask & (val >> bitInWord));
1322   }
1323 }
1324
1325 static __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos)
1326 {
1327   __u32 *map = (__u32 *)tn;
1328   __u32 bitInMap;
1329   __u32 bitInWord;
1330   __u32 wordInMap;
1331   __u32 val;
1332   
1333   pos &= YAFFS_TNODES_LEVEL0_MASK;
1334   
1335   bitInMap = pos * dev->tnodeWidth;
1336   wordInMap = bitInMap /32;
1337   bitInWord = bitInMap & (32 -1);
1338   
1339   val = map[wordInMap] >> bitInWord;
1340   
1341   if(dev->tnodeWidth > (32-bitInWord)) {
1342     bitInWord = (32 - bitInWord);
1343     wordInMap++;;
1344     val |= (map[wordInMap] << bitInWord);
1345   }
1346   
1347   val &= dev->tnodeMask;
1348   val <<= dev->chunkGroupBits;
1349   
1350   return val;
1351 }
1352
1353 /* ------------------- End of individual tnode manipulation -----------------*/
1354
1355 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
1356  * The look up tree is represented by the top tnode and the number of topLevel
1357  * in the tree. 0 means only the level 0 tnode is in the tree.
1358  */
1359
1360 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
1361 static yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device * dev,
1362                                           yaffs_FileStructure * fStruct,
1363                                           __u32 chunkId)
1364 {
1365
1366         yaffs_Tnode *tn = fStruct->top;
1367         __u32 i;
1368         int requiredTallness;
1369         int level = fStruct->topLevel;
1370
1371         /* Check sane level and chunk Id */
1372         if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL) {
1373                 return NULL;
1374         }
1375
1376         if (chunkId > YAFFS_MAX_CHUNK_ID) {
1377                 return NULL;
1378         }
1379
1380         /* First check we're tall enough (ie enough topLevel) */
1381
1382         i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1383         requiredTallness = 0;
1384         while (i) {
1385                 i >>= YAFFS_TNODES_INTERNAL_BITS;
1386                 requiredTallness++;
1387         }
1388
1389         if (requiredTallness > fStruct->topLevel) {
1390                 /* Not tall enough, so we can't find it, return NULL. */
1391                 return NULL;
1392         }
1393
1394         /* Traverse down to level 0 */
1395         while (level > 0 && tn) {
1396                 tn = tn->
1397                     internal[(chunkId >>
1398                                ( YAFFS_TNODES_LEVEL0_BITS + 
1399                                  (level - 1) *
1400                                  YAFFS_TNODES_INTERNAL_BITS)
1401                               ) &
1402                              YAFFS_TNODES_INTERNAL_MASK];
1403                 level--;
1404
1405         }
1406
1407         return tn;
1408 }
1409
1410 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
1411  * This happens in two steps:
1412  *  1. If the tree isn't tall enough, then make it taller.
1413  *  2. Scan down the tree towards the level 0 tnode adding tnodes if required.
1414  *
1415  * Used when modifying the tree.
1416  *
1417  *  If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
1418  *  be plugged into the ttree.
1419  */
1420  
1421 static yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device * dev,
1422                                                yaffs_FileStructure * fStruct,
1423                                                __u32 chunkId,
1424                                                yaffs_Tnode *passedTn)
1425 {
1426
1427         int requiredTallness;
1428         int i;
1429         int l;
1430         yaffs_Tnode *tn;
1431
1432         __u32 x;
1433
1434
1435         /* Check sane level and page Id */
1436         if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL) {
1437                 return NULL;
1438         }
1439
1440         if (chunkId > YAFFS_MAX_CHUNK_ID) {
1441                 return NULL;
1442         }
1443
1444         /* First check we're tall enough (ie enough topLevel) */
1445
1446         x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
1447         requiredTallness = 0;
1448         while (x) {
1449                 x >>= YAFFS_TNODES_INTERNAL_BITS;
1450                 requiredTallness++;
1451         }
1452
1453
1454         if (requiredTallness > fStruct->topLevel) {
1455                 /* Not tall enough,gotta make the tree taller */
1456                 for (i = fStruct->topLevel; i < requiredTallness; i++) {
1457                 
1458                         tn = yaffs_GetTnode(dev);
1459
1460                         if (tn) {
1461                                 tn->internal[0] = fStruct->top;
1462                                 fStruct->top = tn;
1463                         } else {
1464                                 T(YAFFS_TRACE_ERROR,
1465                                   (TSTR("yaffs: no more tnodes" TENDSTR)));
1466                         }
1467                 }
1468
1469                 fStruct->topLevel = requiredTallness;
1470         }
1471
1472         /* Traverse down to level 0, adding anything we need */
1473
1474         l = fStruct->topLevel;
1475         tn = fStruct->top;
1476         
1477         if(l > 0) {
1478                 while (l > 0 && tn) {
1479                         x = (chunkId >>
1480                              ( YAFFS_TNODES_LEVEL0_BITS +
1481                               (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
1482                             YAFFS_TNODES_INTERNAL_MASK;
1483
1484
1485                         if((l>1) && !tn->internal[x]){
1486                                 /* Add missing non-level-zero tnode */
1487                                 tn->internal[x] = yaffs_GetTnode(dev);
1488
1489                         } else if(l == 1) {
1490                                 /* Looking from level 1 at level 0 */
1491                                 if (passedTn) {
1492                                         /* If we already have one, then release it.*/
1493                                         if(tn->internal[x])
1494                                                 yaffs_FreeTnode(dev,tn->internal[x]);
1495                                         tn->internal[x] = passedTn;
1496                         
1497                                 } else if(!tn->internal[x]) {
1498                                         /* Don't have one, none passed in */
1499                                         tn->internal[x] = yaffs_GetTnode(dev);
1500                                 }
1501                         }
1502                 
1503                         tn = tn->internal[x];
1504                         l--;
1505                 }
1506         } else {
1507                 /* top is level 0 */
1508                 if(passedTn) {
1509                         memcpy(tn,passedTn,(dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
1510                         yaffs_FreeTnode(dev,passedTn);
1511                 }
1512         }
1513
1514         return tn;
1515 }
1516
1517 static int yaffs_FindChunkInGroup(yaffs_Device * dev, int theChunk,
1518                                   yaffs_ExtendedTags * tags, int objectId,
1519                                   int chunkInInode)
1520 {
1521         int j;
1522
1523         for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
1524                 if (yaffs_CheckChunkBit
1525                     (dev, theChunk / dev->nChunksPerBlock,
1526                      theChunk % dev->nChunksPerBlock)) {
1527                         yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
1528                                                         tags);
1529                         if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
1530                                 /* found it; */
1531                                 return theChunk;
1532
1533                         }
1534                 }
1535                 theChunk++;
1536         }
1537         return -1;
1538 }
1539
1540
1541 /* DeleteWorker scans backwards through the tnode tree and deletes all the
1542  * chunks and tnodes in the file
1543  * Returns 1 if the tree was deleted. 
1544  * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
1545  */
1546
1547 static int yaffs_DeleteWorker(yaffs_Object * in, yaffs_Tnode * tn, __u32 level,
1548                               int chunkOffset, int *limit)
1549 {
1550         int i;
1551         int chunkInInode;
1552         int theChunk;
1553         yaffs_ExtendedTags tags;
1554         int foundChunk;
1555         yaffs_Device *dev = in->myDev;
1556
1557         int allDone = 1;
1558
1559         if (tn) {
1560                 if (level > 0) {
1561
1562                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1563                              i--) {
1564                                 if (tn->internal[i]) {
1565                                         if (limit && (*limit) < 0) {
1566                                                 allDone = 0;
1567                                         } else {
1568                                                 allDone =
1569                                                     yaffs_DeleteWorker(in,
1570                                                                        tn->
1571                                                                        internal
1572                                                                        [i],
1573                                                                        level -
1574                                                                        1,
1575                                                                        (chunkOffset
1576                                                                         <<
1577                                                                         YAFFS_TNODES_INTERNAL_BITS)
1578                                                                        + i,
1579                                                                        limit);
1580                                         }
1581                                         if (allDone) {
1582                                                 yaffs_FreeTnode(dev,
1583                                                                 tn->
1584                                                                 internal[i]);
1585                                                 tn->internal[i] = NULL;
1586                                         }
1587                                 }
1588
1589                         }
1590                         return (allDone) ? 1 : 0;
1591                 } else if (level == 0) {
1592                         int hitLimit = 0;
1593
1594                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
1595                              i--) {
1596                                 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1597                                 if (theChunk) {
1598
1599                                         chunkInInode =
1600                                             (chunkOffset <<
1601                                              YAFFS_TNODES_LEVEL0_BITS) + i;
1602
1603                                         foundChunk =
1604                                             yaffs_FindChunkInGroup(dev,
1605                                                                    theChunk,
1606                                                                    &tags,
1607                                                                    in->objectId,
1608                                                                    chunkInInode);
1609
1610                                         if (foundChunk > 0) {
1611                                                 yaffs_DeleteChunk(dev,
1612                                                                   foundChunk, 1,
1613                                                                   __LINE__);
1614                                                 in->nDataChunks--;
1615                                                 if (limit) {
1616                                                         *limit = *limit - 1;
1617                                                         if (*limit <= 0) {
1618                                                                 hitLimit = 1;
1619                                                         }
1620                                                 }
1621
1622                                         }
1623
1624                                         yaffs_PutLevel0Tnode(dev,tn,i,0);
1625                                 }
1626
1627                         }
1628                         return (i < 0) ? 1 : 0;
1629
1630                 }
1631
1632         }
1633
1634         return 1;
1635
1636 }
1637
1638 static void yaffs_SoftDeleteChunk(yaffs_Device * dev, int chunk)
1639 {
1640
1641         yaffs_BlockInfo *theBlock;
1642
1643         T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1644
1645         theBlock = yaffs_GetBlockInfo(dev, chunk / dev->nChunksPerBlock);
1646         if (theBlock) {
1647                 theBlock->softDeletions++;
1648                 dev->nFreeChunks++;
1649         }
1650 }
1651
1652 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1653  * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1654  * of the tnode.
1655  * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1656  */
1657  
1658 static int yaffs_SoftDeleteWorker(yaffs_Object * in, yaffs_Tnode * tn,
1659                                   __u32 level, int chunkOffset)
1660 {
1661         int i;
1662         int theChunk;
1663         int allDone = 1;
1664         yaffs_Device *dev = in->myDev;
1665
1666         if (tn) {
1667                 if (level > 0) {
1668
1669                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1670                              i--) {
1671                                 if (tn->internal[i]) {
1672                                         allDone =
1673                                             yaffs_SoftDeleteWorker(in,
1674                                                                    tn->
1675                                                                    internal[i],
1676                                                                    level - 1,
1677                                                                    (chunkOffset
1678                                                                     <<
1679                                                                     YAFFS_TNODES_INTERNAL_BITS)
1680                                                                    + i);
1681                                         if (allDone) {
1682                                                 yaffs_FreeTnode(dev,
1683                                                                 tn->
1684                                                                 internal[i]);
1685                                                 tn->internal[i] = NULL;
1686                                         } else {
1687                                                 /* Hoosterman... how could this happen? */
1688                                         }
1689                                 }
1690                         }
1691                         return (allDone) ? 1 : 0;
1692                 } else if (level == 0) {
1693
1694                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1695                                 theChunk = yaffs_GetChunkGroupBase(dev,tn,i);
1696                                 if (theChunk) {
1697                                         /* Note this does not find the real chunk, only the chunk group.
1698                                          * We make an assumption that a chunk group is not larger than 
1699                                          * a block.
1700                                          */
1701                                         yaffs_SoftDeleteChunk(dev, theChunk);
1702                                         yaffs_PutLevel0Tnode(dev,tn,i,0);
1703                                 }
1704
1705                         }
1706                         return 1;
1707
1708                 }
1709
1710         }
1711
1712         return 1;
1713
1714 }
1715
1716 static void yaffs_SoftDeleteFile(yaffs_Object * obj)
1717 {
1718         if (obj->deleted &&
1719             obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1720                 if (obj->nDataChunks <= 0) {
1721                         /* Empty file with no duplicate object headers, just delete it immediately */
1722                         yaffs_FreeTnode(obj->myDev,
1723                                         obj->variant.fileVariant.top);
1724                         obj->variant.fileVariant.top = NULL;
1725                         T(YAFFS_TRACE_TRACING,
1726                           (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1727                            obj->objectId));
1728                         yaffs_DoGenericObjectDeletion(obj);
1729                 } else {
1730                         yaffs_SoftDeleteWorker(obj,
1731                                                obj->variant.fileVariant.top,
1732                                                obj->variant.fileVariant.
1733                                                topLevel, 0);
1734                         obj->softDeleted = 1;
1735                 }
1736         }
1737 }
1738
1739 /* Pruning removes any part of the file structure tree that is beyond the
1740  * bounds of the file (ie that does not point to chunks).
1741  *
1742  * A file should only get pruned when its size is reduced.
1743  *
1744  * Before pruning, the chunks must be pulled from the tree and the
1745  * level 0 tnode entries must be zeroed out.
1746  * Could also use this for file deletion, but that's probably better handled
1747  * by a special case.
1748  */
1749
1750 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device * dev, yaffs_Tnode * tn,
1751                                       __u32 level, int del0)
1752 {
1753         int i;
1754         int hasData;
1755
1756         if (tn) {
1757                 hasData = 0;
1758
1759                 for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1760                         if (tn->internal[i] && level > 0) {
1761                                 tn->internal[i] =
1762                                     yaffs_PruneWorker(dev, tn->internal[i],
1763                                                       level - 1,
1764                                                       (i == 0) ? del0 : 1);
1765                         }
1766
1767                         if (tn->internal[i]) {
1768                                 hasData++;
1769                         }
1770                 }
1771
1772                 if (hasData == 0 && del0) {
1773                         /* Free and return NULL */
1774
1775                         yaffs_FreeTnode(dev, tn);
1776                         tn = NULL;
1777                 }
1778
1779         }
1780
1781         return tn;
1782
1783 }
1784
1785 static int yaffs_PruneFileStructure(yaffs_Device * dev,
1786                                     yaffs_FileStructure * fStruct)
1787 {
1788         int i;
1789         int hasData;
1790         int done = 0;
1791         yaffs_Tnode *tn;
1792
1793         if (fStruct->topLevel > 0) {
1794                 fStruct->top =
1795                     yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1796
1797                 /* Now we have a tree with all the non-zero branches NULL but the height
1798                  * is the same as it was.
1799                  * Let's see if we can trim internal tnodes to shorten the tree.
1800                  * We can do this if only the 0th element in the tnode is in use 
1801                  * (ie all the non-zero are NULL)
1802                  */
1803
1804                 while (fStruct->topLevel && !done) {
1805                         tn = fStruct->top;
1806
1807                         hasData = 0;
1808                         for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1809                                 if (tn->internal[i]) {
1810                                         hasData++;
1811                                 }
1812                         }
1813
1814                         if (!hasData) {
1815                                 fStruct->top = tn->internal[0];
1816                                 fStruct->topLevel--;
1817                                 yaffs_FreeTnode(dev, tn);
1818                         } else {
1819                                 done = 1;
1820                         }
1821                 }
1822         }
1823
1824         return YAFFS_OK;
1825 }
1826
1827 /*-------------------- End of File Structure functions.-------------------*/
1828
1829 /* yaffs_CreateFreeObjects creates a bunch more objects and
1830  * adds them to the object free list.
1831  */
1832 static int yaffs_CreateFreeObjects(yaffs_Device * dev, int nObjects)
1833 {
1834         int i;
1835         yaffs_Object *newObjects;
1836         yaffs_ObjectList *list;
1837
1838         if (nObjects < 1)
1839                 return YAFFS_OK;
1840
1841         /* make these things */
1842         newObjects = YMALLOC(nObjects * sizeof(yaffs_Object));
1843         list = YMALLOC(sizeof(yaffs_ObjectList));
1844
1845         if (!newObjects || !list) {
1846                 if(newObjects)
1847                         YFREE(newObjects);
1848                 if(list)
1849                         YFREE(list);
1850                 T(YAFFS_TRACE_ALLOCATE,
1851                   (TSTR("yaffs: Could not allocate more objects" TENDSTR)));
1852                 return YAFFS_FAIL;
1853         }
1854         
1855         /* Hook them into the free list */
1856         for (i = 0; i < nObjects - 1; i++) {
1857                 newObjects[i].siblings.next =
1858                     (struct list_head *)(&newObjects[i + 1]);
1859         }
1860
1861         newObjects[nObjects - 1].siblings.next = (void *)dev->freeObjects;
1862         dev->freeObjects = newObjects;
1863         dev->nFreeObjects += nObjects;
1864         dev->nObjectsCreated += nObjects;
1865
1866         /* Now add this bunch of Objects to a list for freeing up. */
1867
1868         list->objects = newObjects;
1869         list->next = dev->allocatedObjectList;
1870         dev->allocatedObjectList = list;
1871
1872         return YAFFS_OK;
1873 }
1874
1875
1876 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1877 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device * dev)
1878 {
1879         yaffs_Object *tn = NULL;
1880
1881         /* If there are none left make more */
1882         if (!dev->freeObjects) {
1883                 yaffs_CreateFreeObjects(dev, YAFFS_ALLOCATION_NOBJECTS);
1884         }
1885
1886         if (dev->freeObjects) {
1887                 tn = dev->freeObjects;
1888                 dev->freeObjects =
1889                     (yaffs_Object *) (dev->freeObjects->siblings.next);
1890                 dev->nFreeObjects--;
1891
1892                 /* Now sweeten it up... */
1893
1894                 memset(tn, 0, sizeof(yaffs_Object));
1895                 tn->myDev = dev;
1896                 tn->chunkId = -1;
1897                 tn->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1898                 INIT_LIST_HEAD(&(tn->hardLinks));
1899                 INIT_LIST_HEAD(&(tn->hashLink));
1900                 INIT_LIST_HEAD(&tn->siblings);
1901
1902                 /* Add it to the lost and found directory.
1903                  * NB Can't put root or lostNFound in lostNFound so
1904                  * check if lostNFound exists first
1905                  */
1906                 if (dev->lostNFoundDir) {
1907                         yaffs_AddObjectToDirectory(dev->lostNFoundDir, tn);
1908                 }
1909         }
1910
1911         return tn;
1912 }
1913
1914 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device * dev, int number,
1915                                                __u32 mode)
1916 {
1917
1918         yaffs_Object *obj =
1919             yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1920         if (obj) {
1921                 obj->fake = 1;          /* it is fake so it has no NAND presence... */
1922                 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1923                 obj->unlinkAllowed = 0; /* ... or unlink it */
1924                 obj->deleted = 0;
1925                 obj->unlinked = 0;
1926                 obj->yst_mode = mode;
1927                 obj->myDev = dev;
1928                 obj->chunkId = 0;       /* Not a valid chunk. */
1929         }
1930
1931         return obj;
1932
1933 }
1934
1935 static void yaffs_UnhashObject(yaffs_Object * tn)
1936 {
1937         int bucket;
1938         yaffs_Device *dev = tn->myDev;
1939
1940         /* If it is still linked into the bucket list, free from the list */
1941         if (!list_empty(&tn->hashLink)) {
1942                 list_del_init(&tn->hashLink);
1943                 bucket = yaffs_HashFunction(tn->objectId);
1944                 dev->objectBucket[bucket].count--;
1945         }
1946
1947 }
1948
1949 /*  FreeObject frees up a Object and puts it back on the free list */
1950 static void yaffs_FreeObject(yaffs_Object * tn)
1951 {
1952
1953         yaffs_Device *dev = tn->myDev;
1954
1955 #ifdef  __KERNEL__
1956         if (tn->myInode) {
1957                 /* We're still hooked up to a cached inode.
1958                  * Don't delete now, but mark for later deletion
1959                  */
1960                 tn->deferedFree = 1;
1961                 return;
1962         }
1963 #endif
1964
1965         yaffs_UnhashObject(tn);
1966
1967         /* Link into the free list. */
1968         tn->siblings.next = (struct list_head *)(dev->freeObjects);
1969         dev->freeObjects = tn;
1970         dev->nFreeObjects++;
1971 }
1972
1973 #ifdef __KERNEL__
1974
1975 void yaffs_HandleDeferedFree(yaffs_Object * obj)
1976 {
1977         if (obj->deferedFree) {
1978                 yaffs_FreeObject(obj);
1979         }
1980 }
1981
1982 #endif
1983
1984 static void yaffs_DeinitialiseObjects(yaffs_Device * dev)
1985 {
1986         /* Free the list of allocated Objects */
1987
1988         yaffs_ObjectList *tmp;
1989
1990         while (dev->allocatedObjectList) {
1991                 tmp = dev->allocatedObjectList->next;
1992                 YFREE(dev->allocatedObjectList->objects);
1993                 YFREE(dev->allocatedObjectList);
1994
1995                 dev->allocatedObjectList = tmp;
1996         }
1997
1998         dev->freeObjects = NULL;
1999         dev->nFreeObjects = 0;
2000 }
2001
2002 static void yaffs_InitialiseObjects(yaffs_Device * dev)
2003 {
2004         int i;
2005
2006         dev->allocatedObjectList = NULL;
2007         dev->freeObjects = NULL;
2008         dev->nFreeObjects = 0;
2009
2010         for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
2011                 INIT_LIST_HEAD(&dev->objectBucket[i].list);
2012                 dev->objectBucket[i].count = 0;
2013         }
2014
2015 }
2016
2017 static int yaffs_FindNiceObjectBucket(yaffs_Device * dev)
2018 {
2019         static int x = 0;
2020         int i;
2021         int l = 999;
2022         int lowest = 999999;
2023
2024         /* First let's see if we can find one that's empty. */
2025
2026         for (i = 0; i < 10 && lowest > 0; i++) {
2027                 x++;
2028                 x %= YAFFS_NOBJECT_BUCKETS;
2029                 if (dev->objectBucket[x].count < lowest) {
2030                         lowest = dev->objectBucket[x].count;
2031                         l = x;
2032                 }
2033
2034         }
2035
2036         /* If we didn't find an empty list, then try
2037          * looking a bit further for a short one
2038          */
2039
2040         for (i = 0; i < 10 && lowest > 3; i++) {
2041                 x++;
2042                 x %= YAFFS_NOBJECT_BUCKETS;
2043                 if (dev->objectBucket[x].count < lowest) {
2044                         lowest = dev->objectBucket[x].count;
2045                         l = x;
2046                 }
2047
2048         }
2049
2050         return l;
2051 }
2052
2053 static int yaffs_CreateNewObjectNumber(yaffs_Device * dev)
2054 {
2055         int bucket = yaffs_FindNiceObjectBucket(dev);
2056
2057         /* Now find an object value that has not already been taken
2058          * by scanning the list.
2059          */
2060
2061         int found = 0;
2062         struct list_head *i;
2063
2064         __u32 n = (__u32) bucket;
2065
2066         /* yaffs_CheckObjectHashSanity();  */
2067
2068         while (!found) {
2069                 found = 1;
2070                 n += YAFFS_NOBJECT_BUCKETS;
2071                 if (1 || dev->objectBucket[bucket].count > 0) {
2072                         list_for_each(i, &dev->objectBucket[bucket].list) {
2073                                 /* If there is already one in the list */
2074                                 if (i
2075                                     && list_entry(i, yaffs_Object,
2076                                                   hashLink)->objectId == n) {
2077                                         found = 0;
2078                                 }
2079                         }
2080                 }
2081         }
2082
2083
2084         return n;
2085 }
2086
2087 static void yaffs_HashObject(yaffs_Object * in)
2088 {
2089         int bucket = yaffs_HashFunction(in->objectId);
2090         yaffs_Device *dev = in->myDev;
2091
2092         list_add(&in->hashLink, &dev->objectBucket[bucket].list);
2093         dev->objectBucket[bucket].count++;
2094
2095 }
2096
2097 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device * dev, __u32 number)
2098 {
2099         int bucket = yaffs_HashFunction(number);
2100         struct list_head *i;
2101         yaffs_Object *in;
2102
2103         list_for_each(i, &dev->objectBucket[bucket].list) {
2104                 /* Look if it is in the list */
2105                 if (i) {
2106                         in = list_entry(i, yaffs_Object, hashLink);
2107                         if (in->objectId == number) {
2108 #ifdef __KERNEL__
2109                                 /* Don't tell the VFS about this one if it is defered free */
2110                                 if (in->deferedFree)
2111                                         return NULL;
2112 #endif
2113
2114                                 return in;
2115                         }
2116                 }
2117         }
2118
2119         return NULL;
2120 }
2121
2122 yaffs_Object *yaffs_CreateNewObject(yaffs_Device * dev, int number,
2123                                     yaffs_ObjectType type)
2124 {
2125
2126         yaffs_Object *theObject;
2127         yaffs_Tnode *tn;
2128
2129         if (number < 0) {
2130                 number = yaffs_CreateNewObjectNumber(dev);
2131         }
2132
2133         theObject = yaffs_AllocateEmptyObject(dev);
2134         if(!theObject)
2135                 return NULL;
2136                 
2137         if(type == YAFFS_OBJECT_TYPE_FILE){
2138                 tn = yaffs_GetTnode(dev);
2139                 if(!tn){
2140                         yaffs_FreeObject(theObject);
2141                         return NULL;
2142                 }
2143         }
2144                 
2145         
2146
2147         if (theObject) {
2148                 theObject->fake = 0;
2149                 theObject->renameAllowed = 1;
2150                 theObject->unlinkAllowed = 1;
2151                 theObject->objectId = number;
2152                 yaffs_HashObject(theObject);
2153                 theObject->variantType = type;
2154 #ifdef CONFIG_YAFFS_WINCE
2155                 yfsd_WinFileTimeNow(theObject->win_atime);
2156                 theObject->win_ctime[0] = theObject->win_mtime[0] =
2157                     theObject->win_atime[0];
2158                 theObject->win_ctime[1] = theObject->win_mtime[1] =
2159                     theObject->win_atime[1];
2160
2161 #else
2162
2163                 theObject->yst_atime = theObject->yst_mtime =
2164                     theObject->yst_ctime = Y_CURRENT_TIME;
2165 #endif
2166                 switch (type) {
2167                 case YAFFS_OBJECT_TYPE_FILE:
2168                         theObject->variant.fileVariant.fileSize = 0;
2169                         theObject->variant.fileVariant.scannedFileSize = 0;
2170                         theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
2171                         theObject->variant.fileVariant.topLevel = 0;
2172                         theObject->variant.fileVariant.top = tn;
2173                         break;
2174                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2175                         INIT_LIST_HEAD(&theObject->variant.directoryVariant.
2176                                        children);
2177                         break;
2178                 case YAFFS_OBJECT_TYPE_SYMLINK:
2179                 case YAFFS_OBJECT_TYPE_HARDLINK:
2180                 case YAFFS_OBJECT_TYPE_SPECIAL:
2181                         /* No action required */
2182                         break;
2183                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2184                         /* todo this should not happen */
2185                         break;
2186                 }
2187         }
2188
2189         return theObject;
2190 }
2191
2192 static yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device * dev,
2193                                                       int number,
2194                                                       yaffs_ObjectType type)
2195 {
2196         yaffs_Object *theObject = NULL;
2197
2198         if (number > 0) {
2199                 theObject = yaffs_FindObjectByNumber(dev, number);
2200         }
2201
2202         if (!theObject) {
2203                 theObject = yaffs_CreateNewObject(dev, number, type);
2204         }
2205
2206         return theObject;
2207
2208 }
2209                         
2210
2211 static YCHAR *yaffs_CloneString(const YCHAR * str)
2212 {
2213         YCHAR *newStr = NULL;
2214
2215         if (str && *str) {
2216                 newStr = YMALLOC((yaffs_strlen(str) + 1) * sizeof(YCHAR));
2217                 if(newStr)
2218                         yaffs_strcpy(newStr, str);
2219         }
2220
2221         return newStr;
2222
2223 }
2224
2225 /*
2226  * Mknod (create) a new object.
2227  * equivalentObject only has meaning for a hard link;
2228  * aliasString only has meaning for a sumlink.
2229  * rdev only has meaning for devices (a subset of special objects)
2230  */
2231  
2232 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
2233                                        yaffs_Object * parent,
2234                                        const YCHAR * name,
2235                                        __u32 mode,
2236                                        __u32 uid,
2237                                        __u32 gid,
2238                                        yaffs_Object * equivalentObject,
2239                                        const YCHAR * aliasString, __u32 rdev)
2240 {
2241         yaffs_Object *in;
2242         YCHAR *str;
2243
2244         yaffs_Device *dev = parent->myDev;
2245
2246         /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
2247         if (yaffs_FindObjectByName(parent, name)) {
2248                 return NULL;
2249         }
2250
2251         in = yaffs_CreateNewObject(dev, -1, type);
2252         
2253         if(type == YAFFS_OBJECT_TYPE_SYMLINK){
2254                 str = yaffs_CloneString(aliasString);
2255                 if(!str){
2256                         yaffs_FreeObject(in);
2257                         return NULL;
2258                 }
2259         }
2260         
2261         
2262
2263         if (in) {
2264                 in->chunkId = -1;
2265                 in->valid = 1;
2266                 in->variantType = type;
2267
2268                 in->yst_mode = mode;
2269
2270 #ifdef CONFIG_YAFFS_WINCE
2271                 yfsd_WinFileTimeNow(in->win_atime);
2272                 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
2273                 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
2274
2275 #else
2276                 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
2277
2278                 in->yst_rdev = rdev;
2279                 in->yst_uid = uid;
2280                 in->yst_gid = gid;
2281 #endif
2282                 in->nDataChunks = 0;
2283
2284                 yaffs_SetObjectName(in, name);
2285                 in->dirty = 1;
2286
2287                 yaffs_AddObjectToDirectory(parent, in);
2288
2289                 in->myDev = parent->myDev;
2290
2291                 switch (type) {
2292                 case YAFFS_OBJECT_TYPE_SYMLINK:
2293                         in->variant.symLinkVariant.alias = str;
2294                         break;
2295                 case YAFFS_OBJECT_TYPE_HARDLINK:
2296                         in->variant.hardLinkVariant.equivalentObject =
2297                             equivalentObject;
2298                         in->variant.hardLinkVariant.equivalentObjectId =
2299                             equivalentObject->objectId;
2300                         list_add(&in->hardLinks, &equivalentObject->hardLinks);
2301                         break;
2302                 case YAFFS_OBJECT_TYPE_FILE:    
2303                 case YAFFS_OBJECT_TYPE_DIRECTORY:
2304                 case YAFFS_OBJECT_TYPE_SPECIAL:
2305                 case YAFFS_OBJECT_TYPE_UNKNOWN:
2306                         /* do nothing */
2307                         break;
2308                 }
2309
2310                 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0) < 0) {
2311                         /* Could not create the object header, fail the creation */
2312                         yaffs_DestroyObject(in);
2313                         in = NULL;
2314                 }
2315
2316         }
2317
2318         return in;
2319 }
2320
2321 yaffs_Object *yaffs_MknodFile(yaffs_Object * parent, const YCHAR * name,
2322                               __u32 mode, __u32 uid, __u32 gid)
2323 {
2324         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
2325                                  uid, gid, NULL, NULL, 0);
2326 }
2327
2328 yaffs_Object *yaffs_MknodDirectory(yaffs_Object * parent, const YCHAR * name,
2329                                    __u32 mode, __u32 uid, __u32 gid)
2330 {
2331         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
2332                                  mode, uid, gid, NULL, NULL, 0);
2333 }
2334
2335 yaffs_Object *yaffs_MknodSpecial(yaffs_Object * parent, const YCHAR * name,
2336                                  __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
2337 {
2338         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
2339                                  uid, gid, NULL, NULL, rdev);
2340 }
2341
2342 yaffs_Object *yaffs_MknodSymLink(yaffs_Object * parent, const YCHAR * name,
2343                                  __u32 mode, __u32 uid, __u32 gid,
2344                                  const YCHAR * alias)
2345 {
2346         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
2347                                  uid, gid, NULL, alias, 0);
2348 }
2349
2350 /* yaffs_Link returns the object id of the equivalent object.*/
2351 yaffs_Object *yaffs_Link(yaffs_Object * parent, const YCHAR * name,
2352                          yaffs_Object * equivalentObject)
2353 {
2354         /* Get the real object in case we were fed a hard link as an equivalent object */
2355         equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
2356
2357         if (yaffs_MknodObject
2358             (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
2359              equivalentObject, NULL, 0)) {
2360                 return equivalentObject;
2361         } else {
2362                 return NULL;
2363         }
2364
2365 }
2366
2367 static int yaffs_ChangeObjectName(yaffs_Object * obj, yaffs_Object * newDir,
2368                                   const YCHAR * newName, int force, int shadows)
2369 {
2370         int unlinkOp;
2371         int deleteOp;
2372
2373         yaffs_Object *existingTarget;
2374
2375         if (newDir == NULL) {
2376                 newDir = obj->parent;   /* use the old directory */
2377         }
2378
2379         if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
2380                 T(YAFFS_TRACE_ALWAYS,
2381                   (TSTR
2382                    ("tragendy: yaffs_ChangeObjectName: newDir is not a directory"
2383                     TENDSTR)));
2384                 YBUG();
2385         }
2386         
2387         /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
2388         if (obj->myDev->isYaffs2) {
2389                 unlinkOp = (newDir == obj->myDev->unlinkedDir);
2390         } else {
2391                 unlinkOp = (newDir == obj->myDev->unlinkedDir
2392                             && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
2393         }
2394
2395         deleteOp = (newDir == obj->myDev->deletedDir);
2396
2397         existingTarget = yaffs_FindObjectByName(newDir, newName);
2398
2399         /* If the object is a file going into the unlinked directory, 
2400          *   then it is OK to just stuff it in since duplicate names are allowed.
2401          *   else only proceed if the new name does not exist and if we're putting 
2402          *   it into a directory.
2403          */
2404         if ((unlinkOp ||
2405              deleteOp ||
2406              force ||
2407              (shadows > 0) ||
2408              !existingTarget) &&
2409             newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
2410                 yaffs_SetObjectName(obj, newName);
2411                 obj->dirty = 1;
2412
2413                 yaffs_AddObjectToDirectory(newDir, obj);
2414
2415                 if (unlinkOp)
2416                         obj->unlinked = 1;
2417
2418                 /* If it is a deletion then we mark it as a shrink for gc purposes. */
2419                 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows)>= 0)
2420                         return YAFFS_OK;
2421         }
2422
2423         return YAFFS_FAIL;
2424 }
2425
2426 int yaffs_RenameObject(yaffs_Object * oldDir, const YCHAR * oldName,
2427                        yaffs_Object * newDir, const YCHAR * newName)
2428 {
2429         yaffs_Object *obj;
2430         yaffs_Object *existingTarget;
2431         int force = 0;
2432
2433 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
2434         /* Special case for case insemsitive systems (eg. WinCE).
2435          * While look-up is case insensitive, the name isn't.
2436          * Therefore we might want to change x.txt to X.txt
2437         */
2438         if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0) {
2439                 force = 1;
2440         }
2441 #endif
2442
2443         obj = yaffs_FindObjectByName(oldDir, oldName);
2444         /* Check new name to long. */
2445         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK &&
2446             yaffs_strlen(newName) > YAFFS_MAX_ALIAS_LENGTH)
2447           /* ENAMETOOLONG */
2448           return YAFFS_FAIL;
2449         else if (obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK &&
2450                  yaffs_strlen(newName) > YAFFS_MAX_NAME_LENGTH)
2451           /* ENAMETOOLONG */
2452           return YAFFS_FAIL;
2453
2454         if (obj && obj->renameAllowed) {
2455
2456                 /* Now do the handling for an existing target, if there is one */
2457
2458                 existingTarget = yaffs_FindObjectByName(newDir, newName);
2459                 if (existingTarget &&
2460                     existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
2461                     !list_empty(&existingTarget->variant.directoryVariant.children)) {
2462                         /* There is a target that is a non-empty directory, so we fail */
2463                         return YAFFS_FAIL;      /* EEXIST or ENOTEMPTY */
2464                 } else if (existingTarget && existingTarget != obj) {
2465                         /* Nuke the target first, using shadowing, 
2466                          * but only if it isn't the same object
2467                          */
2468                         yaffs_ChangeObjectName(obj, newDir, newName, force,
2469                                                existingTarget->objectId);
2470                         yaffs_UnlinkObject(existingTarget);
2471                 }
2472
2473                 return yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
2474         }
2475         return YAFFS_FAIL;
2476 }
2477
2478 /*------------------------- Block Management and Page Allocation ----------------*/
2479
2480 static int yaffs_InitialiseBlocks(yaffs_Device * dev)
2481 {
2482         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2483         
2484         dev->blockInfo = NULL;
2485         dev->chunkBits = NULL;
2486         
2487         dev->allocationBlock = -1;      /* force it to get a new one */
2488
2489         /* If the first allocation strategy fails, thry the alternate one */
2490         dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
2491         if(!dev->blockInfo){
2492                 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
2493                 dev->blockInfoAlt = 1;
2494         }
2495         else
2496                 dev->blockInfoAlt = 0;
2497                 
2498         if(dev->blockInfo){
2499         
2500                 /* Set up dynamic blockinfo stuff. */
2501                 dev->chunkBitmapStride = (dev->nChunksPerBlock + 7) / 8; /* round up bytes */
2502                 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
2503                 if(!dev->chunkBits){
2504                         dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
2505                         dev->chunkBitsAlt = 1;
2506                 }
2507                 else
2508                         dev->chunkBitsAlt = 0;
2509         }
2510         
2511         if (dev->blockInfo && dev->chunkBits) {
2512                 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
2513                 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
2514                 return YAFFS_OK;
2515         }
2516
2517         return YAFFS_FAIL;
2518
2519 }
2520
2521 static void yaffs_DeinitialiseBlocks(yaffs_Device * dev)
2522 {
2523         if(dev->blockInfoAlt && dev->blockInfo)
2524                 YFREE_ALT(dev->blockInfo);
2525         else if(dev->blockInfo)
2526                 YFREE(dev->blockInfo);
2527
2528         dev->blockInfoAlt = 0;
2529
2530         dev->blockInfo = NULL;
2531         
2532         if(dev->chunkBitsAlt && dev->chunkBits)
2533                 YFREE_ALT(dev->chunkBits);
2534         else if(dev->chunkBits)
2535                 YFREE(dev->chunkBits);
2536         dev->chunkBitsAlt = 0;
2537         dev->chunkBits = NULL;
2538 }
2539
2540 static int yaffs_BlockNotDisqualifiedFromGC(yaffs_Device * dev,
2541                                             yaffs_BlockInfo * bi)
2542 {
2543         int i;
2544         __u32 seq;
2545         yaffs_BlockInfo *b;
2546
2547         if (!dev->isYaffs2)
2548                 return 1;       /* disqualification only applies to yaffs2. */
2549
2550         if (!bi->hasShrinkHeader)
2551                 return 1;       /* can gc */
2552
2553         /* Find the oldest dirty sequence number if we don't know it and save it
2554          * so we don't have to keep recomputing it.
2555          */
2556         if (!dev->oldestDirtySequence) {
2557                 seq = dev->sequenceNumber;
2558
2559                 for (i = dev->internalStartBlock; i <= dev->internalEndBlock;
2560                      i++) {
2561                         b = yaffs_GetBlockInfo(dev, i);
2562                         if (b->blockState == YAFFS_BLOCK_STATE_FULL &&
2563                             (b->pagesInUse - b->softDeletions) <
2564                             dev->nChunksPerBlock && b->sequenceNumber < seq) {
2565                                 seq = b->sequenceNumber;
2566                         }
2567                 }
2568                 dev->oldestDirtySequence = seq;
2569         }
2570
2571         /* Can't do gc of this block if there are any blocks older than this one that have
2572          * discarded pages.
2573          */
2574         return (bi->sequenceNumber <= dev->oldestDirtySequence);
2575
2576 }
2577
2578 /* FindDiretiestBlock is used to select the dirtiest block (or close enough)
2579  * for garbage collection.
2580  */
2581
2582 static int yaffs_FindBlockForGarbageCollection(yaffs_Device * dev,
2583                                                int aggressive)
2584 {
2585
2586         int b = dev->currentDirtyChecker;
2587
2588         int i;
2589         int iterations;
2590         int dirtiest = -1;
2591         int pagesInUse = 0;
2592         int prioritised=0;
2593         yaffs_BlockInfo *bi;
2594         static int nonAggressiveSkip = 0;
2595         int pendingPrioritisedExist = 0;
2596         
2597         /* First let's see if we need to grab a prioritised block */
2598         if(dev->hasPendingPrioritisedGCs){
2599                 for(i = dev->internalStartBlock; i < dev->internalEndBlock && !prioritised; i++){
2600
2601                         bi = yaffs_GetBlockInfo(dev, i);
2602                         //yaffs_VerifyBlock(dev,bi,i);
2603                         
2604                         if(bi->gcPrioritise) {
2605                                 pendingPrioritisedExist = 1;
2606                                 if(bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2607                                    yaffs_BlockNotDisqualifiedFromGC(dev, bi)){
2608                                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
2609                                         dirtiest = i;
2610                                         prioritised = 1;
2611                                         aggressive = 1; /* Fool the non-aggressive skip logiv below */
2612                                 }
2613                         }
2614                 }
2615                 
2616                 if(!pendingPrioritisedExist) /* None found, so we can clear this */
2617                         dev->hasPendingPrioritisedGCs = 0;
2618         }
2619
2620         /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2621          * search harder.
2622          * else (we're doing a leasurely gc), then we only bother to do this if the
2623          * block has only a few pages in use.
2624          */
2625
2626         nonAggressiveSkip--;
2627
2628         if (!aggressive && (nonAggressiveSkip > 0)) {
2629                 return -1;
2630         }
2631
2632         if(!prioritised)
2633                 pagesInUse =
2634                         (aggressive) ? dev->nChunksPerBlock : YAFFS_PASSIVE_GC_CHUNKS + 1;
2635
2636         if (aggressive) {
2637                 iterations =
2638                     dev->internalEndBlock - dev->internalStartBlock + 1;
2639         } else {
2640                 iterations =
2641                     dev->internalEndBlock - dev->internalStartBlock + 1;
2642                 iterations = iterations / 16;
2643                 if (iterations > 200) {
2644                         iterations = 200;
2645                 }
2646         }
2647
2648         for (i = 0; i <= iterations && pagesInUse > 0 && !prioritised; i++) {
2649                 b++;
2650                 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2651                         b = dev->internalStartBlock;
2652                 }
2653
2654                 if (b < dev->internalStartBlock || b > dev->internalEndBlock) {
2655                         T(YAFFS_TRACE_ERROR,
2656                           (TSTR("**>> Block %d is not valid" TENDSTR), b));
2657                         YBUG();
2658                 }
2659
2660                 bi = yaffs_GetBlockInfo(dev, b);
2661
2662 #if 0
2663                 if (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT) {
2664                         dirtiest = b;
2665                         pagesInUse = 0;
2666                 }
2667                 else 
2668 #endif
2669
2670                 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2671                        (bi->pagesInUse - bi->softDeletions) < pagesInUse &&
2672                         yaffs_BlockNotDisqualifiedFromGC(dev, bi)) {
2673                         dirtiest = b;
2674                         pagesInUse = (bi->pagesInUse - bi->softDeletions);
2675                 }
2676         }
2677
2678         dev->currentDirtyChecker = b;
2679
2680         if (dirtiest > 0) {
2681                 T(YAFFS_TRACE_GC,
2682                   (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR), dirtiest,
2683                    dev->nChunksPerBlock - pagesInUse,prioritised));
2684         }
2685
2686         dev->oldestDirtySequence = 0;
2687
2688         if (dirtiest > 0) {
2689                 nonAggressiveSkip = 4;
2690         }
2691
2692         return dirtiest;
2693 }
2694
2695 static void yaffs_BlockBecameDirty(yaffs_Device * dev, int blockNo)
2696 {
2697         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
2698
2699         int erasedOk = 0;
2700
2701         /* If the block is still healthy erase it and mark as clean.
2702          * If the block has had a data failure, then retire it.
2703          */
2704          
2705         T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
2706                 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
2707                 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
2708                 
2709         bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
2710
2711         if (!bi->needsRetiring) {
2712                 yaffs_InvalidateCheckpoint(dev);
2713                 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
2714                 if (!erasedOk) {
2715                         dev->nErasureFailures++;
2716                         T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2717                           (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
2718                 }
2719         }
2720
2721         if (erasedOk && 
2722             ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
2723                 int i;
2724                 for (i = 0; i < dev->nChunksPerBlock; i++) {
2725                         if (!yaffs_CheckChunkErased
2726                             (dev, blockNo * dev->nChunksPerBlock + i)) {
2727                                 T(YAFFS_TRACE_ERROR,
2728                                   (TSTR
2729                                    (">>Block %d erasure supposedly OK, but chunk %d not erased"
2730                                     TENDSTR), blockNo, i));
2731                         }
2732                 }
2733         }
2734
2735         if (erasedOk) {
2736                 /* Clean it up... */
2737                 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
2738                 dev->nErasedBlocks++;
2739                 bi->pagesInUse = 0;
2740                 bi->softDeletions = 0;
2741                 bi->hasShrinkHeader = 0;
2742                 bi->skipErasedCheck = 1;  /* This is clean, so no need to check */
2743                 bi->gcPrioritise = 0;
2744                 yaffs_ClearChunkBits(dev, blockNo);
2745
2746                 T(YAFFS_TRACE_ERASE,
2747                   (TSTR("Erased block %d" TENDSTR), blockNo));
2748         } else {
2749                 dev->nFreeChunks -= dev->nChunksPerBlock;       /* We lost a block of free space */
2750
2751                 yaffs_RetireBlock(dev, blockNo);
2752                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
2753                   (TSTR("**>> Block %d retired" TENDSTR), blockNo));
2754         }
2755 }
2756
2757 static int yaffs_FindBlockForAllocation(yaffs_Device * dev)
2758 {
2759         int i;
2760
2761         yaffs_BlockInfo *bi;
2762
2763         if (dev->nErasedBlocks < 1) {
2764                 /* Hoosterman we've got a problem.
2765                  * Can't get space to gc
2766                  */
2767                 T(YAFFS_TRACE_ERROR,
2768                   (TSTR("yaffs tragedy: no more eraased blocks" TENDSTR)));
2769
2770                 return -1;
2771         }
2772         
2773         /* Find an empty block. */
2774
2775         for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
2776                 dev->allocationBlockFinder++;
2777                 if (dev->allocationBlockFinder < dev->internalStartBlock
2778                     || dev->allocationBlockFinder > dev->internalEndBlock) {
2779                         dev->allocationBlockFinder = dev->internalStartBlock;
2780                 }
2781
2782                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
2783
2784                 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
2785                         bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
2786                         dev->sequenceNumber++;
2787                         bi->sequenceNumber = dev->sequenceNumber;
2788                         dev->nErasedBlocks--;
2789                         T(YAFFS_TRACE_ALLOCATE,
2790                           (TSTR("Allocated block %d, seq  %d, %d left" TENDSTR),
2791                            dev->allocationBlockFinder, dev->sequenceNumber,
2792                            dev->nErasedBlocks));
2793                         return dev->allocationBlockFinder;
2794                 }
2795         }
2796
2797         T(YAFFS_TRACE_ALWAYS,
2798           (TSTR
2799            ("yaffs tragedy: no more eraased blocks, but there should have been %d"
2800             TENDSTR), dev->nErasedBlocks));
2801
2802         return -1;
2803 }
2804
2805
2806 // Check if there's space to allocate...
2807 // Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
2808 static int yaffs_CheckSpaceForAllocation(yaffs_Device * dev)
2809 {
2810         int reservedChunks;
2811         int reservedBlocks = dev->nReservedBlocks;
2812         int checkpointBlocks;
2813         
2814         checkpointBlocks =  dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint;
2815         if(checkpointBlocks < 0)
2816                 checkpointBlocks = 0;
2817         
2818         reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->nChunksPerBlock);
2819         
2820         return (dev->nFreeChunks > reservedChunks);
2821 }
2822
2823 static int yaffs_AllocateChunk(yaffs_Device * dev, int useReserve, yaffs_BlockInfo **blockUsedPtr)
2824 {
2825         int retVal;
2826         yaffs_BlockInfo *bi;
2827
2828         if (dev->allocationBlock < 0) {
2829                 /* Get next block to allocate off */
2830                 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2831                 dev->allocationPage = 0;
2832         }
2833
2834         if (!useReserve && !yaffs_CheckSpaceForAllocation(dev)) {
2835                 /* Not enough space to allocate unless we're allowed to use the reserve. */
2836                 return -1;
2837         }
2838
2839         if (dev->nErasedBlocks < dev->nReservedBlocks
2840             && dev->allocationPage == 0) {
2841                 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2842         }
2843
2844         /* Next page please.... */
2845         if (dev->allocationBlock >= 0) {
2846                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2847
2848                 retVal = (dev->allocationBlock * dev->nChunksPerBlock) +
2849                     dev->allocationPage;
2850                 bi->pagesInUse++;
2851                 yaffs_SetChunkBit(dev, dev->allocationBlock,
2852                                   dev->allocationPage);
2853
2854                 dev->allocationPage++;
2855
2856                 dev->nFreeChunks--;
2857
2858                 /* If the block is full set the state to full */
2859                 if (dev->allocationPage >= dev->nChunksPerBlock) {
2860                         bi->blockState = YAFFS_BLOCK_STATE_FULL;
2861                         dev->allocationBlock = -1;
2862                 }
2863
2864                 if(blockUsedPtr)
2865                         *blockUsedPtr = bi;
2866                         
2867                 return retVal;
2868         }
2869         
2870         T(YAFFS_TRACE_ERROR,
2871           (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2872
2873         return -1;
2874 }
2875
2876 static int yaffs_GetErasedChunks(yaffs_Device * dev)
2877 {
2878         int n;
2879
2880         n = dev->nErasedBlocks * dev->nChunksPerBlock;
2881
2882         if (dev->allocationBlock > 0) {
2883                 n += (dev->nChunksPerBlock - dev->allocationPage);
2884         }
2885
2886         return n;
2887
2888 }
2889
2890 static int yaffs_GarbageCollectBlock(yaffs_Device * dev, int block)
2891 {
2892         int oldChunk;
2893         int newChunk;
2894         int chunkInBlock;
2895         int markNAND;
2896         int retVal = YAFFS_OK;
2897         int cleanups = 0;
2898         int i;
2899         int isCheckpointBlock;
2900         int matchingChunk;
2901
2902         int chunksBefore = yaffs_GetErasedChunks(dev);
2903         int chunksAfter;
2904
2905         yaffs_ExtendedTags tags;
2906
2907         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2908
2909         yaffs_Object *object;
2910
2911         isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2912         
2913         bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2914
2915         T(YAFFS_TRACE_TRACING,
2916           (TSTR("Collecting block %d, in use %d, shrink %d, " TENDSTR), block,
2917            bi->pagesInUse, bi->hasShrinkHeader));
2918
2919         /*yaffs_VerifyFreeChunks(dev); */
2920
2921         bi->hasShrinkHeader = 0;        /* clear the flag so that the block can erase */
2922
2923         /* Take off the number of soft deleted entries because
2924          * they're going to get really deleted during GC.
2925          */
2926         dev->nFreeChunks -= bi->softDeletions;
2927
2928         dev->isDoingGC = 1;
2929
2930         if (isCheckpointBlock ||
2931             !yaffs_StillSomeChunkBits(dev, block)) {
2932                 T(YAFFS_TRACE_TRACING,
2933                   (TSTR
2934                    ("Collecting block %d that has no chunks in use" TENDSTR),
2935                    block));
2936                 yaffs_BlockBecameDirty(dev, block);
2937         } else {
2938
2939                 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2940                 
2941                 yaffs_VerifyBlock(dev,bi,block);
2942
2943                 for (chunkInBlock = 0, oldChunk = block * dev->nChunksPerBlock;
2944                      chunkInBlock < dev->nChunksPerBlock
2945                      && yaffs_StillSomeChunkBits(dev, block);
2946                      chunkInBlock++, oldChunk++) {
2947                         if (yaffs_CheckChunkBit(dev, block, chunkInBlock)) {
2948
2949                                 /* This page is in use and might need to be copied off */
2950
2951                                 markNAND = 1;
2952
2953                                 yaffs_InitialiseTags(&tags);
2954
2955                                 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2956                                                                 buffer, &tags);
2957
2958                                 object =
2959                                     yaffs_FindObjectByNumber(dev,
2960                                                              tags.objectId);
2961
2962                                 T(YAFFS_TRACE_GC_DETAIL,
2963                                   (TSTR
2964                                    ("Collecting page %d, %d %d %d " TENDSTR),
2965                                    chunkInBlock, tags.objectId, tags.chunkId,
2966                                    tags.byteCount));
2967                                    
2968                                 if(object && !yaffs_SkipVerification(dev)){
2969                                         if(tags.chunkId == 0)
2970                                                 matchingChunk = object->chunkId;
2971                                         else if(object->softDeleted)
2972                                                 matchingChunk = oldChunk; /* Defeat the test */
2973                                         else
2974                                                 matchingChunk = yaffs_FindChunkInFile(object,tags.chunkId,NULL);
2975                                         
2976                                         if(oldChunk != matchingChunk)
2977                                                 T(YAFFS_TRACE_ERROR,
2978                                                   (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
2979                                                   oldChunk,matchingChunk,tags.objectId, tags.chunkId));
2980                                                 
2981                                 }
2982
2983                                 if (!object) {
2984                                         T(YAFFS_TRACE_ERROR,
2985                                           (TSTR
2986                                            ("page %d in gc has no object: %d %d %d "
2987                                             TENDSTR), oldChunk,
2988                                             tags.objectId, tags.chunkId, tags.byteCount));
2989                                 }
2990
2991                                 if (object && object->deleted
2992                                     && tags.chunkId != 0) {
2993                                         /* Data chunk in a deleted file, throw it away
2994                                          * It's a soft deleted data chunk,
2995                                          * No need to copy this, just forget about it and 
2996                                          * fix up the object.
2997                                          */
2998
2999                                         object->nDataChunks--;
3000
3001                                         if (object->nDataChunks <= 0) {
3002                                                 /* remeber to clean up the object */
3003                                                 dev->gcCleanupList[cleanups] =
3004                                                     tags.objectId;
3005                                                 cleanups++;
3006                                         }
3007                                         markNAND = 0;
3008                                 } else if (0
3009                                            /* Todo object && object->deleted && object->nDataChunks == 0 */
3010                                            ) {
3011                                         /* Deleted object header with no data chunks.
3012                                          * Can be discarded and the file deleted.
3013                                          */
3014                                         object->chunkId = 0;
3015                                         yaffs_FreeTnode(object->myDev,
3016                                                         object->variant.
3017                                                         fileVariant.top);
3018                                         object->variant.fileVariant.top = NULL;
3019                                         yaffs_DoGenericObjectDeletion(object);
3020
3021                                 } else if (object) {
3022                                         /* It's either a data chunk in a live file or
3023                                          * an ObjectHeader, so we're interested in it.
3024                                          * NB Need to keep the ObjectHeaders of deleted files
3025                                          * until the whole file has been deleted off
3026                                          */
3027                                         tags.serialNumber++;
3028
3029                                         dev->nGCCopies++;
3030
3031                                         if (tags.chunkId == 0) {
3032                                                 /* It is an object Id,
3033                                                  * We need to nuke the shrinkheader flags first
3034                                                  * We no longer want the shrinkHeader flag since its work is done
3035                                                  * and if it is left in place it will mess up scanning.
3036                                                  * Also, clear out any shadowing stuff
3037                                                  */
3038
3039                                                 yaffs_ObjectHeader *oh;
3040                                                 oh = (yaffs_ObjectHeader *)buffer;
3041                                                 oh->isShrink = 0;
3042                                                 oh->shadowsObject = -1;
3043                                                 tags.extraShadows = 0;
3044                                                 tags.extraIsShrinkHeader = 0;
3045                                                 
3046                                                 yaffs_VerifyObjectHeader(object,oh,&tags,1);
3047                                         }
3048
3049                                         newChunk =
3050                                             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
3051
3052                                         if (newChunk < 0) {
3053                                                 retVal = YAFFS_FAIL;
3054                                         } else {
3055
3056                                                 /* Ok, now fix up the Tnodes etc. */
3057
3058                                                 if (tags.chunkId == 0) {
3059                                                         /* It's a header */
3060                                                         object->chunkId =  newChunk;
3061                                                         object->serial =   tags.serialNumber;
3062                                                 } else {
3063                                                         /* It's a data chunk */
3064                                                         yaffs_PutChunkIntoFile
3065                                                             (object,
3066                                                              tags.chunkId,
3067                                                              newChunk, 0);
3068                                                 }
3069                                         }
3070                                 }
3071
3072                                 yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
3073
3074                         }
3075                 }
3076
3077                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3078
3079
3080                 /* Do any required cleanups */
3081                 for (i = 0; i < cleanups; i++) {
3082                         /* Time to delete the file too */
3083                         object =
3084                             yaffs_FindObjectByNumber(dev,
3085                                                      dev->gcCleanupList[i]);
3086                         if (object) {
3087                                 yaffs_FreeTnode(dev,
3088                                                 object->variant.fileVariant.
3089                                                 top);
3090                                 object->variant.fileVariant.top = NULL;
3091                                 T(YAFFS_TRACE_GC,
3092                                   (TSTR
3093                                    ("yaffs: About to finally delete object %d"
3094                                     TENDSTR), object->objectId));
3095                                 yaffs_DoGenericObjectDeletion(object);
3096                                 object->myDev->nDeletedFiles--;
3097                         }
3098
3099                 }
3100
3101         }
3102
3103         yaffs_VerifyCollectedBlock(dev,bi,block);
3104           
3105         if (chunksBefore >= (chunksAfter = yaffs_GetErasedChunks(dev))) {
3106                 T(YAFFS_TRACE_GC,
3107                   (TSTR
3108                    ("gc did not increase free chunks before %d after %d"
3109                     TENDSTR), chunksBefore, chunksAfter));
3110         }
3111
3112         dev->isDoingGC = 0;
3113
3114         return YAFFS_OK;
3115 }
3116
3117 /* New garbage collector
3118  * If we're very low on erased blocks then we do aggressive garbage collection
3119  * otherwise we do "leasurely" garbage collection.
3120  * Aggressive gc looks further (whole array) and will accept less dirty blocks.
3121  * Passive gc only inspects smaller areas and will only accept more dirty blocks.
3122  *
3123  * The idea is to help clear out space in a more spread-out manner.
3124  * Dunno if it really does anything useful.
3125  */
3126 static int yaffs_CheckGarbageCollection(yaffs_Device * dev)
3127 {
3128         int block;
3129         int aggressive;
3130         int gcOk = YAFFS_OK;
3131         int maxTries = 0;
3132         
3133         int checkpointBlockAdjust;
3134
3135         if (dev->isDoingGC) {
3136                 /* Bail out so we don't get recursive gc */
3137                 return YAFFS_OK;
3138         }
3139         
3140         /* This loop should pass the first time.
3141          * We'll only see looping here if the erase of the collected block fails.
3142          */
3143
3144         do {
3145                 maxTries++;
3146                 
3147                 checkpointBlockAdjust = (dev->nCheckpointReservedBlocks - dev->blocksInCheckpoint);
3148                 if(checkpointBlockAdjust < 0)
3149                         checkpointBlockAdjust = 0;
3150
3151                 if (dev->nErasedBlocks < (dev->nReservedBlocks + checkpointBlockAdjust + 2)) {
3152                         /* We need a block soon...*/
3153                         aggressive = 1;
3154                 } else {
3155                         /* We're in no hurry */
3156                         aggressive = 0;
3157                 }
3158
3159                 block = yaffs_FindBlockForGarbageCollection(dev, aggressive);
3160
3161                 if (block > 0) {
3162                         dev->garbageCollections++;
3163                         if (!aggressive) {
3164                                 dev->passiveGarbageCollections++;
3165                         }
3166
3167                         T(YAFFS_TRACE_GC,
3168                           (TSTR
3169                            ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
3170                            dev->nErasedBlocks, aggressive));
3171
3172                         gcOk = yaffs_GarbageCollectBlock(dev, block);
3173                 }
3174
3175                 if (dev->nErasedBlocks < (dev->nReservedBlocks) && block > 0) {
3176                         T(YAFFS_TRACE_GC,
3177                           (TSTR
3178                            ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
3179                             TENDSTR), dev->nErasedBlocks, maxTries, block));
3180                 }
3181         } while ((dev->nErasedBlocks < dev->nReservedBlocks) && (block > 0)
3182                  && (maxTries < 2));
3183
3184         return aggressive ? gcOk : YAFFS_OK;
3185 }
3186
3187 /*-------------------------  TAGS --------------------------------*/
3188
3189 static int yaffs_TagsMatch(const yaffs_ExtendedTags * tags, int objectId,
3190                            int chunkInObject)
3191 {
3192         return (tags->chunkId == chunkInObject &&
3193                 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
3194
3195 }
3196
3197
3198 /*-------------------- Data file manipulation -----------------*/
3199
3200 static int yaffs_FindChunkInFile(yaffs_Object * in, int chunkInInode,
3201                                  yaffs_ExtendedTags * tags)
3202 {
3203         /*Get the Tnode, then get the level 0 offset chunk offset */
3204         yaffs_Tnode *tn;
3205         int theChunk = -1;
3206         yaffs_ExtendedTags localTags;
3207         int retVal = -1;
3208
3209         yaffs_Device *dev = in->myDev;
3210
3211         if (!tags) {
3212                 /* Passed a NULL, so use our own tags space */
3213                 tags = &localTags;
3214         }
3215
3216         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3217
3218         if (tn) {
3219                 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3220
3221                 retVal =
3222                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3223                                            chunkInInode);
3224         }
3225         return retVal;
3226 }
3227
3228 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object * in, int chunkInInode,
3229                                           yaffs_ExtendedTags * tags)
3230 {
3231         /* Get the Tnode, then get the level 0 offset chunk offset */
3232         yaffs_Tnode *tn;
3233         int theChunk = -1;
3234         yaffs_ExtendedTags localTags;
3235
3236         yaffs_Device *dev = in->myDev;
3237         int retVal = -1;
3238
3239         if (!tags) {
3240                 /* Passed a NULL, so use our own tags space */
3241                 tags = &localTags;
3242         }
3243
3244         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
3245
3246         if (tn) {
3247
3248                 theChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3249
3250                 retVal =
3251                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
3252                                            chunkInInode);
3253
3254                 /* Delete the entry in the filestructure (if found) */
3255                 if (retVal != -1) {
3256                         yaffs_PutLevel0Tnode(dev,tn,chunkInInode,0);
3257                 }
3258         } else {
3259                 /*T(("No level 0 found for %d\n", chunkInInode)); */
3260         }
3261
3262         if (retVal == -1) {
3263                 /* T(("Could not find %d to delete\n",chunkInInode)); */
3264         }
3265         return retVal;
3266 }
3267
3268 #ifdef YAFFS_PARANOID
3269
3270 static int yaffs_CheckFileSanity(yaffs_Object * in)
3271 {
3272         int chunk;
3273         int nChunks;
3274         int fSize;
3275         int failed = 0;
3276         int objId;
3277         yaffs_Tnode *tn;
3278         yaffs_Tags localTags;
3279         yaffs_Tags *tags = &localTags;
3280         int theChunk;
3281         int chunkDeleted;
3282
3283         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3284                 /* T(("Object not a file\n")); */
3285                 return YAFFS_FAIL;
3286         }
3287
3288         objId = in->objectId;
3289         fSize = in->variant.fileVariant.fileSize;
3290         nChunks =
3291             (fSize + in->myDev->nDataBytesPerChunk - 1) / in->myDev->nDataBytesPerChunk;
3292
3293         for (chunk = 1; chunk <= nChunks; chunk++) {
3294                 tn = yaffs_FindLevel0Tnode(in->myDev, &in->variant.fileVariant,
3295                                            chunk);
3296
3297                 if (tn) {
3298
3299                         theChunk = yaffs_GetChunkGroupBase(dev,tn,chunk);
3300
3301                         if (yaffs_CheckChunkBits
3302                             (dev, theChunk / dev->nChunksPerBlock,
3303                              theChunk % dev->nChunksPerBlock)) {
3304
3305                                 yaffs_ReadChunkTagsFromNAND(in->myDev, theChunk,
3306                                                             tags,
3307                                                             &chunkDeleted);
3308                                 if (yaffs_TagsMatch
3309                                     (tags, in->objectId, chunk, chunkDeleted)) {
3310                                         /* found it; */
3311
3312                                 }
3313                         } else {
3314
3315                                 failed = 1;
3316                         }
3317
3318                 } else {
3319                         /* T(("No level 0 found for %d\n", chunk)); */
3320                 }
3321         }
3322
3323         return failed ? YAFFS_FAIL : YAFFS_OK;
3324 }
3325
3326 #endif
3327
3328 static int yaffs_PutChunkIntoFile(yaffs_Object * in, int chunkInInode,
3329                                   int chunkInNAND, int inScan)
3330 {
3331         /* NB inScan is zero unless scanning. 
3332          * For forward scanning, inScan is > 0; 
3333          * for backward scanning inScan is < 0
3334          */
3335          
3336         yaffs_Tnode *tn;
3337         yaffs_Device *dev = in->myDev;
3338         int existingChunk;
3339         yaffs_ExtendedTags existingTags;
3340         yaffs_ExtendedTags newTags;
3341         unsigned existingSerial, newSerial;
3342
3343         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
3344                 /* Just ignore an attempt at putting a chunk into a non-file during scanning
3345                  * If it is not during Scanning then something went wrong!
3346                  */
3347                 if (!inScan) {
3348                         T(YAFFS_TRACE_ERROR,
3349                           (TSTR
3350                            ("yaffs tragedy:attempt to put data chunk into a non-file"
3351                             TENDSTR)));
3352                         YBUG();
3353                 }
3354
3355                 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
3356                 return YAFFS_OK;
3357         }
3358
3359         tn = yaffs_AddOrFindLevel0Tnode(dev, 
3360                                         &in->variant.fileVariant,
3361                                         chunkInInode,
3362                                         NULL);
3363         if (!tn) {
3364                 return YAFFS_FAIL;
3365         }
3366
3367         existingChunk = yaffs_GetChunkGroupBase(dev,tn,chunkInInode);
3368
3369         if (inScan != 0) {
3370                 /* If we're scanning then we need to test for duplicates
3371                  * NB This does not need to be efficient since it should only ever 
3372                  * happen when the power fails during a write, then only one
3373                  * chunk should ever be affected.
3374                  *
3375                  * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
3376                  * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
3377                  */
3378
3379                 if (existingChunk != 0) {
3380                         /* NB Right now existing chunk will not be real chunkId if the device >= 32MB
3381                          *    thus we have to do a FindChunkInFile to get the real chunk id.
3382                          *
3383                          * We have a duplicate now we need to decide which one to use:
3384                          *
3385                          * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
3386                          * Forward scanning YAFFS2: The new one is what we use, dump the old one.
3387                          * YAFFS1: Get both sets of tags and compare serial numbers.
3388                          */
3389
3390                         if (inScan > 0) {
3391                                 /* Only do this for forward scanning */
3392                                 yaffs_ReadChunkWithTagsFromNAND(dev,
3393                                                                 chunkInNAND,
3394                                                                 NULL, &newTags);
3395
3396                                 /* Do a proper find */
3397                                 existingChunk =
3398                                     yaffs_FindChunkInFile(in, chunkInInode,
3399                                                           &existingTags);
3400                         }
3401
3402                         if (existingChunk <= 0) {
3403                                 /*Hoosterman - how did this happen? */
3404
3405                                 T(YAFFS_TRACE_ERROR,
3406                                   (TSTR
3407                                    ("yaffs tragedy: existing chunk < 0 in scan"
3408                                     TENDSTR)));
3409
3410                         }
3411
3412                         /* NB The deleted flags should be false, otherwise the chunks will 
3413                          * not be loaded during a scan
3414                          */
3415
3416                         newSerial = newTags.serialNumber;
3417                         existingSerial = existingTags.serialNumber;
3418
3419                         if ((inScan > 0) &&
3420                             (in->myDev->isYaffs2 ||
3421                              existingChunk <= 0 ||
3422                              ((existingSerial + 1) & 3) == newSerial)) {
3423                                 /* Forward scanning.                            
3424                                  * Use new
3425                                  * Delete the old one and drop through to update the tnode
3426                                  */
3427                                 yaffs_DeleteChunk(dev, existingChunk, 1,
3428                                                   __LINE__);
3429                         } else {
3430                                 /* Backward scanning or we want to use the existing one
3431                                  * Use existing.
3432                                  * Delete the new one and return early so that the tnode isn't changed
3433                                  */
3434                                 yaffs_DeleteChunk(dev, chunkInNAND, 1,
3435                                                   __LINE__);
3436                                 return YAFFS_OK;
3437                         }
3438                 }
3439
3440         }
3441
3442         if (existingChunk == 0) {
3443                 in->nDataChunks++;
3444         }
3445
3446         yaffs_PutLevel0Tnode(dev,tn,chunkInInode,chunkInNAND);
3447
3448         return YAFFS_OK;
3449 }
3450
3451 static int yaffs_ReadChunkDataFromObject(yaffs_Object * in, int chunkInInode,
3452                                          __u8 * buffer)
3453 {
3454         int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
3455
3456         if (chunkInNAND >= 0) {
3457                 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
3458                                                        buffer,NULL);
3459         } else {
3460                 T(YAFFS_TRACE_NANDACCESS,
3461                   (TSTR("Chunk %d not found zero instead" TENDSTR),
3462                    chunkInNAND));
3463                 /* get sane (zero) data if you read a hole */
3464                 memset(buffer, 0, in->myDev->nDataBytesPerChunk);       
3465                 return 0;
3466         }
3467
3468 }
3469
3470 void yaffs_DeleteChunk(yaffs_Device * dev, int chunkId, int markNAND, int lyn)
3471 {
3472         int block;
3473         int page;
3474         yaffs_ExtendedTags tags;
3475         yaffs_BlockInfo *bi;
3476
3477         if (chunkId <= 0)
3478                 return;
3479                 
3480
3481         dev->nDeletions++;
3482         block = chunkId / dev->nChunksPerBlock;
3483         page = chunkId % dev->nChunksPerBlock;
3484
3485
3486         if(!yaffs_CheckChunkBit(dev,block,page))
3487                 T(YAFFS_TRACE_VERIFY,
3488                         (TSTR("Deleting invalid chunk %d"TENDSTR),
3489                          chunkId));
3490
3491         bi = yaffs_GetBlockInfo(dev, block);
3492
3493         T(YAFFS_TRACE_DELETION,
3494           (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
3495
3496         if (markNAND &&
3497             bi->blockState != YAFFS_BLOCK_STATE_COLLECTING && !dev->isYaffs2) {
3498
3499                 yaffs_InitialiseTags(&tags);
3500
3501                 tags.chunkDeleted = 1;
3502
3503                 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
3504                 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
3505         } else {
3506                 dev->nUnmarkedDeletions++;
3507         }
3508
3509         /* Pull out of the management area.
3510          * If the whole block became dirty, this will kick off an erasure.
3511          */
3512         if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
3513             bi->blockState == YAFFS_BLOCK_STATE_FULL ||
3514             bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
3515             bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
3516                 dev->nFreeChunks++;
3517
3518                 yaffs_ClearChunkBit(dev, block, page);
3519
3520                 bi->pagesInUse--;
3521
3522                 if (bi->pagesInUse == 0 &&
3523                     !bi->hasShrinkHeader &&
3524                     bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
3525                     bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
3526                         yaffs_BlockBecameDirty(dev, block);
3527                 }
3528
3529         } else {
3530                 /* T(("Bad news deleting chunk %d\n",chunkId)); */
3531         }
3532
3533 }
3534
3535 static int yaffs_WriteChunkDataToObject(yaffs_Object * in, int chunkInInode,
3536                                         const __u8 * buffer, int nBytes,
3537                                         int useReserve)
3538 {
3539         /* Find old chunk Need to do this to get serial number
3540          * Write new one and patch into tree.
3541          * Invalidate old tags.
3542          */
3543
3544         int prevChunkId;
3545         yaffs_ExtendedTags prevTags;
3546
3547         int newChunkId;
3548         yaffs_ExtendedTags newTags;
3549
3550         yaffs_Device *dev = in->myDev;
3551
3552         yaffs_CheckGarbageCollection(dev);
3553
3554         /* Get the previous chunk at this location in the file if it exists */
3555         prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
3556
3557         /* Set up new tags */
3558         yaffs_InitialiseTags(&newTags);
3559
3560         newTags.chunkId = chunkInInode;
3561         newTags.objectId = in->objectId;
3562         newTags.serialNumber =
3563             (prevChunkId >= 0) ? prevTags.serialNumber + 1 : 1;
3564         newTags.byteCount = nBytes;
3565
3566         newChunkId =
3567             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3568                                               useReserve);
3569
3570         if (newChunkId >= 0) {
3571                 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
3572
3573                 if (prevChunkId >= 0) {
3574                         yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
3575
3576                 }
3577
3578                 yaffs_CheckFileSanity(in);
3579         }
3580         return newChunkId;
3581
3582 }
3583
3584 /* UpdateObjectHeader updates the header on NAND for an object.
3585  * If name is not NULL, then that new name is used.
3586  */
3587 int yaffs_UpdateObjectHeader(yaffs_Object * in, const YCHAR * name, int force,
3588                              int isShrink, int shadows)
3589 {
3590
3591         yaffs_BlockInfo *bi;
3592
3593         yaffs_Device *dev = in->myDev;
3594
3595         int prevChunkId;
3596         int retVal = 0;
3597         int result = 0;
3598
3599         int newChunkId;
3600         yaffs_ExtendedTags newTags;
3601         yaffs_ExtendedTags oldTags;
3602
3603         __u8 *buffer = NULL;
3604         YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3605
3606         yaffs_ObjectHeader *oh = NULL;
3607         
3608         yaffs_strcpy(oldName,"silly old name");
3609
3610         if (!in->fake || force) {
3611
3612                 yaffs_CheckGarbageCollection(dev);
3613                 yaffs_CheckObjectDetailsLoaded(in);
3614
3615                 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3616                 oh = (yaffs_ObjectHeader *) buffer;
3617
3618                 prevChunkId = in->chunkId;
3619
3620                 if (prevChunkId >= 0) {
3621                         result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3622                                                         buffer, &oldTags);
3623                         
3624                         yaffs_VerifyObjectHeader(in,oh,&oldTags,0);
3625                                                                                 
3626                         memcpy(oldName, oh->name, sizeof(oh->name));
3627                 }
3628
3629                 memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3630
3631                 oh->type = in->variantType;
3632                 oh->yst_mode = in->yst_mode;
3633                 oh->shadowsObject = shadows;
3634
3635 #ifdef CONFIG_YAFFS_WINCE
3636                 oh->win_atime[0] = in->win_atime[0];
3637                 oh->win_ctime[0] = in->win_ctime[0];
3638                 oh->win_mtime[0] = in->win_mtime[0];
3639                 oh->win_atime[1] = in->win_atime[1];
3640                 oh->win_ctime[1] = in->win_ctime[1];
3641                 oh->win_mtime[1] = in->win_mtime[1];
3642 #else
3643                 oh->yst_uid = in->yst_uid;
3644                 oh->yst_gid = in->yst_gid;
3645                 oh->yst_atime = in->yst_atime;
3646                 oh->yst_mtime = in->yst_mtime;
3647                 oh->yst_ctime = in->yst_ctime;
3648                 oh->yst_rdev = in->yst_rdev;
3649 #endif
3650                 if (in->parent) {
3651                         oh->parentObjectId = in->parent->objectId;
3652                 } else {
3653                         oh->parentObjectId = 0;
3654                 }
3655
3656                 if (name && *name) {
3657                         memset(oh->name, 0, sizeof(oh->name));
3658                         yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3659                 } else if (prevChunkId>=0) {
3660                         memcpy(oh->name, oldName, sizeof(oh->name));
3661                 } else {
3662                         memset(oh->name, 0, sizeof(oh->name));
3663                 }
3664
3665                 oh->isShrink = isShrink;
3666
3667                 switch (in->variantType) {
3668                 case YAFFS_OBJECT_TYPE_UNKNOWN:
3669                         /* Should not happen */
3670                         break;
3671                 case YAFFS_OBJECT_TYPE_FILE:
3672                         oh->fileSize =
3673                             (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3674                              || oh->parentObjectId ==
3675                              YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3676                             fileVariant.fileSize;
3677                         break;
3678                 case YAFFS_OBJECT_TYPE_HARDLINK:
3679                         oh->equivalentObjectId =
3680                             in->variant.hardLinkVariant.equivalentObjectId;
3681                         break;
3682                 case YAFFS_OBJECT_TYPE_SPECIAL:
3683                         /* Do nothing */
3684                         break;
3685                 case YAFFS_OBJECT_TYPE_DIRECTORY:
3686                         /* Do nothing */
3687                         break;
3688                 case YAFFS_OBJECT_TYPE_SYMLINK:
3689                         yaffs_strncpy(oh->alias,
3690                                       in->variant.symLinkVariant.alias,
3691                                       YAFFS_MAX_ALIAS_LENGTH);
3692                         oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3693                         break;
3694                 }
3695
3696                 /* Tags */
3697                 yaffs_InitialiseTags(&newTags);
3698                 in->serial++;
3699                 newTags.chunkId = 0;
3700                 newTags.objectId = in->objectId;
3701                 newTags.serialNumber = in->serial;
3702
3703                 /* Add extra info for file header */
3704
3705                 newTags.extraHeaderInfoAvailable = 1;
3706                 newTags.extraParentObjectId = oh->parentObjectId;
3707                 newTags.extraFileLength = oh->fileSize;
3708                 newTags.extraIsShrinkHeader = oh->isShrink;
3709                 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3710                 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3711                 newTags.extraObjectType = in->variantType;
3712
3713                 yaffs_VerifyObjectHeader(in,oh,&newTags,1);
3714
3715                 /* Create new chunk in NAND */
3716                 newChunkId =
3717                     yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3718                                                       (prevChunkId >= 0) ? 1 : 0);
3719
3720                 if (newChunkId >= 0) {
3721
3722                         in->chunkId = newChunkId;
3723
3724                         if (prevChunkId >= 0) {
3725                                 yaffs_DeleteChunk(dev, prevChunkId, 1,
3726                                                   __LINE__);
3727                         }
3728
3729                         if(!yaffs_ObjectHasCachedWriteData(in))
3730                                 in->dirty = 0;
3731
3732                         /* If this was a shrink, then mark the block that the chunk lives on */
3733                         if (isShrink) {
3734                                 bi = yaffs_GetBlockInfo(in->myDev,
3735                                                         newChunkId /in->myDev-> nChunksPerBlock);
3736                                 bi->hasShrinkHeader = 1;
3737                         }
3738
3739                 }
3740
3741                 retVal = newChunkId;
3742
3743         }
3744
3745         if (buffer)
3746                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3747
3748         return retVal;
3749 }
3750
3751 /*------------------------ Short Operations Cache ----------------------------------------
3752  *   In many situations where there is no high level buffering (eg WinCE) a lot of
3753  *   reads might be short sequential reads, and a lot of writes may be short 
3754  *   sequential writes. eg. scanning/writing a jpeg file.
3755  *   In these cases, a short read/write cache can provide a huge perfomance benefit 
3756  *   with dumb-as-a-rock code.
3757  *   In Linux, the page cache provides read buffering aand the short op cache provides write 
3758  *   buffering.
3759  *
3760  *   There are a limited number (~10) of cache chunks per device so that we don't
3761  *   need a very intelligent search.
3762  */
3763
3764 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3765 {
3766         yaffs_Device *dev = obj->myDev;
3767         int i;
3768         yaffs_ChunkCache *cache;
3769         int nCaches = obj->myDev->nShortOpCaches;
3770         
3771         for(i = 0; i < nCaches; i++){
3772                 cache = &dev->srCache[i];
3773                 if (cache->object == obj &&
3774                     cache->dirty)
3775                         return 1;
3776         }
3777         
3778         return 0;
3779 }
3780
3781
3782 static void yaffs_FlushFilesChunkCache(yaffs_Object * obj)
3783 {
3784         yaffs_Device *dev = obj->myDev;
3785         int lowest = -99;       /* Stop compiler whining. */
3786         int i;
3787         yaffs_ChunkCache *cache;
3788         int chunkWritten = 0;
3789         int nCaches = obj->myDev->nShortOpCaches;
3790
3791         if (nCaches > 0) {
3792                 do {
3793                         cache = NULL;
3794
3795                         /* Find the dirty cache for this object with the lowest chunk id. */
3796                         for (i = 0; i < nCaches; i++) {
3797                                 if (dev->srCache[i].object == obj &&
3798                                     dev->srCache[i].dirty) {
3799                                         if (!cache
3800                                             || dev->srCache[i].chunkId <
3801                                             lowest) {
3802                                                 cache = &dev->srCache[i];
3803                                                 lowest = cache->chunkId;
3804                                         }
3805                                 }
3806                         }
3807
3808                         if (cache && !cache->locked) {
3809                                 /* Write it out and free it up */
3810
3811                                 chunkWritten =
3812                                     yaffs_WriteChunkDataToObject(cache->object,
3813                                                                  cache->chunkId,
3814                                                                  cache->data,
3815                                                                  cache->nBytes,
3816                                                                  1);
3817                                 cache->dirty = 0;
3818                                 cache->object = NULL;
3819                         }
3820
3821                 } while (cache && chunkWritten > 0);
3822
3823                 if (cache) {
3824                         /* Hoosterman, disk full while writing cache out. */
3825                         T(YAFFS_TRACE_ERROR,
3826                           (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3827
3828                 }
3829         }
3830
3831 }
3832
3833 /*yaffs_FlushEntireDeviceCache(dev)
3834  *
3835  *
3836  */
3837
3838 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3839 {
3840         yaffs_Object *obj;
3841         int nCaches = dev->nShortOpCaches;
3842         int i;
3843         
3844         /* Find a dirty object in the cache and flush it...
3845          * until there are no further dirty objects.
3846          */
3847         do {
3848                 obj = NULL;
3849                 for( i = 0; i < nCaches && !obj; i++) {
3850                         if (dev->srCache[i].object &&
3851                             dev->srCache[i].dirty)
3852                                 obj = dev->srCache[i].object;
3853                             
3854                 }
3855                 if(obj)
3856                         yaffs_FlushFilesChunkCache(obj);
3857                         
3858         } while(obj);
3859         
3860 }
3861
3862
3863 /* Grab us a cache chunk for use.
3864  * First look for an empty one. 
3865  * Then look for the least recently used non-dirty one.
3866  * Then look for the least recently used dirty one...., flush and look again.
3867  */