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