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