a8b850a71711dda636dc3dd330f5576f0d9c6f2b
[yaffs2.git] / yaffs_guts.c
1 /*
2  * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
3  *
4  * Copyright (C) 2002-2010 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 #include "yportenv.h"
14 #include "yaffs_trace.h"
15
16 #include "yaffsinterface.h"
17 #include "yaffs_guts.h"
18 #include "yaffs_tagsvalidity.h"
19 #include "yaffs_getblockinfo.h"
20
21 #include "yaffs_tagscompat.h"
22
23 #include "yaffs_nand.h"
24
25 #include "yaffs_yaffs1.h"
26 #include "yaffs_yaffs2.h"
27 #include "yaffs_bitmap.h"
28 #include "yaffs_verify.h"
29
30 #include "yaffs_nand.h"
31 #include "yaffs_packedtags2.h"
32
33 #include "yaffs_nameval.h"
34 #include "yaffs_allocator.h"
35
36 /* Note YAFFS_GC_GOOD_ENOUGH must be <= YAFFS_GC_PASSIVE_THRESHOLD */
37 #define YAFFS_GC_GOOD_ENOUGH 2
38 #define YAFFS_GC_PASSIVE_THRESHOLD 4
39
40 #include "yaffs_ecc.h"
41
42
43
44 /* Robustification (if it ever comes about...) */
45 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND);
46 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
47                 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 void yaffs_UpdateParent(yaffs_Object *obj);
56 static int yaffs_UnlinkObject(yaffs_Object *obj);
57 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj);
58
59 static int yaffs_WriteNewChunkWithTagsToNAND(yaffs_Device *dev,
60                                         const __u8 *buffer,
61                                         yaffs_ExtendedTags *tags,
62                                         int useReserve);
63
64
65 static yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
66                                         yaffs_ObjectType type);
67
68
69 static int yaffs_ApplyXMod(yaffs_Device *dev, char *buffer, yaffs_XAttrMod *xmod);
70
71 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj);
72 static int yaffs_CheckStructures(void);
73 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in);
74
75 static yaffs_BlockInfo *yaffs_GetBlockInfo(yaffs_Device *dev, int blockNo);
76
77
78 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
79                                 int chunkInNAND);
80
81 static int yaffs_UnlinkWorker(yaffs_Object *obj);
82
83 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
84                         int chunkInObject);
85
86 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
87                                 yaffs_BlockInfo **blockUsedPtr);
88
89 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in);
90
91 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in);
92 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId);
93
94 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
95                                 yaffs_ExtendedTags *tags);
96
97 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
98                                         int chunkInNAND,
99                                         const __u8 *data,
100                                         yaffs_ExtendedTags *tags);
101
102 /* Function to calculate chunk and offset */
103
104 static void yaffs_AddrToChunk(yaffs_Device *dev, loff_t addr, int *chunkOut,
105                 __u32 *offsetOut)
106 {
107         int chunk;
108         __u32 offset;
109
110         chunk  = (__u32)(addr >> dev->chunkShift);
111
112         if (dev->chunkDiv == 1) {
113                 /* easy power of 2 case */
114                 offset = (__u32)(addr & dev->chunkMask);
115         } else {
116                 /* Non power-of-2 case */
117
118                 loff_t chunkBase;
119
120                 chunk /= dev->chunkDiv;
121
122                 chunkBase = ((loff_t)chunk) * dev->nDataBytesPerChunk;
123                 offset = (__u32)(addr - chunkBase);
124         }
125
126         *chunkOut = chunk;
127         *offsetOut = offset;
128 }
129
130 /* Function to return the number of shifts for a power of 2 greater than or
131  * equal to the given number
132  * Note we don't try to cater for all possible numbers and this does not have to
133  * be hellishly efficient.
134  */
135
136 static __u32 ShiftsGE(__u32 x)
137 {
138         int extraBits;
139         int nShifts;
140
141         nShifts = extraBits = 0;
142
143         while (x > 1) {
144                 if (x & 1)
145                         extraBits++;
146                 x >>= 1;
147                 nShifts++;
148         }
149
150         if (extraBits)
151                 nShifts++;
152
153         return nShifts;
154 }
155
156 /* Function to return the number of shifts to get a 1 in bit 0
157  */
158
159 static __u32 Shifts(__u32 x)
160 {
161         __u32 nShifts;
162
163         nShifts =  0;
164
165         if (!x)
166                 return 0;
167
168         while (!(x&1)) {
169                 x >>= 1;
170                 nShifts++;
171         }
172
173         return nShifts;
174 }
175
176
177
178 /*
179  * Temporary buffer manipulations.
180  */
181
182 static int yaffs_InitialiseTempBuffers(yaffs_Device *dev)
183 {
184         int i;
185         __u8 *buf = (__u8 *)1;
186
187         memset(dev->tempBuffer, 0, sizeof(dev->tempBuffer));
188
189         for (i = 0; buf && i < YAFFS_N_TEMP_BUFFERS; i++) {
190                 dev->tempBuffer[i].line = 0;    /* not in use */
191                 dev->tempBuffer[i].buffer = buf =
192                     YMALLOC_DMA(dev->param.totalBytesPerChunk);
193         }
194
195         return buf ? YAFFS_OK : YAFFS_FAIL;
196 }
197
198 __u8 *yaffs_GetTempBuffer(yaffs_Device *dev, int lineNo)
199 {
200         int i, j;
201
202         dev->tempInUse++;
203         if (dev->tempInUse > dev->maxTemp)
204                 dev->maxTemp = dev->tempInUse;
205
206         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
207                 if (dev->tempBuffer[i].line == 0) {
208                         dev->tempBuffer[i].line = lineNo;
209                         if ((i + 1) > dev->maxTemp) {
210                                 dev->maxTemp = i + 1;
211                                 for (j = 0; j <= i; j++)
212                                         dev->tempBuffer[j].maxLine =
213                                             dev->tempBuffer[j].line;
214                         }
215
216                         return dev->tempBuffer[i].buffer;
217                 }
218         }
219
220         T(YAFFS_TRACE_BUFFERS,
221           (TSTR("Out of temp buffers at line %d, other held by lines:"),
222            lineNo));
223         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
224                 T(YAFFS_TRACE_BUFFERS, (TSTR(" %d "), dev->tempBuffer[i].line));
225
226         T(YAFFS_TRACE_BUFFERS, (TSTR(" " TENDSTR)));
227
228         /*
229          * If we got here then we have to allocate an unmanaged one
230          * This is not good.
231          */
232
233         dev->unmanagedTempAllocations++;
234         return YMALLOC(dev->nDataBytesPerChunk);
235
236 }
237
238 void yaffs_ReleaseTempBuffer(yaffs_Device *dev, __u8 *buffer,
239                                     int lineNo)
240 {
241         int i;
242
243         dev->tempInUse--;
244
245         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
246                 if (dev->tempBuffer[i].buffer == buffer) {
247                         dev->tempBuffer[i].line = 0;
248                         return;
249                 }
250         }
251
252         if (buffer) {
253                 /* assume it is an unmanaged one. */
254                 T(YAFFS_TRACE_BUFFERS,
255                   (TSTR("Releasing unmanaged temp buffer in line %d" TENDSTR),
256                    lineNo));
257                 YFREE(buffer);
258                 dev->unmanagedTempDeallocations++;
259         }
260
261 }
262
263 /*
264  * Determine if we have a managed buffer.
265  */
266 int yaffs_IsManagedTempBuffer(yaffs_Device *dev, const __u8 *buffer)
267 {
268         int i;
269
270         for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++) {
271                 if (dev->tempBuffer[i].buffer == buffer)
272                         return 1;
273         }
274
275         for (i = 0; i < dev->param.nShortOpCaches; i++) {
276                 if (dev->srCache[i].data == buffer)
277                         return 1;
278         }
279
280         if (buffer == dev->checkpointBuffer)
281                 return 1;
282
283         T(YAFFS_TRACE_ALWAYS,
284                 (TSTR("yaffs: unmaged buffer detected.\n" TENDSTR)));
285         return 0;
286 }
287
288 /*
289  * Verification code
290  */
291
292
293
294
295 /*
296  *  Simple hash function. Needs to have a reasonable spread
297  */
298
299 static Y_INLINE int yaffs_HashFunction(int n)
300 {
301         n = abs(n);
302         return n % YAFFS_NOBJECT_BUCKETS;
303 }
304
305 /*
306  * Access functions to useful fake objects.
307  * Note that root might have a presence in NAND if permissions are set.
308  */
309
310 yaffs_Object *yaffs_Root(yaffs_Device *dev)
311 {
312         return dev->rootDir;
313 }
314
315 yaffs_Object *yaffs_LostNFound(yaffs_Device *dev)
316 {
317         return dev->lostNFoundDir;
318 }
319
320
321 /*
322  *  Erased NAND checking functions
323  */
324
325 int yaffs_CheckFF(__u8 *buffer, int nBytes)
326 {
327         /* Horrible, slow implementation */
328         while (nBytes--) {
329                 if (*buffer != 0xFF)
330                         return 0;
331                 buffer++;
332         }
333         return 1;
334 }
335
336 static int yaffs_CheckChunkErased(struct yaffs_DeviceStruct *dev,
337                                 int chunkInNAND)
338 {
339         int retval = YAFFS_OK;
340         __u8 *data = yaffs_GetTempBuffer(dev, __LINE__);
341         yaffs_ExtendedTags tags;
342         int result;
343
344         result = yaffs_ReadChunkWithTagsFromNAND(dev, chunkInNAND, data, &tags);
345
346         if (tags.eccResult > YAFFS_ECC_RESULT_NO_ERROR)
347                 retval = YAFFS_FAIL;
348
349         if (!yaffs_CheckFF(data, dev->nDataBytesPerChunk) || tags.chunkUsed) {
350                 T(YAFFS_TRACE_NANDACCESS,
351                   (TSTR("Chunk %d not erased" TENDSTR), chunkInNAND));
352                 retval = YAFFS_FAIL;
353         }
354
355         yaffs_ReleaseTempBuffer(dev, data, __LINE__);
356
357         return retval;
358
359 }
360
361
362 static int yaffs_VerifyChunkWritten(yaffs_Device *dev,
363                                         int chunkInNAND,
364                                         const __u8 *data,
365                                         yaffs_ExtendedTags *tags)
366 {
367         int retval = YAFFS_OK;
368         yaffs_ExtendedTags tempTags;
369         __u8 *buffer = yaffs_GetTempBuffer(dev,__LINE__);
370         int result;
371         
372         result = yaffs_ReadChunkWithTagsFromNAND(dev,chunkInNAND,buffer,&tempTags);
373         if(memcmp(buffer,data,dev->nDataBytesPerChunk) ||
374                 tempTags.objectId != tags->objectId ||
375                 tempTags.chunkId  != tags->chunkId ||
376                 tempTags.byteCount != tags->byteCount)
377                 retval = YAFFS_FAIL;
378
379         yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
380
381         return retval;
382 }
383
384 static int yaffs_WriteNewChunkWithTagsToNAND(struct yaffs_DeviceStruct *dev,
385                                         const __u8 *data,
386                                         yaffs_ExtendedTags *tags,
387                                         int useReserve)
388 {
389         int attempts = 0;
390         int writeOk = 0;
391         int chunk;
392
393         yaffs2_InvalidateCheckpoint(dev);
394
395         do {
396                 yaffs_BlockInfo *bi = 0;
397                 int erasedOk = 0;
398
399                 chunk = yaffs_AllocateChunk(dev, useReserve, &bi);
400                 if (chunk < 0) {
401                         /* no space */
402                         break;
403                 }
404
405                 /* First check this chunk is erased, if it needs
406                  * checking.  The checking policy (unless forced
407                  * always on) is as follows:
408                  *
409                  * Check the first page we try to write in a block.
410                  * If the check passes then we don't need to check any
411                  * more.        If the check fails, we check again...
412                  * If the block has been erased, we don't need to check.
413                  *
414                  * However, if the block has been prioritised for gc,
415                  * then we think there might be something odd about
416                  * this block and stop using it.
417                  *
418                  * Rationale: We should only ever see chunks that have
419                  * not been erased if there was a partially written
420                  * chunk due to power loss.  This checking policy should
421                  * catch that case with very few checks and thus save a
422                  * lot of checks that are most likely not needed.
423                  *
424                  * Mods to the above
425                  * If an erase check fails or the write fails we skip the 
426                  * rest of the block.
427                  */
428
429                 /* let's give it a try */
430                 attempts++;
431
432 #ifdef CONFIG_YAFFS_ALWAYS_CHECK_CHUNK_ERASED
433                 bi->skipErasedCheck = 0;
434 #endif
435                 if (!bi->skipErasedCheck) {
436                         erasedOk = yaffs_CheckChunkErased(dev, chunk);
437                         if (erasedOk != YAFFS_OK) {
438                                 T(YAFFS_TRACE_ERROR,
439                                 (TSTR("**>> yaffs chunk %d was not erased"
440                                 TENDSTR), chunk));
441
442                                 /* If not erased, delete this one,
443                                  * skip rest of block and
444                                  * try another chunk */
445                                  yaffs_DeleteChunk(dev,chunk,1,__LINE__);
446                                  yaffs_SkipRestOfBlock(dev);
447                                 continue;
448                         }
449                 }
450
451                 writeOk = yaffs_WriteChunkWithTagsToNAND(dev, chunk,
452                                 data, tags);
453
454                 if(!bi->skipErasedCheck)
455                         writeOk = yaffs_VerifyChunkWritten(dev, chunk, data, tags);
456
457                 if (writeOk != YAFFS_OK) {
458                         /* Clean up aborted write, skip to next block and
459                          * try another chunk */
460                         yaffs_HandleWriteChunkError(dev, chunk, erasedOk);
461                         continue;
462                 }
463
464                 bi->skipErasedCheck = 1;
465
466                 /* Copy the data into the robustification buffer */
467                 yaffs_HandleWriteChunkOk(dev, chunk, data, tags);
468
469         } while (writeOk != YAFFS_OK &&
470                 (yaffs_wr_attempts <= 0 || attempts <= yaffs_wr_attempts));
471
472         if (!writeOk)
473                 chunk = -1;
474
475         if (attempts > 1) {
476                 T(YAFFS_TRACE_ERROR,
477                         (TSTR("**>> yaffs write required %d attempts" TENDSTR),
478                         attempts));
479
480                 dev->nRetriedWrites += (attempts - 1);
481         }
482
483         return chunk;
484 }
485
486
487  
488 /*
489  * Block retiring for handling a broken block.
490  */
491
492 static void yaffs_RetireBlock(yaffs_Device *dev, int blockInNAND)
493 {
494         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
495
496         yaffs2_InvalidateCheckpoint(dev);
497         
498         yaffs2_ClearOldestDirtySequence(dev,bi);
499
500         if (yaffs_MarkBlockBad(dev, blockInNAND) != YAFFS_OK) {
501                 if (yaffs_EraseBlockInNAND(dev, blockInNAND) != YAFFS_OK) {
502                         T(YAFFS_TRACE_ALWAYS, (TSTR(
503                                 "yaffs: Failed to mark bad and erase block %d"
504                                 TENDSTR), blockInNAND));
505                 } else {
506                         yaffs_ExtendedTags tags;
507                         int chunkId = blockInNAND * dev->param.nChunksPerBlock;
508
509                         __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
510
511                         memset(buffer, 0xff, dev->nDataBytesPerChunk);
512                         yaffs_InitialiseTags(&tags);
513                         tags.sequenceNumber = YAFFS_SEQUENCE_BAD_BLOCK;
514                         if (dev->param.writeChunkWithTagsToNAND(dev, chunkId -
515                                 dev->chunkOffset, buffer, &tags) != YAFFS_OK)
516                                 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Failed to "
517                                         TCONT("write bad block marker to block %d")
518                                         TENDSTR), blockInNAND));
519
520                         yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
521                 }
522         }
523
524         bi->blockState = YAFFS_BLOCK_STATE_DEAD;
525         bi->gcPrioritise = 0;
526         bi->needsRetiring = 0;
527
528         dev->nRetiredBlocks++;
529 }
530
531 /*
532  * Functions for robustisizing TODO
533  *
534  */
535
536 static void yaffs_HandleWriteChunkOk(yaffs_Device *dev, int chunkInNAND,
537                                 const __u8 *data,
538                                 const yaffs_ExtendedTags *tags)
539 {
540         dev=dev;
541         chunkInNAND=chunkInNAND;
542         data=data;
543         tags=tags;
544 }
545
546 static void yaffs_HandleUpdateChunk(yaffs_Device *dev, int chunkInNAND,
547                                 const yaffs_ExtendedTags *tags)
548 {
549         dev=dev;
550         chunkInNAND=chunkInNAND;
551         tags=tags;
552 }
553
554 void yaffs_HandleChunkError(yaffs_Device *dev, yaffs_BlockInfo *bi)
555 {
556         if (!bi->gcPrioritise) {
557                 bi->gcPrioritise = 1;
558                 dev->hasPendingPrioritisedGCs = 1;
559                 bi->chunkErrorStrikes++;
560
561                 if (bi->chunkErrorStrikes > 3) {
562                         bi->needsRetiring = 1; /* Too many stikes, so retire this */
563                         T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Block struck out" TENDSTR)));
564
565                 }
566         }
567 }
568
569 static void yaffs_HandleWriteChunkError(yaffs_Device *dev, int chunkInNAND,
570                 int erasedOk)
571 {
572         int blockInNAND = chunkInNAND / dev->param.nChunksPerBlock;
573         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockInNAND);
574
575         yaffs_HandleChunkError(dev, bi);
576
577         if (erasedOk) {
578                 /* Was an actual write failure, so mark the block for retirement  */
579                 bi->needsRetiring = 1;
580                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
581                   (TSTR("**>> Block %d needs retiring" TENDSTR), blockInNAND));
582         }
583
584         /* Delete the chunk */
585         yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
586         yaffs_SkipRestOfBlock(dev);
587 }
588
589
590 /*---------------- Name handling functions ------------*/
591
592 static __u16 yaffs_CalcNameSum(const YCHAR *name)
593 {
594         __u16 sum = 0;
595         __u16 i = 1;
596
597         const YUCHAR *bname = (const YUCHAR *) name;
598         if (bname) {
599                 while ((*bname) && (i < (YAFFS_MAX_NAME_LENGTH/2))) {
600
601 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
602                         sum += yaffs_toupper(*bname) * i;
603 #else
604                         sum += (*bname) * i;
605 #endif
606                         i++;
607                         bname++;
608                 }
609         }
610         return sum;
611 }
612
613 void yaffs_SetObjectName(yaffs_Object *obj, const YCHAR *name)
614 {
615 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
616         memset(obj->shortName, 0, sizeof(YCHAR) * (YAFFS_SHORT_NAME_LENGTH+1));
617         if (name && yaffs_strnlen(name,YAFFS_SHORT_NAME_LENGTH+1) <= YAFFS_SHORT_NAME_LENGTH)
618                 yaffs_strcpy(obj->shortName, name);
619         else
620                 obj->shortName[0] = _Y('\0');
621 #endif
622         obj->sum = yaffs_CalcNameSum(name);
623 }
624
625 /*-------------------- TNODES -------------------
626
627  * List of spare tnodes
628  * The list is hooked together using the first pointer
629  * in the tnode.
630  */
631
632
633 yaffs_Tnode *yaffs_GetTnode(yaffs_Device *dev)
634 {
635         yaffs_Tnode *tn = yaffs_AllocateRawTnode(dev);
636         if (tn){
637                 memset(tn, 0, dev->tnodeSize);
638                 dev->nTnodes++;
639         }
640
641         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
642
643         return tn;
644 }
645
646 /* FreeTnode frees up a tnode and puts it back on the free list */
647 static void yaffs_FreeTnode(yaffs_Device *dev, yaffs_Tnode *tn)
648 {
649         yaffs_FreeRawTnode(dev,tn);
650         dev->nTnodes--;
651         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
652 }
653
654 static void yaffs_DeinitialiseTnodesAndObjects(yaffs_Device *dev)
655 {
656         yaffs_DeinitialiseRawTnodesAndObjects(dev);
657         dev->nObjects = 0;
658         dev->nTnodes = 0;
659 }
660
661
662 void yaffs_LoadLevel0Tnode(yaffs_Device *dev, yaffs_Tnode *tn, unsigned pos,
663                 unsigned val)
664 {
665         __u32 *map = (__u32 *)tn;
666         __u32 bitInMap;
667         __u32 bitInWord;
668         __u32 wordInMap;
669         __u32 mask;
670
671         pos &= YAFFS_TNODES_LEVEL0_MASK;
672         val >>= dev->chunkGroupBits;
673
674         bitInMap = pos * dev->tnodeWidth;
675         wordInMap = bitInMap / 32;
676         bitInWord = bitInMap & (32 - 1);
677
678         mask = dev->tnodeMask << bitInWord;
679
680         map[wordInMap] &= ~mask;
681         map[wordInMap] |= (mask & (val << bitInWord));
682
683         if (dev->tnodeWidth > (32 - bitInWord)) {
684                 bitInWord = (32 - bitInWord);
685                 wordInMap++;;
686                 mask = dev->tnodeMask >> (/*dev->tnodeWidth -*/ bitInWord);
687                 map[wordInMap] &= ~mask;
688                 map[wordInMap] |= (mask & (val >> bitInWord));
689         }
690 }
691
692 __u32 yaffs_GetChunkGroupBase(yaffs_Device *dev, yaffs_Tnode *tn,
693                 unsigned pos)
694 {
695         __u32 *map = (__u32 *)tn;
696         __u32 bitInMap;
697         __u32 bitInWord;
698         __u32 wordInMap;
699         __u32 val;
700
701         pos &= YAFFS_TNODES_LEVEL0_MASK;
702
703         bitInMap = pos * dev->tnodeWidth;
704         wordInMap = bitInMap / 32;
705         bitInWord = bitInMap & (32 - 1);
706
707         val = map[wordInMap] >> bitInWord;
708
709         if      (dev->tnodeWidth > (32 - bitInWord)) {
710                 bitInWord = (32 - bitInWord);
711                 wordInMap++;;
712                 val |= (map[wordInMap] << bitInWord);
713         }
714
715         val &= dev->tnodeMask;
716         val <<= dev->chunkGroupBits;
717
718         return val;
719 }
720
721 /* ------------------- End of individual tnode manipulation -----------------*/
722
723 /* ---------Functions to manipulate the look-up tree (made up of tnodes) ------
724  * The look up tree is represented by the top tnode and the number of topLevel
725  * in the tree. 0 means only the level 0 tnode is in the tree.
726  */
727
728 /* FindLevel0Tnode finds the level 0 tnode, if one exists. */
729 yaffs_Tnode *yaffs_FindLevel0Tnode(yaffs_Device *dev,
730                                         yaffs_FileStructure *fStruct,
731                                         __u32 chunkId)
732 {
733         yaffs_Tnode *tn = fStruct->top;
734         __u32 i;
735         int requiredTallness;
736         int level = fStruct->topLevel;
737
738         dev=dev;
739
740         /* Check sane level and chunk Id */
741         if (level < 0 || level > YAFFS_TNODES_MAX_LEVEL)
742                 return NULL;
743
744         if (chunkId > YAFFS_MAX_CHUNK_ID)
745                 return NULL;
746
747         /* First check we're tall enough (ie enough topLevel) */
748
749         i = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
750         requiredTallness = 0;
751         while (i) {
752                 i >>= YAFFS_TNODES_INTERNAL_BITS;
753                 requiredTallness++;
754         }
755
756         if (requiredTallness > fStruct->topLevel)
757                 return NULL; /* Not tall enough, so we can't find it */
758
759         /* Traverse down to level 0 */
760         while (level > 0 && tn) {
761                 tn = tn->internal[(chunkId >>
762                         (YAFFS_TNODES_LEVEL0_BITS +
763                                 (level - 1) *
764                                 YAFFS_TNODES_INTERNAL_BITS)) &
765                         YAFFS_TNODES_INTERNAL_MASK];
766                 level--;
767         }
768
769         return tn;
770 }
771
772 /* AddOrFindLevel0Tnode finds the level 0 tnode if it exists, otherwise first expands the tree.
773  * This happens in two steps:
774  *  1. If the tree isn't tall enough, then make it taller.
775  *  2. Scan down the tree towards the level 0 tnode adding tnodes if required.
776  *
777  * Used when modifying the tree.
778  *
779  *  If the tn argument is NULL, then a fresh tnode will be added otherwise the specified tn will
780  *  be plugged into the ttree.
781  */
782
783 yaffs_Tnode *yaffs_AddOrFindLevel0Tnode(yaffs_Device *dev,
784                                         yaffs_FileStructure *fStruct,
785                                         __u32 chunkId,
786                                         yaffs_Tnode *passedTn)
787 {
788         int requiredTallness;
789         int i;
790         int l;
791         yaffs_Tnode *tn;
792
793         __u32 x;
794
795
796         /* Check sane level and page Id */
797         if (fStruct->topLevel < 0 || fStruct->topLevel > YAFFS_TNODES_MAX_LEVEL)
798                 return NULL;
799
800         if (chunkId > YAFFS_MAX_CHUNK_ID)
801                 return NULL;
802
803         /* First check we're tall enough (ie enough topLevel) */
804
805         x = chunkId >> YAFFS_TNODES_LEVEL0_BITS;
806         requiredTallness = 0;
807         while (x) {
808                 x >>= YAFFS_TNODES_INTERNAL_BITS;
809                 requiredTallness++;
810         }
811
812
813         if (requiredTallness > fStruct->topLevel) {
814                 /* Not tall enough, gotta make the tree taller */
815                 for (i = fStruct->topLevel; i < requiredTallness; i++) {
816
817                         tn = yaffs_GetTnode(dev);
818
819                         if (tn) {
820                                 tn->internal[0] = fStruct->top;
821                                 fStruct->top = tn;
822                                 fStruct->topLevel++;
823                         } else {
824                                 T(YAFFS_TRACE_ERROR,
825                                         (TSTR("yaffs: no more tnodes" TENDSTR)));
826                                 return NULL;
827                         }
828                 }
829         }
830
831         /* Traverse down to level 0, adding anything we need */
832
833         l = fStruct->topLevel;
834         tn = fStruct->top;
835
836         if (l > 0) {
837                 while (l > 0 && tn) {
838                         x = (chunkId >>
839                              (YAFFS_TNODES_LEVEL0_BITS +
840                               (l - 1) * YAFFS_TNODES_INTERNAL_BITS)) &
841                             YAFFS_TNODES_INTERNAL_MASK;
842
843
844                         if ((l > 1) && !tn->internal[x]) {
845                                 /* Add missing non-level-zero tnode */
846                                 tn->internal[x] = yaffs_GetTnode(dev);
847                                 if(!tn->internal[x])
848                                         return NULL;
849                         } else if (l == 1) {
850                                 /* Looking from level 1 at level 0 */
851                                 if (passedTn) {
852                                         /* If we already have one, then release it.*/
853                                         if (tn->internal[x])
854                                                 yaffs_FreeTnode(dev, tn->internal[x]);
855                                         tn->internal[x] = passedTn;
856
857                                 } else if (!tn->internal[x]) {
858                                         /* Don't have one, none passed in */
859                                         tn->internal[x] = yaffs_GetTnode(dev);
860                                         if(!tn->internal[x])
861                                                 return NULL;
862                                 }
863                         }
864
865                         tn = tn->internal[x];
866                         l--;
867                 }
868         } else {
869                 /* top is level 0 */
870                 if (passedTn) {
871                         memcpy(tn, passedTn, (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8);
872                         yaffs_FreeTnode(dev, passedTn);
873                 }
874         }
875
876         return tn;
877 }
878
879 static int yaffs_FindChunkInGroup(yaffs_Device *dev, int theChunk,
880                                 yaffs_ExtendedTags *tags, int objectId,
881                                 int chunkInInode)
882 {
883         int j;
884
885         for (j = 0; theChunk && j < dev->chunkGroupSize; j++) {
886                 if (yaffs_CheckChunkBit(dev, theChunk / dev->param.nChunksPerBlock,
887                                 theChunk % dev->param.nChunksPerBlock)) {
888                         
889                         if(dev->chunkGroupSize == 1)
890                                 return theChunk;
891                         else {
892                                 yaffs_ReadChunkWithTagsFromNAND(dev, theChunk, NULL,
893                                                                 tags);
894                                 if (yaffs_TagsMatch(tags, objectId, chunkInInode)) {
895                                         /* found it; */
896                                         return theChunk;
897                                 }
898                         }
899                 }
900                 theChunk++;
901         }
902         return -1;
903 }
904
905 #if 0
906 /* Experimental code not being used yet. Might speed up file deletion */
907 /* DeleteWorker scans backwards through the tnode tree and deletes all the
908  * chunks and tnodes in the file.
909  * Returns 1 if the tree was deleted.
910  * Returns 0 if it stopped early due to hitting the limit and the delete is incomplete.
911  */
912
913 static int yaffs_DeleteWorker(yaffs_Object *in, yaffs_Tnode *tn, __u32 level,
914                               int chunkOffset, int *limit)
915 {
916         int i;
917         int chunkInInode;
918         int theChunk;
919         yaffs_ExtendedTags tags;
920         int foundChunk;
921         yaffs_Device *dev = in->myDev;
922
923         int allDone = 1;
924
925         if (tn) {
926                 if (level > 0) {
927                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
928                              i--) {
929                                 if (tn->internal[i]) {
930                                         if (limit && (*limit) < 0) {
931                                                 allDone = 0;
932                                         } else {
933                                                 allDone =
934                                                         yaffs_DeleteWorker(in,
935                                                                 tn->
936                                                                 internal
937                                                                 [i],
938                                                                 level -
939                                                                 1,
940                                                                 (chunkOffset
941                                                                         <<
942                                                                         YAFFS_TNODES_INTERNAL_BITS)
943                                                                 + i,
944                                                                 limit);
945                                         }
946                                         if (allDone) {
947                                                 yaffs_FreeTnode(dev,
948                                                                 tn->
949                                                                 internal[i]);
950                                                 tn->internal[i] = NULL;
951                                         }
952                                 }
953                         }
954                         return (allDone) ? 1 : 0;
955                 } else if (level == 0) {
956                         int hitLimit = 0;
957
958                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0 && !hitLimit;
959                                         i--) {
960                                 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
961                                 if (theChunk) {
962
963                                         chunkInInode = (chunkOffset <<
964                                                 YAFFS_TNODES_LEVEL0_BITS) + i;
965
966                                         foundChunk =
967                                                 yaffs_FindChunkInGroup(dev,
968                                                                 theChunk,
969                                                                 &tags,
970                                                                 in->objectId,
971                                                                 chunkInInode);
972
973                                         if (foundChunk > 0) {
974                                                 yaffs_DeleteChunk(dev,
975                                                                   foundChunk, 1,
976                                                                   __LINE__);
977                                                 in->nDataChunks--;
978                                                 if (limit) {
979                                                         *limit = *limit - 1;
980                                                         if (*limit <= 0)
981                                                                 hitLimit = 1;
982                                                 }
983
984                                         }
985
986                                         yaffs_LoadLevel0Tnode(dev, tn, i, 0);
987                                 }
988
989                         }
990                         return (i < 0) ? 1 : 0;
991
992                 }
993
994         }
995
996         return 1;
997
998 }
999
1000 #endif
1001
1002 static void yaffs_SoftDeleteChunk(yaffs_Device *dev, int chunk)
1003 {
1004         yaffs_BlockInfo *theBlock;
1005         unsigned blockNo;
1006
1007         T(YAFFS_TRACE_DELETION, (TSTR("soft delete chunk %d" TENDSTR), chunk));
1008
1009         blockNo =  chunk / dev->param.nChunksPerBlock;
1010         theBlock = yaffs_GetBlockInfo(dev, blockNo);
1011         if (theBlock) {
1012                 theBlock->softDeletions++;
1013                 dev->nFreeChunks++;
1014                 yaffs2_UpdateOldestDirtySequence(dev, blockNo, theBlock);
1015         }
1016 }
1017
1018 /* SoftDeleteWorker scans backwards through the tnode tree and soft deletes all the chunks in the file.
1019  * All soft deleting does is increment the block's softdelete count and pulls the chunk out
1020  * of the tnode.
1021  * Thus, essentially this is the same as DeleteWorker except that the chunks are soft deleted.
1022  */
1023
1024 static int yaffs_SoftDeleteWorker(yaffs_Object *in, yaffs_Tnode *tn,
1025                                   __u32 level, int chunkOffset)
1026 {
1027         int i;
1028         int theChunk;
1029         int allDone = 1;
1030         yaffs_Device *dev = in->myDev;
1031
1032         if (tn) {
1033                 if (level > 0) {
1034
1035                         for (i = YAFFS_NTNODES_INTERNAL - 1; allDone && i >= 0;
1036                              i--) {
1037                                 if (tn->internal[i]) {
1038                                         allDone =
1039                                             yaffs_SoftDeleteWorker(in,
1040                                                                    tn->
1041                                                                    internal[i],
1042                                                                    level - 1,
1043                                                                    (chunkOffset
1044                                                                     <<
1045                                                                     YAFFS_TNODES_INTERNAL_BITS)
1046                                                                    + i);
1047                                         if (allDone) {
1048                                                 yaffs_FreeTnode(dev,
1049                                                                 tn->
1050                                                                 internal[i]);
1051                                                 tn->internal[i] = NULL;
1052                                         } else {
1053                                                 /* Hoosterman... how could this happen? */
1054                                         }
1055                                 }
1056                         }
1057                         return (allDone) ? 1 : 0;
1058                 } else if (level == 0) {
1059
1060                         for (i = YAFFS_NTNODES_LEVEL0 - 1; i >= 0; i--) {
1061                                 theChunk = yaffs_GetChunkGroupBase(dev, tn, i);
1062                                 if (theChunk) {
1063                                         /* Note this does not find the real chunk, only the chunk group.
1064                                          * We make an assumption that a chunk group is not larger than
1065                                          * a block.
1066                                          */
1067                                         yaffs_SoftDeleteChunk(dev, theChunk);
1068                                         yaffs_LoadLevel0Tnode(dev, tn, i, 0);
1069                                 }
1070
1071                         }
1072                         return 1;
1073
1074                 }
1075
1076         }
1077
1078         return 1;
1079
1080 }
1081
1082 static void yaffs_SoftDeleteFile(yaffs_Object *obj)
1083 {
1084         if (obj->deleted &&
1085             obj->variantType == YAFFS_OBJECT_TYPE_FILE && !obj->softDeleted) {
1086                 if (obj->nDataChunks <= 0) {
1087                         /* Empty file with no duplicate object headers, just delete it immediately */
1088                         yaffs_FreeTnode(obj->myDev,
1089                                         obj->variant.fileVariant.top);
1090                         obj->variant.fileVariant.top = NULL;
1091                         T(YAFFS_TRACE_TRACING,
1092                           (TSTR("yaffs: Deleting empty file %d" TENDSTR),
1093                            obj->objectId));
1094                         yaffs_DoGenericObjectDeletion(obj);
1095                 } else {
1096                         yaffs_SoftDeleteWorker(obj,
1097                                                obj->variant.fileVariant.top,
1098                                                obj->variant.fileVariant.
1099                                                topLevel, 0);
1100                         obj->softDeleted = 1;
1101                 }
1102         }
1103 }
1104
1105 /* Pruning removes any part of the file structure tree that is beyond the
1106  * bounds of the file (ie that does not point to chunks).
1107  *
1108  * A file should only get pruned when its size is reduced.
1109  *
1110  * Before pruning, the chunks must be pulled from the tree and the
1111  * level 0 tnode entries must be zeroed out.
1112  * Could also use this for file deletion, but that's probably better handled
1113  * by a special case.
1114  *
1115  * This function is recursive. For levels > 0 the function is called again on
1116  * any sub-tree. For level == 0 we just check if the sub-tree has data.
1117  * If there is no data in a subtree then it is pruned.
1118  */
1119
1120 static yaffs_Tnode *yaffs_PruneWorker(yaffs_Device *dev, yaffs_Tnode *tn,
1121                                 __u32 level, int del0)
1122 {
1123         int i;
1124         int hasData;
1125
1126         if (tn) {
1127                 hasData = 0;
1128
1129                 if(level > 0){
1130                         for (i = 0; i < YAFFS_NTNODES_INTERNAL; i++) {
1131                                 if (tn->internal[i]) {
1132                                         tn->internal[i] =
1133                                                 yaffs_PruneWorker(dev, tn->internal[i],
1134                                                         level - 1,
1135                                                         (i == 0) ? del0 : 1);
1136                                 }
1137
1138                                 if (tn->internal[i])
1139                                         hasData++;
1140                         }
1141                 } else {
1142                         int tnodeSize_u32 = dev->tnodeSize/sizeof(__u32);
1143                         __u32 *map = (__u32 *)tn;
1144
1145                         for(i = 0; !hasData && i < tnodeSize_u32; i++){
1146                                 if(map[i])
1147                                         hasData++;
1148                         }
1149                 }
1150
1151                 if (hasData == 0 && del0) {
1152                         /* Free and return NULL */
1153
1154                         yaffs_FreeTnode(dev, tn);
1155                         tn = NULL;
1156                 }
1157
1158         }
1159
1160         return tn;
1161
1162 }
1163
1164 static int yaffs_PruneFileStructure(yaffs_Device *dev,
1165                                 yaffs_FileStructure *fStruct)
1166 {
1167         int i;
1168         int hasData;
1169         int done = 0;
1170         yaffs_Tnode *tn;
1171
1172         if (fStruct->topLevel > 0) {
1173                 fStruct->top =
1174                     yaffs_PruneWorker(dev, fStruct->top, fStruct->topLevel, 0);
1175
1176                 /* Now we have a tree with all the non-zero branches NULL but the height
1177                  * is the same as it was.
1178                  * Let's see if we can trim internal tnodes to shorten the tree.
1179                  * We can do this if only the 0th element in the tnode is in use
1180                  * (ie all the non-zero are NULL)
1181                  */
1182
1183                 while (fStruct->topLevel && !done) {
1184                         tn = fStruct->top;
1185
1186                         hasData = 0;
1187                         for (i = 1; i < YAFFS_NTNODES_INTERNAL; i++) {
1188                                 if (tn->internal[i])
1189                                         hasData++;
1190                         }
1191
1192                         if (!hasData) {
1193                                 fStruct->top = tn->internal[0];
1194                                 fStruct->topLevel--;
1195                                 yaffs_FreeTnode(dev, tn);
1196                         } else {
1197                                 done = 1;
1198                         }
1199                 }
1200         }
1201
1202         return YAFFS_OK;
1203 }
1204
1205 /*-------------------- End of File Structure functions.-------------------*/
1206
1207
1208 /* AllocateEmptyObject gets us a clean Object. Tries to make allocate more if we run out */
1209 static yaffs_Object *yaffs_AllocateEmptyObject(yaffs_Device *dev)
1210 {
1211         yaffs_Object *obj = yaffs_AllocateRawObject(dev);
1212
1213         if (obj) {
1214                 dev->nObjects++;
1215
1216                 /* Now sweeten it up... */
1217
1218                 memset(obj, 0, sizeof(yaffs_Object));
1219                 obj->beingCreated = 1;
1220
1221                 obj->myDev = dev;
1222                 obj->hdrChunk = 0;
1223                 obj->variantType = YAFFS_OBJECT_TYPE_UNKNOWN;
1224                 YINIT_LIST_HEAD(&(obj->hardLinks));
1225                 YINIT_LIST_HEAD(&(obj->hashLink));
1226                 YINIT_LIST_HEAD(&obj->siblings);
1227
1228
1229                 /* Now make the directory sane */
1230                 if (dev->rootDir) {
1231                         obj->parent = dev->rootDir;
1232                         ylist_add(&(obj->siblings), &dev->rootDir->variant.directoryVariant.children);
1233                 }
1234
1235                 /* Add it to the lost and found directory.
1236                  * NB Can't put root or lostNFound in lostNFound so
1237                  * check if lostNFound exists first
1238                  */
1239                 if (dev->lostNFoundDir)
1240                         yaffs_AddObjectToDirectory(dev->lostNFoundDir, obj);
1241
1242                 obj->beingCreated = 0;
1243         }
1244
1245         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1246
1247         return obj;
1248 }
1249
1250 static yaffs_Object *yaffs_CreateFakeDirectory(yaffs_Device *dev, int number,
1251                                                __u32 mode)
1252 {
1253
1254         yaffs_Object *obj =
1255             yaffs_CreateNewObject(dev, number, YAFFS_OBJECT_TYPE_DIRECTORY);
1256         if (obj) {
1257                 obj->fake = 1;          /* it is fake so it might have no NAND presence... */
1258                 obj->renameAllowed = 0; /* ... and we're not allowed to rename it... */
1259                 obj->unlinkAllowed = 0; /* ... or unlink it */
1260                 obj->deleted = 0;
1261                 obj->unlinked = 0;
1262                 obj->yst_mode = mode;
1263                 obj->myDev = dev;
1264                 obj->hdrChunk = 0;      /* Not a valid chunk. */
1265         }
1266
1267         return obj;
1268
1269 }
1270
1271 static void yaffs_UnhashObject(yaffs_Object *obj)
1272 {
1273         int bucket;
1274         yaffs_Device *dev = obj->myDev;
1275
1276         /* If it is still linked into the bucket list, free from the list */
1277         if (!ylist_empty(&obj->hashLink)) {
1278                 ylist_del_init(&obj->hashLink);
1279                 bucket = yaffs_HashFunction(obj->objectId);
1280                 dev->objectBucket[bucket].count--;
1281         }
1282 }
1283
1284 /*  FreeObject frees up a Object and puts it back on the free list */
1285 static void yaffs_FreeObject(yaffs_Object *obj)
1286 {
1287         yaffs_Device *dev = obj->myDev;
1288
1289         T(YAFFS_TRACE_OS, (TSTR("FreeObject %p inode %p"TENDSTR), obj, obj->myInode));
1290
1291         if (!obj)
1292                 YBUG();
1293         if (obj->parent)
1294                 YBUG();
1295         if (!ylist_empty(&obj->siblings))
1296                 YBUG();
1297
1298
1299         if (obj->myInode) {
1300                 /* We're still hooked up to a cached inode.
1301                  * Don't delete now, but mark for later deletion
1302                  */
1303                 obj->deferedFree = 1;
1304                 return;
1305         }
1306
1307         yaffs_UnhashObject(obj);
1308
1309         yaffs_FreeRawObject(dev,obj);
1310         dev->nObjects--;
1311         dev->nCheckpointBlocksRequired = 0; /* force recalculation*/
1312 }
1313
1314
1315 void yaffs_HandleDeferedFree(yaffs_Object *obj)
1316 {
1317         if (obj->deferedFree)
1318                 yaffs_FreeObject(obj);
1319 }
1320
1321 static void yaffs_InitialiseTnodesAndObjects(yaffs_Device *dev)
1322 {
1323         int i;
1324
1325         dev->nObjects = 0;
1326         dev->nTnodes = 0;
1327
1328         yaffs_InitialiseRawTnodesAndObjects(dev);
1329
1330         for (i = 0; i < YAFFS_NOBJECT_BUCKETS; i++) {
1331                 YINIT_LIST_HEAD(&dev->objectBucket[i].list);
1332                 dev->objectBucket[i].count = 0;
1333         }
1334 }
1335
1336 static int yaffs_FindNiceObjectBucket(yaffs_Device *dev)
1337 {
1338         int i;
1339         int l = 999;
1340         int lowest = 999999;
1341
1342
1343         /* Search for the shortest list or one that
1344          * isn't too long.
1345          */
1346
1347         for (i = 0; i < 10 && lowest > 4; i++) {
1348                 dev->bucketFinder++;
1349                 dev->bucketFinder %= YAFFS_NOBJECT_BUCKETS;
1350                 if (dev->objectBucket[dev->bucketFinder].count < lowest) {
1351                         lowest = dev->objectBucket[dev->bucketFinder].count;
1352                         l = dev->bucketFinder;
1353                 }
1354
1355         }
1356
1357         return l;
1358 }
1359
1360 static int yaffs_CreateNewObjectNumber(yaffs_Device *dev)
1361 {
1362         int bucket = yaffs_FindNiceObjectBucket(dev);
1363
1364         /* Now find an object value that has not already been taken
1365          * by scanning the list.
1366          */
1367
1368         int found = 0;
1369         struct ylist_head *i;
1370
1371         __u32 n = (__u32) bucket;
1372
1373         /* yaffs_CheckObjectHashSanity();  */
1374
1375         while (!found) {
1376                 found = 1;
1377                 n += YAFFS_NOBJECT_BUCKETS;
1378                 if (1 || dev->objectBucket[bucket].count > 0) {
1379                         ylist_for_each(i, &dev->objectBucket[bucket].list) {
1380                                 /* If there is already one in the list */
1381                                 if (i && ylist_entry(i, yaffs_Object,
1382                                                 hashLink)->objectId == n) {
1383                                         found = 0;
1384                                 }
1385                         }
1386                 }
1387         }
1388
1389         return n;
1390 }
1391
1392 static void yaffs_HashObject(yaffs_Object *in)
1393 {
1394         int bucket = yaffs_HashFunction(in->objectId);
1395         yaffs_Device *dev = in->myDev;
1396
1397         ylist_add(&in->hashLink, &dev->objectBucket[bucket].list);
1398         dev->objectBucket[bucket].count++;
1399 }
1400
1401 yaffs_Object *yaffs_FindObjectByNumber(yaffs_Device *dev, __u32 number)
1402 {
1403         int bucket = yaffs_HashFunction(number);
1404         struct ylist_head *i;
1405         yaffs_Object *in;
1406
1407         ylist_for_each(i, &dev->objectBucket[bucket].list) {
1408                 /* Look if it is in the list */
1409                 if (i) {
1410                         in = ylist_entry(i, yaffs_Object, hashLink);
1411                         if (in->objectId == number) {
1412
1413                                 /* Don't tell the VFS about this one if it is defered free */
1414                                 if (in->deferedFree)
1415                                         return NULL;
1416
1417                                 return in;
1418                         }
1419                 }
1420         }
1421
1422         return NULL;
1423 }
1424
1425 yaffs_Object *yaffs_CreateNewObject(yaffs_Device *dev, int number,
1426                                     yaffs_ObjectType type)
1427 {
1428         yaffs_Object *theObject=NULL;
1429         yaffs_Tnode *tn = NULL;
1430
1431         if (number < 0)
1432                 number = yaffs_CreateNewObjectNumber(dev);
1433
1434         if (type == YAFFS_OBJECT_TYPE_FILE) {
1435                 tn = yaffs_GetTnode(dev);
1436                 if (!tn)
1437                         return NULL;
1438         }
1439
1440         theObject = yaffs_AllocateEmptyObject(dev);
1441         if (!theObject){
1442                 if(tn)
1443                         yaffs_FreeTnode(dev,tn);
1444                 return NULL;
1445         }
1446
1447
1448         if (theObject) {
1449                 theObject->fake = 0;
1450                 theObject->renameAllowed = 1;
1451                 theObject->unlinkAllowed = 1;
1452                 theObject->objectId = number;
1453                 yaffs_HashObject(theObject);
1454                 theObject->variantType = type;
1455 #ifdef CONFIG_YAFFS_WINCE
1456                 yfsd_WinFileTimeNow(theObject->win_atime);
1457                 theObject->win_ctime[0] = theObject->win_mtime[0] =
1458                     theObject->win_atime[0];
1459                 theObject->win_ctime[1] = theObject->win_mtime[1] =
1460                     theObject->win_atime[1];
1461
1462 #else
1463
1464                 theObject->yst_atime = theObject->yst_mtime =
1465                     theObject->yst_ctime = Y_CURRENT_TIME;
1466 #endif
1467                 switch (type) {
1468                 case YAFFS_OBJECT_TYPE_FILE:
1469                         theObject->variant.fileVariant.fileSize = 0;
1470                         theObject->variant.fileVariant.scannedFileSize = 0;
1471                         theObject->variant.fileVariant.shrinkSize = 0xFFFFFFFF; /* max __u32 */
1472                         theObject->variant.fileVariant.topLevel = 0;
1473                         theObject->variant.fileVariant.top = tn;
1474                         break;
1475                 case YAFFS_OBJECT_TYPE_DIRECTORY:
1476                         YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
1477                                         children);
1478                         YINIT_LIST_HEAD(&theObject->variant.directoryVariant.
1479                                         dirty);
1480                         break;
1481                 case YAFFS_OBJECT_TYPE_SYMLINK:
1482                 case YAFFS_OBJECT_TYPE_HARDLINK:
1483                 case YAFFS_OBJECT_TYPE_SPECIAL:
1484                         /* No action required */
1485                         break;
1486                 case YAFFS_OBJECT_TYPE_UNKNOWN:
1487                         /* todo this should not happen */
1488                         break;
1489                 }
1490         }
1491
1492         return theObject;
1493 }
1494
1495 yaffs_Object *yaffs_FindOrCreateObjectByNumber(yaffs_Device *dev,
1496                                                 int number,
1497                                                 yaffs_ObjectType type)
1498 {
1499         yaffs_Object *theObject = NULL;
1500
1501         if (number > 0)
1502                 theObject = yaffs_FindObjectByNumber(dev, number);
1503
1504         if (!theObject)
1505                 theObject = yaffs_CreateNewObject(dev, number, type);
1506
1507         return theObject;
1508
1509 }
1510
1511
1512 YCHAR *yaffs_CloneString(const YCHAR *str)
1513 {
1514         YCHAR *newStr = NULL;
1515         int len;
1516
1517         if (!str)
1518                 str = _Y("");
1519
1520         len = yaffs_strnlen(str,YAFFS_MAX_ALIAS_LENGTH);
1521         newStr = YMALLOC((len + 1) * sizeof(YCHAR));
1522         if (newStr){
1523                 yaffs_strncpy(newStr, str,len);
1524                 newStr[len] = 0;
1525         }
1526         return newStr;
1527
1528 }
1529
1530 /*
1531  * Mknod (create) a new object.
1532  * equivalentObject only has meaning for a hard link;
1533  * aliasString only has meaning for a symlink.
1534  * rdev only has meaning for devices (a subset of special objects)
1535  */
1536
1537 static yaffs_Object *yaffs_MknodObject(yaffs_ObjectType type,
1538                                        yaffs_Object *parent,
1539                                        const YCHAR *name,
1540                                        __u32 mode,
1541                                        __u32 uid,
1542                                        __u32 gid,
1543                                        yaffs_Object *equivalentObject,
1544                                        const YCHAR *aliasString, __u32 rdev)
1545 {
1546         yaffs_Object *in;
1547         YCHAR *str = NULL;
1548
1549         yaffs_Device *dev = parent->myDev;
1550
1551         /* Check if the entry exists. If it does then fail the call since we don't want a dup.*/
1552         if (yaffs_FindObjectByName(parent, name))
1553                 return NULL;
1554
1555         if (type == YAFFS_OBJECT_TYPE_SYMLINK) {
1556                 str = yaffs_CloneString(aliasString);
1557                 if (!str)
1558                         return NULL;
1559         }
1560
1561         in = yaffs_CreateNewObject(dev, -1, type);
1562
1563         if (!in){
1564                 if(str)
1565                         YFREE(str);
1566                 return NULL;
1567         }
1568
1569
1570
1571
1572
1573         if (in) {
1574                 in->hdrChunk = 0;
1575                 in->valid = 1;
1576                 in->variantType = type;
1577
1578                 in->yst_mode = mode;
1579
1580 #ifdef CONFIG_YAFFS_WINCE
1581                 yfsd_WinFileTimeNow(in->win_atime);
1582                 in->win_ctime[0] = in->win_mtime[0] = in->win_atime[0];
1583                 in->win_ctime[1] = in->win_mtime[1] = in->win_atime[1];
1584
1585 #else
1586                 in->yst_atime = in->yst_mtime = in->yst_ctime = Y_CURRENT_TIME;
1587
1588                 in->yst_rdev = rdev;
1589                 in->yst_uid = uid;
1590                 in->yst_gid = gid;
1591 #endif
1592                 in->nDataChunks = 0;
1593
1594                 yaffs_SetObjectName(in, name);
1595                 in->dirty = 1;
1596
1597                 yaffs_AddObjectToDirectory(parent, in);
1598
1599                 in->myDev = parent->myDev;
1600
1601                 switch (type) {
1602                 case YAFFS_OBJECT_TYPE_SYMLINK:
1603                         in->variant.symLinkVariant.alias = str;
1604                         break;
1605                 case YAFFS_OBJECT_TYPE_HARDLINK:
1606                         in->variant.hardLinkVariant.equivalentObject =
1607                                 equivalentObject;
1608                         in->variant.hardLinkVariant.equivalentObjectId =
1609                                 equivalentObject->objectId;
1610                         ylist_add(&in->hardLinks, &equivalentObject->hardLinks);
1611                         break;
1612                 case YAFFS_OBJECT_TYPE_FILE:
1613                 case YAFFS_OBJECT_TYPE_DIRECTORY:
1614                 case YAFFS_OBJECT_TYPE_SPECIAL:
1615                 case YAFFS_OBJECT_TYPE_UNKNOWN:
1616                         /* do nothing */
1617                         break;
1618                 }
1619
1620                 if (yaffs_UpdateObjectHeader(in, name, 0, 0, 0, NULL) < 0) {
1621                         /* Could not create the object header, fail the creation */
1622                         yaffs_DeleteObject(in);
1623                         in = NULL;
1624                 }
1625
1626                 yaffs_UpdateParent(parent);
1627         }
1628
1629         return in;
1630 }
1631
1632 yaffs_Object *yaffs_MknodFile(yaffs_Object *parent, const YCHAR *name,
1633                         __u32 mode, __u32 uid, __u32 gid)
1634 {
1635         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_FILE, parent, name, mode,
1636                                 uid, gid, NULL, NULL, 0);
1637 }
1638
1639 yaffs_Object *yaffs_MknodDirectory(yaffs_Object *parent, const YCHAR *name,
1640                                 __u32 mode, __u32 uid, __u32 gid)
1641 {
1642         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_DIRECTORY, parent, name,
1643                                  mode, uid, gid, NULL, NULL, 0);
1644 }
1645
1646 yaffs_Object *yaffs_MknodSpecial(yaffs_Object *parent, const YCHAR *name,
1647                                 __u32 mode, __u32 uid, __u32 gid, __u32 rdev)
1648 {
1649         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SPECIAL, parent, name, mode,
1650                                  uid, gid, NULL, NULL, rdev);
1651 }
1652
1653 yaffs_Object *yaffs_MknodSymLink(yaffs_Object *parent, const YCHAR *name,
1654                                 __u32 mode, __u32 uid, __u32 gid,
1655                                 const YCHAR *alias)
1656 {
1657         return yaffs_MknodObject(YAFFS_OBJECT_TYPE_SYMLINK, parent, name, mode,
1658                                 uid, gid, NULL, alias, 0);
1659 }
1660
1661 /* yaffs_Link returns the object id of the equivalent object.*/
1662 yaffs_Object *yaffs_Link(yaffs_Object *parent, const YCHAR *name,
1663                         yaffs_Object *equivalentObject)
1664 {
1665         /* Get the real object in case we were fed a hard link as an equivalent object */
1666         equivalentObject = yaffs_GetEquivalentObject(equivalentObject);
1667
1668         if (yaffs_MknodObject
1669             (YAFFS_OBJECT_TYPE_HARDLINK, parent, name, 0, 0, 0,
1670              equivalentObject, NULL, 0)) {
1671                 return equivalentObject;
1672         } else {
1673                 return NULL;
1674         }
1675
1676 }
1677
1678 static int yaffs_ChangeObjectName(yaffs_Object *obj, yaffs_Object *newDir,
1679                                 const YCHAR *newName, int force, int shadows)
1680 {
1681         int unlinkOp;
1682         int deleteOp;
1683
1684         yaffs_Object *existingTarget;
1685
1686         if (newDir == NULL)
1687                 newDir = obj->parent;   /* use the old directory */
1688
1689         if (newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
1690                 T(YAFFS_TRACE_ALWAYS,
1691                   (TSTR
1692                    ("tragedy: yaffs_ChangeObjectName: newDir is not a directory"
1693                     TENDSTR)));
1694                 YBUG();
1695         }
1696
1697         /* TODO: Do we need this different handling for YAFFS2 and YAFFS1?? */
1698         if (obj->myDev->param.isYaffs2)
1699                 unlinkOp = (newDir == obj->myDev->unlinkedDir);
1700         else
1701                 unlinkOp = (newDir == obj->myDev->unlinkedDir
1702                             && obj->variantType == YAFFS_OBJECT_TYPE_FILE);
1703
1704         deleteOp = (newDir == obj->myDev->deletedDir);
1705
1706         existingTarget = yaffs_FindObjectByName(newDir, newName);
1707
1708         /* If the object is a file going into the unlinked directory,
1709          *   then it is OK to just stuff it in since duplicate names are allowed.
1710          *   else only proceed if the new name does not exist and if we're putting
1711          *   it into a directory.
1712          */
1713         if ((unlinkOp ||
1714              deleteOp ||
1715              force ||
1716              (shadows > 0) ||
1717              !existingTarget) &&
1718             newDir->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
1719                 yaffs_SetObjectName(obj, newName);
1720                 obj->dirty = 1;
1721
1722                 yaffs_AddObjectToDirectory(newDir, obj);
1723
1724                 if (unlinkOp)
1725                         obj->unlinked = 1;
1726
1727                 /* If it is a deletion then we mark it as a shrink for gc purposes. */
1728                 if (yaffs_UpdateObjectHeader(obj, newName, 0, deleteOp, shadows, NULL) >= 0)
1729                         return YAFFS_OK;
1730         }
1731
1732         return YAFFS_FAIL;
1733 }
1734
1735 int yaffs_RenameObject(yaffs_Object *oldDir, const YCHAR *oldName,
1736                 yaffs_Object *newDir, const YCHAR *newName)
1737 {
1738         yaffs_Object *obj = NULL;
1739         yaffs_Object *existingTarget = NULL;
1740         int force = 0;
1741         int result;
1742         yaffs_Device *dev;
1743
1744
1745         if (!oldDir || oldDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
1746                 YBUG();
1747         if (!newDir || newDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
1748                 YBUG();
1749
1750         dev = oldDir->myDev;
1751
1752 #ifdef CONFIG_YAFFS_CASE_INSENSITIVE
1753         /* Special case for case insemsitive systems (eg. WinCE).
1754          * While look-up is case insensitive, the name isn't.
1755          * Therefore we might want to change x.txt to X.txt
1756         */
1757         if (oldDir == newDir && yaffs_strcmp(oldName, newName) == 0)
1758                 force = 1;
1759 #endif
1760
1761         if(yaffs_strnlen(newName,YAFFS_MAX_NAME_LENGTH+1) > YAFFS_MAX_NAME_LENGTH)
1762                 /* ENAMETOOLONG */
1763                 return YAFFS_FAIL;
1764
1765         obj = yaffs_FindObjectByName(oldDir, oldName);
1766
1767         if (obj && obj->renameAllowed) {
1768
1769                 /* Now do the handling for an existing target, if there is one */
1770
1771                 existingTarget = yaffs_FindObjectByName(newDir, newName);
1772                 if (existingTarget &&
1773                         existingTarget->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
1774                         !ylist_empty(&existingTarget->variant.directoryVariant.children)) {
1775                         /* There is a target that is a non-empty directory, so we fail */
1776                         return YAFFS_FAIL;      /* EEXIST or ENOTEMPTY */
1777                 } else if (existingTarget && existingTarget != obj) {
1778                         /* Nuke the target first, using shadowing,
1779                          * but only if it isn't the same object.
1780                          *
1781                          * Note we must disable gc otherwise it can mess up the shadowing.
1782                          *
1783                          */
1784                         dev->gcDisable=1;
1785                         yaffs_ChangeObjectName(obj, newDir, newName, force,
1786                                                 existingTarget->objectId);
1787                         existingTarget->isShadowed = 1;
1788                         yaffs_UnlinkObject(existingTarget);
1789                         dev->gcDisable=0;
1790                 }
1791
1792                 result = yaffs_ChangeObjectName(obj, newDir, newName, 1, 0);
1793
1794                 yaffs_UpdateParent(oldDir);
1795                 if(newDir != oldDir)
1796                         yaffs_UpdateParent(newDir);
1797                 
1798                 return result;
1799         }
1800         return YAFFS_FAIL;
1801 }
1802
1803 /*------------------------- Block Management and Page Allocation ----------------*/
1804
1805 static int yaffs_InitialiseBlocks(yaffs_Device *dev)
1806 {
1807         int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
1808
1809         dev->blockInfo = NULL;
1810         dev->chunkBits = NULL;
1811
1812         dev->allocationBlock = -1;      /* force it to get a new one */
1813
1814         /* If the first allocation strategy fails, thry the alternate one */
1815         dev->blockInfo = YMALLOC(nBlocks * sizeof(yaffs_BlockInfo));
1816         if (!dev->blockInfo) {
1817                 dev->blockInfo = YMALLOC_ALT(nBlocks * sizeof(yaffs_BlockInfo));
1818                 dev->blockInfoAlt = 1;
1819         } else
1820                 dev->blockInfoAlt = 0;
1821
1822         if (dev->blockInfo) {
1823                 /* Set up dynamic blockinfo stuff. */
1824                 dev->chunkBitmapStride = (dev->param.nChunksPerBlock + 7) / 8; /* round up bytes */
1825                 dev->chunkBits = YMALLOC(dev->chunkBitmapStride * nBlocks);
1826                 if (!dev->chunkBits) {
1827                         dev->chunkBits = YMALLOC_ALT(dev->chunkBitmapStride * nBlocks);
1828                         dev->chunkBitsAlt = 1;
1829                 } else
1830                         dev->chunkBitsAlt = 0;
1831         }
1832
1833         if (dev->blockInfo && dev->chunkBits) {
1834                 memset(dev->blockInfo, 0, nBlocks * sizeof(yaffs_BlockInfo));
1835                 memset(dev->chunkBits, 0, dev->chunkBitmapStride * nBlocks);
1836                 return YAFFS_OK;
1837         }
1838
1839         return YAFFS_FAIL;
1840 }
1841
1842 static void yaffs_DeinitialiseBlocks(yaffs_Device *dev)
1843 {
1844         if (dev->blockInfoAlt && dev->blockInfo)
1845                 YFREE_ALT(dev->blockInfo);
1846         else if (dev->blockInfo)
1847                 YFREE(dev->blockInfo);
1848
1849         dev->blockInfoAlt = 0;
1850
1851         dev->blockInfo = NULL;
1852
1853         if (dev->chunkBitsAlt && dev->chunkBits)
1854                 YFREE_ALT(dev->chunkBits);
1855         else if (dev->chunkBits)
1856                 YFREE(dev->chunkBits);
1857         dev->chunkBitsAlt = 0;
1858         dev->chunkBits = NULL;
1859 }
1860
1861 void yaffs_BlockBecameDirty(yaffs_Device *dev, int blockNo)
1862 {
1863         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, blockNo);
1864
1865         int erasedOk = 0;
1866
1867         /* If the block is still healthy erase it and mark as clean.
1868          * If the block has had a data failure, then retire it.
1869          */
1870
1871         T(YAFFS_TRACE_GC | YAFFS_TRACE_ERASE,
1872                 (TSTR("yaffs_BlockBecameDirty block %d state %d %s"TENDSTR),
1873                 blockNo, bi->blockState, (bi->needsRetiring) ? "needs retiring" : ""));
1874
1875         yaffs2_ClearOldestDirtySequence(dev,bi);
1876
1877         bi->blockState = YAFFS_BLOCK_STATE_DIRTY;
1878
1879         /* If this is the block being garbage collected then stop gc'ing this block */
1880         if(blockNo == dev->gcBlock)
1881                 dev->gcBlock = 0;
1882
1883         /* If this block is currently the best candidate for gc then drop as a candidate */
1884         if(blockNo == dev->gcDirtiest){
1885                 dev->gcDirtiest = 0;
1886                 dev->gcPagesInUse = 0;
1887         }
1888
1889         if (!bi->needsRetiring) {
1890                 yaffs2_InvalidateCheckpoint(dev);
1891                 erasedOk = yaffs_EraseBlockInNAND(dev, blockNo);
1892                 if (!erasedOk) {
1893                         dev->nErasureFailures++;
1894                         T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1895                           (TSTR("**>> Erasure failed %d" TENDSTR), blockNo));
1896                 }
1897         }
1898
1899         if (erasedOk &&
1900             ((yaffs_traceMask & YAFFS_TRACE_ERASE) || !yaffs_SkipVerification(dev))) {
1901                 int i;
1902                 for (i = 0; i < dev->param.nChunksPerBlock; i++) {
1903                         if (!yaffs_CheckChunkErased
1904                             (dev, blockNo * dev->param.nChunksPerBlock + i)) {
1905                                 T(YAFFS_TRACE_ERROR,
1906                                   (TSTR
1907                                    (">>Block %d erasure supposedly OK, but chunk %d not erased"
1908                                     TENDSTR), blockNo, i));
1909                         }
1910                 }
1911         }
1912
1913         if (erasedOk) {
1914                 /* Clean it up... */
1915                 bi->blockState = YAFFS_BLOCK_STATE_EMPTY;
1916                 bi->sequenceNumber = 0;
1917                 dev->nErasedBlocks++;
1918                 bi->pagesInUse = 0;
1919                 bi->softDeletions = 0;
1920                 bi->hasShrinkHeader = 0;
1921                 bi->skipErasedCheck = 1;  /* This is clean, so no need to check */
1922                 bi->gcPrioritise = 0;
1923                 yaffs_ClearChunkBits(dev, blockNo);
1924
1925                 T(YAFFS_TRACE_ERASE,
1926                   (TSTR("Erased block %d" TENDSTR), blockNo));
1927         } else {
1928                 dev->nFreeChunks -= dev->param.nChunksPerBlock; /* We lost a block of free space */
1929
1930                 yaffs_RetireBlock(dev, blockNo);
1931                 T(YAFFS_TRACE_ERROR | YAFFS_TRACE_BAD_BLOCKS,
1932                   (TSTR("**>> Block %d retired" TENDSTR), blockNo));
1933         }
1934 }
1935
1936 static int yaffs_FindBlockForAllocation(yaffs_Device *dev)
1937 {
1938         int i;
1939
1940         yaffs_BlockInfo *bi;
1941
1942         if (dev->nErasedBlocks < 1) {
1943                 /* Hoosterman we've got a problem.
1944                  * Can't get space to gc
1945                  */
1946                 T(YAFFS_TRACE_ERROR,
1947                   (TSTR("yaffs tragedy: no more erased blocks" TENDSTR)));
1948
1949                 return -1;
1950         }
1951
1952         /* Find an empty block. */
1953
1954         for (i = dev->internalStartBlock; i <= dev->internalEndBlock; i++) {
1955                 dev->allocationBlockFinder++;
1956                 if (dev->allocationBlockFinder < dev->internalStartBlock
1957                     || dev->allocationBlockFinder > dev->internalEndBlock) {
1958                         dev->allocationBlockFinder = dev->internalStartBlock;
1959                 }
1960
1961                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlockFinder);
1962
1963                 if (bi->blockState == YAFFS_BLOCK_STATE_EMPTY) {
1964                         bi->blockState = YAFFS_BLOCK_STATE_ALLOCATING;
1965                         dev->sequenceNumber++;
1966                         bi->sequenceNumber = dev->sequenceNumber;
1967                         dev->nErasedBlocks--;
1968                         T(YAFFS_TRACE_ALLOCATE,
1969                           (TSTR("Allocated block %d, seq  %d, %d left" TENDSTR),
1970                            dev->allocationBlockFinder, dev->sequenceNumber,
1971                            dev->nErasedBlocks));
1972                         return dev->allocationBlockFinder;
1973                 }
1974         }
1975
1976         T(YAFFS_TRACE_ALWAYS,
1977           (TSTR
1978            ("yaffs tragedy: no more erased blocks, but there should have been %d"
1979             TENDSTR), dev->nErasedBlocks));
1980
1981         return -1;
1982 }
1983
1984
1985 /*
1986  * Check if there's space to allocate...
1987  * Thinks.... do we need top make this ths same as yaffs_GetFreeChunks()?
1988  */
1989 int yaffs_CheckSpaceForAllocation(yaffs_Device *dev, int nChunks)
1990 {
1991         int reservedChunks;
1992         int reservedBlocks = dev->param.nReservedBlocks;
1993         int checkpointBlocks;
1994
1995         checkpointBlocks = yaffs2_CalcCheckpointBlocksRequired(dev);
1996
1997         reservedChunks = ((reservedBlocks + checkpointBlocks) * dev->param.nChunksPerBlock);
1998
1999         return (dev->nFreeChunks > (reservedChunks + nChunks));
2000 }
2001
2002 static int yaffs_AllocateChunk(yaffs_Device *dev, int useReserve,
2003                 yaffs_BlockInfo **blockUsedPtr)
2004 {
2005         int retVal;
2006         yaffs_BlockInfo *bi;
2007
2008         if (dev->allocationBlock < 0) {
2009                 /* Get next block to allocate off */
2010                 dev->allocationBlock = yaffs_FindBlockForAllocation(dev);
2011                 dev->allocationPage = 0;
2012         }
2013
2014         if (!useReserve && !yaffs_CheckSpaceForAllocation(dev, 1)) {
2015                 /* Not enough space to allocate unless we're allowed to use the reserve. */
2016                 return -1;
2017         }
2018
2019         if (dev->nErasedBlocks < dev->param.nReservedBlocks
2020                         && dev->allocationPage == 0) {
2021                 T(YAFFS_TRACE_ALLOCATE, (TSTR("Allocating reserve" TENDSTR)));
2022         }
2023
2024         /* Next page please.... */
2025         if (dev->allocationBlock >= 0) {
2026                 bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2027
2028                 retVal = (dev->allocationBlock * dev->param.nChunksPerBlock) +
2029                         dev->allocationPage;
2030                 bi->pagesInUse++;
2031                 yaffs_SetChunkBit(dev, dev->allocationBlock,
2032                                 dev->allocationPage);
2033
2034                 dev->allocationPage++;
2035
2036                 dev->nFreeChunks--;
2037
2038                 /* If the block is full set the state to full */
2039                 if (dev->allocationPage >= dev->param.nChunksPerBlock) {
2040                         bi->blockState = YAFFS_BLOCK_STATE_FULL;
2041                         dev->allocationBlock = -1;
2042                 }
2043
2044                 if (blockUsedPtr)
2045                         *blockUsedPtr = bi;
2046
2047                 return retVal;
2048         }
2049
2050         T(YAFFS_TRACE_ERROR,
2051                         (TSTR("!!!!!!!!! Allocator out !!!!!!!!!!!!!!!!!" TENDSTR)));
2052
2053         return -1;
2054 }
2055
2056 static int yaffs_GetErasedChunks(yaffs_Device *dev)
2057 {
2058         int n;
2059
2060         n = dev->nErasedBlocks * dev->param.nChunksPerBlock;
2061
2062         if (dev->allocationBlock > 0)
2063                 n += (dev->param.nChunksPerBlock - dev->allocationPage);
2064
2065         return n;
2066
2067 }
2068
2069 /*
2070  * yaffs_SkipRestOfBlock() skips over the rest of the allocation block
2071  * if we don't want to write to it.
2072  */
2073 void yaffs_SkipRestOfBlock(yaffs_Device *dev)
2074 {
2075         if(dev->allocationBlock > 0){
2076                 yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, dev->allocationBlock);
2077                 if(bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING){
2078                         bi->blockState = YAFFS_BLOCK_STATE_FULL;
2079                         dev->allocationBlock = -1;
2080                 }
2081         }
2082 }
2083
2084
2085 static int yaffs_GarbageCollectBlock(yaffs_Device *dev, int block,
2086                 int wholeBlock)
2087 {
2088         int oldChunk;
2089         int newChunk;
2090         int markNAND;
2091         int retVal = YAFFS_OK;
2092         int cleanups = 0;
2093         int i;
2094         int isCheckpointBlock;
2095         int matchingChunk;
2096         int maxCopies;
2097
2098         int chunksBefore = yaffs_GetErasedChunks(dev);
2099         int chunksAfter;
2100
2101         yaffs_ExtendedTags tags;
2102
2103         yaffs_BlockInfo *bi = yaffs_GetBlockInfo(dev, block);
2104
2105         yaffs_Object *object;
2106
2107         isCheckpointBlock = (bi->blockState == YAFFS_BLOCK_STATE_CHECKPOINT);
2108
2109
2110         T(YAFFS_TRACE_TRACING,
2111                         (TSTR("Collecting block %d, in use %d, shrink %d, wholeBlock %d" TENDSTR),
2112                          block,
2113                          bi->pagesInUse,
2114                          bi->hasShrinkHeader,
2115                          wholeBlock));
2116
2117         /*yaffs_VerifyFreeChunks(dev); */
2118
2119         if(bi->blockState == YAFFS_BLOCK_STATE_FULL)
2120                 bi->blockState = YAFFS_BLOCK_STATE_COLLECTING;
2121         
2122         bi->hasShrinkHeader = 0;        /* clear the flag so that the block can erase */
2123
2124         dev->gcDisable = 1;
2125
2126         if (isCheckpointBlock ||
2127                         !yaffs_StillSomeChunkBits(dev, block)) {
2128                 T(YAFFS_TRACE_TRACING,
2129                                 (TSTR
2130                                  ("Collecting block %d that has no chunks in use" TENDSTR),
2131                                  block));
2132                 yaffs_BlockBecameDirty(dev, block);
2133         } else {
2134
2135                 __u8 *buffer = yaffs_GetTempBuffer(dev, __LINE__);
2136
2137                 yaffs_VerifyBlock(dev, bi, block);
2138
2139                 maxCopies = (wholeBlock) ? dev->param.nChunksPerBlock : 5;
2140                 oldChunk = block * dev->param.nChunksPerBlock + dev->gcChunk;
2141
2142                 for (/* init already done */;
2143                      retVal == YAFFS_OK &&
2144                      dev->gcChunk < dev->param.nChunksPerBlock &&
2145                      (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) &&
2146                      maxCopies > 0;
2147                      dev->gcChunk++, oldChunk++) {
2148                         if (yaffs_CheckChunkBit(dev, block, dev->gcChunk)) {
2149
2150                                 /* This page is in use and might need to be copied off */
2151
2152                                 maxCopies--;
2153
2154                                 markNAND = 1;
2155
2156                                 yaffs_InitialiseTags(&tags);
2157
2158                                 yaffs_ReadChunkWithTagsFromNAND(dev, oldChunk,
2159                                                                 buffer, &tags);
2160
2161                                 object =
2162                                     yaffs_FindObjectByNumber(dev,
2163                                                              tags.objectId);
2164
2165                                 T(YAFFS_TRACE_GC_DETAIL,
2166                                   (TSTR
2167                                    ("Collecting chunk in block %d, %d %d %d " TENDSTR),
2168                                    dev->gcChunk, tags.objectId, tags.chunkId,
2169                                    tags.byteCount));
2170
2171                                 if (object && !yaffs_SkipVerification(dev)) {
2172                                         if (tags.chunkId == 0)
2173                                                 matchingChunk = object->hdrChunk;
2174                                         else if (object->softDeleted)
2175                                                 matchingChunk = oldChunk; /* Defeat the test */
2176                                         else
2177                                                 matchingChunk = yaffs_FindChunkInFile(object, tags.chunkId, NULL);
2178
2179                                         if (oldChunk != matchingChunk)
2180                                                 T(YAFFS_TRACE_ERROR,
2181                                                   (TSTR("gc: page in gc mismatch: %d %d %d %d"TENDSTR),
2182                                                   oldChunk, matchingChunk, tags.objectId, tags.chunkId));
2183
2184                                 }
2185
2186                                 if (!object) {
2187                                         T(YAFFS_TRACE_ERROR,
2188                                           (TSTR
2189                                            ("page %d in gc has no object: %d %d %d "
2190                                             TENDSTR), oldChunk,
2191                                             tags.objectId, tags.chunkId, tags.byteCount));
2192                                 }
2193
2194                                 if (object &&
2195                                     object->deleted &&
2196                                     object->softDeleted &&
2197                                     tags.chunkId != 0) {
2198                                         /* Data chunk in a soft deleted file, throw it away
2199                                          * It's a soft deleted data chunk,
2200                                          * No need to copy this, just forget about it and
2201                                          * fix up the object.
2202                                          */
2203                                          
2204                                         /* Free chunks already includes softdeleted chunks.
2205                                          * How ever this chunk is going to soon be really deleted
2206                                          * which will increment free chunks.
2207                                          * We have to decrement free chunks so this works out properly.
2208                                          */
2209                                         dev->nFreeChunks--;
2210
2211                                         object->nDataChunks--;
2212
2213                                         if (object->nDataChunks <= 0) {
2214                                                 /* remeber to clean up the object */
2215                                                 dev->gcCleanupList[cleanups] =
2216                                                     tags.objectId;
2217                                                 cleanups++;
2218                                         }
2219                                         markNAND = 0;
2220                                 } else if (0) {
2221                                         /* Todo object && object->deleted && object->nDataChunks == 0 */
2222                                         /* Deleted object header with no data chunks.
2223                                          * Can be discarded and the file deleted.
2224                                          */
2225                                         object->hdrChunk = 0;
2226                                         yaffs_FreeTnode(object->myDev,
2227                                                         object->variant.
2228                                                         fileVariant.top);
2229                                         object->variant.fileVariant.top = NULL;
2230                                         yaffs_DoGenericObjectDeletion(object);
2231
2232                                 } else if (object) {
2233                                         /* It's either a data chunk in a live file or
2234                                          * an ObjectHeader, so we're interested in it.
2235                                          * NB Need to keep the ObjectHeaders of deleted files
2236                                          * until the whole file has been deleted off
2237                                          */
2238                                         tags.serialNumber++;
2239
2240                                         dev->nGCCopies++;
2241
2242                                         if (tags.chunkId == 0) {
2243                                                 /* It is an object Id,
2244                                                  * We need to nuke the shrinkheader flags first
2245                                                  * Also need to clean up shadowing.
2246                                                  * We no longer want the shrinkHeader flag since its work is done
2247                                                  * and if it is left in place it will mess up scanning.
2248                                                  */
2249
2250                                                 yaffs_ObjectHeader *oh;
2251                                                 oh = (yaffs_ObjectHeader *)buffer;
2252
2253                                                 oh->isShrink = 0;
2254                                                 tags.extraIsShrinkHeader = 0;
2255
2256                                                 oh->shadowsObject = 0;
2257                                                 oh->inbandShadowsObject = 0;
2258                                                 tags.extraShadows = 0;
2259
2260                                                 /* Update file size */
2261                                                 if(object->variantType == YAFFS_OBJECT_TYPE_FILE){
2262                                                         oh->fileSize = object->variant.fileVariant.fileSize;
2263                                                         tags.extraFileLength = oh->fileSize;
2264                                                 }
2265
2266                                                 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
2267                                                 newChunk =
2268                                                     yaffs_WriteNewChunkWithTagsToNAND(dev,(__u8 *) oh, &tags, 1);
2269                                         } else
2270                                                 newChunk =
2271                                                     yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
2272
2273                                         if (newChunk < 0) {
2274                                                 retVal = YAFFS_FAIL;
2275                                         } else {
2276
2277                                                 /* Ok, now fix up the Tnodes etc. */
2278
2279                                                 if (tags.chunkId == 0) {
2280                                                         /* It's a header */
2281                                                         object->hdrChunk =  newChunk;
2282                                                         object->serial =   tags.serialNumber;
2283                                                 } else {
2284                                                         /* It's a data chunk */
2285                                                         int ok;
2286                                                         ok = yaffs_PutChunkIntoFile
2287                                                             (object,
2288                                                              tags.chunkId,
2289                                                              newChunk, 0);
2290                                                 }
2291                                         }
2292                                 }
2293
2294                                 if (retVal == YAFFS_OK)
2295                                         yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
2296
2297                         }
2298                 }
2299
2300                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2301
2302
2303                 /* Do any required cleanups */
2304                 for (i = 0; i < cleanups; i++) {
2305                         /* Time to delete the file too */
2306                         object =
2307                             yaffs_FindObjectByNumber(dev,
2308                                                      dev->gcCleanupList[i]);
2309                         if (object) {
2310                                 yaffs_FreeTnode(dev,
2311                                                 object->variant.fileVariant.
2312                                                 top);
2313                                 object->variant.fileVariant.top = NULL;
2314                                 T(YAFFS_TRACE_GC,
2315                                   (TSTR
2316                                    ("yaffs: About to finally delete object %d"
2317                                     TENDSTR), object->objectId));
2318                                 yaffs_DoGenericObjectDeletion(object);
2319                                 object->myDev->nDeletedFiles--;
2320                         }
2321
2322                 }
2323
2324         }
2325
2326         yaffs_VerifyCollectedBlock(dev, bi, block);
2327
2328
2329
2330         if (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2331                 /*
2332                  * The gc did not complete. Set block state back to FULL
2333                  * because checkpointing does not restore gc.
2334                  */
2335                 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2336         } else {
2337                 /* The gc completed. */
2338                 chunksAfter = yaffs_GetErasedChunks(dev);
2339                 if (chunksBefore >= chunksAfter) {
2340                         T(YAFFS_TRACE_GC,
2341                           (TSTR
2342                            ("gc did not increase free chunks before %d after %d"
2343                             TENDSTR), chunksBefore, chunksAfter));
2344                 }
2345                 dev->gcBlock = 0;
2346                 dev->gcChunk = 0;
2347         }
2348
2349         dev->gcDisable = 0;
2350
2351         return retVal;
2352 }
2353
2354 /*
2355  * FindBlockForgarbageCollection is used to select the dirtiest block (or close enough)
2356  * for garbage collection.
2357  */
2358
2359 static unsigned yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
2360                                         int aggressive,
2361                                         int background)
2362 {
2363         int i;
2364         int iterations;
2365         unsigned selected = 0;
2366         int prioritised = 0;
2367         int prioritisedExists = 0;
2368         yaffs_BlockInfo *bi;
2369         int threshold;
2370
2371         /* First let's see if we need to grab a prioritised block */
2372         if (dev->hasPendingPrioritisedGCs && !aggressive) {
2373                 dev->gcDirtiest = 0;
2374                 bi = dev->blockInfo;
2375                 for (i = dev->internalStartBlock;
2376                         i <= dev->internalEndBlock && !selected;
2377                         i++) {
2378
2379                         if (bi->gcPrioritise) {
2380                                 prioritisedExists = 1;
2381                                 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2382                                    yaffs2_BlockNotDisqualifiedFromGC(dev, bi)) {
2383                                         selected = i;
2384                                         prioritised = 1;
2385                                 }
2386                         }
2387                         bi++;
2388                 }
2389
2390                 /*
2391                  * If there is a prioritised block and none was selected then
2392                  * this happened because there is at least one old dirty block gumming
2393                  * up the works. Let's gc the oldest dirty block.
2394                  */
2395
2396                 if(prioritisedExists &&
2397                         !selected &&
2398                         dev->oldestDirtyBlock > 0)
2399                         selected = dev->oldestDirtyBlock;
2400
2401                 if (!prioritisedExists) /* None found, so we can clear this */
2402                         dev->hasPendingPrioritisedGCs = 0;
2403         }
2404
2405         /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2406          * search harder.
2407          * else (we're doing a leasurely gc), then we only bother to do this if the
2408          * block has only a few pages in use.
2409          */
2410
2411         if (!selected){
2412                 int pagesUsed;
2413                 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2414                 if (aggressive){
2415                         threshold = dev->param.nChunksPerBlock;
2416                         iterations = nBlocks;
2417                 } else {
2418                         int maxThreshold = dev->param.nChunksPerBlock/2;
2419                         threshold = background ?
2420                                 (dev->gcNotDone + 2) * 2 : 0;
2421                         if(threshold <YAFFS_GC_PASSIVE_THRESHOLD)
2422                                 threshold = YAFFS_GC_PASSIVE_THRESHOLD;
2423                         if(threshold > maxThreshold)
2424                                 threshold = maxThreshold;
2425
2426                         iterations = nBlocks / 16 + 1;
2427                         if (iterations > 100)
2428                                 iterations = 100;
2429                 }
2430
2431                 for (i = 0;
2432                         i < iterations &&
2433                         (dev->gcDirtiest < 1 ||
2434                                 dev->gcPagesInUse > YAFFS_GC_GOOD_ENOUGH);
2435                         i++) {
2436                         dev->gcBlockFinder++;
2437                         if (dev->gcBlockFinder < dev->internalStartBlock ||
2438                                 dev->gcBlockFinder > dev->internalEndBlock)
2439                                 dev->gcBlockFinder = dev->internalStartBlock;
2440
2441                         bi = yaffs_GetBlockInfo(dev, dev->gcBlockFinder);
2442
2443                         pagesUsed = bi->pagesInUse - bi->softDeletions;
2444
2445                         if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2446                                 pagesUsed < dev->param.nChunksPerBlock &&
2447                                 (dev->gcDirtiest < 1 || pagesUsed < dev->gcPagesInUse) &&
2448                                 yaffs2_BlockNotDisqualifiedFromGC(dev, bi)) {
2449                                 dev->gcDirtiest = dev->gcBlockFinder;
2450                                 dev->gcPagesInUse = pagesUsed;
2451                         }
2452                 }
2453
2454                 if(dev->gcDirtiest > 0 && dev->gcPagesInUse <= threshold)
2455                         selected = dev->gcDirtiest;
2456         }
2457
2458         /*
2459          * If nothing has been selected for a while, try selecting the oldest dirty
2460          * because that's gumming up the works.
2461          */
2462
2463         if(!selected && dev->param.isYaffs2 &&
2464                 dev->gcNotDone >= ( background ? 10 : 20)){
2465                 yaffs2_FindOldestDirtySequence(dev);
2466                 if(dev->oldestDirtyBlock > 0) {
2467                         selected = dev->oldestDirtyBlock;
2468                         dev->gcDirtiest = selected;
2469                         dev->oldestDirtyGCs++;
2470                         bi = yaffs_GetBlockInfo(dev, selected);
2471                         dev->gcPagesInUse =  bi->pagesInUse - bi->softDeletions;
2472                 } else
2473                         dev->gcNotDone = 0;
2474         }
2475
2476         if(selected){
2477                 T(YAFFS_TRACE_GC,
2478                   (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR),
2479                   selected,
2480                   dev->param.nChunksPerBlock - dev->gcPagesInUse,
2481                   prioritised));
2482
2483                 if(background)
2484                         dev->backgroundGCs++;
2485                 dev->gcDirtiest = 0;
2486                 dev->gcPagesInUse = 0;
2487                 dev->gcNotDone = 0;
2488                 if(dev->refreshSkip > 0)
2489                         dev->refreshSkip--;
2490         } else{
2491                 dev->gcNotDone++;
2492                 T(YAFFS_TRACE_GC,
2493                   (TSTR("GC none: finder %d skip %d threshold %d dirtiest %d using %d oldest %d%s" TENDSTR),
2494                   dev->gcBlockFinder, dev->gcNotDone,
2495                   threshold,
2496                   dev->gcDirtiest, dev->gcPagesInUse,
2497                   dev->oldestDirtyBlock,
2498                   background ? " bg" : ""));
2499         }
2500
2501         return selected;
2502 }
2503
2504 /* New garbage collector
2505  * If we're very low on erased blocks then we do aggressive garbage collection
2506  * otherwise we do "leasurely" garbage collection.
2507  * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2508  * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2509  *
2510  * The idea is to help clear out space in a more spread-out manner.
2511  * Dunno if it really does anything useful.
2512  */
2513 static int yaffs_CheckGarbageCollection(yaffs_Device *dev, int background)
2514 {
2515         int aggressive = 0;
2516         int gcOk = YAFFS_OK;
2517         int maxTries = 0;
2518
2519         int minErased;
2520         int erasedChunks;
2521
2522         int checkpointBlockAdjust;
2523
2524         if(dev->param.gcControl &&
2525                 (dev->param.gcControl(dev) & 1) == 0)
2526                 return YAFFS_OK;
2527
2528         if (dev->gcDisable) {
2529                 /* Bail out so we don't get recursive gc */
2530                 return YAFFS_OK;
2531         }
2532
2533         /* This loop should pass the first time.
2534          * We'll only see looping here if the collection does not increase space.
2535          */
2536
2537         do {
2538                 maxTries++;
2539
2540                 checkpointBlockAdjust = yaffs2_CalcCheckpointBlocksRequired(dev);
2541
2542                 minErased  = dev->param.nReservedBlocks + checkpointBlockAdjust + 1;
2543                 erasedChunks = dev->nErasedBlocks * dev->param.nChunksPerBlock;
2544
2545                 /* If we need a block soon then do aggressive gc.*/
2546                 if (dev->nErasedBlocks < minErased)
2547                         aggressive = 1;
2548                 else {
2549                         if(dev->gcSkip > 20)
2550                                 dev->gcSkip = 20;
2551                         if(erasedChunks < dev->nFreeChunks/2 ||
2552                                 dev->gcSkip < 1 ||
2553                                 background)
2554                                 aggressive = 0;
2555                         else {
2556                                 dev->gcSkip--;
2557                                 break;
2558                         }
2559                 }
2560
2561                 dev->gcSkip = 5;
2562
2563                 /* If we don't already have a block being gc'd then see if we should start another */
2564
2565                 if (dev->gcBlock < 1 && !aggressive) {
2566                         dev->gcBlock = yaffs2_FindRefreshBlock(dev);
2567                         dev->gcChunk = 0;
2568                 }
2569                 if (dev->gcBlock < 1) {
2570                         dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive, background);
2571                         dev->gcChunk = 0;
2572                 }
2573
2574                 if (dev->gcBlock > 0) {
2575                         dev->allGCs++;
2576                         if (!aggressive)
2577                                 dev->passiveGCs++;
2578
2579                         T(YAFFS_TRACE_GC,
2580                           (TSTR
2581                            ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
2582                            dev->nErasedBlocks, aggressive));
2583
2584                         gcOk = yaffs_GarbageCollectBlock(dev, dev->gcBlock, aggressive);
2585                 }
2586
2587                 if (dev->nErasedBlocks < (dev->param.nReservedBlocks) && dev->gcBlock > 0) {
2588                         T(YAFFS_TRACE_GC,
2589                           (TSTR
2590                            ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
2591                             TENDSTR), dev->nErasedBlocks, maxTries, dev->gcBlock));
2592                 }
2593         } while ((dev->nErasedBlocks < dev->param.nReservedBlocks) &&
2594                  (dev->gcBlock > 0) &&
2595                  (maxTries < 2));
2596
2597         return aggressive ? gcOk : YAFFS_OK;
2598 }
2599
2600 /*
2601  * yaffs_BackgroundGarbageCollect()
2602  * Garbage collects. Intended to be called from a background thread.
2603  * Returns non-zero if at least half the free chunks are erased.
2604  */
2605 int yaffs_BackgroundGarbageCollect(yaffs_Device *dev, unsigned urgency)
2606 {
2607         int erasedChunks = dev->nErasedBlocks * dev->param.nChunksPerBlock;
2608
2609         T(YAFFS_TRACE_BACKGROUND, (TSTR("Background gc %u" TENDSTR),urgency));
2610
2611         yaffs_CheckGarbageCollection(dev, 1);
2612         return erasedChunks > dev->nFreeChunks/2;
2613 }
2614
2615 /*-------------------------  TAGS --------------------------------*/
2616
2617 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
2618                            int chunkInObject)
2619 {
2620         return (tags->chunkId == chunkInObject &&
2621                 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
2622
2623 }
2624
2625
2626 /*-------------------- Data file manipulation -----------------*/
2627
2628 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
2629                                  yaffs_ExtendedTags *tags)
2630 {
2631         /*Get the Tnode, then get the level 0 offset chunk offset */
2632         yaffs_Tnode *tn;
2633         int theChunk = -1;
2634         yaffs_ExtendedTags localTags;
2635         int retVal = -1;
2636
2637         yaffs_Device *dev = in->myDev;
2638
2639         if (!tags) {
2640                 /* Passed a NULL, so use our own tags space */
2641                 tags = &localTags;
2642         }
2643
2644         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2645
2646         if (tn) {
2647                 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
2648
2649                 retVal =
2650                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2651                                            chunkInInode);
2652         }
2653         return retVal;
2654 }
2655
2656 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
2657                                           yaffs_ExtendedTags *tags)
2658 {
2659         /* Get the Tnode, then get the level 0 offset chunk offset */
2660         yaffs_Tnode *tn;
2661         int theChunk = -1;
2662         yaffs_ExtendedTags localTags;
2663
2664         yaffs_Device *dev = in->myDev;
2665         int retVal = -1;
2666
2667         if (!tags) {
2668                 /* Passed a NULL, so use our own tags space */
2669                 tags = &localTags;
2670         }
2671
2672         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2673
2674         if (tn) {
2675
2676                 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
2677
2678                 retVal =
2679                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2680                                            chunkInInode);
2681
2682                 /* Delete the entry in the filestructure (if found) */
2683                 if (retVal != -1)
2684                         yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, 0);
2685         }
2686
2687         return retVal;
2688 }
2689
2690
2691 int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
2692                                 int chunkInNAND, int inScan)
2693 {
2694         /* NB inScan is zero unless scanning.
2695          * For forward scanning, inScan is > 0;
2696          * for backward scanning inScan is < 0
2697          *
2698          * chunkInNAND = 0 is a dummy insert to make sure the tnodes are there.
2699          */
2700
2701         yaffs_Tnode *tn;
2702         yaffs_Device *dev = in->myDev;
2703         int existingChunk;
2704         yaffs_ExtendedTags existingTags;
2705         yaffs_ExtendedTags newTags;
2706         unsigned existingSerial, newSerial;
2707
2708         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2709                 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2710                  * If it is not during Scanning then something went wrong!
2711                  */
2712                 if (!inScan) {
2713                         T(YAFFS_TRACE_ERROR,
2714                           (TSTR
2715                            ("yaffs tragedy:attempt to put data chunk into a non-file"
2716                             TENDSTR)));
2717                         YBUG();
2718                 }
2719
2720                 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
2721                 return YAFFS_OK;
2722         }
2723
2724         tn = yaffs_AddOrFindLevel0Tnode(dev,
2725                                         &in->variant.fileVariant,
2726                                         chunkInInode,
2727                                         NULL);
2728         if (!tn)
2729                 return YAFFS_FAIL;
2730         
2731         if(!chunkInNAND)
2732                 /* Dummy insert, bail now */
2733                 return YAFFS_OK;
2734
2735         existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
2736
2737         if (inScan != 0) {
2738                 /* If we're scanning then we need to test for duplicates
2739                  * NB This does not need to be efficient since it should only ever
2740                  * happen when the power fails during a write, then only one
2741                  * chunk should ever be affected.
2742                  *
2743                  * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2744                  * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2745                  */
2746
2747                 if (existingChunk > 0) {
2748                         /* NB Right now existing chunk will not be real chunkId if the chunk group size > 1
2749                          *    thus we have to do a FindChunkInFile to get the real chunk id.
2750                          *
2751                          * We have a duplicate now we need to decide which one to use:
2752                          *
2753                          * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2754                          * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2755                          * YAFFS1: Get both sets of tags and compare serial numbers.
2756                          */
2757
2758                         if (inScan > 0) {
2759                                 /* Only do this for forward scanning */
2760                                 yaffs_ReadChunkWithTagsFromNAND(dev,
2761                                                                 chunkInNAND,
2762                                                                 NULL, &newTags);
2763
2764                                 /* Do a proper find */
2765                                 existingChunk =
2766                                     yaffs_FindChunkInFile(in, chunkInInode,
2767                                                           &existingTags);
2768                         }
2769
2770                         if (existingChunk <= 0) {
2771                                 /*Hoosterman - how did this happen? */
2772
2773                                 T(YAFFS_TRACE_ERROR,
2774                                   (TSTR
2775                                    ("yaffs tragedy: existing chunk < 0 in scan"
2776                                     TENDSTR)));
2777
2778                         }
2779
2780                         /* NB The deleted flags should be false, otherwise the chunks will
2781                          * not be loaded during a scan
2782                          */
2783
2784                         if (inScan > 0) {
2785                                 newSerial = newTags.serialNumber;
2786                                 existingSerial = existingTags.serialNumber;
2787                         }
2788
2789                         if ((inScan > 0) &&
2790                             (existingChunk <= 0 ||
2791                              ((existingSerial + 1) & 3) == newSerial)) {
2792                                 /* Forward scanning.
2793                                  * Use new
2794                                  * Delete the old one and drop through to update the tnode
2795                                  */
2796                                 yaffs_DeleteChunk(dev, existingChunk, 1,
2797                                                   __LINE__);
2798                         } else {
2799                                 /* Backward scanning or we want to use the existing one
2800                                  * Use existing.
2801                                  * Delete the new one and return early so that the tnode isn't changed
2802                                  */
2803                                 yaffs_DeleteChunk(dev, chunkInNAND, 1,
2804                                                   __LINE__);
2805                                 return YAFFS_OK;
2806                         }
2807                 }
2808
2809         }
2810
2811         if (existingChunk == 0)
2812                 in->nDataChunks++;
2813
2814         yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
2815
2816         return YAFFS_OK;
2817 }
2818
2819 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
2820                                         __u8 *buffer)
2821 {
2822         int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
2823
2824         if (chunkInNAND >= 0)
2825                 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
2826                                                 buffer, NULL);
2827         else {
2828                 T(YAFFS_TRACE_NANDACCESS,
2829                   (TSTR("Chunk %d not found zero instead" TENDSTR),
2830                    chunkInNAND));
2831                 /* get sane (zero) data if you read a hole */
2832                 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
2833                 return 0;
2834         }
2835
2836 }
2837
2838 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
2839 {
2840         int block;
2841         int page;
2842         yaffs_ExtendedTags tags;
2843         yaffs_BlockInfo *bi;
2844
2845         if (chunkId <= 0)
2846                 return;
2847
2848         dev->nDeletions++;
2849         block = chunkId / dev->param.nChunksPerBlock;
2850         page = chunkId % dev->param.nChunksPerBlock;
2851
2852
2853         if (!yaffs_CheckChunkBit(dev, block, page))
2854                 T(YAFFS_TRACE_VERIFY,
2855                         (TSTR("Deleting invalid chunk %d"TENDSTR),
2856                          chunkId));
2857
2858         bi = yaffs_GetBlockInfo(dev, block);
2859         
2860         yaffs2_UpdateOldestDirtySequence(dev, block, bi);
2861
2862         T(YAFFS_TRACE_DELETION,
2863           (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
2864
2865         if (!dev->param.isYaffs2 && markNAND &&
2866             bi->blockState != YAFFS_BLOCK_STATE_COLLECTING) {
2867
2868                 yaffs_InitialiseTags(&tags);
2869
2870                 tags.chunkDeleted = 1;
2871
2872                 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
2873                 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
2874         } else {
2875                 dev->nUnmarkedDeletions++;
2876         }
2877
2878         /* Pull out of the management area.
2879          * If the whole block became dirty, this will kick off an erasure.
2880          */
2881         if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2882             bi->blockState == YAFFS_BLOCK_STATE_FULL ||
2883             bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2884             bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2885                 dev->nFreeChunks++;
2886
2887                 yaffs_ClearChunkBit(dev, block, page);
2888
2889                 bi->pagesInUse--;
2890
2891                 if (bi->pagesInUse == 0 &&
2892                     !bi->hasShrinkHeader &&
2893                     bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
2894                     bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2895                         yaffs_BlockBecameDirty(dev, block);
2896                 }
2897
2898         }
2899
2900 }
2901
2902 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
2903                                         const __u8 *buffer, int nBytes,
2904                                         int useReserve)
2905 {
2906         /* Find old chunk Need to do this to get serial number
2907          * Write new one and patch into tree.
2908          * Invalidate old tags.
2909          */
2910
2911         int prevChunkId;
2912         yaffs_ExtendedTags prevTags;
2913
2914         int newChunkId;
2915         yaffs_ExtendedTags newTags;
2916
2917         yaffs_Device *dev = in->myDev;
2918
2919         yaffs_CheckGarbageCollection(dev,0);
2920
2921         /* Get the previous chunk at this location in the file if it exists.
2922          * If it does not exist then put a zero into the tree. This creates
2923          * the tnode now, rather than later when it is harder to clean up.
2924          */
2925         prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
2926         if(prevChunkId < 1 &&
2927                 !yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0))
2928                 return 0;
2929
2930         /* Set up new tags */
2931         yaffs_InitialiseTags(&newTags);
2932
2933         newTags.chunkId = chunkInInode;
2934         newTags.objectId = in->objectId;
2935         newTags.serialNumber =
2936             (prevChunkId > 0) ? prevTags.serialNumber + 1 : 1;
2937         newTags.byteCount = nBytes;
2938
2939         if (nBytes < 1 || nBytes > dev->param.totalBytesPerChunk) {
2940                 T(YAFFS_TRACE_ERROR,
2941                 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
2942                 YBUG();
2943         }
2944         
2945                 
2946         newChunkId =
2947             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2948                                               useReserve);
2949
2950         if (newChunkId > 0) {
2951                 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
2952
2953                 if (prevChunkId > 0)
2954                         yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
2955
2956                 yaffs_VerifyFileSanity(in);
2957         }
2958         return newChunkId;
2959
2960 }
2961
2962 /* UpdateObjectHeader updates the header on NAND for an object.
2963  * If name is not NULL, then that new name is used.
2964  */
2965 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
2966                              int isShrink, int shadows, yaffs_XAttrMod *xmod)
2967 {
2968
2969         yaffs_BlockInfo *bi;
2970
2971         yaffs_Device *dev = in->myDev;
2972
2973         int prevChunkId;
2974         int retVal = 0;
2975         int result = 0;
2976
2977         int newChunkId;
2978         yaffs_ExtendedTags newTags;
2979         yaffs_ExtendedTags oldTags;
2980         YCHAR *alias = NULL;
2981
2982         __u8 *buffer = NULL;
2983         YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
2984
2985         yaffs_ObjectHeader *oh = NULL;
2986
2987         yaffs_strcpy(oldName, _Y("silly old name"));
2988
2989
2990         if (!in->fake ||
2991                 in == dev->rootDir || /* The rootDir should also be saved */
2992                 force  || xmod) {
2993
2994                 yaffs_CheckGarbageCollection(dev,0);
2995                 yaffs_CheckObjectDetailsLoaded(in);
2996
2997                 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
2998                 oh = (yaffs_ObjectHeader *) buffer;
2999
3000                 prevChunkId = in->hdrChunk;
3001
3002                 if (prevChunkId > 0) {
3003                         result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3004                                                         buffer, &oldTags);
3005
3006                         yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
3007
3008                         memcpy(oldName, oh->name, sizeof(oh->name));
3009                         memset(buffer, 0xFF, sizeof(yaffs_ObjectHeader));
3010                 } else
3011                         memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3012
3013                 oh->type = in->variantType;
3014                 oh->yst_mode = in->yst_mode;
3015                 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3016
3017 #ifdef CONFIG_YAFFS_WINCE
3018                 oh->win_atime[0] = in->win_atime[0];
3019                 oh->win_ctime[0] = in->win_ctime[0];
3020                 oh->win_mtime[0] = in->win_mtime[0];
3021                 oh->win_atime[1] = in->win_atime[1];
3022                 oh->win_ctime[1] = in->win_ctime[1];
3023                 oh->win_mtime[1] = in->win_mtime[1];
3024 #else
3025                 oh->yst_uid = in->yst_uid;
3026                 oh->yst_gid = in->yst_gid;
3027                 oh->yst_atime = in->yst_atime;
3028                 oh->yst_mtime = in->yst_mtime;
3029                 oh->yst_ctime = in->yst_ctime;
3030                 oh->yst_rdev = in->yst_rdev;
3031 #endif
3032                 if (in->parent)
3033                         oh->parentObjectId = in->parent->objectId;
3034                 else
3035                         oh->parentObjectId = 0;
3036
3037                 if (name && *name) {
3038                         memset(oh->name, 0, sizeof(oh->name));
3039                         yaffs_strncpy(oh->name, name, YAFFS_MAX_NAME_LENGTH);
3040                 } else if (prevChunkId > 0)
3041                         memcpy(oh->name, oldName, sizeof(oh->name));
3042                 else
3043                         memset(oh->name, 0, sizeof(oh->name));
3044
3045                 oh->isShrink = isShrink;
3046
3047                 switch (in->variantType) {
3048                 case YAFFS_OBJECT_TYPE_UNKNOWN:
3049                         /* Should not happen */
3050                         break;
3051                 case YAFFS_OBJECT_TYPE_FILE:
3052                         oh->fileSize =
3053                             (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3054                              || oh->parentObjectId ==
3055                              YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3056                             fileVariant.fileSize;
3057                         break;
3058                 case YAFFS_OBJECT_TYPE_HARDLINK:
3059                         oh->equivalentObjectId =
3060                             in->variant.hardLinkVariant.equivalentObjectId;
3061                         break;
3062                 case YAFFS_OBJECT_TYPE_SPECIAL:
3063                         /* Do nothing */
3064                         break;
3065                 case YAFFS_OBJECT_TYPE_DIRECTORY:
3066                         /* Do nothing */
3067                         break;
3068                 case YAFFS_OBJECT_TYPE_SYMLINK:
3069                         alias = in->variant.symLinkVariant.alias;
3070                         if(!alias)
3071                                 alias = _Y("no alias");
3072                         yaffs_strncpy(oh->alias,
3073                                         alias,
3074                                       YAFFS_MAX_ALIAS_LENGTH);
3075                         oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3076                         break;
3077                 }
3078
3079                 /* process any xattrib modifications */
3080                 if(xmod)
3081                         yaffs_ApplyXMod(dev, (char *)buffer, xmod);
3082
3083
3084                 /* Tags */
3085                 yaffs_InitialiseTags(&newTags);
3086                 in->serial++;
3087                 newTags.chunkId = 0;
3088                 newTags.objectId = in->objectId;
3089                 newTags.serialNumber = in->serial;
3090
3091                 /* Add extra info for file header */
3092
3093                 newTags.extraHeaderInfoAvailable = 1;
3094                 newTags.extraParentObjectId = oh->parentObjectId;
3095                 newTags.extraFileLength = oh->fileSize;
3096                 newTags.extraIsShrinkHeader = oh->isShrink;
3097                 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3098                 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3099                 newTags.extraObjectType = in->variantType;
3100
3101                 yaffs_VerifyObjectHeader(in, oh, &newTags, 1);
3102
3103                 /* Create new chunk in NAND */
3104                 newChunkId =
3105                     yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3106                                                       (prevChunkId > 0) ? 1 : 0);
3107
3108                 if (newChunkId >= 0) {
3109
3110                         in->hdrChunk = newChunkId;
3111
3112                         if (prevChunkId > 0) {
3113                                 yaffs_DeleteChunk(dev, prevChunkId, 1,
3114                                                   __LINE__);
3115                         }
3116
3117                         if (!yaffs_ObjectHasCachedWriteData(in))
3118                                 in->dirty = 0;
3119
3120                         /* If this was a shrink, then mark the block that the chunk lives on */
3121                         if (isShrink) {
3122                                 bi = yaffs_GetBlockInfo(in->myDev,
3123                                         newChunkId / in->myDev->param.nChunksPerBlock);
3124                                 bi->hasShrinkHeader = 1;
3125                         }
3126
3127                 }
3128
3129                 retVal = newChunkId;
3130
3131         }
3132
3133         if (buffer)
3134                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3135
3136         return retVal;
3137 }
3138
3139 /*------------------------ Short Operations Cache ----------------------------------------
3140  *   In many situations where there is no high level buffering (eg WinCE) a lot of
3141  *   reads might be short sequential reads, and a lot of writes may be short
3142  *   sequential writes. eg. scanning/writing a jpeg file.
3143  *   In these cases, a short read/write cache can provide a huge perfomance benefit
3144  *   with dumb-as-a-rock code.
3145  *   In Linux, the page cache provides read buffering aand the short op cache provides write
3146  *   buffering.
3147  *
3148  *   There are a limited number (~10) of cache chunks per device so that we don't
3149  *   need a very intelligent search.
3150  */
3151
3152 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3153 {
3154         yaffs_Device *dev = obj->myDev;
3155         int i;
3156         yaffs_ChunkCache *cache;
3157         int nCaches = obj->myDev->param.nShortOpCaches;
3158
3159         for (i = 0; i < nCaches; i++) {
3160                 cache = &dev->srCache[i];
3161                 if (cache->object == obj &&
3162                     cache->dirty)
3163                         return 1;
3164         }
3165
3166         return 0;
3167 }
3168
3169
3170 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
3171 {
3172         yaffs_Device *dev = obj->myDev;
3173         int lowest = -99;       /* Stop compiler whining. */
3174         int i;
3175         yaffs_ChunkCache *cache;
3176         int chunkWritten = 0;
3177         int nCaches = obj->myDev->param.nShortOpCaches;
3178
3179         if (nCaches > 0) {
3180                 do {
3181                         cache = NULL;
3182
3183                         /* Find the dirty cache for this object with the lowest chunk id. */
3184                         for (i = 0; i < nCaches; i++) {
3185                                 if (dev->srCache[i].object == obj &&
3186                                     dev->srCache[i].dirty) {
3187                                         if (!cache
3188                                             || dev->srCache[i].chunkId <
3189                                             lowest) {
3190                                                 cache = &dev->srCache[i];
3191                                                 lowest = cache->chunkId;
3192                                         }
3193                                 }
3194                         }
3195
3196                         if (cache && !cache->locked) {
3197                                 /* Write it out and free it up */
3198
3199                                 chunkWritten =
3200                                     yaffs_WriteChunkDataToObject(cache->object,
3201                                                                  cache->chunkId,
3202                                                                  cache->data,
3203                                                                  cache->nBytes,
3204                                                                  1);
3205                                 cache->dirty = 0;
3206                                 cache->object = NULL;
3207                         }
3208
3209                 } while (cache && chunkWritten > 0);
3210
3211                 if (cache) {
3212                         /* Hoosterman, disk full while writing cache out. */
3213                         T(YAFFS_TRACE_ERROR,
3214                           (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3215
3216                 }
3217         }
3218
3219 }
3220
3221 /*yaffs_FlushEntireDeviceCache(dev)
3222  *
3223  *
3224  */
3225
3226 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3227 {
3228         yaffs_Object *obj;
3229         int nCaches = dev->param.nShortOpCaches;
3230         int i;
3231
3232         /* Find a dirty object in the cache and flush it...
3233          * until there are no further dirty objects.
3234          */
3235         do {
3236                 obj = NULL;
3237                 for (i = 0; i < nCaches && !obj; i++) {
3238                         if (dev->srCache[i].object &&
3239                             dev->srCache[i].dirty)
3240                                 obj = dev->srCache[i].object;
3241
3242                 }
3243                 if (obj)
3244                         yaffs_FlushFilesChunkCache(obj);
3245
3246         } while (obj);
3247
3248 }
3249
3250
3251 /* Grab us a cache chunk for use.
3252  * First look for an empty one.
3253  * Then look for the least recently used non-dirty one.
3254  * Then look for the least recently used dirty one...., flush and look again.
3255  */
3256 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
3257 {
3258         int i;
3259
3260         if (dev->param.nShortOpCaches > 0) {
3261                 for (i = 0; i < dev->param.nShortOpCaches; i++) {
3262                         if (!dev->srCache[i].object)
3263                                 return &dev->srCache[i];
3264                 }
3265         }
3266
3267         return NULL;
3268 }
3269
3270 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
3271 {
3272         yaffs_ChunkCache *cache;
3273         yaffs_Object *theObj;
3274         int usage;
3275         int i;
3276         int pushout;
3277
3278         if (dev->param.nShortOpCaches > 0) {
3279                 /* Try find a non-dirty one... */
3280
3281                 cache = yaffs_GrabChunkCacheWorker(dev);
3282
3283                 if (!cache) {
3284                         /* They were all dirty, find the last recently used object and flush
3285                          * its cache, then  find again.
3286                          * NB what's here is not very accurate, we actually flush the object
3287                          * the last recently used page.
3288                          */
3289
3290                         /* With locking we can't assume we can use entry zero */
3291
3292                         theObj = NULL;
3293                         usage = -1;
3294                         cache = NULL;
3295                         pushout = -1;
3296
3297                         for (i = 0; i < dev->param.nShortOpCaches; i++) {
3298                                 if (dev->srCache[i].object &&
3299                                     !dev->srCache[i].locked &&
3300                                     (dev->srCache[i].lastUse < usage || !cache)) {
3301                                         usage = dev->srCache[i].lastUse;
3302                                         theObj = dev->srCache[i].object;
3303                                         cache = &dev->srCache[i];
3304                                         pushout = i;
3305                                 }
3306                         }
3307
3308                         if (!cache || cache->dirty) {
3309                                 /* Flush and try again */
3310                                 yaffs_FlushFilesChunkCache(theObj);
3311                                 cache = yaffs_GrabChunkCacheWorker(dev);
3312                         }
3313
3314                 }
3315                 return cache;
3316         } else
3317                 return NULL;
3318
3319 }
3320
3321 /* Find a cached chunk */
3322 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj,
3323                                               int chunkId)
3324 {
3325         yaffs_Device *dev = obj->myDev;
3326         int i;
3327         if (dev->param.nShortOpCaches > 0) {
3328                 for (i = 0; i < dev->param.nShortOpCaches; i++) {
3329                         if (dev->srCache[i].object == obj &&
3330                             dev->srCache[i].chunkId == chunkId) {
3331                                 dev->cacheHits++;
3332
3333                                 return &dev->srCache[i];
3334                         }
3335                 }
3336         }
3337         return NULL;
3338 }
3339
3340 /* Mark the chunk for the least recently used algorithym */
3341 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache,
3342                                 int isAWrite)
3343 {
3344
3345         if (dev->param.nShortOpCaches > 0) {
3346                 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
3347                         /* Reset the cache usages */
3348                         int i;
3349                         for (i = 1; i < dev->param.nShortOpCaches; i++)
3350                                 dev->srCache[i].lastUse = 0;
3351
3352                         dev->srLastUse = 0;
3353                 }
3354
3355                 dev->srLastUse++;
3356
3357                 cache->lastUse = dev->srLastUse;
3358
3359                 if (isAWrite)
3360                         cache->dirty = 1;
3361         }
3362 }
3363
3364 /* Invalidate a single cache page.
3365  * Do this when a whole page gets written,
3366  * ie the short cache for this page is no longer valid.
3367  */
3368 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
3369 {
3370         if (object->myDev->param.nShortOpCaches > 0) {
3371                 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
3372
3373                 if (cache)
3374                         cache->object = NULL;
3375         }
3376 }
3377
3378 /* Invalidate all the cache pages associated with this object
3379  * Do this whenever ther file is deleted or resized.
3380  */
3381 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
3382 {
3383         int i;
3384         yaffs_Device *dev = in->myDev;
3385
3386         if (dev->param.nShortOpCaches > 0) {
3387                 /* Invalidate it. */
3388                 for (i = 0; i < dev->param.nShortOpCaches; i++) {
3389                         if (dev->srCache[i].object == in)
3390                                 dev->srCache[i].object = NULL;
3391                 }
3392         }
3393 }
3394
3395
3396 /*--------------------- File read/write ------------------------
3397  * Read and write have very similar structures.
3398  * In general the read/write has three parts to it
3399  * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3400  * Some complete chunks
3401  * An incomplete chunk to end off with
3402  *
3403  * Curve-balls: the first chunk might also be the last chunk.
3404  */
3405
3406 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 *buffer, loff_t offset,
3407                         int nBytes)
3408 {
3409
3410         int chunk;
3411         __u32 start;
3412         int nToCopy;
3413         int n = nBytes;
3414         int nDone = 0;
3415         yaffs_ChunkCache *cache;
3416
3417         yaffs_Device *dev;
3418
3419         dev = in->myDev;
3420
3421         while (n > 0) {
3422                 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
3423                 /* start = offset % dev->nDataBytesPerChunk; */
3424                 yaffs_AddrToChunk(dev, offset, &chunk, &start);
3425                 chunk++;
3426
3427                 /* OK now check for the curveball where the start and end are in
3428                  * the same chunk.
3429                  */
3430                 if ((start + n) < dev->nDataBytesPerChunk)
3431                         nToCopy = n;
3432                 else
3433                         nToCopy = dev->nDataBytesPerChunk - start;
3434
3435                 cache = yaffs_FindChunkCache(in, chunk);
3436
3437                 /* If the chunk is already in the cache or it is less than a whole chunk
3438                  * or we're using inband tags then use the cache (if there is caching)
3439                  * else bypass the cache.
3440                  */
3441                 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
3442                         if (dev->param.nShortOpCaches > 0) {
3443
3444                                 /* If we can't find the data in the cache, then load it up. */
3445
3446                                 if (!cache) {
3447                                         cache = yaffs_GrabChunkCache(in->myDev);
3448                                         cache->object = in;
3449                                         cache->chunkId = chunk;
3450                                         cache->dirty = 0;
3451                                         cache->locked = 0;
3452                                         yaffs_ReadChunkDataFromObject(in, chunk,
3453                                                                       cache->
3454                                                                       data);
3455                                         cache->nBytes = 0;
3456                                 }
3457
3458                                 yaffs_UseChunkCache(dev, cache, 0);
3459
3460                                 cache->locked = 1;
3461
3462
3463                                 memcpy(buffer, &cache->data[start], nToCopy);
3464
3465                                 cache->locked = 0;
3466                         } else {
3467                                 /* Read into the local buffer then copy..*/
3468
3469                                 __u8 *localBuffer =
3470                                     yaffs_GetTempBuffer(dev, __LINE__);
3471                                 yaffs_ReadChunkDataFromObject(in, chunk,
3472                                                               localBuffer);
3473
3474                                 memcpy(buffer, &localBuffer[start], nToCopy);
3475
3476
3477                                 yaffs_ReleaseTempBuffer(dev, localBuffer,
3478                                                         __LINE__);
3479                         }
3480
3481                 } else {
3482
3483                         /* A full chunk. Read directly into the supplied buffer. */
3484                         yaffs_ReadChunkDataFromObject(in, chunk, buffer);
3485
3486                 }
3487
3488                 n -= nToCopy;
3489                 offset += nToCopy;
3490                 buffer += nToCopy;
3491                 nDone += nToCopy;
3492
3493         }
3494
3495         return nDone;
3496 }
3497
3498 int yaffs_DoWriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
3499                         int nBytes, int writeThrough)
3500 {
3501
3502         int chunk;
3503         __u32 start;
3504         int nToCopy;
3505         int n = nBytes;
3506         int nDone = 0;
3507         int nToWriteBack;
3508         int startOfWrite = offset;
3509         int chunkWritten = 0;
3510         __u32 nBytesRead;
3511         __u32 chunkStart;
3512
3513         yaffs_Device *dev;
3514
3515         dev = in->myDev;
3516
3517         while (n > 0 && chunkWritten >= 0) {
3518                 yaffs_AddrToChunk(dev, offset, &chunk, &start);
3519
3520                 if (chunk * dev->nDataBytesPerChunk + start != offset ||
3521                                 start >= dev->nDataBytesPerChunk) {
3522                         T(YAFFS_TRACE_ERROR, (
3523                            TSTR("AddrToChunk of offset %d gives chunk %d start %d"
3524                            TENDSTR),
3525                            (int)offset, chunk, start));
3526                 }
3527                 chunk++; /* File pos to chunk in file offset */
3528
3529                 /* OK now check for the curveball where the start and end are in
3530                  * the same chunk.
3531                  */
3532
3533                 if ((start + n) < dev->nDataBytesPerChunk) {
3534                         nToCopy = n;
3535
3536                         /* Now folks, to calculate how many bytes to write back....
3537                          * If we're overwriting and not writing to then end of file then
3538                          * we need to write back as much as was there before.
3539                          */
3540
3541                         chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
3542
3543                         if (chunkStart > in->variant.fileVariant.fileSize)
3544                                 nBytesRead = 0; /* Past end of file */
3545                         else
3546                                 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
3547
3548                         if (nBytesRead > dev->nDataBytesPerChunk)
3549                                 nBytesRead = dev->nDataBytesPerChunk;
3550
3551                         nToWriteBack =
3552                             (nBytesRead >
3553                              (start + n)) ? nBytesRead : (start + n);
3554
3555                         if (nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
3556                                 YBUG();
3557
3558                 } else {
3559                         nToCopy = dev->nDataBytesPerChunk - start;
3560                         nToWriteBack = dev->nDataBytesPerChunk;
3561                 }
3562
3563                 if (nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
3564                         /* An incomplete start or end chunk (or maybe both start and end chunk),
3565                          * or we're using inband tags, so we want to use the cache buffers.
3566                          */
3567                         if (dev->param.nShortOpCaches > 0) {
3568                                 yaffs_ChunkCache *cache;
3569                                 /* If we can't find the data in the cache, then load the cache */
3570                                 cache = yaffs_FindChunkCache(in, chunk);
3571
3572                                 if (!cache
3573                                     && yaffs_CheckSpaceForAllocation(dev, 1)) {
3574                                         cache = yaffs_GrabChunkCache(dev);
3575                                         cache->object = in;
3576                                         cache->chunkId = chunk;
3577                                         cache->dirty = 0;
3578                                         cache->locked = 0;
3579                                         yaffs_ReadChunkDataFromObject(in, chunk,
3580                                                                       cache->data);
3581                                 } else if (cache &&
3582                                         !cache->dirty &&
3583                                         !yaffs_CheckSpaceForAllocation(dev, 1)) {
3584                                         /* Drop the cache if it was a read cache item and
3585                                          * no space check has been made for it.
3586                                          */
3587                                          cache = NULL;
3588                                 }
3589
3590                                 if (cache) {
3591                                         yaffs_UseChunkCache(dev, cache, 1);
3592                                         cache->locked = 1;
3593
3594
3595                                         memcpy(&cache->data[start], buffer,
3596                                                nToCopy);
3597
3598
3599                                         cache->locked = 0;
3600                                         cache->nBytes = nToWriteBack;
3601
3602                                         if (writeThrough) {
3603                                                 chunkWritten =
3604                                                     yaffs_WriteChunkDataToObject
3605                                                     (cache->object,
3606                                                      cache->chunkId,
3607                                                      cache->data, cache->nBytes,
3608                                                      1);
3609                                                 cache->dirty = 0;
3610                                         }
3611
3612                                 } else {
3613                                         chunkWritten = -1;      /* fail the write */
3614                                 }
3615                         } else {
3616                                 /* An incomplete start or end chunk (or maybe both start and end chunk)
3617                                  * Read into the local buffer then copy, then copy over and write back.
3618                                  */
3619
3620                                 __u8 *localBuffer =
3621                                     yaffs_GetTempBuffer(dev, __LINE__);
3622
3623                                 yaffs_ReadChunkDataFromObject(in, chunk,
3624                                                               localBuffer);
3625
3626
3627
3628                                 memcpy(&localBuffer[start], buffer, nToCopy);
3629
3630                                 chunkWritten =
3631                                     yaffs_WriteChunkDataToObject(in, chunk,
3632                                                                  localBuffer,
3633                                                                  nToWriteBack,
3634                                                                  0);
3635
3636                                 yaffs_ReleaseTempBuffer(dev, localBuffer,
3637                                                         __LINE__);
3638
3639                         }
3640
3641                 } else {
3642                         /* A full chunk. Write directly from the supplied buffer. */
3643
3644
3645
3646                         chunkWritten =
3647                             yaffs_WriteChunkDataToObject(in, chunk, buffer,
3648                                                          dev->nDataBytesPerChunk,
3649                                                          0);
3650
3651                         /* Since we've overwritten the cached data, we better invalidate it. */
3652                         yaffs_InvalidateChunkCache(in, chunk);
3653                 }
3654
3655                 if (chunkWritten >= 0) {
3656                         n -= nToCopy;
3657                         offset += nToCopy;
3658                         buffer += nToCopy;
3659                         nDone += nToCopy;
3660                 }
3661
3662         }
3663
3664         /* Update file object */
3665
3666         if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
3667                 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
3668
3669         in->dirty = 1;
3670
3671         return nDone;
3672 }
3673
3674 int yaffs_WriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
3675                         int nBytes, int writeThrough)
3676 {
3677         yaffs2_HandleHole(in,offset);
3678         return yaffs_DoWriteDataToFile(in,buffer,offset,nBytes,writeThrough);
3679 }
3680
3681
3682
3683 /* ---------------------- File resizing stuff ------------------ */
3684
3685 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
3686 {
3687
3688         yaffs_Device *dev = in->myDev;
3689         int oldFileSize = in->variant.fileVariant.fileSize;
3690
3691         int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
3692
3693         int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
3694             dev->nDataBytesPerChunk;
3695         int i;
3696         int chunkId;
3697
3698         /* Delete backwards so that we don't end up with holes if
3699          * power is lost part-way through the operation.
3700          */
3701         for (i = lastDel; i >= startDel; i--) {
3702                 /* NB this could be optimised somewhat,
3703                  * eg. could retrieve the tags and write them without
3704                  * using yaffs_DeleteChunk
3705                  */
3706
3707                 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
3708                 if (chunkId > 0) {
3709                         if (chunkId <
3710                             (dev->internalStartBlock * dev->param.nChunksPerBlock)
3711                             || chunkId >=
3712                             ((dev->internalEndBlock +
3713                               1) * dev->param.nChunksPerBlock)) {
3714                                 T(YAFFS_TRACE_ALWAYS,
3715                                   (TSTR("Found daft chunkId %d for %d" TENDSTR),
3716                                    chunkId, i));
3717                         } else {
3718                                 in->nDataChunks--;
3719                                 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
3720                         }
3721                 }
3722         }
3723
3724 }
3725
3726
3727 void yaffs_ResizeDown( yaffs_Object *obj, loff_t newSize)
3728 {
3729         int newFullChunks;
3730         __u32 newSizeOfPartialChunk;
3731         yaffs_Device *dev = obj->myDev;
3732
3733         yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
3734
3735         yaffs_PruneResizedChunks(obj, newSize);
3736
3737         if (newSizeOfPartialChunk != 0) {
3738                 int lastChunk = 1 + newFullChunks;
3739                 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3740
3741                 /* Got to read and rewrite the last chunk with its new size and zero pad */
3742                 yaffs_ReadChunkDataFromObject(obj, lastChunk, localBuffer);
3743                 memset(localBuffer + newSizeOfPartialChunk, 0,
3744                         dev->nDataBytesPerChunk - newSizeOfPartialChunk);
3745
3746                 yaffs_WriteChunkDataToObject(obj, lastChunk, localBuffer,
3747                                              newSizeOfPartialChunk, 1);
3748
3749                 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3750         }
3751
3752         obj->variant.fileVariant.fileSize = newSize;
3753
3754         yaffs_PruneFileStructure(dev, &obj->variant.fileVariant);
3755 }
3756
3757
3758 int yaffs_ResizeFile(yaffs_Object *in, loff_t newSize)
3759 {
3760         yaffs_Device *dev = in->myDev;
3761         int oldFileSize = in->variant.fileVariant.fileSize;
3762
3763         yaffs_FlushFilesChunkCache(in);
3764         yaffs_InvalidateWholeChunkCache(in);
3765
3766         yaffs_CheckGarbageCollection(dev,0);
3767
3768         if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3769                 return YAFFS_FAIL;
3770
3771         if (newSize == oldFileSize)
3772                 return YAFFS_OK;
3773                 
3774         if(newSize > oldFileSize){
3775                 yaffs2_HandleHole(in,newSize);
3776                 in->variant.fileVariant.fileSize = newSize;
3777         } else {
3778                 /* newSize < oldFileSize */ 
3779                 yaffs_ResizeDown(in, newSize);
3780         } 
3781
3782         /* Write a new object header to reflect the resize.
3783          * show we've shrunk the file, if need be
3784          * Do this only if the file is not in the deleted directories
3785          * and is not shadowed.
3786          */
3787         if (in->parent &&
3788             !in->isShadowed &&
3789             in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
3790             in->parent->objectId != YAFFS_OBJECTID_DELETED)
3791                 yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0, NULL);
3792
3793
3794         return YAFFS_OK;
3795 }
3796
3797 loff_t yaffs_GetFileSize(yaffs_Object *obj)
3798 {
3799         YCHAR *alias = NULL;
3800         obj = yaffs_GetEquivalentObject(obj);
3801
3802         switch (obj->variantType) {
3803         case YAFFS_OBJECT_TYPE_FILE:
3804                 return obj->variant.fileVariant.fileSize;
3805         case YAFFS_OBJECT_TYPE_SYMLINK:
3806                 alias = obj->variant.symLinkVariant.alias;
3807                 if(!alias)
3808                         return 0;
3809                 return yaffs_strnlen(alias,YAFFS_MAX_ALIAS_LENGTH);
3810         default:
3811                 return 0;
3812         }
3813 }
3814
3815
3816
3817 int yaffs_FlushFile(yaffs_Object *in, int updateTime, int dataSync)
3818 {
3819         int retVal;
3820         if (in->dirty) {
3821                 yaffs_FlushFilesChunkCache(in);
3822                 if(dataSync) /* Only sync data */
3823                         retVal=YAFFS_OK;
3824                 else {
3825                         if (updateTime) {
3826 #ifdef CONFIG_YAFFS_WINCE
3827                                 yfsd_WinFileTimeNow(in->win_mtime);
3828 #else
3829
3830                                 in->yst_mtime = Y_CURRENT_TIME;
3831
3832 #endif
3833                         }
3834
3835                         retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0, NULL) >=
3836                                 0) ? YAFFS_OK : YAFFS_FAIL;
3837                 }
3838         } else {
3839                 retVal = YAFFS_OK;
3840         }
3841
3842         return retVal;
3843
3844 }
3845
3846 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
3847 {
3848
3849         /* First off, invalidate the file's data in the cache, without flushing. */
3850         yaffs_InvalidateWholeChunkCache(in);
3851
3852         if (in->myDev->param.isYaffs2 && (in->parent != in->myDev->deletedDir)) {
3853                 /* Move to the unlinked directory so we have a record that it was deleted. */
3854                 yaffs_ChangeObjectName(in, in->myDev->deletedDir, _Y("deleted"), 0, 0);
3855
3856         }
3857
3858         yaffs_RemoveObjectFromDirectory(in);
3859         yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
3860         in->hdrChunk = 0;
3861
3862         yaffs_FreeObject(in);
3863         return YAFFS_OK;
3864
3865 }
3866
3867 /* yaffs_DeleteFile deletes the whole file data
3868  * and the inode associated with the file.
3869  * It does not delete the links associated with the file.
3870  */
3871 static int yaffs_UnlinkFileIfNeeded(yaffs_Object *in)
3872 {
3873
3874         int retVal;
3875         int immediateDeletion = 0;
3876         yaffs_Device *dev = in->myDev;
3877
3878         if (!in->myInode)
3879                 immediateDeletion = 1;
3880
3881         if (immediateDeletion) {
3882                 retVal =
3883                     yaffs_ChangeObjectName(in, in->myDev->deletedDir,
3884                                            _Y("deleted"), 0, 0);
3885                 T(YAFFS_TRACE_TRACING,
3886                   (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
3887                    in->objectId));
3888                 in->deleted = 1;
3889                 in->myDev->nDeletedFiles++;
3890                 if (dev->param.disableSoftDelete || dev->param.isYaffs2)
3891                         yaffs_ResizeFile(in, 0);
3892                 yaffs_SoftDeleteFile(in);
3893         } else {
3894                 retVal =
3895                     yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
3896                                            _Y("unlinked"), 0, 0);
3897         }
3898
3899
3900         return retVal;
3901 }
3902
3903 int yaffs_DeleteFile(yaffs_Object *in)
3904 {
3905         int retVal = YAFFS_OK;
3906         int deleted; /* Need to cache value on stack if in is freed */
3907         yaffs_Device *dev = in->myDev;
3908
3909         if (dev->param.disableSoftDelete || dev->param.isYaffs2)
3910                 yaffs_ResizeFile(in, 0);
3911
3912         if (in->nDataChunks > 0) {
3913                 /* Use soft deletion if there is data in the file.
3914                  * That won't be the case if it has been resized to zero.
3915                  */
3916                 if (!in->unlinked)
3917                         retVal = yaffs_UnlinkFileIfNeeded(in);
3918
3919                 deleted = in->deleted;
3920
3921                 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
3922                         in->deleted = 1;
3923                         deleted = 1;
3924                         in->myDev->nDeletedFiles++;
3925                         yaffs_SoftDeleteFile(in);
3926                 }
3927                 return deleted ? YAFFS_OK : YAFFS_FAIL;
3928         } else {
3929                 /* The file has no data chunks so we toss it immediately */
3930                 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
3931                 in->variant.fileVariant.top = NULL;
3932                 yaffs_DoGenericObjectDeletion(in);
3933
3934                 return YAFFS_OK;
3935         }
3936 }
3937
3938 static int yaffs_IsNonEmptyDirectory(yaffs_Object *obj)
3939 {
3940         return (obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) &&
3941                 !(ylist_empty(&obj->variant.directoryVariant.children));
3942 }
3943
3944 static int yaffs_DeleteDirectory(yaffs_Object *obj)
3945 {
3946         /* First check that the directory is empty. */
3947         if (yaffs_IsNonEmptyDirectory(obj))
3948                 return YAFFS_FAIL;
3949
3950         return yaffs_DoGenericObjectDeletion(obj);
3951 }
3952
3953 static int yaffs_DeleteSymLink(yaffs_Object *in)
3954 {
3955         if(in->variant.symLinkVariant.alias)
3956                 YFREE(in->variant.symLinkVariant.alias);
3957         in->variant.symLinkVariant.alias=NULL;
3958
3959         return yaffs_DoGenericObjectDeletion(in);
3960 }
3961
3962 static int yaffs_DeleteHardLink(yaffs_Object *in)
3963 {
3964         /* remove this hardlink from the list assocaited with the equivalent
3965          * object
3966          */
3967         ylist_del_init(&in->hardLinks);
3968         return yaffs_DoGenericObjectDeletion(in);
3969 }
3970
3971 int yaffs_DeleteObject(yaffs_Object *obj)
3972 {
3973 int retVal = -1;
3974         switch (obj->variantType) {
3975         case YAFFS_OBJECT_TYPE_FILE:
3976                 retVal = yaffs_DeleteFile(obj);
3977                 break;
3978         case YAFFS_OBJECT_TYPE_DIRECTORY:
3979                 if(!ylist_empty(&obj->variant.directoryVariant.dirty)){
3980                         T(YAFFS_TRACE_BACKGROUND, (TSTR("Remove object %d from dirty directories" TENDSTR),obj->objectId));
3981                         ylist_del_init(&obj->variant.directoryVariant.dirty);
3982                 }
3983                 return yaffs_DeleteDirectory(obj);
3984                 break;
3985         case YAFFS_OBJECT_TYPE_SYMLINK:
3986                 retVal = yaffs_DeleteSymLink(obj);
3987                 break;
3988         case YAFFS_OBJECT_TYPE_HARDLINK:
3989                 retVal = yaffs_DeleteHardLink(obj);
3990                 break;
3991         case YAFFS_OBJECT_TYPE_SPECIAL:
3992                 retVal = yaffs_DoGenericObjectDeletion(obj);
3993                 break;
3994         case YAFFS_OBJECT_TYPE_UNKNOWN:
3995                 retVal = 0;
3996                 break;          /* should not happen. */
3997         }
3998
3999         return retVal;
4000 }
4001
4002 static int yaffs_UnlinkWorker(yaffs_Object *obj)
4003 {
4004
4005         int immediateDeletion = 0;
4006
4007         if (!obj->myInode)
4008                 immediateDeletion = 1;
4009
4010         if(obj)
4011                 yaffs_UpdateParent(obj->parent);
4012
4013         if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4014                 return yaffs_DeleteHardLink(obj);
4015         } else if (!ylist_empty(&obj->hardLinks)) {
4016                 /* Curve ball: We're unlinking an object that has a hardlink.
4017                  *
4018                  * This problem arises because we are not strictly following
4019                  * The Linux link/inode model.
4020                  *
4021                  * We can't really delete the object.
4022                  * Instead, we do the following:
4023                  * - Select a hardlink.
4024                  * - Unhook it from the hard links
4025                  * - Move it from its parent directory (so that the rename can work)
4026                  * - Rename the object to the hardlink's name.
4027                  * - Delete the hardlink
4028                  */
4029
4030                 yaffs_Object *hl;
4031                 yaffs_Object *parent;
4032                 int retVal;
4033                 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
4034
4035                 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
4036
4037                 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
4038                 parent = hl->parent;
4039
4040                 ylist_del_init(&hl->hardLinks);
4041
4042                 yaffs_AddObjectToDirectory(obj->myDev->unlinkedDir, hl);
4043
4044                 retVal = yaffs_ChangeObjectName(obj,parent, name, 0, 0);
4045
4046                 if (retVal == YAFFS_OK)
4047                         retVal = yaffs_DoGenericObjectDeletion(hl);
4048
4049                 return retVal;
4050
4051         } else if (immediateDeletion) {
4052                 switch (obj->variantType) {
4053                 case YAFFS_OBJECT_TYPE_FILE:
4054                         return yaffs_DeleteFile(obj);
4055                         break;
4056                 case YAFFS_OBJECT_TYPE_DIRECTORY:
4057                         ylist_del_init(&obj->variant.directoryVariant.dirty);
4058                         return yaffs_DeleteDirectory(obj);
4059                         break;
4060                 case YAFFS_OBJECT_TYPE_SYMLINK:
4061                         return yaffs_DeleteSymLink(obj);
4062                         break;
4063                 case YAFFS_OBJECT_TYPE_SPECIAL:
4064                         return yaffs_DoGenericObjectDeletion(obj);
4065                         break;
4066                 case YAFFS_OBJECT_TYPE_HARDLINK:
4067                 case YAFFS_OBJECT_TYPE_UNKNOWN:
4068                 default:
4069                         return YAFFS_FAIL;
4070                 }
4071         } else if(yaffs_IsNonEmptyDirectory(obj))
4072                 return YAFFS_FAIL;
4073         else
4074                 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
4075                                            _Y("unlinked"), 0, 0);
4076 }
4077
4078
4079 static int yaffs_UnlinkObject(yaffs_Object *obj)
4080 {
4081
4082         if (obj && obj->unlinkAllowed)
4083                 return yaffs_UnlinkWorker(obj);
4084
4085         return YAFFS_FAIL;
4086
4087 }
4088 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
4089 {
4090         yaffs_Object *obj;
4091
4092         obj = yaffs_FindObjectByName(dir, name);
4093         return yaffs_UnlinkObject(obj);
4094 }
4095
4096 /*----------------------- Initialisation Scanning ---------------------- */
4097
4098 void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
4099                                 int backwardScanning)
4100 {
4101         yaffs_Object *obj;
4102
4103         if (!backwardScanning) {
4104                 /* Handle YAFFS1 forward scanning case
4105                  * For YAFFS1 we always do the deletion
4106                  */
4107
4108         } else {
4109                 /* Handle YAFFS2 case (backward scanning)
4110                  * If the shadowed object exists then ignore.
4111                  */
4112                 obj = yaffs_FindObjectByNumber(dev, objId);
4113                 if(obj)
4114                         return;
4115         }
4116
4117         /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
4118          * We put it in unlinked dir to be cleaned up after the scanning
4119          */
4120         obj =
4121             yaffs_FindOrCreateObjectByNumber(dev, objId,
4122                                              YAFFS_OBJECT_TYPE_FILE);
4123         if (!obj)
4124                 return;
4125         obj->isShadowed = 1;
4126         yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
4127         obj->variant.fileVariant.shrinkSize = 0;
4128         obj->valid = 1;         /* So that we don't read any other info for this file */
4129
4130 }
4131
4132
4133 void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
4134 {
4135         yaffs_Object *hl;
4136         yaffs_Object *in;
4137
4138         while (hardList) {
4139                 hl = hardList;
4140                 hardList = (yaffs_Object *) (hardList->hardLinks.next);
4141
4142                 in = yaffs_FindObjectByNumber(dev,
4143                                               hl->variant.hardLinkVariant.
4144                                               equivalentObjectId);
4145
4146                 if (in) {
4147                         /* Add the hardlink pointers */
4148                         hl->variant.hardLinkVariant.equivalentObject = in;
4149                         ylist_add(&hl->hardLinks, &in->hardLinks);
4150                 } else {
4151                         /* Todo Need to report/handle this better.
4152                          * Got a problem... hardlink to a non-existant object
4153                          */
4154                         hl->variant.hardLinkVariant.equivalentObject = NULL;
4155                         YINIT_LIST_HEAD(&hl->hardLinks);
4156
4157                 }
4158         }
4159 }
4160
4161
4162 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
4163 {
4164         /*
4165         *  Sort out state of unlinked and deleted objects after scanning.
4166         */
4167         struct ylist_head *i;
4168         struct ylist_head *n;
4169         yaffs_Object *l;
4170
4171         /* Soft delete all the unlinked files */
4172         ylist_for_each_safe(i, n,
4173                 &dev->unlinkedDir->variant.directoryVariant.children) {
4174                 if (i) {
4175                         l = ylist_entry(i, yaffs_Object, siblings);
4176                         yaffs_DeleteObject(l);
4177                 }
4178         }
4179
4180         ylist_for_each_safe(i, n,
4181                 &dev->deletedDir->variant.directoryVariant.children) {
4182                 if (i) {
4183                         l = ylist_entry(i, yaffs_Object, siblings);
4184                         yaffs_DeleteObject(l);
4185                 }
4186         }
4187
4188 }
4189
4190 /*
4191  * This code iterates through all the objects making sure that they are rooted.
4192  * Any unrooted objects are re-rooted in lost+found.
4193  * An object needs to be in one of:
4194  * - Directly under deleted, unlinked
4195  * - Directly or indirectly under root.
4196  *
4197  * Note:
4198  *  This code assumes that we don't ever change the current relationships between
4199  *  directories:
4200  *   rootDir->parent == unlinkedDir->parent == deletedDir->parent == NULL
4201  *   lostNfound->parent == rootDir
4202  *
4203  * This fixes the problem where directories might have inadvertently been deleted
4204  * leaving the object "hanging" without being rooted in the directory tree.
4205  */
4206  
4207 static int yaffs_HasNULLParent(yaffs_Device *dev, yaffs_Object *obj)
4208 {
4209         return (obj == dev->deletedDir ||
4210                 obj == dev->unlinkedDir||
4211                 obj == dev->rootDir);
4212 }
4213
4214 static void yaffs_FixHangingObjects(yaffs_Device *dev)
4215 {
4216         yaffs_Object *obj;
4217         yaffs_Object *parent;
4218         int i;
4219         struct ylist_head *lh;
4220         struct ylist_head *n;
4221         int depthLimit;
4222         int hanging;
4223
4224
4225         /* Iterate through the objects in each hash entry,
4226          * looking at each object.
4227          * Make sure it is rooted.
4228          */
4229
4230         for (i = 0; i <  YAFFS_NOBJECT_BUCKETS; i++) {
4231                 ylist_for_each_safe(lh, n, &dev->objectBucket[i].list) {
4232                         if (lh) {
4233                                 obj = ylist_entry(lh, yaffs_Object, hashLink);
4234                                 parent= obj->parent;
4235                                 
4236                                 if(yaffs_HasNULLParent(dev,obj)){
4237                                         /* These directories are not hanging */
4238                                         hanging = 0;
4239                                 }
4240                                 else if(!parent || parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
4241                                         hanging = 1;
4242                                 else if(yaffs_HasNULLParent(dev,parent))
4243                                         hanging = 0;
4244                                 else {
4245                                         /*
4246                                          * Need to follow the parent chain to see if it is hanging.
4247                                          */
4248                                         hanging = 0;
4249                                         depthLimit=100;
4250
4251                                         while(parent != dev->rootDir &&
4252                                                 parent->parent &&
4253                                                 parent->parent->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
4254                                                 depthLimit > 0){
4255                                                 parent = parent->parent;
4256                                                 depthLimit--;
4257                                         }
4258                                         if(parent != dev->rootDir)
4259                                                 hanging = 1;
4260                                 }
4261                                 if(hanging){
4262                                         T(YAFFS_TRACE_SCAN,
4263                                           (TSTR("Hanging object %d moved to lost and found" TENDSTR),
4264                                                 obj->objectId));
4265                                         yaffs_AddObjectToDirectory(dev->lostNFoundDir,obj);
4266                                 }
4267                         }
4268                 }
4269         }
4270 }
4271
4272
4273 /*
4274  * Delete directory contents for cleaning up lost and found.
4275  */
4276 static void yaffs_DeleteDirectoryContents(yaffs_Object *dir)
4277 {
4278         yaffs_Object *obj;
4279         struct ylist_head *lh;
4280         struct ylist_head *n;
4281
4282         if(dir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
4283                 YBUG();
4284         
4285         ylist_for_each_safe(lh, n, &dir->variant.directoryVariant.children) {
4286                 if (lh) {
4287                         obj = ylist_entry(lh, yaffs_Object, siblings);
4288                         if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
4289                                 yaffs_DeleteDirectoryContents(obj);
4290
4291                         T(YAFFS_TRACE_SCAN,
4292                                 (TSTR("Deleting lost_found object %d" TENDSTR),
4293                                 obj->objectId));
4294
4295                         /* Need to use UnlinkObject since Delete would not handle
4296                          * hardlinked objects correctly.
4297                          */
4298                         yaffs_UnlinkObject(obj); 
4299                 }
4300         }
4301                         
4302 }
4303
4304 static void yaffs_EmptyLostAndFound(yaffs_Device *dev)
4305 {
4306         yaffs_DeleteDirectoryContents(dev->lostNFoundDir);
4307 }
4308
4309 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
4310 {
4311         __u8 *chunkData;
4312         yaffs_ObjectHeader *oh;
4313         yaffs_Device *dev;
4314         yaffs_ExtendedTags tags;
4315         int result;
4316         int alloc_failed = 0;
4317
4318         if (!in)
4319                 return;
4320
4321         dev = in->myDev;
4322
4323 #if 0
4324         T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
4325                 in->objectId,
4326                 in->lazyLoaded ? "not yet" : "already"));
4327 #endif
4328
4329         if (in->lazyLoaded && in->hdrChunk > 0) {
4330                 in->lazyLoaded = 0;
4331                 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4332
4333                 result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
4334                 oh = (yaffs_ObjectHeader *) chunkData;
4335
4336                 in->yst_mode = oh->yst_mode;
4337 #ifdef CONFIG_YAFFS_WINCE
4338                 in->win_atime[0] = oh->win_atime[0];
4339                 in->win_ctime[0] = oh->win_ctime[0];
4340                 in->win_mtime[0] = oh->win_mtime[0];
4341                 in->win_atime[1] = oh->win_atime[1];
4342                 in->win_ctime[1] = oh->win_ctime[1];
4343                 in->win_mtime[1] = oh->win_mtime[1];
4344 #else
4345                 in->yst_uid = oh->yst_uid;
4346                 in->yst_gid = oh->yst_gid;
4347                 in->yst_atime = oh->yst_atime;
4348                 in->yst_mtime = oh->yst_mtime;
4349                 in->yst_ctime = oh->yst_ctime;
4350                 in->yst_rdev = oh->yst_rdev;
4351
4352 #endif
4353                 yaffs_SetObjectName(in, oh->name);
4354
4355                 if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
4356                         in->variant.symLinkVariant.alias =
4357                                                     yaffs_CloneString(oh->alias);
4358                         if (!in->variant.symLinkVariant.alias)
4359                                 alloc_failed = 1; /* Not returned to caller */
4360                 }
4361
4362                 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
4363         }
4364 }
4365
4366 /*------------------------------  Directory Functions ----------------------------- */
4367
4368 /*
4369  *yaffs_UpdateParent() handles fixing a directories mtime and ctime when a new
4370  * link (ie. name) is created or deleted in the directory.
4371  *
4372  * ie.
4373  *   create dir/a : update dir's mtime/ctime
4374  *   rm dir/a:   update dir's mtime/ctime
4375  *   modify dir/a: don't update dir's mtimme/ctime
4376  *
4377  * This can be handled immediately or defered. Defering helps reduce the number
4378  * of updates when many files in a directory are changed within a brief period.
4379  *
4380  * If the directory updating is defered then yaffs_UpdateDirtyDirecories must be
4381  * called periodically.
4382  */
4383  
4384 static void yaffs_UpdateParent(yaffs_Object *obj)
4385 {
4386         yaffs_Device *dev;
4387         if(!obj)
4388                 return;
4389
4390         dev = obj->myDev;
4391         obj->dirty = 1;
4392         obj->yst_mtime = obj->yst_ctime = Y_CURRENT_TIME;
4393         if(dev->param.deferDirectoryUpdate){
4394                 struct ylist_head *link = &obj->variant.directoryVariant.dirty; 
4395         
4396                 if(ylist_empty(link)){
4397                         ylist_add(link,&dev->dirtyDirectories);
4398                         T(YAFFS_TRACE_BACKGROUND, (TSTR("Added object %d to dirty directories" TENDSTR),obj->objectId));
4399                 }
4400
4401         } else
4402                 yaffs_UpdateObjectHeader(obj, NULL, 0, 0, 0, NULL);
4403 }
4404
4405 void yaffs_UpdateDirtyDirectories(yaffs_Device *dev)
4406 {
4407         struct ylist_head *link;
4408         yaffs_Object *obj;
4409         yaffs_DirectoryStructure *dS;
4410         yaffs_ObjectVariant *oV;
4411
4412         T(YAFFS_TRACE_BACKGROUND, (TSTR("Update dirty directories" TENDSTR)));
4413
4414         while(!ylist_empty(&dev->dirtyDirectories)){
4415                 link = dev->dirtyDirectories.next;
4416                 ylist_del_init(link);
4417                 
4418                 dS=ylist_entry(link,yaffs_DirectoryStructure,dirty);
4419                 oV = ylist_entry(dS,yaffs_ObjectVariant,directoryVariant);
4420                 obj = ylist_entry(oV,yaffs_Object,variant);
4421
4422                 T(YAFFS_TRACE_BACKGROUND, (TSTR("Update directory %d" TENDSTR), obj->objectId));
4423
4424                 if(obj->dirty)
4425                         yaffs_UpdateObjectHeader(obj, NULL, 0, 0, 0, NULL);
4426         }
4427 }
4428
4429 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
4430 {
4431         yaffs_Device *dev = obj->myDev;
4432         yaffs_Object *parent;
4433
4434         yaffs_VerifyObjectInDirectory(obj);
4435         parent = obj->parent;
4436
4437         yaffs_VerifyDirectory(parent);
4438
4439         if (dev && dev->param.removeObjectCallback)
4440                 dev->param.removeObjectCallback(obj);
4441
4442
4443         ylist_del_init(&obj->siblings);
4444         obj->parent = NULL;
4445         
4446         yaffs_VerifyDirectory(parent);
4447 }
4448
4449 void yaffs_AddObjectToDirectory(yaffs_Object *directory,
4450                                         yaffs_Object *obj)
4451 {
4452         if (!directory) {
4453                 T(YAFFS_TRACE_ALWAYS,
4454                   (TSTR
4455                    ("tragedy: Trying to add an object to a null pointer directory"
4456                     TENDSTR)));
4457                 YBUG();
4458                 return;
4459         }
4460         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4461                 T(YAFFS_TRACE_ALWAYS,
4462                   (TSTR
4463                    ("tragedy: Trying to add an object to a non-directory"
4464                     TENDSTR)));
4465                 YBUG();
4466         }
4467
4468         if (obj->siblings.prev == NULL) {
4469                 /* Not initialised */
4470                 YBUG();
4471         }
4472
4473
4474         yaffs_VerifyDirectory(directory);
4475
4476         yaffs_RemoveObjectFromDirectory(obj);
4477
4478
4479         /* Now add it */
4480         ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
4481         obj->parent = directory;
4482
4483         if (directory == obj->myDev->unlinkedDir
4484                         || directory == obj->myDev->deletedDir) {
4485                 obj->unlinked = 1;
4486                 obj->myDev->nUnlinkedFiles++;
4487                 obj->renameAllowed = 0;
4488         }
4489
4490         yaffs_VerifyDirectory(directory);
4491         yaffs_VerifyObjectInDirectory(obj);
4492 }
4493
4494 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
4495                                      const YCHAR *name)
4496 {
4497         int sum;
4498
4499         struct ylist_head *i;
4500         YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
4501
4502         yaffs_Object *l;
4503
4504         if (!name)
4505                 return NULL;
4506
4507         if (!directory) {
4508                 T(YAFFS_TRACE_ALWAYS,
4509                   (TSTR
4510                    ("tragedy: yaffs_FindObjectByName: null pointer directory"
4511                     TENDSTR)));
4512                 YBUG();
4513                 return NULL;
4514         }
4515         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4516                 T(YAFFS_TRACE_ALWAYS,
4517                   (TSTR
4518                    ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
4519                 YBUG();
4520         }
4521
4522         sum = yaffs_CalcNameSum(name);
4523
4524         ylist_for_each(i, &directory->variant.directoryVariant.children) {
4525                 if (i) {
4526                         l = ylist_entry(i, yaffs_Object, siblings);
4527
4528                         if (l->parent != directory)
4529                                 YBUG();
4530
4531                         yaffs_CheckObjectDetailsLoaded(l);
4532
4533                         /* Special case for lost-n-found */
4534                         if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
4535                                 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
4536                                         return l;
4537                         } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
4538                                 /* LostnFound chunk called Objxxx
4539                                  * Do a real check
4540                                  */
4541                                 yaffs_GetObjectName(l, buffer,
4542                                                     YAFFS_MAX_NAME_LENGTH + 1);
4543                                 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
4544                                         return l;
4545                         }
4546                 }
4547         }
4548
4549         return NULL;
4550 }
4551
4552
4553 #if 0
4554 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
4555                                         int (*fn) (yaffs_Object *))
4556 {
4557         struct ylist_head *i;
4558         yaffs_Object *l;
4559
4560         if (!theDir) {
4561                 T(YAFFS_TRACE_ALWAYS,
4562                   (TSTR
4563                    ("tragedy: yaffs_FindObjectByName: null pointer directory"
4564                     TENDSTR)));
4565                 YBUG();
4566                 return YAFFS_FAIL;
4567         }
4568         if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4569                 T(YAFFS_TRACE_ALWAYS,
4570                   (TSTR
4571                    ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
4572                 YBUG();
4573                 return YAFFS_FAIL;
4574         }
4575
4576         ylist_for_each(i, &theDir->variant.directoryVariant.children) {
4577                 if (i) {
4578                         l = ylist_entry(i, yaffs_Object, siblings);
4579                         if (l && !fn(l))
4580                                 return YAFFS_FAIL;
4581                 }
4582         }
4583
4584         return YAFFS_OK;
4585
4586 }
4587 #endif
4588
4589 /* GetEquivalentObject dereferences any hard links to get to the
4590  * actual object.
4591  */
4592
4593 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
4594 {
4595         if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4596                 /* We want the object id of the equivalent object, not this one */
4597                 obj = obj->variant.hardLinkVariant.equivalentObject;
4598                 yaffs_CheckObjectDetailsLoaded(obj);
4599         }
4600         return obj;
4601 }
4602
4603 int yaffs_GetObjectName(yaffs_Object *obj, YCHAR *name, int buffSize)
4604 {
4605         memset(name, 0, buffSize * sizeof(YCHAR));
4606
4607         yaffs_CheckObjectDetailsLoaded(obj);
4608
4609         if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
4610                 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
4611         } else if (obj->hdrChunk <= 0) {
4612                 YCHAR locName[20];
4613                 YCHAR numString[20];
4614                 YCHAR *x = &numString[19];
4615                 unsigned v = obj->objectId;
4616                 numString[19] = 0;
4617                 while (v > 0) {
4618                         x--;
4619                         *x = '0' + (v % 10);
4620                         v /= 10;
4621                 }
4622                 /* make up a name */
4623                 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
4624                 yaffs_strcat(locName, x);
4625                 yaffs_strncpy(name, locName, buffSize - 1);
4626
4627         }
4628 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
4629         else if (obj->shortName[0])
4630                 yaffs_strncpy(name, obj->shortName,YAFFS_SHORT_NAME_LENGTH+1);
4631 #endif
4632         else {
4633                 int result;
4634                 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
4635
4636                 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
4637
4638                 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
4639
4640                 if (obj->hdrChunk > 0) {
4641                         result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
4642                                                         obj->hdrChunk, buffer,
4643                                                         NULL);
4644                 }
4645                 yaffs_strncpy(name, oh->name, buffSize - 1);
4646                 name[buffSize-1]=0;
4647
4648                 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
4649         }
4650
4651         return yaffs_strnlen(name,buffSize-1);
4652 }
4653
4654 int yaffs_GetObjectFileLength(yaffs_Object *obj)
4655 {
4656         /* Dereference any hard linking */
4657         obj = yaffs_GetEquivalentObject(obj);
4658
4659         if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4660                 return obj->variant.fileVariant.fileSize;
4661         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
4662                 if(!obj->variant.symLinkVariant.alias)
4663                         return 0;
4664                 return yaffs_strnlen(obj->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
4665         } else {
4666                 /* Only a directory should drop through to here */
4667                 return obj->myDev->nDataBytesPerChunk;
4668         }
4669 }
4670
4671 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
4672 {
4673         int count = 0;
4674         struct ylist_head *i;
4675
4676         if (!obj->unlinked)
4677                 count++;                /* the object itself */
4678
4679         ylist_for_each(i, &obj->hardLinks)
4680                 count++;                /* add the hard links; */
4681
4682         return count;
4683 }
4684
4685 int yaffs_GetObjectInode(yaffs_Object *obj)
4686 {
4687         obj = yaffs_GetEquivalentObject(obj);
4688
4689         return obj->objectId;
4690 }
4691
4692 unsigned yaffs_GetObjectType(yaffs_Object *obj)
4693 {
4694         obj = yaffs_GetEquivalentObject(obj);
4695
4696         switch (obj->variantType) {
4697         case YAFFS_OBJECT_TYPE_FILE:
4698                 return DT_REG;
4699                 break;
4700         case YAFFS_OBJECT_TYPE_DIRECTORY:
4701                 return DT_DIR;
4702                 break;
4703         case YAFFS_OBJECT_TYPE_SYMLINK:
4704                 return DT_LNK;
4705                 break;
4706         case YAFFS_OBJECT_TYPE_HARDLINK:
4707                 return DT_REG;
4708                 break;
4709         case YAFFS_OBJECT_TYPE_SPECIAL:
4710                 if (S_ISFIFO(obj->yst_mode))
4711                         return DT_FIFO;
4712                 if (S_ISCHR(obj->yst_mode))
4713                         return DT_CHR;
4714                 if (S_ISBLK(obj->yst_mode))
4715                         return DT_BLK;
4716                 if (S_ISSOCK(obj->yst_mode))
4717                         return DT_SOCK;
4718         default:
4719                 return DT_REG;
4720                 break;
4721         }
4722 }
4723
4724 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
4725 {
4726         obj = yaffs_GetEquivalentObject(obj);
4727         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
4728                 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
4729         else
4730                 return yaffs_CloneString(_Y(""));
4731 }
4732
4733 #ifndef CONFIG_YAFFS_WINCE
4734
4735 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
4736 {
4737         unsigned int valid = attr->ia_valid;
4738
4739         if (valid & ATTR_MODE)
4740                 obj->yst_mode = attr->ia_mode;
4741         if (valid & ATTR_UID)
4742                 obj->yst_uid = attr->ia_uid;
4743         if (valid & ATTR_GID)
4744                 obj->yst_gid = attr->ia_gid;
4745
4746         if (valid & ATTR_ATIME)
4747                 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
4748         if (valid & ATTR_CTIME)
4749                 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
4750         if (valid & ATTR_MTIME)
4751                 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
4752
4753         if (valid & ATTR_SIZE)
4754                 yaffs_ResizeFile(obj, attr->ia_size);
4755
4756         yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0, NULL);
4757
4758         return YAFFS_OK;
4759
4760 }
4761 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
4762 {
4763         unsigned int valid = 0;
4764
4765         attr->ia_mode = obj->yst_mode;
4766         valid |= ATTR_MODE;
4767         attr->ia_uid = obj->yst_uid;
4768         valid |= ATTR_UID;
4769         attr->ia_gid = obj->yst_gid;
4770         valid |= ATTR_GID;
4771
4772         Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
4773         valid |= ATTR_ATIME;
4774         Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
4775         valid |= ATTR_CTIME;
4776         Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
4777         valid |= ATTR_MTIME;
4778
4779         attr->ia_size = yaffs_GetFileSize(obj);
4780         valid |= ATTR_SIZE;
4781
4782         attr->ia_valid = valid;
4783
4784         return YAFFS_OK;
4785 }
4786
4787 #endif
4788
4789
4790 static int yaffs_DoXMod(yaffs_Object *obj, int set, const char *name, const void *value, int size, int flags)
4791 {
4792         yaffs_XAttrMod xmod;
4793
4794         int result;
4795
4796         xmod.set = set;
4797         xmod.name = name;
4798         xmod.data = value;
4799         xmod.size =  size;
4800         xmod.flags = flags;
4801         xmod.result = -ENOSPC;
4802
4803         result = yaffs_UpdateObjectHeader(obj, NULL, 0, 0, 0, &xmod);
4804
4805         if(result > 0)
4806                 return xmod.result;
4807         else
4808                 return -ENOSPC;
4809 }
4810
4811 static int yaffs_ApplyXMod(yaffs_Device *dev, char *buffer, yaffs_XAttrMod *xmod)
4812 {
4813         int retval = 0;
4814         int x_offs = sizeof(yaffs_ObjectHeader);
4815         int x_size = dev->nDataBytesPerChunk - sizeof(yaffs_ObjectHeader);
4816
4817         char * x_buffer = buffer + x_offs;
4818
4819         if(xmod->set)
4820                 retval = nval_set(x_buffer, x_size, xmod->name, xmod->data, xmod->size, xmod->flags);
4821         else
4822                 retval = nval_del(x_buffer, x_size, xmod->name);
4823
4824         xmod->result = retval;
4825
4826         return retval;
4827 }
4828
4829 static int yaffs_DoXFetch(yaffs_Object *obj, const char *name, void *value, int size)
4830 {
4831         char *buffer = NULL;
4832         int result;
4833         yaffs_ExtendedTags tags;
4834         yaffs_Device *dev = obj->myDev;
4835         int x_offs = sizeof(yaffs_ObjectHeader);
4836         int x_size = dev->nDataBytesPerChunk - sizeof(yaffs_ObjectHeader);
4837
4838         __u8 * x_buffer;
4839
4840         int retval = 0;
4841
4842         if(obj->hdrChunk < 1)
4843                 return -ENODATA;
4844
4845         buffer = yaffs_GetTempBuffer(dev, __LINE__);
4846         if(!buffer)
4847                 return -ENOMEM;
4848
4849         result = yaffs_ReadChunkWithTagsFromNAND(dev,obj->hdrChunk, buffer, &tags);
4850
4851         if(result != YAFFS_OK)
4852                 retval = -ENOENT;
4853         else{
4854                 x_buffer =  buffer + x_offs;
4855
4856                 if(name)
4857                         retval = nval_get(x_buffer, x_size, name, value, size);
4858                 else
4859                         retval = nval_list(x_buffer, x_size, value,size);
4860         }
4861         yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
4862         return retval;
4863 }
4864
4865 int yaffs_SetXAttribute(yaffs_Object *obj, const char *name, const void * value, int size, int flags)
4866 {
4867         return yaffs_DoXMod(obj, 1, name, value, size, flags);
4868 }
4869
4870 int yaffs_RemoveXAttribute(yaffs_Object *obj, const char *name)
4871 {
4872         return yaffs_DoXMod(obj, 0, name, NULL, 0, 0);
4873 }
4874
4875 int yaffs_GetXAttribute(yaffs_Object *obj, const char *name, void *value, int size)
4876 {
4877         return yaffs_DoXFetch(obj, name, value, size);
4878 }
4879
4880 int yaffs_ListXAttributes(yaffs_Object *obj, char *buffer, int size)
4881 {
4882         return yaffs_DoXFetch(obj, NULL, buffer,size);
4883 }
4884
4885
4886
4887 #if 0
4888 int yaffs_DumpObject(yaffs_Object *obj)
4889 {
4890         YCHAR name[257];
4891
4892         yaffs_GetObjectName(obj, name, YAFFS_MAX_NAME_LENGTH + 1);
4893
4894         T(YAFFS_TRACE_ALWAYS,
4895           (TSTR
4896            ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
4897             " chunk %d type %d size %d\n"
4898             TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
4899            obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
4900            yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
4901
4902         return YAFFS_OK;
4903 }
4904 #endif
4905
4906 /*---------------------------- Initialisation code -------------------------------------- */
4907
4908 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
4909 {
4910
4911         /* Common functions, gotta have */
4912         if (!dev->param.eraseBlockInNAND || !dev->param.initialiseNAND)
4913                 return 0;
4914
4915 #ifdef CONFIG_YAFFS_YAFFS2
4916
4917         /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
4918         if (dev->param.writeChunkWithTagsToNAND &&
4919             dev->param.readChunkWithTagsFromNAND &&
4920             !dev->param.writeChunkToNAND &&
4921             !dev->param.readChunkFromNAND &&
4922             dev->param.markNANDBlockBad &&
4923             dev->param.queryNANDBlock)
4924                 return 1;
4925 #endif
4926
4927         /* Can use the "spare" style interface for yaffs1 */
4928         if (!dev->param.isYaffs2 &&
4929             !dev->param.writeChunkWithTagsToNAND &&
4930             !dev->param.readChunkWithTagsFromNAND &&
4931             dev->param.writeChunkToNAND &&
4932             dev->param.readChunkFromNAND &&
4933             !dev->param.markNANDBlockBad &&
4934             !dev->param.queryNANDBlock)
4935                 return 1;
4936
4937         return 0;       /* bad */
4938 }
4939
4940
4941 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
4942 {
4943         /* Initialise the unlinked, deleted, root and lost and found directories */
4944
4945         dev->lostNFoundDir = dev->rootDir =  NULL;
4946         dev->unlinkedDir = dev->deletedDir = NULL;
4947
4948         dev->unlinkedDir =
4949             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
4950
4951         dev->deletedDir =
4952             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
4953
4954         dev->rootDir =
4955             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
4956                                       YAFFS_ROOT_MODE | S_IFDIR);
4957         dev->lostNFoundDir =
4958             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
4959                                       YAFFS_LOSTNFOUND_MODE | S_IFDIR);
4960
4961         if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
4962                 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
4963                 return YAFFS_OK;
4964         }
4965
4966         return YAFFS_FAIL;
4967 }
4968
4969 int yaffs_GutsInitialise(yaffs_Device *dev)
4970 {
4971         int init_failed = 0;
4972         unsigned x;
4973         int bits;
4974
4975         T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
4976
4977         /* Check stuff that must be set */
4978
4979         if (!dev) {
4980                 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
4981                 return YAFFS_FAIL;
4982         }
4983
4984         dev->internalStartBlock = dev->param.startBlock;
4985         dev->internalEndBlock = dev->param.endBlock;
4986         dev->blockOffset = 0;
4987         dev->chunkOffset = 0;
4988         dev->nFreeChunks = 0;
4989
4990         dev->gcBlock = 0;
4991
4992         if (dev->param.startBlock == 0) {
4993                 dev->internalStartBlock = dev->param.startBlock + 1;
4994                 dev->internalEndBlock = dev->param.endBlock + 1;
4995                 dev->blockOffset = 1;
4996                 dev->chunkOffset = dev->param.nChunksPerBlock;
4997         }
4998
4999         /* Check geometry parameters. */
5000
5001         if ((!dev->param.inbandTags && dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 1024) ||
5002             (!dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 512) ||
5003             (dev->param.inbandTags && !dev->param.isYaffs2) ||
5004              dev->param.nChunksPerBlock < 2 ||
5005              dev->param.nReservedBlocks < 2 ||
5006              dev->internalStartBlock <= 0 ||
5007              dev->internalEndBlock <= 0 ||
5008              dev->internalEndBlock <= (dev->internalStartBlock + dev->param.nReservedBlocks + 2)) {     /* otherwise it is too small */
5009                 T(YAFFS_TRACE_ALWAYS,
5010                   (TSTR
5011                    ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
5012                     TENDSTR), dev->param.totalBytesPerChunk, dev->param.isYaffs2 ? "2" : "", dev->param.inbandTags));
5013                 return YAFFS_FAIL;
5014         }
5015
5016         if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
5017                 T(YAFFS_TRACE_ALWAYS,
5018                   (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
5019                 return YAFFS_FAIL;
5020         }
5021
5022         /* Sort out space for inband tags, if required */
5023         if (dev->param.inbandTags)
5024                 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
5025         else
5026                 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk;
5027
5028         /* Got the right mix of functions? */
5029         if (!yaffs_CheckDevFunctions(dev)) {
5030                 /* Function missing */
5031                 T(YAFFS_TRACE_ALWAYS,
5032                   (TSTR
5033                    ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
5034
5035                 return YAFFS_FAIL;
5036         }
5037
5038         /* This is really a compilation check. */
5039         if (!yaffs_CheckStructures()) {
5040                 T(YAFFS_TRACE_ALWAYS,
5041                   (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
5042                 return YAFFS_FAIL;
5043         }
5044
5045         if (dev->isMounted) {
5046                 T(YAFFS_TRACE_ALWAYS,
5047                   (TSTR("yaffs: device already mounted\n" TENDSTR)));
5048                 return YAFFS_FAIL;
5049         }
5050
5051         /* Finished with most checks. One or two more checks happen later on too. */
5052
5053         dev->isMounted = 1;
5054
5055         /* OK now calculate a few things for the device */
5056
5057         /*
5058          *  Calculate all the chunk size manipulation numbers:
5059          */
5060         x = dev->nDataBytesPerChunk;
5061         /* We always use dev->chunkShift and dev->chunkDiv */
5062         dev->chunkShift = Shifts(x);
5063         x >>= dev->chunkShift;
5064         dev->chunkDiv = x;
5065         /* We only use chunk mask if chunkDiv is 1 */
5066         dev->chunkMask = (1<<dev->chunkShift) - 1;
5067
5068         /*
5069          * Calculate chunkGroupBits.
5070          * We need to find the next power of 2 > than internalEndBlock
5071          */
5072
5073         x = dev->param.nChunksPerBlock * (dev->internalEndBlock + 1);
5074
5075         bits = ShiftsGE(x);
5076
5077         /* Set up tnode width if wide tnodes are enabled. */
5078         if (!dev->param.wideTnodesDisabled) {
5079                 /* bits must be even so that we end up with 32-bit words */
5080                 if (bits & 1)
5081                         bits++;
5082                 if (bits < 16)
5083                         dev->tnodeWidth = 16;
5084                 else
5085                         dev->tnodeWidth = bits;
5086         } else
5087                 dev->tnodeWidth = 16;
5088
5089         dev->tnodeMask = (1<<dev->tnodeWidth)-1;
5090
5091         /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
5092          * so if the bitwidth of the
5093          * chunk range we're using is greater than 16 we need
5094          * to figure out chunk shift and chunkGroupSize
5095          */
5096
5097         if (bits <= dev->tnodeWidth)
5098                 dev->chunkGroupBits = 0;
5099         else
5100                 dev->chunkGroupBits = bits - dev->tnodeWidth;
5101
5102         dev->tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
5103         if(dev->tnodeSize < sizeof(yaffs_Tnode))
5104                 dev->tnodeSize = sizeof(yaffs_Tnode);
5105
5106         dev->chunkGroupSize = 1 << dev->chunkGroupBits;
5107
5108         if (dev->param.nChunksPerBlock < dev->chunkGroupSize) {
5109                 /* We have a problem because the soft delete won't work if
5110                  * the chunk group size > chunks per block.
5111                  * This can be remedied by using larger "virtual blocks".
5112                  */
5113                 T(YAFFS_TRACE_ALWAYS,
5114                   (TSTR("yaffs: chunk group too large\n" TENDSTR)));
5115
5116                 return YAFFS_FAIL;
5117         }
5118
5119         /* OK, we've finished verifying the device, lets continue with initialisation */
5120
5121         /* More device initialisation */
5122         dev->allGCs = 0;
5123         dev->passiveGCs = 0;
5124         dev->oldestDirtyGCs = 0;
5125         dev->backgroundGCs = 0;
5126         dev->gcBlockFinder = 0;
5127         dev->bufferedBlock = -1;
5128         dev->doingBufferedBlockRewrite = 0;
5129         dev->nDeletedFiles = 0;
5130         dev->nBackgroundDeletions = 0;
5131         dev->nUnlinkedFiles = 0;
5132         dev->eccFixed = 0;
5133         dev->eccUnfixed = 0;
5134         dev->tagsEccFixed = 0;
5135         dev->tagsEccUnfixed = 0;
5136         dev->nErasureFailures = 0;
5137         dev->nErasedBlocks = 0;
5138         dev->gcDisable= 0;
5139         dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
5140         YINIT_LIST_HEAD(&dev->dirtyDirectories);
5141         dev->oldestDirtySequence = 0;
5142         dev->oldestDirtyBlock = 0;
5143
5144         /* Initialise temporary buffers and caches. */
5145         if (!yaffs_InitialiseTempBuffers(dev))
5146                 init_failed = 1;
5147
5148         dev->srCache = NULL;
5149         dev->gcCleanupList = NULL;
5150
5151
5152         if (!init_failed &&
5153             dev->param.nShortOpCaches > 0) {
5154                 int i;
5155                 void *buf;
5156                 int srCacheBytes = dev->param.nShortOpCaches * sizeof(yaffs_ChunkCache);
5157
5158                 if (dev->param.nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
5159                         dev->param.nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
5160
5161                 dev->srCache =  YMALLOC(srCacheBytes);
5162
5163                 buf = (__u8 *) dev->srCache;
5164
5165                 if (dev->srCache)
5166                         memset(dev->srCache, 0, srCacheBytes);
5167
5168                 for (i = 0; i < dev->param.nShortOpCaches && buf; i++) {
5169                         dev->srCache[i].object = NULL;
5170                         dev->srCache[i].lastUse = 0;
5171                         dev->srCache[i].dirty = 0;
5172                         dev->srCache[i].data = buf = YMALLOC_DMA(dev->param.totalBytesPerChunk);
5173                 }
5174                 if (!buf)
5175                         init_failed = 1;
5176
5177                 dev->srLastUse = 0;
5178         }
5179
5180         dev->cacheHits = 0;
5181
5182         if (!init_failed) {
5183                 dev->gcCleanupList = YMALLOC(dev->param.nChunksPerBlock * sizeof(__u32));
5184                 if (!dev->gcCleanupList)
5185                         init_failed = 1;
5186         }
5187
5188         if (dev->param.isYaffs2)
5189                 dev->param.useHeaderFileSize = 1;
5190
5191         if (!init_failed && !yaffs_InitialiseBlocks(dev))
5192                 init_failed = 1;
5193
5194         yaffs_InitialiseTnodesAndObjects(dev);
5195
5196         if (!init_failed && !yaffs_CreateInitialDirectories(dev))
5197                 init_failed = 1;
5198
5199
5200         if (!init_failed) {
5201                 /* Now scan the flash. */
5202                 if (dev->param.isYaffs2) {
5203                         if (yaffs2_CheckpointRestore(dev)) {
5204                                 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
5205                                 T(YAFFS_TRACE_ALWAYS,
5206                                   (TSTR("yaffs: restored from checkpoint" TENDSTR)));
5207                         } else {
5208
5209                                 /* Clean up the mess caused by an aborted checkpoint load
5210                                  * and scan backwards.
5211                                  */
5212                                 yaffs_DeinitialiseBlocks(dev);
5213
5214                                 yaffs_DeinitialiseTnodesAndObjects(dev);
5215
5216                                 dev->nErasedBlocks = 0;
5217                                 dev->nFreeChunks = 0;
5218                                 dev->allocationBlock = -1;
5219                                 dev->allocationPage = -1;
5220                                 dev->nDeletedFiles = 0;
5221                                 dev->nUnlinkedFiles = 0;
5222                                 dev->nBackgroundDeletions = 0;
5223
5224                                 if (!init_failed && !yaffs_InitialiseBlocks(dev))
5225                                         init_failed = 1;
5226
5227                                 yaffs_InitialiseTnodesAndObjects(dev);
5228
5229                                 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
5230                                         init_failed = 1;
5231
5232                                 if (!init_failed && !yaffs2_ScanBackwards(dev))
5233                                         init_failed = 1;
5234                         }
5235                 } else if (!yaffs1_Scan(dev))
5236                                 init_failed = 1;
5237
5238                 yaffs_StripDeletedObjects(dev);
5239                 yaffs_FixHangingObjects(dev);
5240                 if(dev->param.emptyLostAndFound)
5241                         yaffs_EmptyLostAndFound(dev);
5242         }
5243
5244         if (init_failed) {
5245                 /* Clean up the mess */
5246                 T(YAFFS_TRACE_TRACING,
5247                   (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
5248
5249                 yaffs_Deinitialise(dev);
5250                 return YAFFS_FAIL;
5251         }
5252
5253         /* Zero out stats */
5254         dev->nPageReads = 0;
5255         dev->nPageWrites = 0;
5256         dev->nBlockErasures = 0;
5257         dev->nGCCopies = 0;
5258         dev->nRetriedWrites = 0;
5259
5260         dev->nRetiredBlocks = 0;
5261
5262         yaffs_VerifyFreeChunks(dev);
5263         yaffs_VerifyBlocks(dev);
5264
5265         /* Clean up any aborted checkpoint data */
5266         if(!dev->isCheckpointed && dev->blocksInCheckpoint > 0)
5267                 yaffs2_InvalidateCheckpoint(dev);
5268
5269         T(YAFFS_TRACE_TRACING,
5270           (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
5271         return YAFFS_OK;
5272
5273 }
5274
5275 void yaffs_Deinitialise(yaffs_Device *dev)
5276 {
5277         if (dev->isMounted) {
5278                 int i;
5279
5280                 yaffs_DeinitialiseBlocks(dev);
5281                 yaffs_DeinitialiseTnodesAndObjects(dev);
5282                 if (dev->param.nShortOpCaches > 0 &&
5283                     dev->srCache) {
5284
5285                         for (i = 0; i < dev->param.nShortOpCaches; i++) {
5286                                 if (dev->srCache[i].data)
5287                                         YFREE(dev->srCache[i].data);
5288                                 dev->srCache[i].data = NULL;
5289                         }
5290
5291                         YFREE(dev->srCache);
5292                         dev->srCache = NULL;
5293                 }
5294
5295                 YFREE(dev->gcCleanupList);
5296
5297                 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
5298                         YFREE(dev->tempBuffer[i].buffer);
5299
5300                 dev->isMounted = 0;
5301
5302                 if (dev->param.deinitialiseNAND)
5303                         dev->param.deinitialiseNAND(dev);
5304         }
5305 }
5306
5307 int yaffs_CountFreeChunks(yaffs_Device *dev)
5308 {
5309         int nFree=0;
5310         int b;
5311
5312         yaffs_BlockInfo *blk;
5313
5314         blk = dev->blockInfo;
5315         for (b = dev->internalStartBlock; b <= dev->internalEndBlock; b++) {
5316                 switch (blk->blockState) {
5317                 case YAFFS_BLOCK_STATE_EMPTY:
5318                 case YAFFS_BLOCK_STATE_ALLOCATING:
5319                 case YAFFS_BLOCK_STATE_COLLECTING:
5320                 case YAFFS_BLOCK_STATE_FULL:
5321                         nFree +=
5322                             (dev->param.nChunksPerBlock - blk->pagesInUse +
5323                              blk->softDeletions);
5324                         break;
5325                 default:
5326                         break;
5327                 }
5328                 blk++;
5329         }
5330
5331         return nFree;
5332 }
5333
5334 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
5335 {
5336         /* This is what we report to the outside world */
5337
5338         int nFree;
5339         int nDirtyCacheChunks;
5340         int blocksForCheckpoint;
5341         int i;
5342
5343 #if 1
5344         nFree = dev->nFreeChunks;
5345 #else
5346         nFree = yaffs_CountFreeChunks(dev);
5347 #endif
5348
5349         nFree += dev->nDeletedFiles;
5350
5351         /* Now count the number of dirty chunks in the cache and subtract those */
5352
5353         for (nDirtyCacheChunks = 0, i = 0; i < dev->param.nShortOpCaches; i++) {
5354                 if (dev->srCache[i].dirty)
5355                         nDirtyCacheChunks++;
5356         }
5357
5358         nFree -= nDirtyCacheChunks;
5359
5360         nFree -= ((dev->param.nReservedBlocks + 1) * dev->param.nChunksPerBlock);
5361
5362         /* Now we figure out how much to reserve for the checkpoint and report that... */
5363         blocksForCheckpoint = yaffs2_CalcCheckpointBlocksRequired(dev);
5364
5365         nFree -= (blocksForCheckpoint * dev->param.nChunksPerBlock);
5366
5367         if (nFree < 0)
5368                 nFree = 0;
5369
5370         return nFree;
5371
5372 }
5373
5374
5375 /*---------------------------------------- YAFFS test code ----------------------*/
5376
5377 #define yaffs_CheckStruct(structure, syze, name) \
5378         do { \
5379                 if (sizeof(structure) != syze) { \
5380                         T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
5381                                 name, syze, (int) sizeof(structure))); \
5382                         return YAFFS_FAIL; \
5383                 } \
5384         } while (0)
5385
5386 static int yaffs_CheckStructures(void)
5387 {
5388 /*      yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
5389 /*      yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
5390 /*      yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
5391 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
5392 /*      yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode"); */
5393 #endif
5394 #ifndef CONFIG_YAFFS_WINCE
5395         yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");
5396 #endif
5397         return YAFFS_OK;
5398 }