yaffs: Batter read-only support handling
[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
2227                                         object->nDataChunks--;
2228
2229                                         if (object->nDataChunks <= 0) {
2230                                                 /* remeber to clean up the object */
2231                                                 dev->gcCleanupList[dev->nCleanups] =
2232                                                     tags.objectId;
2233                                                 dev->nCleanups++;
2234                                         }
2235                                         markNAND = 0;
2236                                 } else if (0) {
2237                                         /* Todo object && object->deleted && object->nDataChunks == 0 */
2238                                         /* Deleted object header with no data chunks.
2239                                          * Can be discarded and the file deleted.
2240                                          */
2241                                         object->hdrChunk = 0;
2242                                         yaffs_FreeTnode(object->myDev,
2243                                                         object->variant.
2244                                                         fileVariant.top);
2245                                         object->variant.fileVariant.top = NULL;
2246                                         yaffs_DoGenericObjectDeletion(object);
2247
2248                                 } else if (object) {
2249                                         /* It's either a data chunk in a live file or
2250                                          * an ObjectHeader, so we're interested in it.
2251                                          * NB Need to keep the ObjectHeaders of deleted files
2252                                          * until the whole file has been deleted off
2253                                          */
2254                                         tags.serialNumber++;
2255
2256                                         dev->nGCCopies++;
2257
2258                                         if (tags.chunkId == 0) {
2259                                                 /* It is an object Id,
2260                                                  * We need to nuke the shrinkheader flags first
2261                                                  * Also need to clean up shadowing.
2262                                                  * We no longer want the shrinkHeader flag since its work is done
2263                                                  * and if it is left in place it will mess up scanning.
2264                                                  */
2265
2266                                                 yaffs_ObjectHeader *oh;
2267                                                 oh = (yaffs_ObjectHeader *)buffer;
2268
2269                                                 oh->isShrink = 0;
2270                                                 tags.extraIsShrinkHeader = 0;
2271
2272                                                 oh->shadowsObject = 0;
2273                                                 oh->inbandShadowsObject = 0;
2274                                                 tags.extraShadows = 0;
2275
2276                                                 /* Update file size */
2277                                                 if(object->variantType == YAFFS_OBJECT_TYPE_FILE){
2278                                                         oh->fileSize = object->variant.fileVariant.fileSize;
2279                                                         tags.extraFileLength = oh->fileSize;
2280                                                 }
2281
2282                                                 yaffs_VerifyObjectHeader(object, oh, &tags, 1);
2283                                                 newChunk =
2284                                                     yaffs_WriteNewChunkWithTagsToNAND(dev,(__u8 *) oh, &tags, 1);
2285                                         } else
2286                                                 newChunk =
2287                                                     yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &tags, 1);
2288
2289                                         if (newChunk < 0) {
2290                                                 retVal = YAFFS_FAIL;
2291                                         } else {
2292
2293                                                 /* Ok, now fix up the Tnodes etc. */
2294
2295                                                 if (tags.chunkId == 0) {
2296                                                         /* It's a header */
2297                                                         object->hdrChunk =  newChunk;
2298                                                         object->serial =   tags.serialNumber;
2299                                                 } else {
2300                                                         /* It's a data chunk */
2301                                                         int ok;
2302                                                         ok = yaffs_PutChunkIntoFile
2303                                                             (object,
2304                                                              tags.chunkId,
2305                                                              newChunk, 0);
2306                                                 }
2307                                         }
2308                                 }
2309
2310                                 if (retVal == YAFFS_OK)
2311                                         yaffs_DeleteChunk(dev, oldChunk, markNAND, __LINE__);
2312
2313                         }
2314                 }
2315
2316                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
2317
2318
2319
2320         }
2321
2322         yaffs_VerifyCollectedBlock(dev, bi, block);
2323
2324
2325
2326         if (bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2327                 /*
2328                  * The gc did not complete. Set block state back to FULL
2329                  * because checkpointing does not restore gc.
2330                  */
2331                 bi->blockState = YAFFS_BLOCK_STATE_FULL;
2332         } else {
2333                 /* The gc completed. */
2334                 /* Do any required cleanups */
2335                 for (i = 0; i < dev->nCleanups; i++) {
2336                         /* Time to delete the file too */
2337                         object =
2338                             yaffs_FindObjectByNumber(dev,
2339                                                      dev->gcCleanupList[i]);
2340                         if (object) {
2341                                 yaffs_FreeTnode(dev,
2342                                                 object->variant.fileVariant.
2343                                                 top);
2344                                 object->variant.fileVariant.top = NULL;
2345                                 T(YAFFS_TRACE_GC,
2346                                   (TSTR
2347                                    ("yaffs: About to finally delete object %d"
2348                                     TENDSTR), object->objectId));
2349                                 yaffs_DoGenericObjectDeletion(object);
2350                                 object->myDev->nDeletedFiles--;
2351                         }
2352
2353                 }
2354
2355
2356                 chunksAfter = yaffs_GetErasedChunks(dev);
2357                 if (chunksBefore >= chunksAfter) {
2358                         T(YAFFS_TRACE_GC,
2359                           (TSTR
2360                            ("gc did not increase free chunks before %d after %d"
2361                             TENDSTR), chunksBefore, chunksAfter));
2362                 }
2363                 dev->gcBlock = 0;
2364                 dev->gcChunk = 0;
2365                 dev->nCleanups = 0;
2366         }
2367
2368         dev->gcDisable = 0;
2369
2370         return retVal;
2371 }
2372
2373 /*
2374  * FindBlockForgarbageCollection is used to select the dirtiest block (or close enough)
2375  * for garbage collection.
2376  */
2377
2378 static unsigned yaffs_FindBlockForGarbageCollection(yaffs_Device *dev,
2379                                         int aggressive,
2380                                         int background)
2381 {
2382         int i;
2383         int iterations;
2384         unsigned selected = 0;
2385         int prioritised = 0;
2386         int prioritisedExists = 0;
2387         yaffs_BlockInfo *bi;
2388         int threshold;
2389
2390         /* First let's see if we need to grab a prioritised block */
2391         if (dev->hasPendingPrioritisedGCs && !aggressive) {
2392                 dev->gcDirtiest = 0;
2393                 bi = dev->blockInfo;
2394                 for (i = dev->internalStartBlock;
2395                         i <= dev->internalEndBlock && !selected;
2396                         i++) {
2397
2398                         if (bi->gcPrioritise) {
2399                                 prioritisedExists = 1;
2400                                 if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2401                                    yaffs2_BlockNotDisqualifiedFromGC(dev, bi)) {
2402                                         selected = i;
2403                                         prioritised = 1;
2404                                 }
2405                         }
2406                         bi++;
2407                 }
2408
2409                 /*
2410                  * If there is a prioritised block and none was selected then
2411                  * this happened because there is at least one old dirty block gumming
2412                  * up the works. Let's gc the oldest dirty block.
2413                  */
2414
2415                 if(prioritisedExists &&
2416                         !selected &&
2417                         dev->oldestDirtyBlock > 0)
2418                         selected = dev->oldestDirtyBlock;
2419
2420                 if (!prioritisedExists) /* None found, so we can clear this */
2421                         dev->hasPendingPrioritisedGCs = 0;
2422         }
2423
2424         /* If we're doing aggressive GC then we are happy to take a less-dirty block, and
2425          * search harder.
2426          * else (we're doing a leasurely gc), then we only bother to do this if the
2427          * block has only a few pages in use.
2428          */
2429
2430         if (!selected){
2431                 int pagesUsed;
2432                 int nBlocks = dev->internalEndBlock - dev->internalStartBlock + 1;
2433                 if (aggressive){
2434                         threshold = dev->param.nChunksPerBlock;
2435                         iterations = nBlocks;
2436                 } else {
2437                         int maxThreshold = dev->param.nChunksPerBlock/2;
2438                         threshold = background ?
2439                                 (dev->gcNotDone + 2) * 2 : 0;
2440                         if(threshold <YAFFS_GC_PASSIVE_THRESHOLD)
2441                                 threshold = YAFFS_GC_PASSIVE_THRESHOLD;
2442                         if(threshold > maxThreshold)
2443                                 threshold = maxThreshold;
2444
2445                         iterations = nBlocks / 16 + 1;
2446                         if (iterations > 100)
2447                                 iterations = 100;
2448                 }
2449
2450                 for (i = 0;
2451                         i < iterations &&
2452                         (dev->gcDirtiest < 1 ||
2453                                 dev->gcPagesInUse > YAFFS_GC_GOOD_ENOUGH);
2454                         i++) {
2455                         dev->gcBlockFinder++;
2456                         if (dev->gcBlockFinder < dev->internalStartBlock ||
2457                                 dev->gcBlockFinder > dev->internalEndBlock)
2458                                 dev->gcBlockFinder = dev->internalStartBlock;
2459
2460                         bi = yaffs_GetBlockInfo(dev, dev->gcBlockFinder);
2461
2462                         pagesUsed = bi->pagesInUse - bi->softDeletions;
2463
2464                         if (bi->blockState == YAFFS_BLOCK_STATE_FULL &&
2465                                 pagesUsed < dev->param.nChunksPerBlock &&
2466                                 (dev->gcDirtiest < 1 || pagesUsed < dev->gcPagesInUse) &&
2467                                 yaffs2_BlockNotDisqualifiedFromGC(dev, bi)) {
2468                                 dev->gcDirtiest = dev->gcBlockFinder;
2469                                 dev->gcPagesInUse = pagesUsed;
2470                         }
2471                 }
2472
2473                 if(dev->gcDirtiest > 0 && dev->gcPagesInUse <= threshold)
2474                         selected = dev->gcDirtiest;
2475         }
2476
2477         /*
2478          * If nothing has been selected for a while, try selecting the oldest dirty
2479          * because that's gumming up the works.
2480          */
2481
2482         if(!selected && dev->param.isYaffs2 &&
2483                 dev->gcNotDone >= ( background ? 10 : 20)){
2484                 yaffs2_FindOldestDirtySequence(dev);
2485                 if(dev->oldestDirtyBlock > 0) {
2486                         selected = dev->oldestDirtyBlock;
2487                         dev->gcDirtiest = selected;
2488                         dev->oldestDirtyGCs++;
2489                         bi = yaffs_GetBlockInfo(dev, selected);
2490                         dev->gcPagesInUse =  bi->pagesInUse - bi->softDeletions;
2491                 } else
2492                         dev->gcNotDone = 0;
2493         }
2494
2495         if(selected){
2496                 T(YAFFS_TRACE_GC,
2497                   (TSTR("GC Selected block %d with %d free, prioritised:%d" TENDSTR),
2498                   selected,
2499                   dev->param.nChunksPerBlock - dev->gcPagesInUse,
2500                   prioritised));
2501
2502                 if(background)
2503                         dev->backgroundGCs++;
2504                 dev->gcDirtiest = 0;
2505                 dev->gcPagesInUse = 0;
2506                 dev->gcNotDone = 0;
2507                 if(dev->refreshSkip > 0)
2508                         dev->refreshSkip--;
2509         } else{
2510                 dev->gcNotDone++;
2511                 T(YAFFS_TRACE_GC,
2512                   (TSTR("GC none: finder %d skip %d threshold %d dirtiest %d using %d oldest %d%s" TENDSTR),
2513                   dev->gcBlockFinder, dev->gcNotDone,
2514                   threshold,
2515                   dev->gcDirtiest, dev->gcPagesInUse,
2516                   dev->oldestDirtyBlock,
2517                   background ? " bg" : ""));
2518         }
2519
2520         return selected;
2521 }
2522
2523 /* New garbage collector
2524  * If we're very low on erased blocks then we do aggressive garbage collection
2525  * otherwise we do "leasurely" garbage collection.
2526  * Aggressive gc looks further (whole array) and will accept less dirty blocks.
2527  * Passive gc only inspects smaller areas and will only accept more dirty blocks.
2528  *
2529  * The idea is to help clear out space in a more spread-out manner.
2530  * Dunno if it really does anything useful.
2531  */
2532 static int yaffs_CheckGarbageCollection(yaffs_Device *dev, int background)
2533 {
2534         int aggressive = 0;
2535         int gcOk = YAFFS_OK;
2536         int maxTries = 0;
2537
2538         int minErased;
2539         int erasedChunks;
2540
2541         int checkpointBlockAdjust;
2542
2543         if(dev->param.gcControl &&
2544                 (dev->param.gcControl(dev) & 1) == 0)
2545                 return YAFFS_OK;
2546
2547         if (dev->gcDisable) {
2548                 /* Bail out so we don't get recursive gc */
2549                 return YAFFS_OK;
2550         }
2551
2552         /* This loop should pass the first time.
2553          * We'll only see looping here if the collection does not increase space.
2554          */
2555
2556         do {
2557                 maxTries++;
2558
2559                 checkpointBlockAdjust = yaffs2_CalcCheckpointBlocksRequired(dev);
2560
2561                 minErased  = dev->param.nReservedBlocks + checkpointBlockAdjust + 1;
2562                 erasedChunks = dev->nErasedBlocks * dev->param.nChunksPerBlock;
2563
2564                 /* If we need a block soon then do aggressive gc.*/
2565                 if (dev->nErasedBlocks < minErased)
2566                         aggressive = 1;
2567                 else {
2568                         if(dev->gcSkip > 20)
2569                                 dev->gcSkip = 20;
2570                         if(erasedChunks < dev->nFreeChunks/2 ||
2571                                 dev->gcSkip < 1 ||
2572                                 background)
2573                                 aggressive = 0;
2574                         else {
2575                                 dev->gcSkip--;
2576                                 break;
2577                         }
2578                 }
2579
2580                 dev->gcSkip = 5;
2581
2582                 /* If we don't already have a block being gc'd then see if we should start another */
2583
2584                 if (dev->gcBlock < 1 && !aggressive) {
2585                         dev->gcBlock = yaffs2_FindRefreshBlock(dev);
2586                         dev->gcChunk = 0;
2587                         dev->nCleanups=0;
2588                 }
2589                 if (dev->gcBlock < 1) {
2590                         dev->gcBlock = yaffs_FindBlockForGarbageCollection(dev, aggressive, background);
2591                         dev->gcChunk = 0;
2592                         dev->nCleanups=0;
2593                 }
2594
2595                 if (dev->gcBlock > 0) {
2596                         dev->allGCs++;
2597                         if (!aggressive)
2598                                 dev->passiveGCs++;
2599
2600                         T(YAFFS_TRACE_GC,
2601                           (TSTR
2602                            ("yaffs: GC erasedBlocks %d aggressive %d" TENDSTR),
2603                            dev->nErasedBlocks, aggressive));
2604
2605                         gcOk = yaffs_GarbageCollectBlock(dev, dev->gcBlock, aggressive);
2606                 }
2607
2608                 if (dev->nErasedBlocks < (dev->param.nReservedBlocks) && dev->gcBlock > 0) {
2609                         T(YAFFS_TRACE_GC,
2610                           (TSTR
2611                            ("yaffs: GC !!!no reclaim!!! erasedBlocks %d after try %d block %d"
2612                             TENDSTR), dev->nErasedBlocks, maxTries, dev->gcBlock));
2613                 }
2614         } while ((dev->nErasedBlocks < dev->param.nReservedBlocks) &&
2615                  (dev->gcBlock > 0) &&
2616                  (maxTries < 2));
2617
2618         return aggressive ? gcOk : YAFFS_OK;
2619 }
2620
2621 /*
2622  * yaffs_BackgroundGarbageCollect()
2623  * Garbage collects. Intended to be called from a background thread.
2624  * Returns non-zero if at least half the free chunks are erased.
2625  */
2626 int yaffs_BackgroundGarbageCollect(yaffs_Device *dev, unsigned urgency)
2627 {
2628         int erasedChunks = dev->nErasedBlocks * dev->param.nChunksPerBlock;
2629
2630         T(YAFFS_TRACE_BACKGROUND, (TSTR("Background gc %u" TENDSTR),urgency));
2631
2632         yaffs_CheckGarbageCollection(dev, 1);
2633         return erasedChunks > dev->nFreeChunks/2;
2634 }
2635
2636 /*-------------------------  TAGS --------------------------------*/
2637
2638 static int yaffs_TagsMatch(const yaffs_ExtendedTags *tags, int objectId,
2639                            int chunkInObject)
2640 {
2641         return (tags->chunkId == chunkInObject &&
2642                 tags->objectId == objectId && !tags->chunkDeleted) ? 1 : 0;
2643
2644 }
2645
2646
2647 /*-------------------- Data file manipulation -----------------*/
2648
2649 static int yaffs_FindChunkInFile(yaffs_Object *in, int chunkInInode,
2650                                  yaffs_ExtendedTags *tags)
2651 {
2652         /*Get the Tnode, then get the level 0 offset chunk offset */
2653         yaffs_Tnode *tn;
2654         int theChunk = -1;
2655         yaffs_ExtendedTags localTags;
2656         int retVal = -1;
2657
2658         yaffs_Device *dev = in->myDev;
2659
2660         if (!tags) {
2661                 /* Passed a NULL, so use our own tags space */
2662                 tags = &localTags;
2663         }
2664
2665         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2666
2667         if (tn) {
2668                 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
2669
2670                 retVal =
2671                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2672                                            chunkInInode);
2673         }
2674         return retVal;
2675 }
2676
2677 static int yaffs_FindAndDeleteChunkInFile(yaffs_Object *in, int chunkInInode,
2678                                           yaffs_ExtendedTags *tags)
2679 {
2680         /* Get the Tnode, then get the level 0 offset chunk offset */
2681         yaffs_Tnode *tn;
2682         int theChunk = -1;
2683         yaffs_ExtendedTags localTags;
2684
2685         yaffs_Device *dev = in->myDev;
2686         int retVal = -1;
2687
2688         if (!tags) {
2689                 /* Passed a NULL, so use our own tags space */
2690                 tags = &localTags;
2691         }
2692
2693         tn = yaffs_FindLevel0Tnode(dev, &in->variant.fileVariant, chunkInInode);
2694
2695         if (tn) {
2696
2697                 theChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
2698
2699                 retVal =
2700                     yaffs_FindChunkInGroup(dev, theChunk, tags, in->objectId,
2701                                            chunkInInode);
2702
2703                 /* Delete the entry in the filestructure (if found) */
2704                 if (retVal != -1)
2705                         yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, 0);
2706         }
2707
2708         return retVal;
2709 }
2710
2711
2712 int yaffs_PutChunkIntoFile(yaffs_Object *in, int chunkInInode,
2713                                 int chunkInNAND, int inScan)
2714 {
2715         /* NB inScan is zero unless scanning.
2716          * For forward scanning, inScan is > 0;
2717          * for backward scanning inScan is < 0
2718          *
2719          * chunkInNAND = 0 is a dummy insert to make sure the tnodes are there.
2720          */
2721
2722         yaffs_Tnode *tn;
2723         yaffs_Device *dev = in->myDev;
2724         int existingChunk;
2725         yaffs_ExtendedTags existingTags;
2726         yaffs_ExtendedTags newTags;
2727         unsigned existingSerial, newSerial;
2728
2729         if (in->variantType != YAFFS_OBJECT_TYPE_FILE) {
2730                 /* Just ignore an attempt at putting a chunk into a non-file during scanning
2731                  * If it is not during Scanning then something went wrong!
2732                  */
2733                 if (!inScan) {
2734                         T(YAFFS_TRACE_ERROR,
2735                           (TSTR
2736                            ("yaffs tragedy:attempt to put data chunk into a non-file"
2737                             TENDSTR)));
2738                         YBUG();
2739                 }
2740
2741                 yaffs_DeleteChunk(dev, chunkInNAND, 1, __LINE__);
2742                 return YAFFS_OK;
2743         }
2744
2745         tn = yaffs_AddOrFindLevel0Tnode(dev,
2746                                         &in->variant.fileVariant,
2747                                         chunkInInode,
2748                                         NULL);
2749         if (!tn)
2750                 return YAFFS_FAIL;
2751         
2752         if(!chunkInNAND)
2753                 /* Dummy insert, bail now */
2754                 return YAFFS_OK;
2755
2756         existingChunk = yaffs_GetChunkGroupBase(dev, tn, chunkInInode);
2757
2758         if (inScan != 0) {
2759                 /* If we're scanning then we need to test for duplicates
2760                  * NB This does not need to be efficient since it should only ever
2761                  * happen when the power fails during a write, then only one
2762                  * chunk should ever be affected.
2763                  *
2764                  * Correction for YAFFS2: This could happen quite a lot and we need to think about efficiency! TODO
2765                  * Update: For backward scanning we don't need to re-read tags so this is quite cheap.
2766                  */
2767
2768                 if (existingChunk > 0) {
2769                         /* NB Right now existing chunk will not be real chunkId if the chunk group size > 1
2770                          *    thus we have to do a FindChunkInFile to get the real chunk id.
2771                          *
2772                          * We have a duplicate now we need to decide which one to use:
2773                          *
2774                          * Backwards scanning YAFFS2: The old one is what we use, dump the new one.
2775                          * Forward scanning YAFFS2: The new one is what we use, dump the old one.
2776                          * YAFFS1: Get both sets of tags and compare serial numbers.
2777                          */
2778
2779                         if (inScan > 0) {
2780                                 /* Only do this for forward scanning */
2781                                 yaffs_ReadChunkWithTagsFromNAND(dev,
2782                                                                 chunkInNAND,
2783                                                                 NULL, &newTags);
2784
2785                                 /* Do a proper find */
2786                                 existingChunk =
2787                                     yaffs_FindChunkInFile(in, chunkInInode,
2788                                                           &existingTags);
2789                         }
2790
2791                         if (existingChunk <= 0) {
2792                                 /*Hoosterman - how did this happen? */
2793
2794                                 T(YAFFS_TRACE_ERROR,
2795                                   (TSTR
2796                                    ("yaffs tragedy: existing chunk < 0 in scan"
2797                                     TENDSTR)));
2798
2799                         }
2800
2801                         /* NB The deleted flags should be false, otherwise the chunks will
2802                          * not be loaded during a scan
2803                          */
2804
2805                         if (inScan > 0) {
2806                                 newSerial = newTags.serialNumber;
2807                                 existingSerial = existingTags.serialNumber;
2808                         }
2809
2810                         if ((inScan > 0) &&
2811                             (existingChunk <= 0 ||
2812                              ((existingSerial + 1) & 3) == newSerial)) {
2813                                 /* Forward scanning.
2814                                  * Use new
2815                                  * Delete the old one and drop through to update the tnode
2816                                  */
2817                                 yaffs_DeleteChunk(dev, existingChunk, 1,
2818                                                   __LINE__);
2819                         } else {
2820                                 /* Backward scanning or we want to use the existing one
2821                                  * Use existing.
2822                                  * Delete the new one and return early so that the tnode isn't changed
2823                                  */
2824                                 yaffs_DeleteChunk(dev, chunkInNAND, 1,
2825                                                   __LINE__);
2826                                 return YAFFS_OK;
2827                         }
2828                 }
2829
2830         }
2831
2832         if (existingChunk == 0)
2833                 in->nDataChunks++;
2834
2835         yaffs_LoadLevel0Tnode(dev, tn, chunkInInode, chunkInNAND);
2836
2837         return YAFFS_OK;
2838 }
2839
2840 static int yaffs_ReadChunkDataFromObject(yaffs_Object *in, int chunkInInode,
2841                                         __u8 *buffer)
2842 {
2843         int chunkInNAND = yaffs_FindChunkInFile(in, chunkInInode, NULL);
2844
2845         if (chunkInNAND >= 0)
2846                 return yaffs_ReadChunkWithTagsFromNAND(in->myDev, chunkInNAND,
2847                                                 buffer, NULL);
2848         else {
2849                 T(YAFFS_TRACE_NANDACCESS,
2850                   (TSTR("Chunk %d not found zero instead" TENDSTR),
2851                    chunkInNAND));
2852                 /* get sane (zero) data if you read a hole */
2853                 memset(buffer, 0, in->myDev->nDataBytesPerChunk);
2854                 return 0;
2855         }
2856
2857 }
2858
2859 void yaffs_DeleteChunk(yaffs_Device *dev, int chunkId, int markNAND, int lyn)
2860 {
2861         int block;
2862         int page;
2863         yaffs_ExtendedTags tags;
2864         yaffs_BlockInfo *bi;
2865
2866         if (chunkId <= 0)
2867                 return;
2868
2869         dev->nDeletions++;
2870         block = chunkId / dev->param.nChunksPerBlock;
2871         page = chunkId % dev->param.nChunksPerBlock;
2872
2873
2874         if (!yaffs_CheckChunkBit(dev, block, page))
2875                 T(YAFFS_TRACE_VERIFY,
2876                         (TSTR("Deleting invalid chunk %d"TENDSTR),
2877                          chunkId));
2878
2879         bi = yaffs_GetBlockInfo(dev, block);
2880         
2881         yaffs2_UpdateOldestDirtySequence(dev, block, bi);
2882
2883         T(YAFFS_TRACE_DELETION,
2884           (TSTR("line %d delete of chunk %d" TENDSTR), lyn, chunkId));
2885
2886         if (!dev->param.isYaffs2 && markNAND &&
2887             bi->blockState != YAFFS_BLOCK_STATE_COLLECTING) {
2888
2889                 yaffs_InitialiseTags(&tags);
2890
2891                 tags.chunkDeleted = 1;
2892
2893                 yaffs_WriteChunkWithTagsToNAND(dev, chunkId, NULL, &tags);
2894                 yaffs_HandleUpdateChunk(dev, chunkId, &tags);
2895         } else {
2896                 dev->nUnmarkedDeletions++;
2897         }
2898
2899         /* Pull out of the management area.
2900          * If the whole block became dirty, this will kick off an erasure.
2901          */
2902         if (bi->blockState == YAFFS_BLOCK_STATE_ALLOCATING ||
2903             bi->blockState == YAFFS_BLOCK_STATE_FULL ||
2904             bi->blockState == YAFFS_BLOCK_STATE_NEEDS_SCANNING ||
2905             bi->blockState == YAFFS_BLOCK_STATE_COLLECTING) {
2906                 dev->nFreeChunks++;
2907
2908                 yaffs_ClearChunkBit(dev, block, page);
2909
2910                 bi->pagesInUse--;
2911
2912                 if (bi->pagesInUse == 0 &&
2913                     !bi->hasShrinkHeader &&
2914                     bi->blockState != YAFFS_BLOCK_STATE_ALLOCATING &&
2915                     bi->blockState != YAFFS_BLOCK_STATE_NEEDS_SCANNING) {
2916                         yaffs_BlockBecameDirty(dev, block);
2917                 }
2918
2919         }
2920
2921 }
2922
2923 static int yaffs_WriteChunkDataToObject(yaffs_Object *in, int chunkInInode,
2924                                         const __u8 *buffer, int nBytes,
2925                                         int useReserve)
2926 {
2927         /* Find old chunk Need to do this to get serial number
2928          * Write new one and patch into tree.
2929          * Invalidate old tags.
2930          */
2931
2932         int prevChunkId;
2933         yaffs_ExtendedTags prevTags;
2934
2935         int newChunkId;
2936         yaffs_ExtendedTags newTags;
2937
2938         yaffs_Device *dev = in->myDev;
2939
2940         yaffs_CheckGarbageCollection(dev,0);
2941
2942         /* Get the previous chunk at this location in the file if it exists.
2943          * If it does not exist then put a zero into the tree. This creates
2944          * the tnode now, rather than later when it is harder to clean up.
2945          */
2946         prevChunkId = yaffs_FindChunkInFile(in, chunkInInode, &prevTags);
2947         if(prevChunkId < 1 &&
2948                 !yaffs_PutChunkIntoFile(in, chunkInInode, 0, 0))
2949                 return 0;
2950
2951         /* Set up new tags */
2952         yaffs_InitialiseTags(&newTags);
2953
2954         newTags.chunkId = chunkInInode;
2955         newTags.objectId = in->objectId;
2956         newTags.serialNumber =
2957             (prevChunkId > 0) ? prevTags.serialNumber + 1 : 1;
2958         newTags.byteCount = nBytes;
2959
2960         if (nBytes < 1 || nBytes > dev->param.totalBytesPerChunk) {
2961                 T(YAFFS_TRACE_ERROR,
2962                 (TSTR("Writing %d bytes to chunk!!!!!!!!!" TENDSTR), nBytes));
2963                 YBUG();
2964         }
2965         
2966                 
2967         newChunkId =
2968             yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
2969                                               useReserve);
2970
2971         if (newChunkId > 0) {
2972                 yaffs_PutChunkIntoFile(in, chunkInInode, newChunkId, 0);
2973
2974                 if (prevChunkId > 0)
2975                         yaffs_DeleteChunk(dev, prevChunkId, 1, __LINE__);
2976
2977                 yaffs_VerifyFileSanity(in);
2978         }
2979         return newChunkId;
2980
2981 }
2982
2983 /* UpdateObjectHeader updates the header on NAND for an object.
2984  * If name is not NULL, then that new name is used.
2985  */
2986 int yaffs_UpdateObjectHeader(yaffs_Object *in, const YCHAR *name, int force,
2987                              int isShrink, int shadows, yaffs_XAttrMod *xmod)
2988 {
2989
2990         yaffs_BlockInfo *bi;
2991
2992         yaffs_Device *dev = in->myDev;
2993
2994         int prevChunkId;
2995         int retVal = 0;
2996         int result = 0;
2997
2998         int newChunkId;
2999         yaffs_ExtendedTags newTags;
3000         yaffs_ExtendedTags oldTags;
3001         YCHAR *alias = NULL;
3002
3003         __u8 *buffer = NULL;
3004         YCHAR oldName[YAFFS_MAX_NAME_LENGTH + 1];
3005
3006         yaffs_ObjectHeader *oh = NULL;
3007
3008         yaffs_strcpy(oldName, _Y("silly old name"));
3009
3010
3011         if (!in->fake ||
3012                 in == dev->rootDir || /* The rootDir should also be saved */
3013                 force  || xmod) {
3014
3015                 yaffs_CheckGarbageCollection(dev,0);
3016                 yaffs_CheckObjectDetailsLoaded(in);
3017
3018                 buffer = yaffs_GetTempBuffer(in->myDev, __LINE__);
3019                 oh = (yaffs_ObjectHeader *) buffer;
3020
3021                 prevChunkId = in->hdrChunk;
3022
3023                 if (prevChunkId > 0) {
3024                         result = yaffs_ReadChunkWithTagsFromNAND(dev, prevChunkId,
3025                                                         buffer, &oldTags);
3026
3027                         yaffs_VerifyObjectHeader(in, oh, &oldTags, 0);
3028
3029                         memcpy(oldName, oh->name, sizeof(oh->name));
3030                         memset(buffer, 0xFF, sizeof(yaffs_ObjectHeader));
3031                 } else
3032                         memset(buffer, 0xFF, dev->nDataBytesPerChunk);
3033
3034                 oh->type = in->variantType;
3035                 oh->yst_mode = in->yst_mode;
3036                 oh->shadowsObject = oh->inbandShadowsObject = shadows;
3037
3038 #ifdef CONFIG_YAFFS_WINCE
3039                 oh->win_atime[0] = in->win_atime[0];
3040                 oh->win_ctime[0] = in->win_ctime[0];
3041                 oh->win_mtime[0] = in->win_mtime[0];
3042                 oh->win_atime[1] = in->win_atime[1];
3043                 oh->win_ctime[1] = in->win_ctime[1];
3044                 oh->win_mtime[1] = in->win_mtime[1];
3045 #else
3046                 oh->yst_uid = in->yst_uid;
3047                 oh->yst_gid = in->yst_gid;
3048                 oh->yst_atime = in->yst_atime;
3049                 oh->yst_mtime = in->yst_mtime;
3050                 oh->yst_ctime = in->yst_ctime;
3051                 oh->yst_rdev = in->yst_rdev;
3052 #endif
3053                 if (in->parent)
3054                         oh->parentObjectId = in->parent->objectId;
3055                 else
3056                         oh->parentObjectId = 0;
3057
3058                 if (name && *name) {
3059                         memset(oh->name, 0, sizeof(oh->name));
3060                         yaffs_LoadObjectHeaderFromName(dev,oh->name,name);
3061                 } else if (prevChunkId > 0)
3062                         memcpy(oh->name, oldName, sizeof(oh->name));
3063                 else
3064                         memset(oh->name, 0, sizeof(oh->name));
3065
3066                 oh->isShrink = isShrink;
3067
3068                 switch (in->variantType) {
3069                 case YAFFS_OBJECT_TYPE_UNKNOWN:
3070                         /* Should not happen */
3071                         break;
3072                 case YAFFS_OBJECT_TYPE_FILE:
3073                         oh->fileSize =
3074                             (oh->parentObjectId == YAFFS_OBJECTID_DELETED
3075                              || oh->parentObjectId ==
3076                              YAFFS_OBJECTID_UNLINKED) ? 0 : in->variant.
3077                             fileVariant.fileSize;
3078                         break;
3079                 case YAFFS_OBJECT_TYPE_HARDLINK:
3080                         oh->equivalentObjectId =
3081                             in->variant.hardLinkVariant.equivalentObjectId;
3082                         break;
3083                 case YAFFS_OBJECT_TYPE_SPECIAL:
3084                         /* Do nothing */
3085                         break;
3086                 case YAFFS_OBJECT_TYPE_DIRECTORY:
3087                         /* Do nothing */
3088                         break;
3089                 case YAFFS_OBJECT_TYPE_SYMLINK:
3090                         alias = in->variant.symLinkVariant.alias;
3091                         if(!alias)
3092                                 alias = _Y("no alias");
3093                         yaffs_strncpy(oh->alias,
3094                                         alias,
3095                                       YAFFS_MAX_ALIAS_LENGTH);
3096                         oh->alias[YAFFS_MAX_ALIAS_LENGTH] = 0;
3097                         break;
3098                 }
3099
3100                 /* process any xattrib modifications */
3101                 if(xmod)
3102                         yaffs_ApplyXMod(dev, (char *)buffer, xmod);
3103
3104
3105                 /* Tags */
3106                 yaffs_InitialiseTags(&newTags);
3107                 in->serial++;
3108                 newTags.chunkId = 0;
3109                 newTags.objectId = in->objectId;
3110                 newTags.serialNumber = in->serial;
3111
3112                 /* Add extra info for file header */
3113
3114                 newTags.extraHeaderInfoAvailable = 1;
3115                 newTags.extraParentObjectId = oh->parentObjectId;
3116                 newTags.extraFileLength = oh->fileSize;
3117                 newTags.extraIsShrinkHeader = oh->isShrink;
3118                 newTags.extraEquivalentObjectId = oh->equivalentObjectId;
3119                 newTags.extraShadows = (oh->shadowsObject > 0) ? 1 : 0;
3120                 newTags.extraObjectType = in->variantType;
3121
3122                 yaffs_VerifyObjectHeader(in, oh, &newTags, 1);
3123
3124                 /* Create new chunk in NAND */
3125                 newChunkId =
3126                     yaffs_WriteNewChunkWithTagsToNAND(dev, buffer, &newTags,
3127                                                       (prevChunkId > 0) ? 1 : 0);
3128
3129                 if (newChunkId >= 0) {
3130
3131                         in->hdrChunk = newChunkId;
3132
3133                         if (prevChunkId > 0) {
3134                                 yaffs_DeleteChunk(dev, prevChunkId, 1,
3135                                                   __LINE__);
3136                         }
3137
3138                         if (!yaffs_ObjectHasCachedWriteData(in))
3139                                 in->dirty = 0;
3140
3141                         /* If this was a shrink, then mark the block that the chunk lives on */
3142                         if (isShrink) {
3143                                 bi = yaffs_GetBlockInfo(in->myDev,
3144                                         newChunkId / in->myDev->param.nChunksPerBlock);
3145                                 bi->hasShrinkHeader = 1;
3146                         }
3147
3148                 }
3149
3150                 retVal = newChunkId;
3151
3152         }
3153
3154         if (buffer)
3155                 yaffs_ReleaseTempBuffer(dev, buffer, __LINE__);
3156
3157         return retVal;
3158 }
3159
3160 /*------------------------ Short Operations Cache ----------------------------------------
3161  *   In many situations where there is no high level buffering (eg WinCE) a lot of
3162  *   reads might be short sequential reads, and a lot of writes may be short
3163  *   sequential writes. eg. scanning/writing a jpeg file.
3164  *   In these cases, a short read/write cache can provide a huge perfomance benefit
3165  *   with dumb-as-a-rock code.
3166  *   In Linux, the page cache provides read buffering aand the short op cache provides write
3167  *   buffering.
3168  *
3169  *   There are a limited number (~10) of cache chunks per device so that we don't
3170  *   need a very intelligent search.
3171  */
3172
3173 static int yaffs_ObjectHasCachedWriteData(yaffs_Object *obj)
3174 {
3175         yaffs_Device *dev = obj->myDev;
3176         int i;
3177         yaffs_ChunkCache *cache;
3178         int nCaches = obj->myDev->param.nShortOpCaches;
3179
3180         for (i = 0; i < nCaches; i++) {
3181                 cache = &dev->srCache[i];
3182                 if (cache->object == obj &&
3183                     cache->dirty)
3184                         return 1;
3185         }
3186
3187         return 0;
3188 }
3189
3190
3191 static void yaffs_FlushFilesChunkCache(yaffs_Object *obj)
3192 {
3193         yaffs_Device *dev = obj->myDev;
3194         int lowest = -99;       /* Stop compiler whining. */
3195         int i;
3196         yaffs_ChunkCache *cache;
3197         int chunkWritten = 0;
3198         int nCaches = obj->myDev->param.nShortOpCaches;
3199
3200         if (nCaches > 0) {
3201                 do {
3202                         cache = NULL;
3203
3204                         /* Find the dirty cache for this object with the lowest chunk id. */
3205                         for (i = 0; i < nCaches; i++) {
3206                                 if (dev->srCache[i].object == obj &&
3207                                     dev->srCache[i].dirty) {
3208                                         if (!cache
3209                                             || dev->srCache[i].chunkId <
3210                                             lowest) {
3211                                                 cache = &dev->srCache[i];
3212                                                 lowest = cache->chunkId;
3213                                         }
3214                                 }
3215                         }
3216
3217                         if (cache && !cache->locked) {
3218                                 /* Write it out and free it up */
3219
3220                                 chunkWritten =
3221                                     yaffs_WriteChunkDataToObject(cache->object,
3222                                                                  cache->chunkId,
3223                                                                  cache->data,
3224                                                                  cache->nBytes,
3225                                                                  1);
3226                                 cache->dirty = 0;
3227                                 cache->object = NULL;
3228                         }
3229
3230                 } while (cache && chunkWritten > 0);
3231
3232                 if (cache) {
3233                         /* Hoosterman, disk full while writing cache out. */
3234                         T(YAFFS_TRACE_ERROR,
3235                           (TSTR("yaffs tragedy: no space during cache write" TENDSTR)));
3236
3237                 }
3238         }
3239
3240 }
3241
3242 /*yaffs_FlushEntireDeviceCache(dev)
3243  *
3244  *
3245  */
3246
3247 void yaffs_FlushEntireDeviceCache(yaffs_Device *dev)
3248 {
3249         yaffs_Object *obj;
3250         int nCaches = dev->param.nShortOpCaches;
3251         int i;
3252
3253         /* Find a dirty object in the cache and flush it...
3254          * until there are no further dirty objects.
3255          */
3256         do {
3257                 obj = NULL;
3258                 for (i = 0; i < nCaches && !obj; i++) {
3259                         if (dev->srCache[i].object &&
3260                             dev->srCache[i].dirty)
3261                                 obj = dev->srCache[i].object;
3262
3263                 }
3264                 if (obj)
3265                         yaffs_FlushFilesChunkCache(obj);
3266
3267         } while (obj);
3268
3269 }
3270
3271
3272 /* Grab us a cache chunk for use.
3273  * First look for an empty one.
3274  * Then look for the least recently used non-dirty one.
3275  * Then look for the least recently used dirty one...., flush and look again.
3276  */
3277 static yaffs_ChunkCache *yaffs_GrabChunkCacheWorker(yaffs_Device *dev)
3278 {
3279         int i;
3280
3281         if (dev->param.nShortOpCaches > 0) {
3282                 for (i = 0; i < dev->param.nShortOpCaches; i++) {
3283                         if (!dev->srCache[i].object)
3284                                 return &dev->srCache[i];
3285                 }
3286         }
3287
3288         return NULL;
3289 }
3290
3291 static yaffs_ChunkCache *yaffs_GrabChunkCache(yaffs_Device *dev)
3292 {
3293         yaffs_ChunkCache *cache;
3294         yaffs_Object *theObj;
3295         int usage;
3296         int i;
3297         int pushout;
3298
3299         if (dev->param.nShortOpCaches > 0) {
3300                 /* Try find a non-dirty one... */
3301
3302                 cache = yaffs_GrabChunkCacheWorker(dev);
3303
3304                 if (!cache) {
3305                         /* They were all dirty, find the last recently used object and flush
3306                          * its cache, then  find again.
3307                          * NB what's here is not very accurate, we actually flush the object
3308                          * the last recently used page.
3309                          */
3310
3311                         /* With locking we can't assume we can use entry zero */
3312
3313                         theObj = NULL;
3314                         usage = -1;
3315                         cache = NULL;
3316                         pushout = -1;
3317
3318                         for (i = 0; i < dev->param.nShortOpCaches; i++) {
3319                                 if (dev->srCache[i].object &&
3320                                     !dev->srCache[i].locked &&
3321                                     (dev->srCache[i].lastUse < usage || !cache)) {
3322                                         usage = dev->srCache[i].lastUse;
3323                                         theObj = dev->srCache[i].object;
3324                                         cache = &dev->srCache[i];
3325                                         pushout = i;
3326                                 }
3327                         }
3328
3329                         if (!cache || cache->dirty) {
3330                                 /* Flush and try again */
3331                                 yaffs_FlushFilesChunkCache(theObj);
3332                                 cache = yaffs_GrabChunkCacheWorker(dev);
3333                         }
3334
3335                 }
3336                 return cache;
3337         } else
3338                 return NULL;
3339
3340 }
3341
3342 /* Find a cached chunk */
3343 static yaffs_ChunkCache *yaffs_FindChunkCache(const yaffs_Object *obj,
3344                                               int chunkId)
3345 {
3346         yaffs_Device *dev = obj->myDev;
3347         int i;
3348         if (dev->param.nShortOpCaches > 0) {
3349                 for (i = 0; i < dev->param.nShortOpCaches; i++) {
3350                         if (dev->srCache[i].object == obj &&
3351                             dev->srCache[i].chunkId == chunkId) {
3352                                 dev->cacheHits++;
3353
3354                                 return &dev->srCache[i];
3355                         }
3356                 }
3357         }
3358         return NULL;
3359 }
3360
3361 /* Mark the chunk for the least recently used algorithym */
3362 static void yaffs_UseChunkCache(yaffs_Device *dev, yaffs_ChunkCache *cache,
3363                                 int isAWrite)
3364 {
3365
3366         if (dev->param.nShortOpCaches > 0) {
3367                 if (dev->srLastUse < 0 || dev->srLastUse > 100000000) {
3368                         /* Reset the cache usages */
3369                         int i;
3370                         for (i = 1; i < dev->param.nShortOpCaches; i++)
3371                                 dev->srCache[i].lastUse = 0;
3372
3373                         dev->srLastUse = 0;
3374                 }
3375
3376                 dev->srLastUse++;
3377
3378                 cache->lastUse = dev->srLastUse;
3379
3380                 if (isAWrite)
3381                         cache->dirty = 1;
3382         }
3383 }
3384
3385 /* Invalidate a single cache page.
3386  * Do this when a whole page gets written,
3387  * ie the short cache for this page is no longer valid.
3388  */
3389 static void yaffs_InvalidateChunkCache(yaffs_Object *object, int chunkId)
3390 {
3391         if (object->myDev->param.nShortOpCaches > 0) {
3392                 yaffs_ChunkCache *cache = yaffs_FindChunkCache(object, chunkId);
3393
3394                 if (cache)
3395                         cache->object = NULL;
3396         }
3397 }
3398
3399 /* Invalidate all the cache pages associated with this object
3400  * Do this whenever ther file is deleted or resized.
3401  */
3402 static void yaffs_InvalidateWholeChunkCache(yaffs_Object *in)
3403 {
3404         int i;
3405         yaffs_Device *dev = in->myDev;
3406
3407         if (dev->param.nShortOpCaches > 0) {
3408                 /* Invalidate it. */
3409                 for (i = 0; i < dev->param.nShortOpCaches; i++) {
3410                         if (dev->srCache[i].object == in)
3411                                 dev->srCache[i].object = NULL;
3412                 }
3413         }
3414 }
3415
3416
3417 /*--------------------- File read/write ------------------------
3418  * Read and write have very similar structures.
3419  * In general the read/write has three parts to it
3420  * An incomplete chunk to start with (if the read/write is not chunk-aligned)
3421  * Some complete chunks
3422  * An incomplete chunk to end off with
3423  *
3424  * Curve-balls: the first chunk might also be the last chunk.
3425  */
3426
3427 int yaffs_ReadDataFromFile(yaffs_Object *in, __u8 *buffer, loff_t offset,
3428                         int nBytes)
3429 {
3430
3431         int chunk;
3432         __u32 start;
3433         int nToCopy;
3434         int n = nBytes;
3435         int nDone = 0;
3436         yaffs_ChunkCache *cache;
3437
3438         yaffs_Device *dev;
3439
3440         dev = in->myDev;
3441
3442         while (n > 0) {
3443                 /* chunk = offset / dev->nDataBytesPerChunk + 1; */
3444                 /* start = offset % dev->nDataBytesPerChunk; */
3445                 yaffs_AddrToChunk(dev, offset, &chunk, &start);
3446                 chunk++;
3447
3448                 /* OK now check for the curveball where the start and end are in
3449                  * the same chunk.
3450                  */
3451                 if ((start + n) < dev->nDataBytesPerChunk)
3452                         nToCopy = n;
3453                 else
3454                         nToCopy = dev->nDataBytesPerChunk - start;
3455
3456                 cache = yaffs_FindChunkCache(in, chunk);
3457
3458                 /* If the chunk is already in the cache or it is less than a whole chunk
3459                  * or we're using inband tags then use the cache (if there is caching)
3460                  * else bypass the cache.
3461                  */
3462                 if (cache || nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
3463                         if (dev->param.nShortOpCaches > 0) {
3464
3465                                 /* If we can't find the data in the cache, then load it up. */
3466
3467                                 if (!cache) {
3468                                         cache = yaffs_GrabChunkCache(in->myDev);
3469                                         cache->object = in;
3470                                         cache->chunkId = chunk;
3471                                         cache->dirty = 0;
3472                                         cache->locked = 0;
3473                                         yaffs_ReadChunkDataFromObject(in, chunk,
3474                                                                       cache->
3475                                                                       data);
3476                                         cache->nBytes = 0;
3477                                 }
3478
3479                                 yaffs_UseChunkCache(dev, cache, 0);
3480
3481                                 cache->locked = 1;
3482
3483
3484                                 memcpy(buffer, &cache->data[start], nToCopy);
3485
3486                                 cache->locked = 0;
3487                         } else {
3488                                 /* Read into the local buffer then copy..*/
3489
3490                                 __u8 *localBuffer =
3491                                     yaffs_GetTempBuffer(dev, __LINE__);
3492                                 yaffs_ReadChunkDataFromObject(in, chunk,
3493                                                               localBuffer);
3494
3495                                 memcpy(buffer, &localBuffer[start], nToCopy);
3496
3497
3498                                 yaffs_ReleaseTempBuffer(dev, localBuffer,
3499                                                         __LINE__);
3500                         }
3501
3502                 } else {
3503
3504                         /* A full chunk. Read directly into the supplied buffer. */
3505                         yaffs_ReadChunkDataFromObject(in, chunk, buffer);
3506
3507                 }
3508
3509                 n -= nToCopy;
3510                 offset += nToCopy;
3511                 buffer += nToCopy;
3512                 nDone += nToCopy;
3513
3514         }
3515
3516         return nDone;
3517 }
3518
3519 int yaffs_DoWriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
3520                         int nBytes, int writeThrough)
3521 {
3522
3523         int chunk;
3524         __u32 start;
3525         int nToCopy;
3526         int n = nBytes;
3527         int nDone = 0;
3528         int nToWriteBack;
3529         int startOfWrite = offset;
3530         int chunkWritten = 0;
3531         __u32 nBytesRead;
3532         __u32 chunkStart;
3533
3534         yaffs_Device *dev;
3535
3536         dev = in->myDev;
3537
3538         while (n > 0 && chunkWritten >= 0) {
3539                 yaffs_AddrToChunk(dev, offset, &chunk, &start);
3540
3541                 if (chunk * dev->nDataBytesPerChunk + start != offset ||
3542                                 start >= dev->nDataBytesPerChunk) {
3543                         T(YAFFS_TRACE_ERROR, (
3544                            TSTR("AddrToChunk of offset %d gives chunk %d start %d"
3545                            TENDSTR),
3546                            (int)offset, chunk, start));
3547                 }
3548                 chunk++; /* File pos to chunk in file offset */
3549
3550                 /* OK now check for the curveball where the start and end are in
3551                  * the same chunk.
3552                  */
3553
3554                 if ((start + n) < dev->nDataBytesPerChunk) {
3555                         nToCopy = n;
3556
3557                         /* Now folks, to calculate how many bytes to write back....
3558                          * If we're overwriting and not writing to then end of file then
3559                          * we need to write back as much as was there before.
3560                          */
3561
3562                         chunkStart = ((chunk - 1) * dev->nDataBytesPerChunk);
3563
3564                         if (chunkStart > in->variant.fileVariant.fileSize)
3565                                 nBytesRead = 0; /* Past end of file */
3566                         else
3567                                 nBytesRead = in->variant.fileVariant.fileSize - chunkStart;
3568
3569                         if (nBytesRead > dev->nDataBytesPerChunk)
3570                                 nBytesRead = dev->nDataBytesPerChunk;
3571
3572                         nToWriteBack =
3573                             (nBytesRead >
3574                              (start + n)) ? nBytesRead : (start + n);
3575
3576                         if (nToWriteBack < 0 || nToWriteBack > dev->nDataBytesPerChunk)
3577                                 YBUG();
3578
3579                 } else {
3580                         nToCopy = dev->nDataBytesPerChunk - start;
3581                         nToWriteBack = dev->nDataBytesPerChunk;
3582                 }
3583
3584                 if (nToCopy != dev->nDataBytesPerChunk || dev->param.inbandTags) {
3585                         /* An incomplete start or end chunk (or maybe both start and end chunk),
3586                          * or we're using inband tags, so we want to use the cache buffers.
3587                          */
3588                         if (dev->param.nShortOpCaches > 0) {
3589                                 yaffs_ChunkCache *cache;
3590                                 /* If we can't find the data in the cache, then load the cache */
3591                                 cache = yaffs_FindChunkCache(in, chunk);
3592
3593                                 if (!cache
3594                                     && yaffs_CheckSpaceForAllocation(dev, 1)) {
3595                                         cache = yaffs_GrabChunkCache(dev);
3596                                         cache->object = in;
3597                                         cache->chunkId = chunk;
3598                                         cache->dirty = 0;
3599                                         cache->locked = 0;
3600                                         yaffs_ReadChunkDataFromObject(in, chunk,
3601                                                                       cache->data);
3602                                 } else if (cache &&
3603                                         !cache->dirty &&
3604                                         !yaffs_CheckSpaceForAllocation(dev, 1)) {
3605                                         /* Drop the cache if it was a read cache item and
3606                                          * no space check has been made for it.
3607                                          */
3608                                          cache = NULL;
3609                                 }
3610
3611                                 if (cache) {
3612                                         yaffs_UseChunkCache(dev, cache, 1);
3613                                         cache->locked = 1;
3614
3615
3616                                         memcpy(&cache->data[start], buffer,
3617                                                nToCopy);
3618
3619
3620                                         cache->locked = 0;
3621                                         cache->nBytes = nToWriteBack;
3622
3623                                         if (writeThrough) {
3624                                                 chunkWritten =
3625                                                     yaffs_WriteChunkDataToObject
3626                                                     (cache->object,
3627                                                      cache->chunkId,
3628                                                      cache->data, cache->nBytes,
3629                                                      1);
3630                                                 cache->dirty = 0;
3631                                         }
3632
3633                                 } else {
3634                                         chunkWritten = -1;      /* fail the write */
3635                                 }
3636                         } else {
3637                                 /* An incomplete start or end chunk (or maybe both start and end chunk)
3638                                  * Read into the local buffer then copy, then copy over and write back.
3639                                  */
3640
3641                                 __u8 *localBuffer =
3642                                     yaffs_GetTempBuffer(dev, __LINE__);
3643
3644                                 yaffs_ReadChunkDataFromObject(in, chunk,
3645                                                               localBuffer);
3646
3647
3648
3649                                 memcpy(&localBuffer[start], buffer, nToCopy);
3650
3651                                 chunkWritten =
3652                                     yaffs_WriteChunkDataToObject(in, chunk,
3653                                                                  localBuffer,
3654                                                                  nToWriteBack,
3655                                                                  0);
3656
3657                                 yaffs_ReleaseTempBuffer(dev, localBuffer,
3658                                                         __LINE__);
3659
3660                         }
3661
3662                 } else {
3663                         /* A full chunk. Write directly from the supplied buffer. */
3664
3665
3666
3667                         chunkWritten =
3668                             yaffs_WriteChunkDataToObject(in, chunk, buffer,
3669                                                          dev->nDataBytesPerChunk,
3670                                                          0);
3671
3672                         /* Since we've overwritten the cached data, we better invalidate it. */
3673                         yaffs_InvalidateChunkCache(in, chunk);
3674                 }
3675
3676                 if (chunkWritten >= 0) {
3677                         n -= nToCopy;
3678                         offset += nToCopy;
3679                         buffer += nToCopy;
3680                         nDone += nToCopy;
3681                 }
3682
3683         }
3684
3685         /* Update file object */
3686
3687         if ((startOfWrite + nDone) > in->variant.fileVariant.fileSize)
3688                 in->variant.fileVariant.fileSize = (startOfWrite + nDone);
3689
3690         in->dirty = 1;
3691
3692         return nDone;
3693 }
3694
3695 int yaffs_WriteDataToFile(yaffs_Object *in, const __u8 *buffer, loff_t offset,
3696                         int nBytes, int writeThrough)
3697 {
3698         yaffs2_HandleHole(in,offset);
3699         return yaffs_DoWriteDataToFile(in,buffer,offset,nBytes,writeThrough);
3700 }
3701
3702
3703
3704 /* ---------------------- File resizing stuff ------------------ */
3705
3706 static void yaffs_PruneResizedChunks(yaffs_Object *in, int newSize)
3707 {
3708
3709         yaffs_Device *dev = in->myDev;
3710         int oldFileSize = in->variant.fileVariant.fileSize;
3711
3712         int lastDel = 1 + (oldFileSize - 1) / dev->nDataBytesPerChunk;
3713
3714         int startDel = 1 + (newSize + dev->nDataBytesPerChunk - 1) /
3715             dev->nDataBytesPerChunk;
3716         int i;
3717         int chunkId;
3718
3719         /* Delete backwards so that we don't end up with holes if
3720          * power is lost part-way through the operation.
3721          */
3722         for (i = lastDel; i >= startDel; i--) {
3723                 /* NB this could be optimised somewhat,
3724                  * eg. could retrieve the tags and write them without
3725                  * using yaffs_DeleteChunk
3726                  */
3727
3728                 chunkId = yaffs_FindAndDeleteChunkInFile(in, i, NULL);
3729                 if (chunkId > 0) {
3730                         if (chunkId <
3731                             (dev->internalStartBlock * dev->param.nChunksPerBlock)
3732                             || chunkId >=
3733                             ((dev->internalEndBlock +
3734                               1) * dev->param.nChunksPerBlock)) {
3735                                 T(YAFFS_TRACE_ALWAYS,
3736                                   (TSTR("Found daft chunkId %d for %d" TENDSTR),
3737                                    chunkId, i));
3738                         } else {
3739                                 in->nDataChunks--;
3740                                 yaffs_DeleteChunk(dev, chunkId, 1, __LINE__);
3741                         }
3742                 }
3743         }
3744
3745 }
3746
3747
3748 void yaffs_ResizeDown( yaffs_Object *obj, loff_t newSize)
3749 {
3750         int newFullChunks;
3751         __u32 newSizeOfPartialChunk;
3752         yaffs_Device *dev = obj->myDev;
3753
3754         yaffs_AddrToChunk(dev, newSize, &newFullChunks, &newSizeOfPartialChunk);
3755
3756         yaffs_PruneResizedChunks(obj, newSize);
3757
3758         if (newSizeOfPartialChunk != 0) {
3759                 int lastChunk = 1 + newFullChunks;
3760                 __u8 *localBuffer = yaffs_GetTempBuffer(dev, __LINE__);
3761
3762                 /* Got to read and rewrite the last chunk with its new size and zero pad */
3763                 yaffs_ReadChunkDataFromObject(obj, lastChunk, localBuffer);
3764                 memset(localBuffer + newSizeOfPartialChunk, 0,
3765                         dev->nDataBytesPerChunk - newSizeOfPartialChunk);
3766
3767                 yaffs_WriteChunkDataToObject(obj, lastChunk, localBuffer,
3768                                              newSizeOfPartialChunk, 1);
3769
3770                 yaffs_ReleaseTempBuffer(dev, localBuffer, __LINE__);
3771         }
3772
3773         obj->variant.fileVariant.fileSize = newSize;
3774
3775         yaffs_PruneFileStructure(dev, &obj->variant.fileVariant);
3776 }
3777
3778
3779 int yaffs_ResizeFile(yaffs_Object *in, loff_t newSize)
3780 {
3781         yaffs_Device *dev = in->myDev;
3782         int oldFileSize = in->variant.fileVariant.fileSize;
3783
3784         yaffs_FlushFilesChunkCache(in);
3785         yaffs_InvalidateWholeChunkCache(in);
3786
3787         yaffs_CheckGarbageCollection(dev,0);
3788
3789         if (in->variantType != YAFFS_OBJECT_TYPE_FILE)
3790                 return YAFFS_FAIL;
3791
3792         if (newSize == oldFileSize)
3793                 return YAFFS_OK;
3794                 
3795         if(newSize > oldFileSize){
3796                 yaffs2_HandleHole(in,newSize);
3797                 in->variant.fileVariant.fileSize = newSize;
3798         } else {
3799                 /* newSize < oldFileSize */ 
3800                 yaffs_ResizeDown(in, newSize);
3801         } 
3802
3803         /* Write a new object header to reflect the resize.
3804          * show we've shrunk the file, if need be
3805          * Do this only if the file is not in the deleted directories
3806          * and is not shadowed.
3807          */
3808         if (in->parent &&
3809             !in->isShadowed &&
3810             in->parent->objectId != YAFFS_OBJECTID_UNLINKED &&
3811             in->parent->objectId != YAFFS_OBJECTID_DELETED)
3812                 yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0, NULL);
3813
3814
3815         return YAFFS_OK;
3816 }
3817
3818 loff_t yaffs_GetFileSize(yaffs_Object *obj)
3819 {
3820         YCHAR *alias = NULL;
3821         obj = yaffs_GetEquivalentObject(obj);
3822
3823         switch (obj->variantType) {
3824         case YAFFS_OBJECT_TYPE_FILE:
3825                 return obj->variant.fileVariant.fileSize;
3826         case YAFFS_OBJECT_TYPE_SYMLINK:
3827                 alias = obj->variant.symLinkVariant.alias;
3828                 if(!alias)
3829                         return 0;
3830                 return yaffs_strnlen(alias,YAFFS_MAX_ALIAS_LENGTH);
3831         default:
3832                 return 0;
3833         }
3834 }
3835
3836
3837
3838 int yaffs_FlushFile(yaffs_Object *in, int updateTime, int dataSync)
3839 {
3840         int retVal;
3841         if (in->dirty) {
3842                 yaffs_FlushFilesChunkCache(in);
3843                 if(dataSync) /* Only sync data */
3844                         retVal=YAFFS_OK;
3845                 else {
3846                         if (updateTime) {
3847 #ifdef CONFIG_YAFFS_WINCE
3848                                 yfsd_WinFileTimeNow(in->win_mtime);
3849 #else
3850
3851                                 in->yst_mtime = Y_CURRENT_TIME;
3852
3853 #endif
3854                         }
3855
3856                         retVal = (yaffs_UpdateObjectHeader(in, NULL, 0, 0, 0, NULL) >=
3857                                 0) ? YAFFS_OK : YAFFS_FAIL;
3858                 }
3859         } else {
3860                 retVal = YAFFS_OK;
3861         }
3862
3863         return retVal;
3864
3865 }
3866
3867 static int yaffs_DoGenericObjectDeletion(yaffs_Object *in)
3868 {
3869
3870         /* First off, invalidate the file's data in the cache, without flushing. */
3871         yaffs_InvalidateWholeChunkCache(in);
3872
3873         if (in->myDev->param.isYaffs2 && (in->parent != in->myDev->deletedDir)) {
3874                 /* Move to the unlinked directory so we have a record that it was deleted. */
3875                 yaffs_ChangeObjectName(in, in->myDev->deletedDir, _Y("deleted"), 0, 0);
3876
3877         }
3878
3879         yaffs_RemoveObjectFromDirectory(in);
3880         yaffs_DeleteChunk(in->myDev, in->hdrChunk, 1, __LINE__);
3881         in->hdrChunk = 0;
3882
3883         yaffs_FreeObject(in);
3884         return YAFFS_OK;
3885
3886 }
3887
3888 /* yaffs_DeleteFile deletes the whole file data
3889  * and the inode associated with the file.
3890  * It does not delete the links associated with the file.
3891  */
3892 static int yaffs_UnlinkFileIfNeeded(yaffs_Object *in)
3893 {
3894
3895         int retVal;
3896         int immediateDeletion = 0;
3897         yaffs_Device *dev = in->myDev;
3898
3899         if (!in->myInode)
3900                 immediateDeletion = 1;
3901
3902         if (immediateDeletion) {
3903                 retVal =
3904                     yaffs_ChangeObjectName(in, in->myDev->deletedDir,
3905                                            _Y("deleted"), 0, 0);
3906                 T(YAFFS_TRACE_TRACING,
3907                   (TSTR("yaffs: immediate deletion of file %d" TENDSTR),
3908                    in->objectId));
3909                 in->deleted = 1;
3910                 in->myDev->nDeletedFiles++;
3911                 if (dev->param.disableSoftDelete || dev->param.isYaffs2)
3912                         yaffs_ResizeFile(in, 0);
3913                 yaffs_SoftDeleteFile(in);
3914         } else {
3915                 retVal =
3916                     yaffs_ChangeObjectName(in, in->myDev->unlinkedDir,
3917                                            _Y("unlinked"), 0, 0);
3918         }
3919
3920
3921         return retVal;
3922 }
3923
3924 int yaffs_DeleteFile(yaffs_Object *in)
3925 {
3926         int retVal = YAFFS_OK;
3927         int deleted; /* Need to cache value on stack if in is freed */
3928         yaffs_Device *dev = in->myDev;
3929
3930         if (dev->param.disableSoftDelete || dev->param.isYaffs2)
3931                 yaffs_ResizeFile(in, 0);
3932
3933         if (in->nDataChunks > 0) {
3934                 /* Use soft deletion if there is data in the file.
3935                  * That won't be the case if it has been resized to zero.
3936                  */
3937                 if (!in->unlinked)
3938                         retVal = yaffs_UnlinkFileIfNeeded(in);
3939
3940                 deleted = in->deleted;
3941
3942                 if (retVal == YAFFS_OK && in->unlinked && !in->deleted) {
3943                         in->deleted = 1;
3944                         deleted = 1;
3945                         in->myDev->nDeletedFiles++;
3946                         yaffs_SoftDeleteFile(in);
3947                 }
3948                 return deleted ? YAFFS_OK : YAFFS_FAIL;
3949         } else {
3950                 /* The file has no data chunks so we toss it immediately */
3951                 yaffs_FreeTnode(in->myDev, in->variant.fileVariant.top);
3952                 in->variant.fileVariant.top = NULL;
3953                 yaffs_DoGenericObjectDeletion(in);
3954
3955                 return YAFFS_OK;
3956         }
3957 }
3958
3959 static int yaffs_IsNonEmptyDirectory(yaffs_Object *obj)
3960 {
3961         return (obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) &&
3962                 !(ylist_empty(&obj->variant.directoryVariant.children));
3963 }
3964
3965 static int yaffs_DeleteDirectory(yaffs_Object *obj)
3966 {
3967         /* First check that the directory is empty. */
3968         if (yaffs_IsNonEmptyDirectory(obj))
3969                 return YAFFS_FAIL;
3970
3971         return yaffs_DoGenericObjectDeletion(obj);
3972 }
3973
3974 static int yaffs_DeleteSymLink(yaffs_Object *in)
3975 {
3976         if(in->variant.symLinkVariant.alias)
3977                 YFREE(in->variant.symLinkVariant.alias);
3978         in->variant.symLinkVariant.alias=NULL;
3979
3980         return yaffs_DoGenericObjectDeletion(in);
3981 }
3982
3983 static int yaffs_DeleteHardLink(yaffs_Object *in)
3984 {
3985         /* remove this hardlink from the list assocaited with the equivalent
3986          * object
3987          */
3988         ylist_del_init(&in->hardLinks);
3989         return yaffs_DoGenericObjectDeletion(in);
3990 }
3991
3992 int yaffs_DeleteObject(yaffs_Object *obj)
3993 {
3994 int retVal = -1;
3995         switch (obj->variantType) {
3996         case YAFFS_OBJECT_TYPE_FILE:
3997                 retVal = yaffs_DeleteFile(obj);
3998                 break;
3999         case YAFFS_OBJECT_TYPE_DIRECTORY:
4000                 if(!ylist_empty(&obj->variant.directoryVariant.dirty)){
4001                         T(YAFFS_TRACE_BACKGROUND, (TSTR("Remove object %d from dirty directories" TENDSTR),obj->objectId));
4002                         ylist_del_init(&obj->variant.directoryVariant.dirty);
4003                 }
4004                 return yaffs_DeleteDirectory(obj);
4005                 break;
4006         case YAFFS_OBJECT_TYPE_SYMLINK:
4007                 retVal = yaffs_DeleteSymLink(obj);
4008                 break;
4009         case YAFFS_OBJECT_TYPE_HARDLINK:
4010                 retVal = yaffs_DeleteHardLink(obj);
4011                 break;
4012         case YAFFS_OBJECT_TYPE_SPECIAL:
4013                 retVal = yaffs_DoGenericObjectDeletion(obj);
4014                 break;
4015         case YAFFS_OBJECT_TYPE_UNKNOWN:
4016                 retVal = 0;
4017                 break;          /* should not happen. */
4018         }
4019
4020         return retVal;
4021 }
4022
4023 static int yaffs_UnlinkWorker(yaffs_Object *obj)
4024 {
4025
4026         int immediateDeletion = 0;
4027
4028         if (!obj->myInode)
4029                 immediateDeletion = 1;
4030
4031         if(obj)
4032                 yaffs_UpdateParent(obj->parent);
4033
4034         if (obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4035                 return yaffs_DeleteHardLink(obj);
4036         } else if (!ylist_empty(&obj->hardLinks)) {
4037                 /* Curve ball: We're unlinking an object that has a hardlink.
4038                  *
4039                  * This problem arises because we are not strictly following
4040                  * The Linux link/inode model.
4041                  *
4042                  * We can't really delete the object.
4043                  * Instead, we do the following:
4044                  * - Select a hardlink.
4045                  * - Unhook it from the hard links
4046                  * - Move it from its parent directory (so that the rename can work)
4047                  * - Rename the object to the hardlink's name.
4048                  * - Delete the hardlink
4049                  */
4050
4051                 yaffs_Object *hl;
4052                 yaffs_Object *parent;
4053                 int retVal;
4054                 YCHAR name[YAFFS_MAX_NAME_LENGTH + 1];
4055
4056                 hl = ylist_entry(obj->hardLinks.next, yaffs_Object, hardLinks);
4057
4058                 yaffs_GetObjectName(hl, name, YAFFS_MAX_NAME_LENGTH + 1);
4059                 parent = hl->parent;
4060
4061                 ylist_del_init(&hl->hardLinks);
4062
4063                 yaffs_AddObjectToDirectory(obj->myDev->unlinkedDir, hl);
4064
4065                 retVal = yaffs_ChangeObjectName(obj,parent, name, 0, 0);
4066
4067                 if (retVal == YAFFS_OK)
4068                         retVal = yaffs_DoGenericObjectDeletion(hl);
4069
4070                 return retVal;
4071
4072         } else if (immediateDeletion) {
4073                 switch (obj->variantType) {
4074                 case YAFFS_OBJECT_TYPE_FILE:
4075                         return yaffs_DeleteFile(obj);
4076                         break;
4077                 case YAFFS_OBJECT_TYPE_DIRECTORY:
4078                         ylist_del_init(&obj->variant.directoryVariant.dirty);
4079                         return yaffs_DeleteDirectory(obj);
4080                         break;
4081                 case YAFFS_OBJECT_TYPE_SYMLINK:
4082                         return yaffs_DeleteSymLink(obj);
4083                         break;
4084                 case YAFFS_OBJECT_TYPE_SPECIAL:
4085                         return yaffs_DoGenericObjectDeletion(obj);
4086                         break;
4087                 case YAFFS_OBJECT_TYPE_HARDLINK:
4088                 case YAFFS_OBJECT_TYPE_UNKNOWN:
4089                 default:
4090                         return YAFFS_FAIL;
4091                 }
4092         } else if(yaffs_IsNonEmptyDirectory(obj))
4093                 return YAFFS_FAIL;
4094         else
4095                 return yaffs_ChangeObjectName(obj, obj->myDev->unlinkedDir,
4096                                            _Y("unlinked"), 0, 0);
4097 }
4098
4099
4100 static int yaffs_UnlinkObject(yaffs_Object *obj)
4101 {
4102
4103         if (obj && obj->unlinkAllowed)
4104                 return yaffs_UnlinkWorker(obj);
4105
4106         return YAFFS_FAIL;
4107
4108 }
4109 int yaffs_Unlink(yaffs_Object *dir, const YCHAR *name)
4110 {
4111         yaffs_Object *obj;
4112
4113         obj = yaffs_FindObjectByName(dir, name);
4114         return yaffs_UnlinkObject(obj);
4115 }
4116
4117 /*----------------------- Initialisation Scanning ---------------------- */
4118
4119 void yaffs_HandleShadowedObject(yaffs_Device *dev, int objId,
4120                                 int backwardScanning)
4121 {
4122         yaffs_Object *obj;
4123
4124         if (!backwardScanning) {
4125                 /* Handle YAFFS1 forward scanning case
4126                  * For YAFFS1 we always do the deletion
4127                  */
4128
4129         } else {
4130                 /* Handle YAFFS2 case (backward scanning)
4131                  * If the shadowed object exists then ignore.
4132                  */
4133                 obj = yaffs_FindObjectByNumber(dev, objId);
4134                 if(obj)
4135                         return;
4136         }
4137
4138         /* Let's create it (if it does not exist) assuming it is a file so that it can do shrinking etc.
4139          * We put it in unlinked dir to be cleaned up after the scanning
4140          */
4141         obj =
4142             yaffs_FindOrCreateObjectByNumber(dev, objId,
4143                                              YAFFS_OBJECT_TYPE_FILE);
4144         if (!obj)
4145                 return;
4146         obj->isShadowed = 1;
4147         yaffs_AddObjectToDirectory(dev->unlinkedDir, obj);
4148         obj->variant.fileVariant.shrinkSize = 0;
4149         obj->valid = 1;         /* So that we don't read any other info for this file */
4150
4151 }
4152
4153
4154 void yaffs_HardlinkFixup(yaffs_Device *dev, yaffs_Object *hardList)
4155 {
4156         yaffs_Object *hl;
4157         yaffs_Object *in;
4158
4159         while (hardList) {
4160                 hl = hardList;
4161                 hardList = (yaffs_Object *) (hardList->hardLinks.next);
4162
4163                 in = yaffs_FindObjectByNumber(dev,
4164                                               hl->variant.hardLinkVariant.
4165                                               equivalentObjectId);
4166
4167                 if (in) {
4168                         /* Add the hardlink pointers */
4169                         hl->variant.hardLinkVariant.equivalentObject = in;
4170                         ylist_add(&hl->hardLinks, &in->hardLinks);
4171                 } else {
4172                         /* Todo Need to report/handle this better.
4173                          * Got a problem... hardlink to a non-existant object
4174                          */
4175                         hl->variant.hardLinkVariant.equivalentObject = NULL;
4176                         YINIT_LIST_HEAD(&hl->hardLinks);
4177
4178                 }
4179         }
4180 }
4181
4182
4183 static void yaffs_StripDeletedObjects(yaffs_Device *dev)
4184 {
4185         /*
4186         *  Sort out state of unlinked and deleted objects after scanning.
4187         */
4188         struct ylist_head *i;
4189         struct ylist_head *n;
4190         yaffs_Object *l;
4191
4192         if (dev->readOnly)
4193                 return;
4194
4195         /* Soft delete all the unlinked files */
4196         ylist_for_each_safe(i, n,
4197                 &dev->unlinkedDir->variant.directoryVariant.children) {
4198                 if (i) {
4199                         l = ylist_entry(i, yaffs_Object, siblings);
4200                         yaffs_DeleteObject(l);
4201                 }
4202         }
4203
4204         ylist_for_each_safe(i, n,
4205                 &dev->deletedDir->variant.directoryVariant.children) {
4206                 if (i) {
4207                         l = ylist_entry(i, yaffs_Object, siblings);
4208                         yaffs_DeleteObject(l);
4209                 }
4210         }
4211
4212 }
4213
4214 /*
4215  * This code iterates through all the objects making sure that they are rooted.
4216  * Any unrooted objects are re-rooted in lost+found.
4217  * An object needs to be in one of:
4218  * - Directly under deleted, unlinked
4219  * - Directly or indirectly under root.
4220  *
4221  * Note:
4222  *  This code assumes that we don't ever change the current relationships between
4223  *  directories:
4224  *   rootDir->parent == unlinkedDir->parent == deletedDir->parent == NULL
4225  *   lostNfound->parent == rootDir
4226  *
4227  * This fixes the problem where directories might have inadvertently been deleted
4228  * leaving the object "hanging" without being rooted in the directory tree.
4229  */
4230  
4231 static int yaffs_HasNULLParent(yaffs_Device *dev, yaffs_Object *obj)
4232 {
4233         return (obj == dev->deletedDir ||
4234                 obj == dev->unlinkedDir||
4235                 obj == dev->rootDir);
4236 }
4237
4238 static void yaffs_FixHangingObjects(yaffs_Device *dev)
4239 {
4240         yaffs_Object *obj;
4241         yaffs_Object *parent;
4242         int i;
4243         struct ylist_head *lh;
4244         struct ylist_head *n;
4245         int depthLimit;
4246         int hanging;
4247
4248         if (dev->readOnly)
4249                 return;
4250
4251         /* Iterate through the objects in each hash entry,
4252          * looking at each object.
4253          * Make sure it is rooted.
4254          */
4255
4256         for (i = 0; i <  YAFFS_NOBJECT_BUCKETS; i++) {
4257                 ylist_for_each_safe(lh, n, &dev->objectBucket[i].list) {
4258                         if (lh) {
4259                                 obj = ylist_entry(lh, yaffs_Object, hashLink);
4260                                 parent= obj->parent;
4261                                 
4262                                 if(yaffs_HasNULLParent(dev,obj)){
4263                                         /* These directories are not hanging */
4264                                         hanging = 0;
4265                                 }
4266                                 else if(!parent || parent->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
4267                                         hanging = 1;
4268                                 else if(yaffs_HasNULLParent(dev,parent))
4269                                         hanging = 0;
4270                                 else {
4271                                         /*
4272                                          * Need to follow the parent chain to see if it is hanging.
4273                                          */
4274                                         hanging = 0;
4275                                         depthLimit=100;
4276
4277                                         while(parent != dev->rootDir &&
4278                                                 parent->parent &&
4279                                                 parent->parent->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
4280                                                 depthLimit > 0){
4281                                                 parent = parent->parent;
4282                                                 depthLimit--;
4283                                         }
4284                                         if(parent != dev->rootDir)
4285                                                 hanging = 1;
4286                                 }
4287                                 if(hanging){
4288                                         T(YAFFS_TRACE_SCAN,
4289                                           (TSTR("Hanging object %d moved to lost and found" TENDSTR),
4290                                                 obj->objectId));
4291                                         yaffs_AddObjectToDirectory(dev->lostNFoundDir,obj);
4292                                 }
4293                         }
4294                 }
4295         }
4296 }
4297
4298
4299 /*
4300  * Delete directory contents for cleaning up lost and found.
4301  */
4302 static void yaffs_DeleteDirectoryContents(yaffs_Object *dir)
4303 {
4304         yaffs_Object *obj;
4305         struct ylist_head *lh;
4306         struct ylist_head *n;
4307
4308         if(dir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
4309                 YBUG();
4310         
4311         ylist_for_each_safe(lh, n, &dir->variant.directoryVariant.children) {
4312                 if (lh) {
4313                         obj = ylist_entry(lh, yaffs_Object, siblings);
4314                         if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
4315                                 yaffs_DeleteDirectoryContents(obj);
4316
4317                         T(YAFFS_TRACE_SCAN,
4318                                 (TSTR("Deleting lost_found object %d" TENDSTR),
4319                                 obj->objectId));
4320
4321                         /* Need to use UnlinkObject since Delete would not handle
4322                          * hardlinked objects correctly.
4323                          */
4324                         yaffs_UnlinkObject(obj); 
4325                 }
4326         }
4327                         
4328 }
4329
4330 static void yaffs_EmptyLostAndFound(yaffs_Device *dev)
4331 {
4332         yaffs_DeleteDirectoryContents(dev->lostNFoundDir);
4333 }
4334
4335 static void yaffs_CheckObjectDetailsLoaded(yaffs_Object *in)
4336 {
4337         __u8 *chunkData;
4338         yaffs_ObjectHeader *oh;
4339         yaffs_Device *dev;
4340         yaffs_ExtendedTags tags;
4341         int result;
4342         int alloc_failed = 0;
4343
4344         if (!in)
4345                 return;
4346
4347         dev = in->myDev;
4348
4349 #if 0
4350         T(YAFFS_TRACE_SCAN, (TSTR("details for object %d %s loaded" TENDSTR),
4351                 in->objectId,
4352                 in->lazyLoaded ? "not yet" : "already"));
4353 #endif
4354
4355         if (in->lazyLoaded && in->hdrChunk > 0) {
4356                 in->lazyLoaded = 0;
4357                 chunkData = yaffs_GetTempBuffer(dev, __LINE__);
4358
4359                 result = yaffs_ReadChunkWithTagsFromNAND(dev, in->hdrChunk, chunkData, &tags);
4360                 oh = (yaffs_ObjectHeader *) chunkData;
4361
4362                 in->yst_mode = oh->yst_mode;
4363 #ifdef CONFIG_YAFFS_WINCE
4364                 in->win_atime[0] = oh->win_atime[0];
4365                 in->win_ctime[0] = oh->win_ctime[0];
4366                 in->win_mtime[0] = oh->win_mtime[0];
4367                 in->win_atime[1] = oh->win_atime[1];
4368                 in->win_ctime[1] = oh->win_ctime[1];
4369                 in->win_mtime[1] = oh->win_mtime[1];
4370 #else
4371                 in->yst_uid = oh->yst_uid;
4372                 in->yst_gid = oh->yst_gid;
4373                 in->yst_atime = oh->yst_atime;
4374                 in->yst_mtime = oh->yst_mtime;
4375                 in->yst_ctime = oh->yst_ctime;
4376                 in->yst_rdev = oh->yst_rdev;
4377
4378 #endif
4379                 yaffs_SetObjectNameFromOH(in, oh);
4380
4381                 if (in->variantType == YAFFS_OBJECT_TYPE_SYMLINK) {
4382                         in->variant.symLinkVariant.alias =
4383                                                     yaffs_CloneString(oh->alias);
4384                         if (!in->variant.symLinkVariant.alias)
4385                                 alloc_failed = 1; /* Not returned to caller */
4386                 }
4387
4388                 yaffs_ReleaseTempBuffer(dev, chunkData, __LINE__);
4389         }
4390 }
4391
4392 /*------------------------------  Directory Functions ----------------------------- */
4393
4394 /*
4395  *yaffs_UpdateParent() handles fixing a directories mtime and ctime when a new
4396  * link (ie. name) is created or deleted in the directory.
4397  *
4398  * ie.
4399  *   create dir/a : update dir's mtime/ctime
4400  *   rm dir/a:   update dir's mtime/ctime
4401  *   modify dir/a: don't update dir's mtimme/ctime
4402  *
4403  * This can be handled immediately or defered. Defering helps reduce the number
4404  * of updates when many files in a directory are changed within a brief period.
4405  *
4406  * If the directory updating is defered then yaffs_UpdateDirtyDirecories must be
4407  * called periodically.
4408  */
4409  
4410 static void yaffs_UpdateParent(yaffs_Object *obj)
4411 {
4412         yaffs_Device *dev;
4413         if(!obj)
4414                 return;
4415 #ifndef CONFIG_YAFFS_WINCE
4416
4417         dev = obj->myDev;
4418         obj->dirty = 1;
4419         obj->yst_mtime = obj->yst_ctime = Y_CURRENT_TIME;
4420         if(dev->param.deferDirectoryUpdate){
4421                 struct ylist_head *link = &obj->variant.directoryVariant.dirty; 
4422         
4423                 if(ylist_empty(link)){
4424                         ylist_add(link,&dev->dirtyDirectories);
4425                         T(YAFFS_TRACE_BACKGROUND, (TSTR("Added object %d to dirty directories" TENDSTR),obj->objectId));
4426                 }
4427
4428         } else
4429                 yaffs_UpdateObjectHeader(obj, NULL, 0, 0, 0, NULL);
4430 #endif
4431 }
4432
4433 void yaffs_UpdateDirtyDirectories(yaffs_Device *dev)
4434 {
4435         struct ylist_head *link;
4436         yaffs_Object *obj;
4437         yaffs_DirectoryStructure *dS;
4438         yaffs_ObjectVariant *oV;
4439
4440         T(YAFFS_TRACE_BACKGROUND, (TSTR("Update dirty directories" TENDSTR)));
4441
4442         while(!ylist_empty(&dev->dirtyDirectories)){
4443                 link = dev->dirtyDirectories.next;
4444                 ylist_del_init(link);
4445                 
4446                 dS=ylist_entry(link,yaffs_DirectoryStructure,dirty);
4447                 oV = ylist_entry(dS,yaffs_ObjectVariant,directoryVariant);
4448                 obj = ylist_entry(oV,yaffs_Object,variant);
4449
4450                 T(YAFFS_TRACE_BACKGROUND, (TSTR("Update directory %d" TENDSTR), obj->objectId));
4451
4452                 if(obj->dirty)
4453                         yaffs_UpdateObjectHeader(obj, NULL, 0, 0, 0, NULL);
4454         }
4455 }
4456
4457 static void yaffs_RemoveObjectFromDirectory(yaffs_Object *obj)
4458 {
4459         yaffs_Device *dev = obj->myDev;
4460         yaffs_Object *parent;
4461
4462         yaffs_VerifyObjectInDirectory(obj);
4463         parent = obj->parent;
4464
4465         yaffs_VerifyDirectory(parent);
4466
4467         if (dev && dev->param.removeObjectCallback)
4468                 dev->param.removeObjectCallback(obj);
4469
4470
4471         ylist_del_init(&obj->siblings);
4472         obj->parent = NULL;
4473         
4474         yaffs_VerifyDirectory(parent);
4475 }
4476
4477 void yaffs_AddObjectToDirectory(yaffs_Object *directory,
4478                                         yaffs_Object *obj)
4479 {
4480         if (!directory) {
4481                 T(YAFFS_TRACE_ALWAYS,
4482                   (TSTR
4483                    ("tragedy: Trying to add an object to a null pointer directory"
4484                     TENDSTR)));
4485                 YBUG();
4486                 return;
4487         }
4488         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4489                 T(YAFFS_TRACE_ALWAYS,
4490                   (TSTR
4491                    ("tragedy: Trying to add an object to a non-directory"
4492                     TENDSTR)));
4493                 YBUG();
4494         }
4495
4496         if (obj->siblings.prev == NULL) {
4497                 /* Not initialised */
4498                 YBUG();
4499         }
4500
4501
4502         yaffs_VerifyDirectory(directory);
4503
4504         yaffs_RemoveObjectFromDirectory(obj);
4505
4506
4507         /* Now add it */
4508         ylist_add(&obj->siblings, &directory->variant.directoryVariant.children);
4509         obj->parent = directory;
4510
4511         if (directory == obj->myDev->unlinkedDir
4512                         || directory == obj->myDev->deletedDir) {
4513                 obj->unlinked = 1;
4514                 obj->myDev->nUnlinkedFiles++;
4515                 obj->renameAllowed = 0;
4516         }
4517
4518         yaffs_VerifyDirectory(directory);
4519         yaffs_VerifyObjectInDirectory(obj);
4520 }
4521
4522 yaffs_Object *yaffs_FindObjectByName(yaffs_Object *directory,
4523                                      const YCHAR *name)
4524 {
4525         int sum;
4526
4527         struct ylist_head *i;
4528         YCHAR buffer[YAFFS_MAX_NAME_LENGTH + 1];
4529
4530         yaffs_Object *l;
4531
4532         if (!name)
4533                 return NULL;
4534
4535         if (!directory) {
4536                 T(YAFFS_TRACE_ALWAYS,
4537                   (TSTR
4538                    ("tragedy: yaffs_FindObjectByName: null pointer directory"
4539                     TENDSTR)));
4540                 YBUG();
4541                 return NULL;
4542         }
4543         if (directory->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4544                 T(YAFFS_TRACE_ALWAYS,
4545                   (TSTR
4546                    ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
4547                 YBUG();
4548         }
4549
4550         sum = yaffs_CalcNameSum(name);
4551
4552         ylist_for_each(i, &directory->variant.directoryVariant.children) {
4553                 if (i) {
4554                         l = ylist_entry(i, yaffs_Object, siblings);
4555
4556                         if (l->parent != directory)
4557                                 YBUG();
4558
4559                         yaffs_CheckObjectDetailsLoaded(l);
4560
4561                         /* Special case for lost-n-found */
4562                         if (l->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
4563                                 if (yaffs_strcmp(name, YAFFS_LOSTNFOUND_NAME) == 0)
4564                                         return l;
4565                         } else if (yaffs_SumCompare(l->sum, sum) || l->hdrChunk <= 0) {
4566                                 /* LostnFound chunk called Objxxx
4567                                  * Do a real check
4568                                  */
4569                                 yaffs_GetObjectName(l, buffer,
4570                                                     YAFFS_MAX_NAME_LENGTH + 1);
4571                                 if (yaffs_strncmp(name, buffer, YAFFS_MAX_NAME_LENGTH) == 0)
4572                                         return l;
4573                         }
4574                 }
4575         }
4576
4577         return NULL;
4578 }
4579
4580
4581 #if 0
4582 int yaffs_ApplyToDirectoryChildren(yaffs_Object *theDir,
4583                                         int (*fn) (yaffs_Object *))
4584 {
4585         struct ylist_head *i;
4586         yaffs_Object *l;
4587
4588         if (!theDir) {
4589                 T(YAFFS_TRACE_ALWAYS,
4590                   (TSTR
4591                    ("tragedy: yaffs_FindObjectByName: null pointer directory"
4592                     TENDSTR)));
4593                 YBUG();
4594                 return YAFFS_FAIL;
4595         }
4596         if (theDir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY) {
4597                 T(YAFFS_TRACE_ALWAYS,
4598                   (TSTR
4599                    ("tragedy: yaffs_FindObjectByName: non-directory" TENDSTR)));
4600                 YBUG();
4601                 return YAFFS_FAIL;
4602         }
4603
4604         ylist_for_each(i, &theDir->variant.directoryVariant.children) {
4605                 if (i) {
4606                         l = ylist_entry(i, yaffs_Object, siblings);
4607                         if (l && !fn(l))
4608                                 return YAFFS_FAIL;
4609                 }
4610         }
4611
4612         return YAFFS_OK;
4613
4614 }
4615 #endif
4616
4617 /* GetEquivalentObject dereferences any hard links to get to the
4618  * actual object.
4619  */
4620
4621 yaffs_Object *yaffs_GetEquivalentObject(yaffs_Object *obj)
4622 {
4623         if (obj && obj->variantType == YAFFS_OBJECT_TYPE_HARDLINK) {
4624                 /* We want the object id of the equivalent object, not this one */
4625                 obj = obj->variant.hardLinkVariant.equivalentObject;
4626                 yaffs_CheckObjectDetailsLoaded(obj);
4627         }
4628         return obj;
4629 }
4630
4631 /*
4632  *  A note or two on object names.
4633  *  * If the object name is missing, we then make one up in the form objnnn
4634  *
4635  *  * ASCII names are stored in the object header's name field from byte zero
4636  *  * Unicode names are historically stored starting from byte zero.
4637  *
4638  * Then there are automatic Unicode names...
4639  * The purpose of these is to save names in a way that can be read as
4640  * ASCII or Unicode names as appropriate, thus allowing a Unicode and ASCII
4641  * system to share files.
4642  *
4643  * These automatic unicode are stored slightly differently...
4644  *  - If the name can fit in the ASCII character space then they are saved as 
4645  *    ascii names as per above.
4646  *  - If the name needs Unicode then the name is saved in Unicode
4647  *    starting at oh->name[1].
4648
4649  */
4650 static void yaffs_FixNullName(yaffs_Object * obj,YCHAR * name, int buffSize)
4651 {
4652         /* Create an object name if we could not find one. */
4653         if(yaffs_strnlen(name,YAFFS_MAX_NAME_LENGTH) == 0){
4654                 YCHAR locName[20];
4655                 YCHAR numString[20];
4656                 YCHAR *x = &numString[19];
4657                 unsigned v = obj->objectId;
4658                 numString[19] = 0;
4659                 while(v>0){
4660                         x--;
4661                         *x = '0' + (v % 10);
4662                         v /= 10;
4663                 }
4664                 /* make up a name */
4665                 yaffs_strcpy(locName, YAFFS_LOSTNFOUND_PREFIX);
4666                 yaffs_strcat(locName,x);
4667                 yaffs_strncpy(name, locName, buffSize - 1);
4668         }
4669 }
4670
4671 static void yaffs_LoadNameFromObjectHeader(yaffs_Device *dev,YCHAR *name, const YCHAR *ohName, int bufferSize)
4672 {
4673 #ifdef CONFIG_YAFFS_AUTO_UNICODE
4674         if(dev->param.autoUnicode){
4675                 if(*ohName){
4676                         /* It is an ASCII name, so do an ASCII to unicode conversion */
4677                         const char *asciiOhName = (const char *)ohName;
4678                         int n = bufferSize - 1;
4679                         while(n > 0 && *asciiOhName){
4680                                 *name = *asciiOhName;
4681                                 name++;
4682                                 asciiOhName++;
4683                                 n--;
4684                         }
4685                 } else 
4686                         yaffs_strncpy(name,ohName+1, bufferSize -1);
4687         } else
4688 #endif
4689                 yaffs_strncpy(name, ohName, bufferSize - 1);
4690 }
4691
4692
4693 static void yaffs_LoadObjectHeaderFromName(yaffs_Device *dev, YCHAR *ohName, const YCHAR *name)
4694 {
4695 #ifdef CONFIG_YAFFS_AUTO_UNICODE
4696
4697         int isAscii;
4698         YCHAR *w;
4699
4700         if(dev->param.autoUnicode){
4701
4702                 isAscii = 1;
4703                 w = name;
4704         
4705                 /* Figure out if the name will fit in ascii character set */
4706                 while(isAscii && *w){
4707                         if((*w) & 0xff00)
4708                                 isAscii = 0;
4709                         w++;
4710                 }
4711
4712                 if(isAscii){
4713                         /* It is an ASCII name, so do a unicode to ascii conversion */
4714                         char *asciiOhName = (char *)ohName;
4715                         int n = YAFFS_MAX_NAME_LENGTH  - 1;
4716                         while(n > 0 && *name){
4717                                 *asciiOhName= *name;
4718                                 name++;
4719                                 asciiOhName++;
4720                                 n--;
4721                         }
4722                 } else{
4723                         /* It is a unicode name, so save starting at the second YCHAR */
4724                         *ohName = 0;
4725                         yaffs_strncpy(ohName+1,name, YAFFS_MAX_NAME_LENGTH -2);
4726                 }
4727         }
4728         else 
4729 #endif
4730                 yaffs_strncpy(ohName,name, YAFFS_MAX_NAME_LENGTH - 1);
4731
4732 }
4733
4734 int yaffs_GetObjectName(yaffs_Object * obj, YCHAR * name, int buffSize)
4735 {
4736         memset(name, 0, buffSize * sizeof(YCHAR));
4737         
4738         yaffs_CheckObjectDetailsLoaded(obj);
4739
4740         if (obj->objectId == YAFFS_OBJECTID_LOSTNFOUND) {
4741                 yaffs_strncpy(name, YAFFS_LOSTNFOUND_NAME, buffSize - 1);
4742         } 
4743 #ifdef CONFIG_YAFFS_SHORT_NAMES_IN_RAM
4744         else if (obj->shortName[0]) {
4745                 yaffs_strcpy(name, obj->shortName);
4746         }
4747 #endif
4748         else if(obj->hdrChunk > 0) {
4749                 int result;
4750                 __u8 *buffer = yaffs_GetTempBuffer(obj->myDev, __LINE__);
4751
4752                 yaffs_ObjectHeader *oh = (yaffs_ObjectHeader *) buffer;
4753
4754                 memset(buffer, 0, obj->myDev->nDataBytesPerChunk);
4755
4756                 if (obj->hdrChunk > 0) {
4757                         result = yaffs_ReadChunkWithTagsFromNAND(obj->myDev,
4758                                                         obj->hdrChunk, buffer,
4759                                                         NULL);
4760                 }
4761                 yaffs_LoadNameFromObjectHeader(obj->myDev,name,oh->name,buffSize);
4762
4763                 yaffs_ReleaseTempBuffer(obj->myDev, buffer, __LINE__);
4764         }
4765
4766         yaffs_FixNullName(obj,name,buffSize);
4767
4768         return yaffs_strnlen(name,YAFFS_MAX_NAME_LENGTH);
4769 }
4770
4771
4772 int yaffs_GetObjectFileLength(yaffs_Object *obj)
4773 {
4774         /* Dereference any hard linking */
4775         obj = yaffs_GetEquivalentObject(obj);
4776
4777         if (obj->variantType == YAFFS_OBJECT_TYPE_FILE)
4778                 return obj->variant.fileVariant.fileSize;
4779         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
4780                 if(!obj->variant.symLinkVariant.alias)
4781                         return 0;
4782                 return yaffs_strnlen(obj->variant.symLinkVariant.alias,YAFFS_MAX_ALIAS_LENGTH);
4783         } else {
4784                 /* Only a directory should drop through to here */
4785                 return obj->myDev->nDataBytesPerChunk;
4786         }
4787 }
4788
4789 int yaffs_GetObjectLinkCount(yaffs_Object *obj)
4790 {
4791         int count = 0;
4792         struct ylist_head *i;
4793
4794         if (!obj->unlinked)
4795                 count++;                /* the object itself */
4796
4797         ylist_for_each(i, &obj->hardLinks)
4798                 count++;                /* add the hard links; */
4799
4800         return count;
4801 }
4802
4803 int yaffs_GetObjectInode(yaffs_Object *obj)
4804 {
4805         obj = yaffs_GetEquivalentObject(obj);
4806
4807         return obj->objectId;
4808 }
4809
4810 unsigned yaffs_GetObjectType(yaffs_Object *obj)
4811 {
4812         obj = yaffs_GetEquivalentObject(obj);
4813
4814         switch (obj->variantType) {
4815         case YAFFS_OBJECT_TYPE_FILE:
4816                 return DT_REG;
4817                 break;
4818         case YAFFS_OBJECT_TYPE_DIRECTORY:
4819                 return DT_DIR;
4820                 break;
4821         case YAFFS_OBJECT_TYPE_SYMLINK:
4822                 return DT_LNK;
4823                 break;
4824         case YAFFS_OBJECT_TYPE_HARDLINK:
4825                 return DT_REG;
4826                 break;
4827         case YAFFS_OBJECT_TYPE_SPECIAL:
4828                 if (S_ISFIFO(obj->yst_mode))
4829                         return DT_FIFO;
4830                 if (S_ISCHR(obj->yst_mode))
4831                         return DT_CHR;
4832                 if (S_ISBLK(obj->yst_mode))
4833                         return DT_BLK;
4834                 if (S_ISSOCK(obj->yst_mode))
4835                         return DT_SOCK;
4836         default:
4837                 return DT_REG;
4838                 break;
4839         }
4840 }
4841
4842 YCHAR *yaffs_GetSymlinkAlias(yaffs_Object *obj)
4843 {
4844         obj = yaffs_GetEquivalentObject(obj);
4845         if (obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
4846                 return yaffs_CloneString(obj->variant.symLinkVariant.alias);
4847         else
4848                 return yaffs_CloneString(_Y(""));
4849 }
4850
4851 #ifndef CONFIG_YAFFS_WINCE
4852
4853 int yaffs_SetAttributes(yaffs_Object *obj, struct iattr *attr)
4854 {
4855         unsigned int valid = attr->ia_valid;
4856
4857         if (valid & ATTR_MODE)
4858                 obj->yst_mode = attr->ia_mode;
4859         if (valid & ATTR_UID)
4860                 obj->yst_uid = attr->ia_uid;
4861         if (valid & ATTR_GID)
4862                 obj->yst_gid = attr->ia_gid;
4863
4864         if (valid & ATTR_ATIME)
4865                 obj->yst_atime = Y_TIME_CONVERT(attr->ia_atime);
4866         if (valid & ATTR_CTIME)
4867                 obj->yst_ctime = Y_TIME_CONVERT(attr->ia_ctime);
4868         if (valid & ATTR_MTIME)
4869                 obj->yst_mtime = Y_TIME_CONVERT(attr->ia_mtime);
4870
4871         if (valid & ATTR_SIZE)
4872                 yaffs_ResizeFile(obj, attr->ia_size);
4873
4874         yaffs_UpdateObjectHeader(obj, NULL, 1, 0, 0, NULL);
4875
4876         return YAFFS_OK;
4877
4878 }
4879 int yaffs_GetAttributes(yaffs_Object *obj, struct iattr *attr)
4880 {
4881         unsigned int valid = 0;
4882
4883         attr->ia_mode = obj->yst_mode;
4884         valid |= ATTR_MODE;
4885         attr->ia_uid = obj->yst_uid;
4886         valid |= ATTR_UID;
4887         attr->ia_gid = obj->yst_gid;
4888         valid |= ATTR_GID;
4889
4890         Y_TIME_CONVERT(attr->ia_atime) = obj->yst_atime;
4891         valid |= ATTR_ATIME;
4892         Y_TIME_CONVERT(attr->ia_ctime) = obj->yst_ctime;
4893         valid |= ATTR_CTIME;
4894         Y_TIME_CONVERT(attr->ia_mtime) = obj->yst_mtime;
4895         valid |= ATTR_MTIME;
4896
4897         attr->ia_size = yaffs_GetFileSize(obj);
4898         valid |= ATTR_SIZE;
4899
4900         attr->ia_valid = valid;
4901
4902         return YAFFS_OK;
4903 }
4904
4905 #endif
4906
4907
4908 static int yaffs_DoXMod(yaffs_Object *obj, int set, const YCHAR *name, const void *value, int size, int flags)
4909 {
4910         yaffs_XAttrMod xmod;
4911
4912         int result;
4913
4914         xmod.set = set;
4915         xmod.name = name;
4916         xmod.data = value;
4917         xmod.size =  size;
4918         xmod.flags = flags;
4919         xmod.result = -ENOSPC;
4920
4921         result = yaffs_UpdateObjectHeader(obj, NULL, 0, 0, 0, &xmod);
4922
4923         if(result > 0)
4924                 return xmod.result;
4925         else
4926                 return -ENOSPC;
4927 }
4928
4929 static int yaffs_ApplyXMod(yaffs_Device *dev, char *buffer, yaffs_XAttrMod *xmod)
4930 {
4931         int retval = 0;
4932         int x_offs = sizeof(yaffs_ObjectHeader);
4933         int x_size = dev->nDataBytesPerChunk - sizeof(yaffs_ObjectHeader);
4934
4935         char * x_buffer = buffer + x_offs;
4936
4937         if(xmod->set)
4938                 retval = nval_set(x_buffer, x_size, xmod->name, xmod->data, xmod->size, xmod->flags);
4939         else
4940                 retval = nval_del(x_buffer, x_size, xmod->name);
4941
4942         xmod->result = retval;
4943
4944         return retval;
4945 }
4946
4947 static int yaffs_DoXFetch(yaffs_Object *obj, const YCHAR *name, void *value, int size)
4948 {
4949         char *buffer = NULL;
4950         int result;
4951         yaffs_ExtendedTags tags;
4952         yaffs_Device *dev = obj->myDev;
4953         int x_offs = sizeof(yaffs_ObjectHeader);
4954         int x_size = dev->nDataBytesPerChunk - sizeof(yaffs_ObjectHeader);
4955
4956         __u8 * x_buffer;
4957
4958         int retval = 0;
4959
4960         if(obj->hdrChunk < 1)
4961                 return -ENODATA;
4962
4963         buffer = yaffs_GetTempBuffer(dev, __LINE__);
4964         if(!buffer)
4965                 return -ENOMEM;
4966
4967         result = yaffs_ReadChunkWithTagsFromNAND(dev,obj->hdrChunk, buffer, &tags);
4968
4969         if(result != YAFFS_OK)
4970                 retval = -ENOENT;
4971         else{
4972                 x_buffer =  buffer + x_offs;
4973
4974                 if(name)
4975                         retval = nval_get(x_buffer, x_size, name, value, size);
4976                 else
4977                         retval = nval_list(x_buffer, x_size, value,size);
4978         }
4979         yaffs_ReleaseTempBuffer(dev,buffer,__LINE__);
4980         return retval;
4981 }
4982
4983 int yaffs_SetXAttribute(yaffs_Object *obj, const YCHAR *name, const void * value, int size, int flags)
4984 {
4985         return yaffs_DoXMod(obj, 1, name, value, size, flags);
4986 }
4987
4988 int yaffs_RemoveXAttribute(yaffs_Object *obj, const YCHAR *name)
4989 {
4990         return yaffs_DoXMod(obj, 0, name, NULL, 0, 0);
4991 }
4992
4993 int yaffs_GetXAttribute(yaffs_Object *obj, const YCHAR *name, void *value, int size)
4994 {
4995         return yaffs_DoXFetch(obj, name, value, size);
4996 }
4997
4998 int yaffs_ListXAttributes(yaffs_Object *obj, char *buffer, int size)
4999 {
5000         return yaffs_DoXFetch(obj, NULL, buffer,size);
5001 }
5002
5003
5004
5005 #if 0
5006 int yaffs_DumpObject(yaffs_Object *obj)
5007 {
5008         YCHAR name[257];
5009
5010         yaffs_GetObjectName(obj, name, YAFFS_MAX_NAME_LENGTH + 1);
5011
5012         T(YAFFS_TRACE_ALWAYS,
5013           (TSTR
5014            ("Object %d, inode %d \"%s\"\n dirty %d valid %d serial %d sum %d"
5015             " chunk %d type %d size %d\n"
5016             TENDSTR), obj->objectId, yaffs_GetObjectInode(obj), name,
5017            obj->dirty, obj->valid, obj->serial, obj->sum, obj->hdrChunk,
5018            yaffs_GetObjectType(obj), yaffs_GetObjectFileLength(obj)));
5019
5020         return YAFFS_OK;
5021 }
5022 #endif
5023
5024 /*---------------------------- Initialisation code -------------------------------------- */
5025
5026 static int yaffs_CheckDevFunctions(const yaffs_Device *dev)
5027 {
5028
5029         /* Common functions, gotta have */
5030         if (!dev->param.eraseBlockInNAND || !dev->param.initialiseNAND)
5031                 return 0;
5032
5033 #ifdef CONFIG_YAFFS_YAFFS2
5034
5035         /* Can use the "with tags" style interface for yaffs1 or yaffs2 */
5036         if (dev->param.writeChunkWithTagsToNAND &&
5037             dev->param.readChunkWithTagsFromNAND &&
5038             !dev->param.writeChunkToNAND &&
5039             !dev->param.readChunkFromNAND &&
5040             dev->param.markNANDBlockBad &&
5041             dev->param.queryNANDBlock)
5042                 return 1;
5043 #endif
5044
5045         /* Can use the "spare" style interface for yaffs1 */
5046         if (!dev->param.isYaffs2 &&
5047             !dev->param.writeChunkWithTagsToNAND &&
5048             !dev->param.readChunkWithTagsFromNAND &&
5049             dev->param.writeChunkToNAND &&
5050             dev->param.readChunkFromNAND &&
5051             !dev->param.markNANDBlockBad &&
5052             !dev->param.queryNANDBlock)
5053                 return 1;
5054
5055         return 0;       /* bad */
5056 }
5057
5058
5059 static int yaffs_CreateInitialDirectories(yaffs_Device *dev)
5060 {
5061         /* Initialise the unlinked, deleted, root and lost and found directories */
5062
5063         dev->lostNFoundDir = dev->rootDir =  NULL;
5064         dev->unlinkedDir = dev->deletedDir = NULL;
5065
5066         dev->unlinkedDir =
5067             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_UNLINKED, S_IFDIR);
5068
5069         dev->deletedDir =
5070             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_DELETED, S_IFDIR);
5071
5072         dev->rootDir =
5073             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_ROOT,
5074                                       YAFFS_ROOT_MODE | S_IFDIR);
5075         dev->lostNFoundDir =
5076             yaffs_CreateFakeDirectory(dev, YAFFS_OBJECTID_LOSTNFOUND,
5077                                       YAFFS_LOSTNFOUND_MODE | S_IFDIR);
5078
5079         if (dev->lostNFoundDir && dev->rootDir && dev->unlinkedDir && dev->deletedDir) {
5080                 yaffs_AddObjectToDirectory(dev->rootDir, dev->lostNFoundDir);
5081                 return YAFFS_OK;
5082         }
5083
5084         return YAFFS_FAIL;
5085 }
5086
5087 int yaffs_GutsInitialise(yaffs_Device *dev)
5088 {
5089         int init_failed = 0;
5090         unsigned x;
5091         int bits;
5092
5093         T(YAFFS_TRACE_TRACING, (TSTR("yaffs: yaffs_GutsInitialise()" TENDSTR)));
5094
5095         /* Check stuff that must be set */
5096
5097         if (!dev) {
5098                 T(YAFFS_TRACE_ALWAYS, (TSTR("yaffs: Need a device" TENDSTR)));
5099                 return YAFFS_FAIL;
5100         }
5101
5102         dev->internalStartBlock = dev->param.startBlock;
5103         dev->internalEndBlock = dev->param.endBlock;
5104         dev->blockOffset = 0;
5105         dev->chunkOffset = 0;
5106         dev->nFreeChunks = 0;
5107
5108         dev->gcBlock = 0;
5109
5110         if (dev->param.startBlock == 0) {
5111                 dev->internalStartBlock = dev->param.startBlock + 1;
5112                 dev->internalEndBlock = dev->param.endBlock + 1;
5113                 dev->blockOffset = 1;
5114                 dev->chunkOffset = dev->param.nChunksPerBlock;
5115         }
5116
5117         /* Check geometry parameters. */
5118
5119         if ((!dev->param.inbandTags && dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 1024) ||
5120             (!dev->param.isYaffs2 && dev->param.totalBytesPerChunk < 512) ||
5121             (dev->param.inbandTags && !dev->param.isYaffs2) ||
5122              dev->param.nChunksPerBlock < 2 ||
5123              dev->param.nReservedBlocks < 2 ||
5124              dev->internalStartBlock <= 0 ||
5125              dev->internalEndBlock <= 0 ||
5126              dev->internalEndBlock <= (dev->internalStartBlock + dev->param.nReservedBlocks + 2)) {     /* otherwise it is too small */
5127                 T(YAFFS_TRACE_ALWAYS,
5128                   (TSTR
5129                    ("yaffs: NAND geometry problems: chunk size %d, type is yaffs%s, inbandTags %d "
5130                     TENDSTR), dev->param.totalBytesPerChunk, dev->param.isYaffs2 ? "2" : "", dev->param.inbandTags));
5131                 return YAFFS_FAIL;
5132         }
5133
5134         if (yaffs_InitialiseNAND(dev) != YAFFS_OK) {
5135                 T(YAFFS_TRACE_ALWAYS,
5136                   (TSTR("yaffs: InitialiseNAND failed" TENDSTR)));
5137                 return YAFFS_FAIL;
5138         }
5139
5140         /* Sort out space for inband tags, if required */
5141         if (dev->param.inbandTags)
5142                 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk - sizeof(yaffs_PackedTags2TagsPart);
5143         else
5144                 dev->nDataBytesPerChunk = dev->param.totalBytesPerChunk;
5145
5146         /* Got the right mix of functions? */
5147         if (!yaffs_CheckDevFunctions(dev)) {
5148                 /* Function missing */
5149                 T(YAFFS_TRACE_ALWAYS,
5150                   (TSTR
5151                    ("yaffs: device function(s) missing or wrong\n" TENDSTR)));
5152
5153                 return YAFFS_FAIL;
5154         }
5155
5156         /* This is really a compilation check. */
5157         if (!yaffs_CheckStructures()) {
5158                 T(YAFFS_TRACE_ALWAYS,
5159                   (TSTR("yaffs_CheckStructures failed\n" TENDSTR)));
5160                 return YAFFS_FAIL;
5161         }
5162
5163         if (dev->isMounted) {
5164                 T(YAFFS_TRACE_ALWAYS,
5165                   (TSTR("yaffs: device already mounted\n" TENDSTR)));
5166                 return YAFFS_FAIL;
5167         }
5168
5169         /* Finished with most checks. One or two more checks happen later on too. */
5170
5171         dev->isMounted = 1;
5172
5173         /* OK now calculate a few things for the device */
5174
5175         /*
5176          *  Calculate all the chunk size manipulation numbers:
5177          */
5178         x = dev->nDataBytesPerChunk;
5179         /* We always use dev->chunkShift and dev->chunkDiv */
5180         dev->chunkShift = Shifts(x);
5181         x >>= dev->chunkShift;
5182         dev->chunkDiv = x;
5183         /* We only use chunk mask if chunkDiv is 1 */
5184         dev->chunkMask = (1<<dev->chunkShift) - 1;
5185
5186         /*
5187          * Calculate chunkGroupBits.
5188          * We need to find the next power of 2 > than internalEndBlock
5189          */
5190
5191         x = dev->param.nChunksPerBlock * (dev->internalEndBlock + 1);
5192
5193         bits = ShiftsGE(x);
5194
5195         /* Set up tnode width if wide tnodes are enabled. */
5196         if (!dev->param.wideTnodesDisabled) {
5197                 /* bits must be even so that we end up with 32-bit words */
5198                 if (bits & 1)
5199                         bits++;
5200                 if (bits < 16)
5201                         dev->tnodeWidth = 16;
5202                 else
5203                         dev->tnodeWidth = bits;
5204         } else
5205                 dev->tnodeWidth = 16;
5206
5207         dev->tnodeMask = (1<<dev->tnodeWidth)-1;
5208
5209         /* Level0 Tnodes are 16 bits or wider (if wide tnodes are enabled),
5210          * so if the bitwidth of the
5211          * chunk range we're using is greater than 16 we need
5212          * to figure out chunk shift and chunkGroupSize
5213          */
5214
5215         if (bits <= dev->tnodeWidth)
5216                 dev->chunkGroupBits = 0;
5217         else
5218                 dev->chunkGroupBits = bits - dev->tnodeWidth;
5219
5220         dev->tnodeSize = (dev->tnodeWidth * YAFFS_NTNODES_LEVEL0)/8;
5221         if(dev->tnodeSize < sizeof(yaffs_Tnode))
5222                 dev->tnodeSize = sizeof(yaffs_Tnode);
5223
5224         dev->chunkGroupSize = 1 << dev->chunkGroupBits;
5225
5226         if (dev->param.nChunksPerBlock < dev->chunkGroupSize) {
5227                 /* We have a problem because the soft delete won't work if
5228                  * the chunk group size > chunks per block.
5229                  * This can be remedied by using larger "virtual blocks".
5230                  */
5231                 T(YAFFS_TRACE_ALWAYS,
5232                   (TSTR("yaffs: chunk group too large\n" TENDSTR)));
5233
5234                 return YAFFS_FAIL;
5235         }
5236
5237         /* OK, we've finished verifying the device, lets continue with initialisation */
5238
5239         /* More device initialisation */
5240         dev->allGCs = 0;
5241         dev->passiveGCs = 0;
5242         dev->oldestDirtyGCs = 0;
5243         dev->backgroundGCs = 0;
5244         dev->gcBlockFinder = 0;
5245         dev->bufferedBlock = -1;
5246         dev->doingBufferedBlockRewrite = 0;
5247         dev->nDeletedFiles = 0;
5248         dev->nBackgroundDeletions = 0;
5249         dev->nUnlinkedFiles = 0;
5250         dev->eccFixed = 0;
5251         dev->eccUnfixed = 0;
5252         dev->tagsEccFixed = 0;
5253         dev->tagsEccUnfixed = 0;
5254         dev->nErasureFailures = 0;
5255         dev->nErasedBlocks = 0;
5256         dev->gcDisable= 0;
5257         dev->hasPendingPrioritisedGCs = 1; /* Assume the worst for now, will get fixed on first GC */
5258         YINIT_LIST_HEAD(&dev->dirtyDirectories);
5259         dev->oldestDirtySequence = 0;
5260         dev->oldestDirtyBlock = 0;
5261
5262         /* Initialise temporary buffers and caches. */
5263         if (!yaffs_InitialiseTempBuffers(dev))
5264                 init_failed = 1;
5265
5266         dev->srCache = NULL;
5267         dev->gcCleanupList = NULL;
5268
5269
5270         if (!init_failed &&
5271             dev->param.nShortOpCaches > 0) {
5272                 int i;
5273                 void *buf;
5274                 int srCacheBytes = dev->param.nShortOpCaches * sizeof(yaffs_ChunkCache);
5275
5276                 if (dev->param.nShortOpCaches > YAFFS_MAX_SHORT_OP_CACHES)
5277                         dev->param.nShortOpCaches = YAFFS_MAX_SHORT_OP_CACHES;
5278
5279                 dev->srCache =  YMALLOC(srCacheBytes);
5280
5281                 buf = (__u8 *) dev->srCache;
5282
5283                 if (dev->srCache)
5284                         memset(dev->srCache, 0, srCacheBytes);
5285
5286                 for (i = 0; i < dev->param.nShortOpCaches && buf; i++) {
5287                         dev->srCache[i].object = NULL;
5288                         dev->srCache[i].lastUse = 0;
5289                         dev->srCache[i].dirty = 0;
5290                         dev->srCache[i].data = buf = YMALLOC_DMA(dev->param.totalBytesPerChunk);
5291                 }
5292                 if (!buf)
5293                         init_failed = 1;
5294
5295                 dev->srLastUse = 0;
5296         }
5297
5298         dev->cacheHits = 0;
5299
5300         if (!init_failed) {
5301                 dev->gcCleanupList = YMALLOC(dev->param.nChunksPerBlock * sizeof(__u32));
5302                 if (!dev->gcCleanupList)
5303                         init_failed = 1;
5304         }
5305
5306         if (dev->param.isYaffs2)
5307                 dev->param.useHeaderFileSize = 1;
5308
5309         if (!init_failed && !yaffs_InitialiseBlocks(dev))
5310                 init_failed = 1;
5311
5312         yaffs_InitialiseTnodesAndObjects(dev);
5313
5314         if (!init_failed && !yaffs_CreateInitialDirectories(dev))
5315                 init_failed = 1;
5316
5317
5318         if (!init_failed) {
5319                 /* Now scan the flash. */
5320                 if (dev->param.isYaffs2) {
5321                         if (yaffs2_CheckpointRestore(dev)) {
5322                                 yaffs_CheckObjectDetailsLoaded(dev->rootDir);
5323                                 T(YAFFS_TRACE_ALWAYS,
5324                                   (TSTR("yaffs: restored from checkpoint" TENDSTR)));
5325                         } else {
5326
5327                                 /* Clean up the mess caused by an aborted checkpoint load
5328                                  * and scan backwards.
5329                                  */
5330                                 yaffs_DeinitialiseBlocks(dev);
5331
5332                                 yaffs_DeinitialiseTnodesAndObjects(dev);
5333
5334                                 dev->nErasedBlocks = 0;
5335                                 dev->nFreeChunks = 0;
5336                                 dev->allocationBlock = -1;
5337                                 dev->allocationPage = -1;
5338                                 dev->nDeletedFiles = 0;
5339                                 dev->nUnlinkedFiles = 0;
5340                                 dev->nBackgroundDeletions = 0;
5341
5342                                 if (!init_failed && !yaffs_InitialiseBlocks(dev))
5343                                         init_failed = 1;
5344
5345                                 yaffs_InitialiseTnodesAndObjects(dev);
5346
5347                                 if (!init_failed && !yaffs_CreateInitialDirectories(dev))
5348                                         init_failed = 1;
5349
5350                                 if (!init_failed && !yaffs2_ScanBackwards(dev))
5351                                         init_failed = 1;
5352                         }
5353                 } else if (!yaffs1_Scan(dev))
5354                                 init_failed = 1;
5355
5356                 yaffs_StripDeletedObjects(dev);
5357                 yaffs_FixHangingObjects(dev);
5358                 if(dev->param.emptyLostAndFound)
5359                         yaffs_EmptyLostAndFound(dev);
5360         }
5361
5362         if (init_failed) {
5363                 /* Clean up the mess */
5364                 T(YAFFS_TRACE_TRACING,
5365                   (TSTR("yaffs: yaffs_GutsInitialise() aborted.\n" TENDSTR)));
5366
5367                 yaffs_Deinitialise(dev);
5368                 return YAFFS_FAIL;
5369         }
5370
5371         /* Zero out stats */
5372         dev->nPageReads = 0;
5373         dev->nPageWrites = 0;
5374         dev->nBlockErasures = 0;
5375         dev->nGCCopies = 0;
5376         dev->nRetriedWrites = 0;
5377
5378         dev->nRetiredBlocks = 0;
5379
5380         yaffs_VerifyFreeChunks(dev);
5381         yaffs_VerifyBlocks(dev);
5382
5383         /* Clean up any aborted checkpoint data */
5384         if(!dev->isCheckpointed && dev->blocksInCheckpoint > 0)
5385                 yaffs2_InvalidateCheckpoint(dev);
5386
5387         T(YAFFS_TRACE_TRACING,
5388           (TSTR("yaffs: yaffs_GutsInitialise() done.\n" TENDSTR)));
5389         return YAFFS_OK;
5390
5391 }
5392
5393 void yaffs_Deinitialise(yaffs_Device *dev)
5394 {
5395         if (dev->isMounted) {
5396                 int i;
5397
5398                 yaffs_DeinitialiseBlocks(dev);
5399                 yaffs_DeinitialiseTnodesAndObjects(dev);
5400                 if (dev->param.nShortOpCaches > 0 &&
5401                     dev->srCache) {
5402
5403                         for (i = 0; i < dev->param.nShortOpCaches; i++) {
5404                                 if (dev->srCache[i].data)
5405                                         YFREE(dev->srCache[i].data);
5406                                 dev->srCache[i].data = NULL;
5407                         }
5408
5409                         YFREE(dev->srCache);
5410                         dev->srCache = NULL;
5411                 }
5412
5413                 YFREE(dev->gcCleanupList);
5414
5415                 for (i = 0; i < YAFFS_N_TEMP_BUFFERS; i++)
5416                         YFREE(dev->tempBuffer[i].buffer);
5417
5418                 dev->isMounted = 0;
5419
5420                 if (dev->param.deinitialiseNAND)
5421                         dev->param.deinitialiseNAND(dev);
5422         }
5423 }
5424
5425 int yaffs_CountFreeChunks(yaffs_Device *dev)
5426 {
5427         int nFree=0;
5428         int b;
5429
5430         yaffs_BlockInfo *blk;
5431
5432         blk = dev->blockInfo;
5433         for (b = dev->internalStartBlock; b <= dev->internalEndBlock; b++) {
5434                 switch (blk->blockState) {
5435                 case YAFFS_BLOCK_STATE_EMPTY:
5436                 case YAFFS_BLOCK_STATE_ALLOCATING:
5437                 case YAFFS_BLOCK_STATE_COLLECTING:
5438                 case YAFFS_BLOCK_STATE_FULL:
5439                         nFree +=
5440                             (dev->param.nChunksPerBlock - blk->pagesInUse +
5441                              blk->softDeletions);
5442                         break;
5443                 default:
5444                         break;
5445                 }
5446                 blk++;
5447         }
5448
5449         return nFree;
5450 }
5451
5452 int yaffs_GetNumberOfFreeChunks(yaffs_Device *dev)
5453 {
5454         /* This is what we report to the outside world */
5455
5456         int nFree;
5457         int nDirtyCacheChunks;
5458         int blocksForCheckpoint;
5459         int i;
5460
5461 #if 1
5462         nFree = dev->nFreeChunks;
5463 #else
5464         nFree = yaffs_CountFreeChunks(dev);
5465 #endif
5466
5467         nFree += dev->nDeletedFiles;
5468
5469         /* Now count the number of dirty chunks in the cache and subtract those */
5470
5471         for (nDirtyCacheChunks = 0, i = 0; i < dev->param.nShortOpCaches; i++) {
5472                 if (dev->srCache[i].dirty)
5473                         nDirtyCacheChunks++;
5474         }
5475
5476         nFree -= nDirtyCacheChunks;
5477
5478         nFree -= ((dev->param.nReservedBlocks + 1) * dev->param.nChunksPerBlock);
5479
5480         /* Now we figure out how much to reserve for the checkpoint and report that... */
5481         blocksForCheckpoint = yaffs2_CalcCheckpointBlocksRequired(dev);
5482
5483         nFree -= (blocksForCheckpoint * dev->param.nChunksPerBlock);
5484
5485         if (nFree < 0)
5486                 nFree = 0;
5487
5488         return nFree;
5489
5490 }
5491
5492
5493 /*---------------------------------------- YAFFS test code ----------------------*/
5494
5495 #define yaffs_CheckStruct(structure, syze, name) \
5496         do { \
5497                 if (sizeof(structure) != syze) { \
5498                         T(YAFFS_TRACE_ALWAYS, (TSTR("%s should be %d but is %d\n" TENDSTR),\
5499                                 name, syze, (int) sizeof(structure))); \
5500                         return YAFFS_FAIL; \
5501                 } \
5502         } while (0)
5503
5504 static int yaffs_CheckStructures(void)
5505 {
5506 /*      yaffs_CheckStruct(yaffs_Tags,8,"yaffs_Tags"); */
5507 /*      yaffs_CheckStruct(yaffs_TagsUnion,8,"yaffs_TagsUnion"); */
5508 /*      yaffs_CheckStruct(yaffs_Spare,16,"yaffs_Spare"); */
5509 #ifndef CONFIG_YAFFS_TNODE_LIST_DEBUG
5510 /*      yaffs_CheckStruct(yaffs_Tnode, 2 * YAFFS_NTNODES_LEVEL0, "yaffs_Tnode"); */
5511 #endif
5512 #ifndef CONFIG_YAFFS_WINCE
5513         yaffs_CheckStruct(yaffs_ObjectHeader, 512, "yaffs_ObjectHeader");
5514 #endif
5515         return YAFFS_OK;
5516 }