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